@aiqa/sdk 2.2.0-develop.1 → 2.2.0-develop.3
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 +17 -0
- package/dist/browser/browser.d.ts +14 -0
- package/dist/browser/browser.js +1 -1
- package/dist/browser/browser.js.map +1 -1
- package/dist/node/node.d.ts +14 -0
- package/dist/node/node.js +1 -1
- package/dist/node/node.js.map +1 -1
- package/package.json +1 -1
package/dist/node/node.d.ts
CHANGED
|
@@ -56,6 +56,17 @@ type Application = {
|
|
|
56
56
|
agent_first_name: string;
|
|
57
57
|
/** Comes back empty. Set an agent name with `updateConversation()`. */
|
|
58
58
|
agent_last_name: string;
|
|
59
|
+
/**
|
|
60
|
+
* The status you last reported with `updateConversation({ externalStatus })`,
|
|
61
|
+
* folded to lowercase by the server. Missing when you never reported one —
|
|
62
|
+
* which is not the same as `"draft"`. Unlike the fields above it is never in
|
|
63
|
+
* the authentication snapshot, so on the fallback path described under
|
|
64
|
+
* `verification` it is absent rather than stale.
|
|
65
|
+
*
|
|
66
|
+
* Same open union as the input side: the members autocomplete, and a status
|
|
67
|
+
* the server learns before this package does still type-checks.
|
|
68
|
+
*/
|
|
69
|
+
external_status?: ExternalStatus | (string & {});
|
|
59
70
|
/**
|
|
60
71
|
* How the call is going so far. When it is missing there is no summary —
|
|
61
72
|
* which is not the same as all zeros — and the fields above may then be the
|
|
@@ -170,6 +181,8 @@ type ApplicationFactInput = {
|
|
|
170
181
|
*/
|
|
171
182
|
critical?: boolean;
|
|
172
183
|
is_skipped?: boolean;
|
|
184
|
+
/** Optional (default: `false`). Use `true` when the fact was collected before the conversation started. It is stored, not verified. */
|
|
185
|
+
prefilled?: boolean;
|
|
173
186
|
/**
|
|
174
187
|
* Your own identifiers for this fact — a form field ID, a section name,
|
|
175
188
|
* anything that lets your UI map the result back to the right place.
|
|
@@ -217,6 +230,7 @@ interface AddFactResult {
|
|
|
217
230
|
answer_type?: string;
|
|
218
231
|
agent_answer?: string;
|
|
219
232
|
ai_answer?: string;
|
|
233
|
+
/** `false` for a fact that was never verified, such as a prefilled one. */
|
|
220
234
|
is_valid_answer: boolean;
|
|
221
235
|
question_asked?: boolean;
|
|
222
236
|
/**
|
package/dist/node/node.js
CHANGED
|
@@ -70,7 +70,7 @@ var compareVersions = (left, right) => {
|
|
|
70
70
|
// package.json
|
|
71
71
|
var package_default = {
|
|
72
72
|
name: "@aiqa/sdk",
|
|
73
|
-
version: "2.
|
|
73
|
+
version: "2.2.0-develop.2",
|
|
74
74
|
main: "dist/node/node.js",
|
|
75
75
|
module: "dist/node/node.js",
|
|
76
76
|
types: "dist/node/node.d.ts",
|
package/dist/node/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shared.ts","../../src/types.ts","../../src/utils/compareVersions.ts","../../package.json"],"sourcesContent":["import { io, Socket } from \"socket.io-client\";\nimport {\n Methods,\n Application,\n ApplicationFact,\n ApplicationFactInput,\n SdkEvent,\n IAiqaSdk,\n AddFactResult,\n FlagFactResult,\n SetConversationProductResult,\n SetConversationLanguageResult,\n UpdateConversationInput,\n UpdateConversationResult,\n ConversationLanguage,\n} from \"./types.js\";\nimport { compareVersions } from \"./utils/compareVersions.js\";\n// @ts-ignore - compiled builds resolve this at build time\nimport pkg from \"../package.json\";\n\nconst SDK_VERSION = (pkg as { version?: string }).version ?? \"0.0.1\";\nconst DEFAULT_URL = \"ws://localhost:3025/ws\";\nconst DEFAULT_TIMEOUT_MS = 60000; // 1 minute\n\nconst RUNTIME: \"browser\" | \"node\" =\n typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n ? \"browser\"\n : \"node\";\n\nconst USER_AGENT: string =\n RUNTIME === \"browser\"\n ? typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : \"browser/unknown\"\n : typeof process !== \"undefined\"\n ? `node ${process.version} ${process.platform}`\n : \"node/unknown\";\n\nfunction isRequestTimeout(error: unknown, method: Methods): boolean {\n return (\n error instanceof Error &&\n error.message === `Request timed out for ${method}`\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\n// Fires the trailing ack callback (when present) after delivering the\n// payload to user code. Throws and async rejections are routed to\n// console.error — propagating them would skip subsequent listeners in\n// @socket.io/component-emitter's untryCatched loop.\n//\n// Auto-parses string args as JSON. The backend's broadcast emits\n// (`FACT_VERIFIED`, `TRANSCRIPTION_UPDATED`, `CALL_STATUS_UPDATED`) all\n// send `JSON.stringify(...)` payloads, but `FactVerifiedPayload` and\n// friends are typed as plain objects. Without this parse, a consumer\n// writing `payload.factId` would read a property off a string and get\n// `undefined`. Strings that don't parse (e.g. a primitive event name)\n// pass through unchanged.\nexport function wrapEventHandler(\n callback: (...args: any[]) => any,\n): (...args: any[]) => void {\n return (...args: any[]) => {\n const last = args[args.length - 1];\n const hasAck = typeof last === \"function\";\n const rawPayload = hasAck ? args.slice(0, -1) : args;\n const payload = rawPayload.map((arg) => {\n if (typeof arg !== \"string\") return arg;\n try {\n return JSON.parse(arg);\n } catch {\n return arg;\n }\n });\n try {\n const handlerResult = callback(...payload);\n if (isThenable(handlerResult)) {\n handlerResult.then(undefined, (err) => {\n // eslint-disable-next-line no-console\n console.error(\"[AiQaSdk] async event handler rejected:\", err);\n });\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[AiQaSdk] event handler threw:\", err);\n } finally {\n if (hasAck) {\n try {\n last();\n } catch {\n /* swallow */\n }\n }\n }\n };\n}\n\nclass AiQaSdk implements IAiqaSdk {\n socket: Socket | null = null;\n url: string;\n applicationId: string;\n applicationSecretKey: string;\n cachedApplication?: Application;\n internalListeners: Map<SdkEvent, Set<(...args: any[]) => void>>;\n internalEvents: Set<SdkEvent>;\n // event → originalCallback → Set<wrappedCallback> registered on\n // socket.io. A Set per (event, callback) so that subscribing the\n // same fn twice registers two wrappers and two off() calls clear\n // both.\n private wrappersByEvent: Map<\n SdkEvent,\n Map<(...args: any[]) => any, Set<(...args: any[]) => void>>\n > = new Map();\n\n constructor(applicationId: string, applicationSecret: string, url?: string) {\n this.url = url ?? DEFAULT_URL;\n this.internalListeners = new Map();\n this.internalEvents = new Set([\"authenticated\"]);\n\n if (applicationId && applicationSecret) {\n this.applicationId = applicationId;\n this.applicationSecretKey = applicationSecret;\n } else {\n throw new Error(\"Application id and application secret are required\");\n }\n }\n\n on(name: SdkEvent, callback: (...args: any[]) => any) {\n if (this.internalEvents.has(name)) {\n if (!this.internalListeners.has(name)) {\n this.internalListeners.set(name, new Set());\n }\n this.internalListeners.get(name)!.add(callback);\n return;\n }\n\n if (!this.socket) {\n throw new Error(\"Not connected\");\n }\n\n if (this.isManagerEvent(name)) {\n this.socket.io.on(name, callback);\n } else {\n const wrapped = wrapEventHandler(callback);\n let wrappersByCallback = this.wrappersByEvent.get(name);\n if (!wrappersByCallback) {\n wrappersByCallback = new Map();\n this.wrappersByEvent.set(name, wrappersByCallback);\n }\n let wrappers = wrappersByCallback.get(callback);\n if (!wrappers) {\n wrappers = new Set();\n wrappersByCallback.set(callback, wrappers);\n }\n wrappers.add(wrapped);\n this.socket.on(name, wrapped);\n }\n }\n\n off(name: SdkEvent, callback?: (...args: any[]) => any) {\n if (this.internalEvents.has(name)) {\n if (!callback) {\n this.internalListeners.delete(name);\n return;\n }\n const handlers = this.internalListeners.get(name);\n if (handlers) {\n handlers.delete(callback);\n if (handlers.size === 0) {\n this.internalListeners.delete(name);\n }\n }\n return;\n }\n\n if (!this.socket) {\n throw new Error(\"Not connected\");\n }\n\n if (this.isManagerEvent(name)) {\n this.socket.io.off(name, callback);\n return;\n }\n\n if (!callback) {\n this.socket.off(name);\n this.wrappersByEvent.delete(name);\n return;\n }\n\n const wrappersByCallback = this.wrappersByEvent.get(name);\n const wrappers = wrappersByCallback?.get(callback);\n if (wrappers && wrappers.size > 0) {\n const wrapped = wrappers.values().next().value as (\n ...args: any[]\n ) => void;\n wrappers.delete(wrapped);\n this.socket.off(name, wrapped);\n if (wrappers.size === 0) {\n wrappersByCallback!.delete(callback);\n if (wrappersByCallback!.size === 0) {\n this.wrappersByEvent.delete(name);\n }\n }\n } else {\n this.socket.off(name, callback);\n }\n }\n\n connect() {\n if (!this.url) {\n return;\n }\n\n const url = new URL(this.url);\n\n const socketOptions: any = {\n reconnectionDelayMax: 10000,\n path: url.pathname,\n // WebSocket only, skipping engine.io's default HTTP long-polling phase.\n // Some embedders sit behind proxies/security gateways that duplicate the\n // polling GETs across a fleet; the concurrent polls violate engine.io's\n // one-inflight-poll-per-session rule and tear the session down, so every\n // poll then returns \"Session ID unknown\" (HTTP 400) and the client never\n // authenticates. A single WebSocket has no repeated requests to duplicate.\n transports: [\"websocket\"],\n };\n\n this.socket = io(url.origin, socketOptions);\n\n this.socket.on(\"connect\", () => {\n this.authenticate();\n });\n\n this.socket.on(\n \"app_version\",\n wrapEventHandler((payload: any) => {\n const minVersion = payload?.min;\n const maxVersion = payload?.max;\n\n if (minVersion || maxVersion) {\n const tooLow = minVersion\n ? compareVersions(SDK_VERSION, minVersion) < 0\n : false;\n const tooHigh = maxVersion\n ? compareVersions(SDK_VERSION, maxVersion) > 0\n : false;\n if (tooLow || tooHigh) {\n const error = new Error(\n `SDK version ${SDK_VERSION} is not supported. Supported range: ${minVersion || \"-\"} to ${maxVersion || \"-\"}.`,\n );\n this.socket!.disconnect();\n this.socket!.emit(\"error\", error);\n }\n }\n }),\n );\n }\n\n disconnect() {\n if (this.socket) {\n this.socket.disconnect();\n }\n this.wrappersByEvent.clear();\n }\n\n sendMessage(method: Methods, data?: any): Promise<any> {\n return new Promise((resolve, reject) => {\n if (!this.socket || !this.socket.connected) {\n reject(new Error(\"Socket is not connected\"));\n return;\n }\n\n const requestId = this.createRequestId();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const handler = (payload: any) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n this.socket!.off(requestId, handler);\n let parsed = payload;\n if (typeof payload === \"string\") {\n try {\n parsed = JSON.parse(payload);\n } catch (error) {\n parsed = payload;\n }\n }\n\n if (parsed && parsed.error !== undefined) {\n reject(parsed.error);\n return;\n }\n\n // Return the full parsed envelope. Every caller below\n // (addFact, getFacts, flagFact, set*) already does its own\n // `result.data !== undefined ? result.data : result` unwrap,\n // so removing the unwrap here is behaviourally a no-op for\n // them — but it exposes top-level envelope fields like\n // `verification_status` to addFact() so the terminal\n // resolution can carry them alongside the inner data block.\n resolve(parsed);\n };\n\n this.socket.on(requestId, handler);\n\n const payload =\n data && typeof data === \"object\"\n ? { ...data, requestId }\n : { requestId, data };\n this.socket.emit(method, JSON.stringify(payload));\n\n timeout = setTimeout(() => {\n this.socket!.off(requestId, handler);\n reject(new Error(`Request timed out for ${method}`));\n }, DEFAULT_TIMEOUT_MS);\n });\n }\n\n async getApplication(): Promise<Application> {\n try {\n const result = await this.sendMessage(Methods.GET_APPLICATION);\n const application =\n result && result.data !== undefined ? result.data : result;\n if (application && application.application_id !== undefined) {\n return application;\n }\n throw new Error(\"GET_APPLICATION returned no application\");\n } catch (error) {\n // Only a server that predates GET_APPLICATION is worth absorbing: it\n // never answers, so the request can only end in a timeout. Anything else\n // — a rejected request, a dropped socket, a server-side failure — is a\n // real error, and swallowing it would hand back the authentication\n // snapshot as though it were live.\n if (!isRequestTimeout(error, Methods.GET_APPLICATION)) {\n throw error;\n }\n }\n\n // Never overwritten by this method, so it stays the snapshot taken at\n // authentication: identity fields only, no `verification`. That absence is\n // the signal the caller reads — a stale summary would be indistinguishable\n // from a live one.\n if (this.cachedApplication) {\n return this.cachedApplication;\n }\n throw new Error(\n \"Application is not available yet. Wait for authentication to complete.\",\n );\n }\n\n async getFacts(): Promise<ApplicationFact[]> {\n const result = await this.sendMessage(Methods.GET_FACTS);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async addFact(fact: ApplicationFactInput): Promise<AddFactResult> {\n const payload = {\n ...fact,\n critical: fact.critical ?? false,\n is_skipped: fact.is_skipped ?? false,\n };\n const result = await this.sendMessage(Methods.ADD_FACT, payload);\n if (!result) return result;\n const inner = result.data !== undefined ? result.data : result;\n\n // Older backends emit only `data` (or even a primitive like\n // `true`). New backends emit a `FactVerifiedResponseDto` envelope\n // carrying `verification_status` / `matched_components` /\n // `missing_components` at the top level ALONGSIDE the inner\n // `FactVerifiedDataDto`. Merge the envelope onto the resolved\n // value so callers awaiting addFact() see the full terminal\n // shape without subscribing to the broadcast `FACT_VERIFIED`\n // event. Skip the merge when the envelope is absent OR when inner\n // is not an object — spreading a primitive (`{ ...true }`) would\n // silently turn the resolution into `{}`.\n const hasEnvelope =\n result.verification_status !== undefined ||\n result.matched_components !== undefined ||\n result.missing_components !== undefined;\n if (!hasEnvelope || typeof inner !== \"object\" || inner === null) {\n return inner;\n }\n const merged = { ...inner } as AddFactResult;\n if (result.verification_status !== undefined) {\n merged.verification_status = result.verification_status;\n }\n if (result.matched_components !== undefined) {\n merged.matched_components = result.matched_components;\n }\n if (result.missing_components !== undefined) {\n merged.missing_components = result.missing_components;\n }\n return merged;\n }\n\n async flagFact(factId: string): Promise<FlagFactResult> {\n const result = await this.sendMessage(Methods.FLAG_FACT, {\n factId,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async setConversationProduct(\n product: string,\n ): Promise<SetConversationProductResult> {\n const result = await this.sendMessage(Methods.SET_CONVERSATION_PRODUCT, {\n product,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async setConversationLanguage(\n language: ConversationLanguage,\n ): Promise<SetConversationLanguageResult> {\n const result = await this.sendMessage(Methods.SET_CONVERSATION_LANGUAGE, {\n language,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async updateConversation(\n input: UpdateConversationInput,\n ): Promise<UpdateConversationResult> {\n const result = await this.sendMessage(Methods.UPDATE_CONVERSATION, input);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async authenticate(): Promise<void> {\n try {\n const result = await this.sendMessage(Methods.AUTHENTICATE, {\n applicationId: this.applicationId,\n applicationSecretKey: this.applicationSecretKey,\n sdkVersion: SDK_VERSION,\n runtime: RUNTIME,\n userAgent: USER_AGENT,\n });\n\n const application =\n result && result.data !== undefined ? result.data : result;\n\n this.cachedApplication = application;\n\n this.emitInternal(\"authenticated\", application);\n } catch (error) {\n this.socket!.emit(\"error\", error);\n }\n }\n\n async startRecording(): Promise<boolean> {\n const result = await this.sendMessage(Methods.START_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async stopRecording(): Promise<boolean> {\n const result = await this.sendMessage(Methods.STOP_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async isRecordingNow(): Promise<boolean> {\n // @TODO: track it from the server, should be sent on successfull connect\n const result = await this.sendMessage(Methods.IS_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n private emitInternal(name: SdkEvent, ...args: any[]) {\n const handlers = this.internalListeners.get(name);\n if (!handlers) {\n return;\n }\n handlers.forEach((handler) => handler(...args));\n }\n\n private createRequestId() {\n return `req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n }\n\n private isManagerEvent(name: SdkEvent) {\n return (\n name === \"reconnect_attempt\" ||\n name === \"reconnect_error\" ||\n name === \"reconnect_failed\" ||\n name === \"error\"\n );\n }\n}\n\nexport default AiQaSdk;\n","/**\n * Overall result for the call: `critical_errors` if a fact you sent with\n * `critical: true` failed, `errors` if any other fact failed, else\n * `no_errors`.\n *\n * Only answers count. A question that was never asked never raises it, so a\n * call where nothing was asked reads `no_errors`.\n *\n * Not the same as `VerificationStatus`, which describes a single fact.\n */\nexport type ApplicationVerificationStatus =\n | \"no_errors\"\n | \"errors\"\n | \"critical_errors\";\n\n/**\n * How the facts on one application are counted up. None of these is a count of\n * facts that passed, and they overlap — to show a pass count, count the facts\n * whose `verification_status` is `matched` in `getFacts()`.\n */\nexport type ApplicationVerificationSummary = {\n status: ApplicationVerificationStatus;\n /** Facts whose answer did not match the expected one. */\n count_errors: number;\n /** The facts in `count_errors` that you sent with `critical: true`. */\n count_critical_errors: number;\n /**\n * Every fact on the application, checked or not. The other counters are\n * subsets of it and can overlap each other, so no subtraction from\n * `count_total` yields a pass count.\n */\n count_total: number;\n /**\n * Facts whose question was never asked. Excludes the still-pending ones, but\n * overlaps `count_errors`: a fact never asked that came back wrong is in both.\n */\n count_not_asked: number;\n /** The facts in `count_not_asked` that you sent with `critical: true`. */\n count_critical_not_asked: number;\n /**\n * Facts added but not resolved yet. During a live call most facts sit here\n * and move into the other counters as their results arrive.\n */\n count_pending: number;\n /**\n * Facts flagged as suspicious when the call is reviewed — for instance the\n * agent leading the customer to the expected answer. Independent of the\n * answer: a matched fact can be flagged. Reads 0 while the call is running.\n */\n count_suspicious: number;\n};\n\nexport type Application = {\n application_id: string;\n client_name: string;\n client_phone_number: string;\n agent_id: string;\n /** Comes back empty. Set an agent name with `updateConversation()`. */\n agent_first_name: string;\n /** Comes back empty. Set an agent name with `updateConversation()`. */\n agent_last_name: string;\n /**\n * How the call is going so far. When it is missing there is no summary —\n * which is not the same as all zeros — and the fields above may then be the\n * ones from authentication, without an `updateConversation()` you made since.\n */\n verification?: ApplicationVerificationSummary;\n};\n\nexport enum Methods {\n AUTHENTICATE = \"AUTHENTICATE\",\n GET_FACTS = \"GET_FACTS\",\n GET_APPLICATION = \"GET_APPLICATION\",\n START_RECORDING = \"START_RECORDING\",\n STOP_RECORDING = \"STOP_RECORDING\",\n IS_RECORDING = \"IS_RECORDING\",\n ADD_FACT = \"ADD_FACT\",\n FLAG_FACT = \"FLAG_FACT\",\n SET_CONVERSATION_PRODUCT = \"SET_CONVERSATION_PRODUCT\",\n SET_CONVERSATION_LANGUAGE = \"SET_CONVERSATION_LANGUAGE\",\n UPDATE_CONVERSATION = \"UPDATE_CONVERSATION\",\n}\n\nexport type SetConversationProductResult = {\n success: boolean;\n product: string;\n};\n\nexport type SetConversationLanguageResult = {\n success: boolean;\n language: string;\n};\n\n/** User-provided application status. */\nexport enum ExternalStatus {\n DRAFT = \"draft\",\n PENDING = \"pending\",\n COMPLETED = \"completed\",\n EXPIRED = \"expired\",\n CLOSED = \"closed\",\n}\n\nexport type UpdateConversationInput = {\n policyNumber?: string;\n insuredPhone?: string;\n clientName?: string;\n clientPhone?: string;\n clientEmail?: string;\n clientId?: string;\n agentId?: string;\n agentName?: string;\n advisorId?: string;\n advisorName?: string;\n agentGroups?: string[];\n externalStatus?: ExternalStatus | (string & {});\n};\n\n/** Only the fields you sent come back in `conversation`. */\nexport type UpdateConversationResult = {\n success: boolean;\n conversation: {\n policy_number?: string;\n insured_phone?: string;\n client_name?: string;\n client_phone?: string;\n client_email?: string;\n client_id?: string;\n agent_id?: string;\n agent_name?: string;\n advisor_id?: string;\n advisor_name?: string;\n agent_groups?: string[];\n external_status?: string;\n };\n};\n\nexport enum ConversationLanguage {\n EN = \"en\",\n ES = \"es\",\n FR = \"fr\",\n}\n\nexport type SdkEvent =\n | Methods\n | \"connect\"\n | \"disconnect\"\n | \"close\"\n | \"error\"\n | \"reconnect_attempt\"\n | \"reconnect_error\"\n | \"reconnect_failed\"\n | \"authenticated\"\n | \"app_version\"\n // Every verification state change, for every fact. Payload:\n // `FactVerifiedPayload`.\n | \"FACT_VERIFIED\"\n // Every utterance, as it is transcribed. Payload: `TranscriptionUpdate`.\n | \"TRANSCRIPTION_UPDATED\";\n\nexport enum FactAnswerFormatType {\n string = \"STRING\",\n number = \"NUMBER\",\n integer = \"INT\",\n float = \"FLOAT\",\n bool = \"BOOL\",\n list = \"LIST\",\n strict = \"STRICT\",\n single_choice = \"SINGLE_CHOICE\",\n multiple_choices = \"MULTIPLE_CHOICES\",\n}\n\nexport type ApplicationFactAnswerChoice = {\n key: string;\n text: string;\n};\n\nexport type ApplicationFactAnswerFormat = {\n type: FactAnswerFormatType;\n choices?: ApplicationFactAnswerChoice[];\n};\n\nexport type ApplicationFactInput = {\n id: string;\n /**\n * Stable identifier for the underlying question, shared across applications\n * and conversations. When provided it identifies the question instead of\n * `id`. Keep it consistent across calls: whatever AIQA has tuned for a\n * question is attached to this identity.\n */\n questionId?: string;\n question: string;\n expected_answer: any;\n answer_format: ApplicationFactAnswerFormat;\n\n category_id?: string;\n category_name?: string;\n language?: string;\n\n /**\n * Mark the question critical: its failures land in `count_critical_errors`,\n * and one of them sets the call's `status` to `critical_errors`.\n */\n critical?: boolean;\n is_skipped?: boolean;\n /**\n * Your own identifiers for this fact — a form field ID, a section name,\n * anything that lets your UI map the result back to the right place.\n * `getFacts()` returns it unchanged — `{}` for a fact you added without\n * one — and it plays no part in verification.\n *\n * Keys and values must all be strings, and each value is limited to 1024\n * characters. A payload that breaks either rule is rejected.\n */\n metadata?: Record<string, string>;\n};\n\nexport type QuestionStatus = \"searching\" | \"asked\" | \"not_asked\";\n\n/**\n * Per-fact verification state. Handle any value you don't recognize as\n * `processing`.\n *\n * - `processing` queued, or nothing to go on yet\n * - `awaiting_question` the agent hasn't asked the question yet\n * - `awaiting_answer` asked, the customer hasn't answered yet\n * - `partial` partial evidence so far (e.g. \"305\" of \"30521\")\n * - `pending_confirmation_matched` a matching answer is held briefly in case\n * the customer corrects it mid-answer\n * (spellings, \"I mean…\"); resolves to\n * `matched`/`unmatched`\n * - `pending_confirmation_unmatched` same, with an unmatched answer held; show\n * \"we heard X but it doesn't match, waiting\n * to confirm\" rather than a hard result\n * - `matched` final: the answer matched\n * - `unmatched` final: the answer did not match\n */\nexport type VerificationStatus =\n | \"processing\"\n | \"awaiting_question\"\n | \"awaiting_answer\"\n | \"partial\"\n | \"pending_confirmation_matched\"\n | \"pending_confirmation_unmatched\"\n | \"matched\"\n | \"unmatched\";\n\nexport type ApplicationFact = ApplicationFactInput & {\n ai_answer?: any;\n question_status: QuestionStatus;\n verification_status: VerificationStatus;\n /** True once `flagFact(factId)` has been called for this fact. */\n flagged: boolean;\n};\n\nexport interface AddFactResult {\n /** Conversation the fact was attached to. */\n conversation_id?: string;\n /** Echo of the original question text from the fact input. */\n question?: string;\n /** Echo of the resolved `answer_format.type` (e.g. \"STRING\", \"NUMBER\", \"SINGLE_CHOICE\"). */\n answer_type?: string;\n agent_answer?: string;\n ai_answer?: string;\n is_valid_answer: boolean;\n question_asked?: boolean;\n /**\n * How closely the agent's utterance matched the expected question, on a 0–1\n * or a 0–100 scale. Higher is closer.\n */\n question_match_score?: number;\n /**\n * 0–1 score for how closely the customer's answer matched the expected one.\n * Undefined when there is no partial signal to score.\n */\n answer_match_score?: number;\n metadata?: Record<string, string>;\n /**\n * The final state: `matched` or `unmatched` whenever it is present. Fall\n * back to `is_valid_answer` when it is missing.\n */\n verification_status?: VerificationStatus;\n /**\n * Component labels describing which parts of the expected answer\n * matched. Currently `[\"prefix\"]` / `[\"suffix\"]` for numeric facts;\n * treat the set as open-ended.\n */\n matched_components?: string[];\n missing_components?: string[];\n}\n\n/**\n * Payload of the `FACT_VERIFIED` event, which fires on every state change —\n * see `VerificationStatus`. Use it to show progress; `addFact()` resolves\n * only once a fact is done.\n */\nexport interface FactVerifiedPayload {\n factId: string;\n success: boolean;\n verification_status?: VerificationStatus;\n question_match_score?: number;\n answer_match_score?: number;\n matched_components?: string[];\n missing_components?: string[];\n /** Inner payload, shaped like `AddFactResult`. */\n data?: AddFactResult;\n error?: string;\n}\n\nexport type FlagFactResult = {\n success: boolean;\n};\n\n/**\n * What the utterance appears to be doing in the conversation. A best-effort\n * guess: display it if it helps, but do not gate behaviour on it. Its\n * confidence band is `dialog_act_confidence`.\n */\nexport type DialogAct =\n | \"question\"\n | \"answer\"\n | \"acknowledgement\"\n | \"filler\"\n | \"other\";\n\n/**\n * Confidence band for `dialog_act` only. Unrelated to the numeric\n * `confidence` field on the same utterance — do not compare the two.\n */\nexport type DialogActConfidence = \"high\" | \"medium\" | \"low\";\n\n/**\n * An utterance from the `TRANSCRIPTION_UPDATED` event.\n *\n * A missing optional field means \"unknown\", not \"no\".\n */\nexport type Utterance = {\n /** Sort utterances by this: ids sort in chronological order. */\n id: string;\n call_id: number;\n /** Always 0. Sort by `id`, not this. */\n order: number;\n is_agent: boolean | null;\n speaker: number;\n text: string;\n text_en: string | null;\n start_time: number;\n end_time: number;\n dialog_act?: DialogAct;\n dialog_act_confidence?: DialogActConfidence;\n confidence?: number | null;\n top_alt_margin?: number | null;\n is_ivr_filler_candidate?: boolean;\n spoken_digits_normalized?: string | null;\n vendor?: string | null;\n};\n\n/** Payload of the `TRANSCRIPTION_UPDATED` broadcast event. */\nexport type TranscriptionUpdate = {\n policyNumber: string;\n conversationId: string;\n utterance: Utterance;\n};\n\nexport type SdkError = {\n code:\n | \"INVALID_CONFIG\"\n | \"CONNECTION_ERROR\"\n | \"TIMEOUT\"\n | \"SERVER_ERROR\"\n | \"UNEXPECTED_RESPONSE\";\n message: string;\n details?: any;\n};\n\nexport abstract class IAiqaSdk {\n abstract connect(): void;\n abstract disconnect(): void;\n\n abstract on(eventName: string, callback: (...args: any[]) => any): void;\n abstract off(eventName: string, callback?: (...args: any[]) => any): void;\n\n abstract getApplication(): Promise<Application>;\n abstract addFact(fact: ApplicationFactInput): Promise<AddFactResult>;\n abstract flagFact(factId: string): Promise<FlagFactResult>;\n abstract getFacts(): Promise<ApplicationFact[]>;\n abstract setConversationProduct(\n product: string,\n ): Promise<SetConversationProductResult>;\n abstract setConversationLanguage(\n language: ConversationLanguage,\n ): Promise<SetConversationLanguageResult>;\n abstract updateConversation(\n input: UpdateConversationInput,\n ): Promise<UpdateConversationResult>;\n}\n","const splitVersion = (value: string) => {\n const [core] = value.split(\"-\", 2);\n return core.split(\".\").map((part) => Number(part));\n};\n\nexport const compareVersions = (left: string, right: string): number => {\n const leftParts = splitVersion(left);\n const rightParts = splitVersion(right);\n const maxLength = Math.max(leftParts.length, rightParts.length);\n\n for (let i = 0; i < maxLength; i += 1) {\n const l = leftParts[i] ?? 0;\n const r = rightParts[i] ?? 0;\n if (l > r) {\n return 1;\n }\n if (l < r) {\n return -1;\n }\n }\n\n return 0;\n};\n","{\n \"name\": \"@aiqa/sdk\",\n \"version\": \"2.1.1-develop.1\",\n \"main\": \"dist/node/node.js\",\n \"module\": \"dist/node/node.js\",\n \"types\": \"dist/node/node.d.ts\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup && node -e \\\"const fs=require('fs');['dist/node/node','dist/browser/browser'].forEach(f=>{const mts=f+'.d.mts';const ts=f+'.d.ts';if(fs.existsSync(mts)){fs.renameSync(mts,ts);}});\\\"\",\n \"commitlint\": \"commitlint\",\n \"dev:node\": \"tsx src/node.ts\",\n \"lint\": \"tsc --noEmit -p tsconfig.json\",\n \"format\": \"prettier --check \\\"{src,tests}/**/*.{ts,tsx,js,json,md,yml,yaml}\\\" \\\"*.{js,json,md,yml,yaml,ts}\\\" --ignore-path .prettierignore\",\n \"release\": \"semantic-release\",\n \"start:node\": \"node dist/node/node.js\",\n \"serve:browser\": \"serve .\",\n \"test\": \"jest\",\n \"prepare\": \"husky\",\n \"lint-staged\": \"lint-staged\"\n },\n \"lint-staged\": {\n \"*.{ts,tsx,js,json,md,yml,yaml}\": [\n \"prettier --write\"\n ]\n },\n \"exports\": {\n \".\": {\n \"node\": {\n \"import\": \"./dist/node/node.js\",\n \"types\": \"./dist/node/node.d.ts\"\n },\n \"browser\": {\n \"import\": \"./dist/browser/browser.js\",\n \"types\": \"./dist/browser/browser.d.ts\"\n },\n \"default\": \"./dist/node/node.js\"\n }\n },\n \"private\": false,\n \"license\": \"MIT\",\n \"author\": \"AIQA\",\n \"description\": \"TypeScript/JavaScript SDK for interacting with the AIQA.\",\n \"keywords\": [\n \"aiqa\",\n \"sdk\"\n ],\n \"files\": [\n \"dist\"\n ],\n \"devDependencies\": {\n \"@commitlint/cli\": \"^20.4.4\",\n \"@commitlint/config-conventional\": \"^20.4.4\",\n \"@jest/globals\": \"^29.7.0\",\n \"@semantic-release/commit-analyzer\": \"^13.0.1\",\n \"@semantic-release/git\": \"^10.0.1\",\n \"@semantic-release/npm\": \"^12.0.2\",\n \"@semantic-release/release-notes-generator\": \"^14.1.0\",\n \"@types/node\": \"^22.0.0\",\n \"conventional-changelog-conventionalcommits\": \"^9.3.0\",\n \"esbuild\": \"^0.23.0\",\n \"husky\": \"^9.1.7\",\n \"jest\": \"^29.7.0\",\n \"lint-staged\": \"^16.4.0\",\n \"prettier\": \"^3.8.1\",\n \"semantic-release\": \"^24.2.9\",\n \"serve\": \"^14.2.3\",\n \"socket.io\": \"^4.7.5\",\n \"ts-jest\": \"^29.2.3\",\n \"ts-node\": \"^10.9.2\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.7.0\"\n },\n \"dependencies\": {\n \"socket.io-client\": \"^4.7.5\"\n }\n}\n"],"mappings":";AAAA,SAAS,UAAkB;;;ACqEpB,IAAK,UAAL,kBAAKA,aAAL;AACL,EAAAA,SAAA,kBAAe;AACf,EAAAA,SAAA,eAAY;AACZ,EAAAA,SAAA,qBAAkB;AAClB,EAAAA,SAAA,qBAAkB;AAClB,EAAAA,SAAA,oBAAiB;AACjB,EAAAA,SAAA,kBAAe;AACf,EAAAA,SAAA,cAAW;AACX,EAAAA,SAAA,eAAY;AACZ,EAAAA,SAAA,8BAA2B;AAC3B,EAAAA,SAAA,+BAA4B;AAC5B,EAAAA,SAAA,yBAAsB;AAXZ,SAAAA;AAAA,GAAA;AAyBL,IAAK,iBAAL,kBAAKC,oBAAL;AACL,EAAAA,gBAAA,WAAQ;AACR,EAAAA,gBAAA,aAAU;AACV,EAAAA,gBAAA,eAAY;AACZ,EAAAA,gBAAA,aAAU;AACV,EAAAA,gBAAA,YAAS;AALC,SAAAA;AAAA,GAAA;AA0CL,IAAK,uBAAL,kBAAKC,0BAAL;AACL,EAAAA,sBAAA,QAAK;AACL,EAAAA,sBAAA,QAAK;AACL,EAAAA,sBAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AAuBL,IAAK,uBAAL,kBAAKC,0BAAL;AACL,EAAAA,sBAAA,YAAS;AACT,EAAAA,sBAAA,YAAS;AACT,EAAA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AAY,OAAO,OAAO;AAAA,EAC7D;AAAA,EAEA,MAAM,gBAAkC;AACtC,UAAM,SAAS,MAAM,KAAK,iDAAkC;AAC5D,WAAO,UAAU,OAAO,SAAS,SAAY,OAAO,OAAO;AAAA,EAC7D;AAAA,EAEA,MAAM,iBAAmC;AAEvC,UAAM,SAAS,MAAM,KAAK,6CAAgC;AAC1D,WAAO,UAAU,OAAO,SAAS,SAAY,OAAO,OAAO;AAAA,EAC7D;AAAA,EAEQ,aAAa,SAAmB,MAAa;AACnD,UAAM,WAAW,KAAK,kBAAkB,IAAI,IAAI;AAChD,QAAI,CAAC,UAAU;AACb;AAAA,IACF;AACA,aAAS,QAAQ,CAAC,YAAY,QAAQ,GAAG,IAAI,CAAC;AAAA,EAChD;AAAA,EAEQ,kBAAkB;AACxB,WAAO,OAAO,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AAAA,EAClF;AAAA,EAEQ,eAAe,MAAgB;AACrC,WACE,SAAS,uBACT,SAAS,qBACT,SAAS,sBACT,SAAS;AAAA,EAEb;AACF;AAEA,IAAO,iBAAQ;","names":["Methods","ExternalStatus","ConversationLanguage","FactAnswerFormatType","payload"]}
|
|
1
|
+
{"version":3,"sources":["../../src/shared.ts","../../src/types.ts","../../src/utils/compareVersions.ts","../../package.json"],"sourcesContent":["import { io, Socket } from \"socket.io-client\";\nimport {\n Methods,\n Application,\n ApplicationFact,\n ApplicationFactInput,\n SdkEvent,\n IAiqaSdk,\n AddFactResult,\n FlagFactResult,\n SetConversationProductResult,\n SetConversationLanguageResult,\n UpdateConversationInput,\n UpdateConversationResult,\n ConversationLanguage,\n} from \"./types.js\";\nimport { compareVersions } from \"./utils/compareVersions.js\";\n// @ts-ignore - compiled builds resolve this at build time\nimport pkg from \"../package.json\";\n\nconst SDK_VERSION = (pkg as { version?: string }).version ?? \"0.0.1\";\nconst DEFAULT_URL = \"ws://localhost:3025/ws\";\nconst DEFAULT_TIMEOUT_MS = 60000; // 1 minute\n\nconst RUNTIME: \"browser\" | \"node\" =\n typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n ? \"browser\"\n : \"node\";\n\nconst USER_AGENT: string =\n RUNTIME === \"browser\"\n ? typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : \"browser/unknown\"\n : typeof process !== \"undefined\"\n ? `node ${process.version} ${process.platform}`\n : \"node/unknown\";\n\nfunction isRequestTimeout(error: unknown, method: Methods): boolean {\n return (\n error instanceof Error &&\n error.message === `Request timed out for ${method}`\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\n// Fires the trailing ack callback (when present) after delivering the\n// payload to user code. Throws and async rejections are routed to\n// console.error — propagating them would skip subsequent listeners in\n// @socket.io/component-emitter's untryCatched loop.\n//\n// Auto-parses string args as JSON. The backend's broadcast emits\n// (`FACT_VERIFIED`, `TRANSCRIPTION_UPDATED`, `CALL_STATUS_UPDATED`) all\n// send `JSON.stringify(...)` payloads, but `FactVerifiedPayload` and\n// friends are typed as plain objects. Without this parse, a consumer\n// writing `payload.factId` would read a property off a string and get\n// `undefined`. Strings that don't parse (e.g. a primitive event name)\n// pass through unchanged.\nexport function wrapEventHandler(\n callback: (...args: any[]) => any,\n): (...args: any[]) => void {\n return (...args: any[]) => {\n const last = args[args.length - 1];\n const hasAck = typeof last === \"function\";\n const rawPayload = hasAck ? args.slice(0, -1) : args;\n const payload = rawPayload.map((arg) => {\n if (typeof arg !== \"string\") return arg;\n try {\n return JSON.parse(arg);\n } catch {\n return arg;\n }\n });\n try {\n const handlerResult = callback(...payload);\n if (isThenable(handlerResult)) {\n handlerResult.then(undefined, (err) => {\n // eslint-disable-next-line no-console\n console.error(\"[AiQaSdk] async event handler rejected:\", err);\n });\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[AiQaSdk] event handler threw:\", err);\n } finally {\n if (hasAck) {\n try {\n last();\n } catch {\n /* swallow */\n }\n }\n }\n };\n}\n\nclass AiQaSdk implements IAiqaSdk {\n socket: Socket | null = null;\n url: string;\n applicationId: string;\n applicationSecretKey: string;\n cachedApplication?: Application;\n internalListeners: Map<SdkEvent, Set<(...args: any[]) => void>>;\n internalEvents: Set<SdkEvent>;\n // event → originalCallback → Set<wrappedCallback> registered on\n // socket.io. A Set per (event, callback) so that subscribing the\n // same fn twice registers two wrappers and two off() calls clear\n // both.\n private wrappersByEvent: Map<\n SdkEvent,\n Map<(...args: any[]) => any, Set<(...args: any[]) => void>>\n > = new Map();\n\n constructor(applicationId: string, applicationSecret: string, url?: string) {\n this.url = url ?? DEFAULT_URL;\n this.internalListeners = new Map();\n this.internalEvents = new Set([\"authenticated\"]);\n\n if (applicationId && applicationSecret) {\n this.applicationId = applicationId;\n this.applicationSecretKey = applicationSecret;\n } else {\n throw new Error(\"Application id and application secret are required\");\n }\n }\n\n on(name: SdkEvent, callback: (...args: any[]) => any) {\n if (this.internalEvents.has(name)) {\n if (!this.internalListeners.has(name)) {\n this.internalListeners.set(name, new Set());\n }\n this.internalListeners.get(name)!.add(callback);\n return;\n }\n\n if (!this.socket) {\n throw new Error(\"Not connected\");\n }\n\n if (this.isManagerEvent(name)) {\n this.socket.io.on(name, callback);\n } else {\n const wrapped = wrapEventHandler(callback);\n let wrappersByCallback = this.wrappersByEvent.get(name);\n if (!wrappersByCallback) {\n wrappersByCallback = new Map();\n this.wrappersByEvent.set(name, wrappersByCallback);\n }\n let wrappers = wrappersByCallback.get(callback);\n if (!wrappers) {\n wrappers = new Set();\n wrappersByCallback.set(callback, wrappers);\n }\n wrappers.add(wrapped);\n this.socket.on(name, wrapped);\n }\n }\n\n off(name: SdkEvent, callback?: (...args: any[]) => any) {\n if (this.internalEvents.has(name)) {\n if (!callback) {\n this.internalListeners.delete(name);\n return;\n }\n const handlers = this.internalListeners.get(name);\n if (handlers) {\n handlers.delete(callback);\n if (handlers.size === 0) {\n this.internalListeners.delete(name);\n }\n }\n return;\n }\n\n if (!this.socket) {\n throw new Error(\"Not connected\");\n }\n\n if (this.isManagerEvent(name)) {\n this.socket.io.off(name, callback);\n return;\n }\n\n if (!callback) {\n this.socket.off(name);\n this.wrappersByEvent.delete(name);\n return;\n }\n\n const wrappersByCallback = this.wrappersByEvent.get(name);\n const wrappers = wrappersByCallback?.get(callback);\n if (wrappers && wrappers.size > 0) {\n const wrapped = wrappers.values().next().value as (\n ...args: any[]\n ) => void;\n wrappers.delete(wrapped);\n this.socket.off(name, wrapped);\n if (wrappers.size === 0) {\n wrappersByCallback!.delete(callback);\n if (wrappersByCallback!.size === 0) {\n this.wrappersByEvent.delete(name);\n }\n }\n } else {\n this.socket.off(name, callback);\n }\n }\n\n connect() {\n if (!this.url) {\n return;\n }\n\n const url = new URL(this.url);\n\n const socketOptions: any = {\n reconnectionDelayMax: 10000,\n path: url.pathname,\n // WebSocket only, skipping engine.io's default HTTP long-polling phase.\n // Some embedders sit behind proxies/security gateways that duplicate the\n // polling GETs across a fleet; the concurrent polls violate engine.io's\n // one-inflight-poll-per-session rule and tear the session down, so every\n // poll then returns \"Session ID unknown\" (HTTP 400) and the client never\n // authenticates. A single WebSocket has no repeated requests to duplicate.\n transports: [\"websocket\"],\n };\n\n this.socket = io(url.origin, socketOptions);\n\n this.socket.on(\"connect\", () => {\n this.authenticate();\n });\n\n this.socket.on(\n \"app_version\",\n wrapEventHandler((payload: any) => {\n const minVersion = payload?.min;\n const maxVersion = payload?.max;\n\n if (minVersion || maxVersion) {\n const tooLow = minVersion\n ? compareVersions(SDK_VERSION, minVersion) < 0\n : false;\n const tooHigh = maxVersion\n ? compareVersions(SDK_VERSION, maxVersion) > 0\n : false;\n if (tooLow || tooHigh) {\n const error = new Error(\n `SDK version ${SDK_VERSION} is not supported. Supported range: ${minVersion || \"-\"} to ${maxVersion || \"-\"}.`,\n );\n this.socket!.disconnect();\n this.socket!.emit(\"error\", error);\n }\n }\n }),\n );\n }\n\n disconnect() {\n if (this.socket) {\n this.socket.disconnect();\n }\n this.wrappersByEvent.clear();\n }\n\n sendMessage(method: Methods, data?: any): Promise<any> {\n return new Promise((resolve, reject) => {\n if (!this.socket || !this.socket.connected) {\n reject(new Error(\"Socket is not connected\"));\n return;\n }\n\n const requestId = this.createRequestId();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const handler = (payload: any) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n this.socket!.off(requestId, handler);\n let parsed = payload;\n if (typeof payload === \"string\") {\n try {\n parsed = JSON.parse(payload);\n } catch (error) {\n parsed = payload;\n }\n }\n\n if (parsed && parsed.error !== undefined) {\n reject(parsed.error);\n return;\n }\n\n // Return the full parsed envelope. Every caller below\n // (addFact, getFacts, flagFact, set*) already does its own\n // `result.data !== undefined ? result.data : result` unwrap,\n // so removing the unwrap here is behaviourally a no-op for\n // them — but it exposes top-level envelope fields like\n // `verification_status` to addFact() so the terminal\n // resolution can carry them alongside the inner data block.\n resolve(parsed);\n };\n\n this.socket.on(requestId, handler);\n\n const payload =\n data && typeof data === \"object\"\n ? { ...data, requestId }\n : { requestId, data };\n this.socket.emit(method, JSON.stringify(payload));\n\n timeout = setTimeout(() => {\n this.socket!.off(requestId, handler);\n reject(new Error(`Request timed out for ${method}`));\n }, DEFAULT_TIMEOUT_MS);\n });\n }\n\n async getApplication(): Promise<Application> {\n try {\n const result = await this.sendMessage(Methods.GET_APPLICATION);\n const application =\n result && result.data !== undefined ? result.data : result;\n if (application && application.application_id !== undefined) {\n return application;\n }\n throw new Error(\"GET_APPLICATION returned no application\");\n } catch (error) {\n // Only a server that predates GET_APPLICATION is worth absorbing: it\n // never answers, so the request can only end in a timeout. Anything else\n // — a rejected request, a dropped socket, a server-side failure — is a\n // real error, and swallowing it would hand back the authentication\n // snapshot as though it were live.\n if (!isRequestTimeout(error, Methods.GET_APPLICATION)) {\n throw error;\n }\n }\n\n // Never overwritten by this method, so it stays the snapshot taken at\n // authentication: identity fields only, no `verification`. That absence is\n // the signal the caller reads — a stale summary would be indistinguishable\n // from a live one.\n if (this.cachedApplication) {\n return this.cachedApplication;\n }\n throw new Error(\n \"Application is not available yet. Wait for authentication to complete.\",\n );\n }\n\n async getFacts(): Promise<ApplicationFact[]> {\n const result = await this.sendMessage(Methods.GET_FACTS);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async addFact(fact: ApplicationFactInput): Promise<AddFactResult> {\n // No `?? false` for `prefilled`, unlike critical/is_skipped: defaulting it\n // would relabel every existing integration's facts as agent-entered.\n const payload = {\n ...fact,\n critical: fact.critical ?? false,\n is_skipped: fact.is_skipped ?? false,\n };\n const result = await this.sendMessage(Methods.ADD_FACT, payload);\n if (!result) return result;\n const inner = result.data !== undefined ? result.data : result;\n\n // Older backends emit only `data` (or even a primitive like\n // `true`). New backends emit a `FactVerifiedResponseDto` envelope\n // carrying `verification_status` / `matched_components` /\n // `missing_components` at the top level ALONGSIDE the inner\n // `FactVerifiedDataDto`. Merge the envelope onto the resolved\n // value so callers awaiting addFact() see the full terminal\n // shape without subscribing to the broadcast `FACT_VERIFIED`\n // event. Skip the merge when the envelope is absent OR when inner\n // is not an object — spreading a primitive (`{ ...true }`) would\n // silently turn the resolution into `{}`.\n const hasEnvelope =\n result.verification_status !== undefined ||\n result.matched_components !== undefined ||\n result.missing_components !== undefined;\n if (!hasEnvelope || typeof inner !== \"object\" || inner === null) {\n return inner;\n }\n const merged = { ...inner } as AddFactResult;\n if (result.verification_status !== undefined) {\n merged.verification_status = result.verification_status;\n }\n if (result.matched_components !== undefined) {\n merged.matched_components = result.matched_components;\n }\n if (result.missing_components !== undefined) {\n merged.missing_components = result.missing_components;\n }\n return merged;\n }\n\n async flagFact(factId: string): Promise<FlagFactResult> {\n const result = await this.sendMessage(Methods.FLAG_FACT, {\n factId,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async setConversationProduct(\n product: string,\n ): Promise<SetConversationProductResult> {\n const result = await this.sendMessage(Methods.SET_CONVERSATION_PRODUCT, {\n product,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async setConversationLanguage(\n language: ConversationLanguage,\n ): Promise<SetConversationLanguageResult> {\n const result = await this.sendMessage(Methods.SET_CONVERSATION_LANGUAGE, {\n language,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async updateConversation(\n input: UpdateConversationInput,\n ): Promise<UpdateConversationResult> {\n const result = await this.sendMessage(Methods.UPDATE_CONVERSATION, input);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async authenticate(): Promise<void> {\n try {\n const result = await this.sendMessage(Methods.AUTHENTICATE, {\n applicationId: this.applicationId,\n applicationSecretKey: this.applicationSecretKey,\n sdkVersion: SDK_VERSION,\n runtime: RUNTIME,\n userAgent: USER_AGENT,\n });\n\n const application =\n result && result.data !== undefined ? result.data : result;\n\n this.cachedApplication = application;\n\n this.emitInternal(\"authenticated\", application);\n } catch (error) {\n this.socket!.emit(\"error\", error);\n }\n }\n\n async startRecording(): Promise<boolean> {\n const result = await this.sendMessage(Methods.START_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async stopRecording(): Promise<boolean> {\n const result = await this.sendMessage(Methods.STOP_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async isRecordingNow(): Promise<boolean> {\n // @TODO: track it from the server, should be sent on successfull connect\n const result = await this.sendMessage(Methods.IS_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n private emitInternal(name: SdkEvent, ...args: any[]) {\n const handlers = this.internalListeners.get(name);\n if (!handlers) {\n return;\n }\n handlers.forEach((handler) => handler(...args));\n }\n\n private createRequestId() {\n return `req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n }\n\n private isManagerEvent(name: SdkEvent) {\n return (\n name === \"reconnect_attempt\" ||\n name === \"reconnect_error\" ||\n name === \"reconnect_failed\" ||\n name === \"error\"\n );\n }\n}\n\nexport default AiQaSdk;\n","/**\n * Overall result for the call: `critical_errors` if a fact you sent with\n * `critical: true` failed, `errors` if any other fact failed, else\n * `no_errors`.\n *\n * Only answers count. A question that was never asked never raises it, so a\n * call where nothing was asked reads `no_errors`.\n *\n * Not the same as `VerificationStatus`, which describes a single fact.\n */\nexport type ApplicationVerificationStatus =\n | \"no_errors\"\n | \"errors\"\n | \"critical_errors\";\n\n/**\n * How the facts on one application are counted up. None of these is a count of\n * facts that passed, and they overlap — to show a pass count, count the facts\n * whose `verification_status` is `matched` in `getFacts()`.\n */\nexport type ApplicationVerificationSummary = {\n status: ApplicationVerificationStatus;\n /** Facts whose answer did not match the expected one. */\n count_errors: number;\n /** The facts in `count_errors` that you sent with `critical: true`. */\n count_critical_errors: number;\n /**\n * Every fact on the application, checked or not. The other counters are\n * subsets of it and can overlap each other, so no subtraction from\n * `count_total` yields a pass count.\n */\n count_total: number;\n /**\n * Facts whose question was never asked. Excludes the still-pending ones, but\n * overlaps `count_errors`: a fact never asked that came back wrong is in both.\n */\n count_not_asked: number;\n /** The facts in `count_not_asked` that you sent with `critical: true`. */\n count_critical_not_asked: number;\n /**\n * Facts added but not resolved yet. During a live call most facts sit here\n * and move into the other counters as their results arrive.\n */\n count_pending: number;\n /**\n * Facts flagged as suspicious when the call is reviewed — for instance the\n * agent leading the customer to the expected answer. Independent of the\n * answer: a matched fact can be flagged. Reads 0 while the call is running.\n */\n count_suspicious: number;\n};\n\nexport type Application = {\n application_id: string;\n client_name: string;\n client_phone_number: string;\n agent_id: string;\n /** Comes back empty. Set an agent name with `updateConversation()`. */\n agent_first_name: string;\n /** Comes back empty. Set an agent name with `updateConversation()`. */\n agent_last_name: string;\n /**\n * The status you last reported with `updateConversation({ externalStatus })`,\n * folded to lowercase by the server. Missing when you never reported one —\n * which is not the same as `\"draft\"`. Unlike the fields above it is never in\n * the authentication snapshot, so on the fallback path described under\n * `verification` it is absent rather than stale.\n *\n * Same open union as the input side: the members autocomplete, and a status\n * the server learns before this package does still type-checks.\n */\n external_status?: ExternalStatus | (string & {});\n /**\n * How the call is going so far. When it is missing there is no summary —\n * which is not the same as all zeros — and the fields above may then be the\n * ones from authentication, without an `updateConversation()` you made since.\n */\n verification?: ApplicationVerificationSummary;\n};\n\nexport enum Methods {\n AUTHENTICATE = \"AUTHENTICATE\",\n GET_FACTS = \"GET_FACTS\",\n GET_APPLICATION = \"GET_APPLICATION\",\n START_RECORDING = \"START_RECORDING\",\n STOP_RECORDING = \"STOP_RECORDING\",\n IS_RECORDING = \"IS_RECORDING\",\n ADD_FACT = \"ADD_FACT\",\n FLAG_FACT = \"FLAG_FACT\",\n SET_CONVERSATION_PRODUCT = \"SET_CONVERSATION_PRODUCT\",\n SET_CONVERSATION_LANGUAGE = \"SET_CONVERSATION_LANGUAGE\",\n UPDATE_CONVERSATION = \"UPDATE_CONVERSATION\",\n}\n\nexport type SetConversationProductResult = {\n success: boolean;\n product: string;\n};\n\nexport type SetConversationLanguageResult = {\n success: boolean;\n language: string;\n};\n\n/** User-provided application status. */\nexport enum ExternalStatus {\n DRAFT = \"draft\",\n PENDING = \"pending\",\n COMPLETED = \"completed\",\n EXPIRED = \"expired\",\n CLOSED = \"closed\",\n}\n\nexport type UpdateConversationInput = {\n policyNumber?: string;\n insuredPhone?: string;\n clientName?: string;\n clientPhone?: string;\n clientEmail?: string;\n clientId?: string;\n agentId?: string;\n agentName?: string;\n advisorId?: string;\n advisorName?: string;\n agentGroups?: string[];\n externalStatus?: ExternalStatus | (string & {});\n};\n\n/** Only the fields you sent come back in `conversation`. */\nexport type UpdateConversationResult = {\n success: boolean;\n conversation: {\n policy_number?: string;\n insured_phone?: string;\n client_name?: string;\n client_phone?: string;\n client_email?: string;\n client_id?: string;\n agent_id?: string;\n agent_name?: string;\n advisor_id?: string;\n advisor_name?: string;\n agent_groups?: string[];\n external_status?: string;\n };\n};\n\nexport enum ConversationLanguage {\n EN = \"en\",\n ES = \"es\",\n FR = \"fr\",\n}\n\nexport type SdkEvent =\n | Methods\n | \"connect\"\n | \"disconnect\"\n | \"close\"\n | \"error\"\n | \"reconnect_attempt\"\n | \"reconnect_error\"\n | \"reconnect_failed\"\n | \"authenticated\"\n | \"app_version\"\n // Every verification state change, for every fact. Payload:\n // `FactVerifiedPayload`.\n | \"FACT_VERIFIED\"\n // Every utterance, as it is transcribed. Payload: `TranscriptionUpdate`.\n | \"TRANSCRIPTION_UPDATED\";\n\nexport enum FactAnswerFormatType {\n string = \"STRING\",\n number = \"NUMBER\",\n integer = \"INT\",\n float = \"FLOAT\",\n bool = \"BOOL\",\n list = \"LIST\",\n strict = \"STRICT\",\n single_choice = \"SINGLE_CHOICE\",\n multiple_choices = \"MULTIPLE_CHOICES\",\n}\n\nexport type ApplicationFactAnswerChoice = {\n key: string;\n text: string;\n};\n\nexport type ApplicationFactAnswerFormat = {\n type: FactAnswerFormatType;\n choices?: ApplicationFactAnswerChoice[];\n};\n\nexport type ApplicationFactInput = {\n id: string;\n /**\n * Stable identifier for the underlying question, shared across applications\n * and conversations. When provided it identifies the question instead of\n * `id`. Keep it consistent across calls: whatever AIQA has tuned for a\n * question is attached to this identity.\n */\n questionId?: string;\n question: string;\n expected_answer: any;\n answer_format: ApplicationFactAnswerFormat;\n\n category_id?: string;\n category_name?: string;\n language?: string;\n\n /**\n * Mark the question critical: its failures land in `count_critical_errors`,\n * and one of them sets the call's `status` to `critical_errors`.\n */\n critical?: boolean;\n is_skipped?: boolean;\n /** Optional (default: `false`). Use `true` when the fact was collected before the conversation started. It is stored, not verified. */\n prefilled?: boolean;\n /**\n * Your own identifiers for this fact — a form field ID, a section name,\n * anything that lets your UI map the result back to the right place.\n * `getFacts()` returns it unchanged — `{}` for a fact you added without\n * one — and it plays no part in verification.\n *\n * Keys and values must all be strings, and each value is limited to 1024\n * characters. A payload that breaks either rule is rejected.\n */\n metadata?: Record<string, string>;\n};\n\nexport type QuestionStatus = \"searching\" | \"asked\" | \"not_asked\";\n\n/**\n * Per-fact verification state. Handle any value you don't recognize as\n * `processing`.\n *\n * - `processing` queued, or nothing to go on yet\n * - `awaiting_question` the agent hasn't asked the question yet\n * - `awaiting_answer` asked, the customer hasn't answered yet\n * - `partial` partial evidence so far (e.g. \"305\" of \"30521\")\n * - `pending_confirmation_matched` a matching answer is held briefly in case\n * the customer corrects it mid-answer\n * (spellings, \"I mean…\"); resolves to\n * `matched`/`unmatched`\n * - `pending_confirmation_unmatched` same, with an unmatched answer held; show\n * \"we heard X but it doesn't match, waiting\n * to confirm\" rather than a hard result\n * - `matched` final: the answer matched\n * - `unmatched` final: the answer did not match\n */\nexport type VerificationStatus =\n | \"processing\"\n | \"awaiting_question\"\n | \"awaiting_answer\"\n | \"partial\"\n | \"pending_confirmation_matched\"\n | \"pending_confirmation_unmatched\"\n | \"matched\"\n | \"unmatched\";\n\nexport type ApplicationFact = ApplicationFactInput & {\n ai_answer?: any;\n question_status: QuestionStatus;\n verification_status: VerificationStatus;\n /** True once `flagFact(factId)` has been called for this fact. */\n flagged: boolean;\n};\n\nexport interface AddFactResult {\n /** Conversation the fact was attached to. */\n conversation_id?: string;\n /** Echo of the original question text from the fact input. */\n question?: string;\n /** Echo of the resolved `answer_format.type` (e.g. \"STRING\", \"NUMBER\", \"SINGLE_CHOICE\"). */\n answer_type?: string;\n agent_answer?: string;\n ai_answer?: string;\n /** `false` for a fact that was never verified, such as a prefilled one. */\n is_valid_answer: boolean;\n question_asked?: boolean;\n /**\n * How closely the agent's utterance matched the expected question, on a 0–1\n * or a 0–100 scale. Higher is closer.\n */\n question_match_score?: number;\n /**\n * 0–1 score for how closely the customer's answer matched the expected one.\n * Undefined when there is no partial signal to score.\n */\n answer_match_score?: number;\n metadata?: Record<string, string>;\n /**\n * The final state: `matched` or `unmatched` whenever it is present. Fall\n * back to `is_valid_answer` when it is missing.\n */\n verification_status?: VerificationStatus;\n /**\n * Component labels describing which parts of the expected answer\n * matched. Currently `[\"prefix\"]` / `[\"suffix\"]` for numeric facts;\n * treat the set as open-ended.\n */\n matched_components?: string[];\n missing_components?: string[];\n}\n\n/**\n * Payload of the `FACT_VERIFIED` event, which fires on every state change —\n * see `VerificationStatus`. Use it to show progress; `addFact()` resolves\n * only once a fact is done.\n */\nexport interface FactVerifiedPayload {\n factId: string;\n success: boolean;\n verification_status?: VerificationStatus;\n question_match_score?: number;\n answer_match_score?: number;\n matched_components?: string[];\n missing_components?: string[];\n /** Inner payload, shaped like `AddFactResult`. */\n data?: AddFactResult;\n error?: string;\n}\n\nexport type FlagFactResult = {\n success: boolean;\n};\n\n/**\n * What the utterance appears to be doing in the conversation. A best-effort\n * guess: display it if it helps, but do not gate behaviour on it. Its\n * confidence band is `dialog_act_confidence`.\n */\nexport type DialogAct =\n | \"question\"\n | \"answer\"\n | \"acknowledgement\"\n | \"filler\"\n | \"other\";\n\n/**\n * Confidence band for `dialog_act` only. Unrelated to the numeric\n * `confidence` field on the same utterance — do not compare the two.\n */\nexport type DialogActConfidence = \"high\" | \"medium\" | \"low\";\n\n/**\n * An utterance from the `TRANSCRIPTION_UPDATED` event.\n *\n * A missing optional field means \"unknown\", not \"no\".\n */\nexport type Utterance = {\n /** Sort utterances by this: ids sort in chronological order. */\n id: string;\n call_id: number;\n /** Always 0. Sort by `id`, not this. */\n order: number;\n is_agent: boolean | null;\n speaker: number;\n text: string;\n text_en: string | null;\n start_time: number;\n end_time: number;\n dialog_act?: DialogAct;\n dialog_act_confidence?: DialogActConfidence;\n confidence?: number | null;\n top_alt_margin?: number | null;\n is_ivr_filler_candidate?: boolean;\n spoken_digits_normalized?: string | null;\n vendor?: string | null;\n};\n\n/** Payload of the `TRANSCRIPTION_UPDATED` broadcast event. */\nexport type TranscriptionUpdate = {\n policyNumber: string;\n conversationId: string;\n utterance: Utterance;\n};\n\nexport type SdkError = {\n code:\n | \"INVALID_CONFIG\"\n | \"CONNECTION_ERROR\"\n | \"TIMEOUT\"\n | \"SERVER_ERROR\"\n | \"UNEXPECTED_RESPONSE\";\n message: string;\n details?: any;\n};\n\nexport abstract class IAiqaSdk {\n abstract connect(): void;\n abstract disconnect(): void;\n\n abstract on(eventName: string, callback: (...args: any[]) => any): void;\n abstract off(eventName: string, callback?: (...args: any[]) => any): void;\n\n abstract getApplication(): Promise<Application>;\n abstract addFact(fact: ApplicationFactInput): Promise<AddFactResult>;\n abstract flagFact(factId: string): Promise<FlagFactResult>;\n abstract getFacts(): Promise<ApplicationFact[]>;\n abstract setConversationProduct(\n product: string,\n ): Promise<SetConversationProductResult>;\n abstract setConversationLanguage(\n language: ConversationLanguage,\n ): Promise<SetConversationLanguageResult>;\n abstract updateConversation(\n input: UpdateConversationInput,\n ): Promise<UpdateConversationResult>;\n}\n","const splitVersion = (value: string) => {\n const [core] = value.split(\"-\", 2);\n return core.split(\".\").map((part) => Number(part));\n};\n\nexport const compareVersions = (left: string, right: string): number => {\n const leftParts = splitVersion(left);\n const rightParts = splitVersion(right);\n const maxLength = Math.max(leftParts.length, rightParts.length);\n\n for (let i = 0; i < maxLength; i += 1) {\n const l = leftParts[i] ?? 0;\n const r = rightParts[i] ?? 0;\n if (l > r) {\n return 1;\n }\n if (l < r) {\n return -1;\n }\n }\n\n return 0;\n};\n","{\n \"name\": \"@aiqa/sdk\",\n \"version\": \"2.2.0-develop.2\",\n \"main\": \"dist/node/node.js\",\n \"module\": \"dist/node/node.js\",\n \"types\": \"dist/node/node.d.ts\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup && node -e \\\"const fs=require('fs');['dist/node/node','dist/browser/browser'].forEach(f=>{const mts=f+'.d.mts';const ts=f+'.d.ts';if(fs.existsSync(mts)){fs.renameSync(mts,ts);}});\\\"\",\n \"commitlint\": \"commitlint\",\n \"dev:node\": \"tsx src/node.ts\",\n \"lint\": \"tsc --noEmit -p tsconfig.json\",\n \"format\": \"prettier --check \\\"{src,tests}/**/*.{ts,tsx,js,json,md,yml,yaml}\\\" \\\"*.{js,json,md,yml,yaml,ts}\\\" --ignore-path .prettierignore\",\n \"release\": \"semantic-release\",\n \"start:node\": \"node dist/node/node.js\",\n \"serve:browser\": \"serve .\",\n \"test\": \"jest\",\n \"prepare\": \"husky\",\n \"lint-staged\": \"lint-staged\"\n },\n \"lint-staged\": {\n \"*.{ts,tsx,js,json,md,yml,yaml}\": [\n \"prettier --write\"\n ]\n },\n \"exports\": {\n \".\": {\n \"node\": {\n \"import\": \"./dist/node/node.js\",\n \"types\": \"./dist/node/node.d.ts\"\n },\n \"browser\": {\n \"import\": \"./dist/browser/browser.js\",\n \"types\": \"./dist/browser/browser.d.ts\"\n },\n \"default\": \"./dist/node/node.js\"\n }\n },\n \"private\": false,\n \"license\": \"MIT\",\n \"author\": \"AIQA\",\n \"description\": \"TypeScript/JavaScript SDK for interacting with the AIQA.\",\n \"keywords\": [\n \"aiqa\",\n \"sdk\"\n ],\n \"files\": [\n \"dist\"\n ],\n \"devDependencies\": {\n \"@commitlint/cli\": \"^20.4.4\",\n \"@commitlint/config-conventional\": \"^20.4.4\",\n \"@jest/globals\": \"^29.7.0\",\n \"@semantic-release/commit-analyzer\": \"^13.0.1\",\n \"@semantic-release/git\": \"^10.0.1\",\n \"@semantic-release/npm\": \"^12.0.2\",\n \"@semantic-release/release-notes-generator\": \"^14.1.0\",\n \"@types/node\": \"^22.0.0\",\n \"conventional-changelog-conventionalcommits\": \"^9.3.0\",\n \"esbuild\": \"^0.23.0\",\n \"husky\": \"^9.1.7\",\n \"jest\": \"^29.7.0\",\n \"lint-staged\": \"^16.4.0\",\n \"prettier\": \"^3.8.1\",\n \"semantic-release\": \"^24.2.9\",\n \"serve\": \"^14.2.3\",\n \"socket.io\": \"^4.7.5\",\n \"ts-jest\": \"^29.2.3\",\n \"ts-node\": \"^10.9.2\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.7.0\"\n },\n \"dependencies\": {\n \"socket.io-client\": \"^4.7.5\"\n }\n}\n"],"mappings":";AAAA,SAAS,UAAkB;;;ACgFpB,IAAK,UAAL,kBAAKA,aAAL;AACL,EAAAA,SAAA,kBAAe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