@webority/chat-core 0.141.0 → 0.142.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.
Files changed (42) hide show
  1. package/dist/audioType.js +1 -1
  2. package/dist/client.js +3 -3
  3. package/dist/conversationList.js +1 -1
  4. package/dist/decode/enums.js +1 -0
  5. package/dist/decode/events.js +1 -0
  6. package/dist/decode/fixture.js +1 -0
  7. package/dist/decode/messages.js +1 -0
  8. package/dist/decode/parts.js +1 -0
  9. package/dist/decode/primitives.js +1 -0
  10. package/dist/decode/profile.js +1 -0
  11. package/dist/decode/replies.js +1 -0
  12. package/dist/dictation.js +1 -1
  13. package/dist/explain.js +1 -1
  14. package/dist/figures.js +1 -1
  15. package/dist/fixtureClient.js +1 -1
  16. package/dist/guards.js +1 -0
  17. package/dist/handoff.js +1 -1
  18. package/dist/idleSession.js +1 -0
  19. package/dist/index.js +1 -1
  20. package/dist/live.js +1 -1
  21. package/dist/profile.js +1 -1
  22. package/dist/runtime.js +1 -0
  23. package/dist/session.js +2 -2
  24. package/dist/stream.js +3 -3
  25. package/dist/transcript.js +1 -1
  26. package/dist/types/contract.d.ts +5 -1
  27. package/dist/types/decode/enums.d.ts +19 -0
  28. package/dist/types/decode/events.d.ts +3 -0
  29. package/dist/types/decode/fixture.d.ts +3 -0
  30. package/dist/types/decode/index.d.ts +6 -0
  31. package/dist/types/decode/messages.d.ts +10 -0
  32. package/dist/types/decode/parts.d.ts +15 -0
  33. package/dist/types/decode/primitives.d.ts +35 -0
  34. package/dist/types/decode/profile.d.ts +21 -0
  35. package/dist/types/decode/replies.d.ts +7 -0
  36. package/dist/types/figures.d.ts +1 -1
  37. package/dist/types/guards.d.ts +3 -0
  38. package/dist/types/idleSession.d.ts +3 -0
  39. package/dist/types/index.d.ts +2 -0
  40. package/dist/types/profile.d.ts +2 -0
  41. package/dist/types/runtime.d.ts +35 -0
  42. package/package.json +5 -5
package/dist/audioType.js CHANGED
@@ -1 +1 @@
1
- function e(e){let t=new Uint8Array(e),n=(e,n)=>String.fromCharCode(...t.slice(e,n));return n(0,4)===`OggS`?`audio/ogg`:t[0]===26&&t[1]===69&&t[2]===223&&t[3]===163?`audio/webm`:n(4,8)===`ftyp`?`audio/mp4`:n(0,4)===`RIFF`?`audio/wav`:n(0,3)===`ID3`||t[0]===255&&(t[1]&224)==224?`audio/mpeg`:`application/octet-stream`}export{e as sniffAudioType};
1
+ function e(e){let t=new Uint8Array(e),n=(e,n)=>String.fromCharCode(...t.slice(e,n));return n(0,4)===`OggS`?`audio/ogg`:t[0]===26&&t[1]===69&&t[2]===223&&t[3]===163?`audio/webm`:n(4,8)===`ftyp`?`audio/mp4`:n(0,4)===`RIFF`?`audio/wav`:n(0,3)===`ID3`||t[0]===255&&((t[1]??0)&224)==224?`audio/mpeg`:`application/octet-stream`}export{e as sniffAudioType};
package/dist/client.js CHANGED
@@ -1,3 +1,3 @@
1
- import"./contract.js";import{DEFAULT_CHAT_LABELS as e}from"./labels.js";import{createStreamReader as t}from"./stream.js";var n=class extends Error{code;status;resetsDateTimeUtc;errors;constructor(e,t,n,r=null,i=null){super(t),this.name=`ChatApiError`,this.code=e,this.status=n,this.resetsDateTimeUtc=r,this.errors=i}},r=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch{return null}return e??null},i=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return null;let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&typeof r[0]==`string`&&(t[n]=r[0]);return Object.keys(t).length>0?t:null},a=(e,t)=>!!t?.aborted||e?.code===`ERR_CANCELED`||e?.name===`CanceledError`||e?.name===`AbortError`,o=(t,o)=>{if(t instanceof n)return t;let s=t;if(a(s,o))return new n(`aborted`,`The request was cancelled.`);let c=s?.response;if(!c)return new n(`network`,e.errorGeneric);let l=r(c.data),u=typeof l?.code==`string`&&l.code?l.code:`unknown`,d=typeof l?.detail==`string`&&l.detail?l.detail:e.errorGeneric,f=typeof l?.resetsDateTimeUtc==`string`?l.resetsDateTimeUtc:null;return new n(u,d,typeof c.status==`number`?c.status:void 0,f,i(l?.errors))},s=async e=>{try{return(await e()).data}catch(e){throw o(e)}},c=e=>{let t=e?.event?.target;if(t&&typeof t.responseText==`string`&&!(typeof t.status==`number`&&(t.status<200||t.status>=300)))return t.responseText},l=()=>{let e=globalThis.FormData;if(!e)throw Error(`FormData is not available.`);return new e},u=e=>typeof e.uri==`string`,d=(e,t)=>{if(u(t)){e.append(`file`,t);return}let n=t.name;if(typeof n!=`string`||n===``)throw Error(`The file needs a name.`);e.append(`file`,t,n)},f=()=>{let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`},p=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t},m=globalThis,h=e=>{let t=``,n=null;return r=>{let i=(t+r).split(`
2
- `);t=i.pop()??``;for(let t of i){let r=t.endsWith(`\r`)?t.slice(0,-1):t;if(!r.startsWith(`id:`))continue;let i=r.slice(3).replace(/^ /,``);if(!/^\d+$/.test(i))continue;let a=Number(i);(n===null||a>n)&&(n=a,e?.(a))}}},g=(r,{base:i})=>{if(typeof i!=`string`||i.trim()===``)throw TypeError(`createChatClient needs a base path, e.g. { base: "/api/assistant" }.`);let a=i.replace(/\/+$/,``),u={"Chat-Contract":`4`},g=e=>`${a}/conversations/${encodeURIComponent(e)}`,_=e=>`${a}/attachments/${encodeURIComponent(e)}`,v=e=>`${a}/actions/${encodeURIComponent(e)}`,y=/* @__PURE__ */ new Map,b=async t=>{let i=t===void 0?``:`?screen=${encodeURIComponent(t)}`;try{let t=await s(()=>r.get(`${a}/profile${i}`,{headers:u}));if(typeof t?.contractVersion!=`number`||t.contractVersion<4)throw new n(`assistant_outdated`,e.assistantOutdated);return t}catch(t){throw t instanceof n&&t.status===404?new n(`assistant_outdated`,e.assistantOutdated,404):t}},x=e=>{let t=e??``,n=y.get(t);return n||(n=b(e).catch(e=>{throw y.delete(t),e}),y.set(t,n)),n},S=async(i,a,s)=>{let l=t(s.onEvent),u=0,d=e=>{typeof e!=`string`||e.length<=u||(l.push(e.slice(u)),u=e.length)},f;try{f=await r.post(i,a,{responseType:`text`,headers:s.headers,signal:s.signal,onDownloadProgress:e=>d(c(e))})}catch(e){throw o(e,s.signal)}d(f.data),l.end();let p=l.failure;if(p)throw new n(p.code||`unknown`,p.message||e.errorGeneric);let m=l.last;if(!m)throw new n(`invalid-response`,e.errorGeneric,f.status);return m};return{getProfile:x,send:(e,t={})=>{let n=p({conversationId:e.conversationId,text:e.text,quickReplyId:e.quickReplyId,attachmentIds:e.attachmentIds&&e.attachmentIds.length>0?e.attachmentIds:void 0,replacesMessageId:e.replacesMessageId,pageContext:e.pageContext,captchaToken:e.captchaToken});return S(`${a}/messages`,n,{signal:t.signal,onEvent:t.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},answerInput:(e,t,n={})=>{let r=p({values:t.values,captchaToken:t.captchaToken,codes:t.codes,attribution:t.attribution});return S(`${a}/inputs/${encodeURIComponent(e)}`,r,{signal:n.signal,onEvent:n.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},confirmAction:e=>s(()=>r.post(`${v(e)}/confirm`,{},{headers:u})),rejectAction:(e,t)=>s(()=>r.post(`${v(e)}/reject`,t===void 0?{}:{reason:t},{headers:u})),listConversations:(e={})=>{let t=[];e.page!==void 0&&t.push(`page=${encodeURIComponent(String(e.page))}`),e.pageSize!==void 0&&t.push(`pageSize=${encodeURIComponent(String(e.pageSize))}`);let n=t.join(`&`),i=n?`${a}/conversations?${n}`:`${a}/conversations`;return s(()=>r.get(i,{headers:u}))},getConversation:(e,t)=>{let n=t===void 0?g(e):`${g(e)}?afterSequence=${t}`;return s(()=>r.get(n,{headers:u}))},renameConversation:async(e,t)=>{await s(()=>r.put(`${g(e)}/title`,{title:t},{headers:u}))},deleteConversation:async e=>{await s(()=>r.delete(g(e),{headers:u}))},rateMessage:async(e,t)=>{let n=typeof t.note==`string`?t.note.trim():``;await s(()=>r.put(`${a}/messages/${encodeURIComponent(e)}/rating`,{rating:t.rating,note:n||null},{headers:u}))},uploadAttachment:(e,t={})=>{let n=l();return d(n,e),s(()=>r.post(`${a}/attachments`,n,{headers:{...u,"Content-Type":`multipart/form-data`},timeout:3e5,signal:t.signal,onUploadProgress:({loaded:e,total:n})=>{t.onProgress&&n&&t.onProgress((e??0)/n)}}))},deleteAttachment:async e=>{await s(()=>r.delete(_(e),{headers:u}))},getAttachment:e=>s(()=>r.get(_(e),{headers:u,responseType:`arraybuffer`})),sendOtp:async(e,t)=>{await s(()=>r.post(`${a}/inputs/${encodeURIComponent(e)}/otp`,t,{headers:u}))},requestHandoff:(e,t={})=>{let n=typeof e.reason==`string`&&e.reason.trim()!==``?e.reason:void 0;return S(`${a}/handoff`,p({conversationId:e.conversationId,reason:n}),{signal:t.signal,onEvent:t.onEvent,headers:{...u,Accept:`text/event-stream`,"Idempotency-Key":f()}})},watchConversation:async(i,a)=>{let s=new m.AbortController,l=()=>s.abort();a.signal?.aborted&&s.abort(),a.signal?.addEventListener(`abort`,l);let d=!1,f=null,p=()=>{f!==null&&m.clearTimeout(f),f=m.setTimeout(()=>{d=!0,s.abort()},a.stallTimeoutMs??9e4)},_=h(a.onCursor),v=t(a.onEvent),y=0,b=e=>{if(typeof e!=`string`||e.length<=y)return;let t=e.slice(y);y=e.length,_(t),v.push(t)},x={...u,Accept:`text/event-stream`};typeof a.afterSequence==`number`&&Number.isFinite(a.afterSequence)&&(x[`Last-Event-ID`]=String(a.afterSequence)),p();try{b((await r.get(`${g(i)}/events`,{headers:x,responseType:`text`,timeout:0,signal:s.signal,onDownloadProgress:e=>{let t=c(e);t!==void 0&&(p(),b(t))}})).data),_(`
3
- `),v.end();let t=v.failure;if(t)throw new n(t.code||`unknown`,t.message||e.errorGeneric)}catch(t){if(a.signal?.aborted)return;throw d?new n(`stalled`,e.errorGeneric):o(t,s.signal)}finally{f!==null&&m.clearTimeout(f),a.signal?.removeEventListener(`abort`,l)}},sendTyping:async e=>{await s(()=>r.post(`${g(e)}/typing`,void 0,{headers:u}))},listOpenTickets:async()=>{let t=await s(()=>r.get(`${a}/tickets/open`,{headers:u}));if(!Array.isArray(t))throw new n(`invalid-response`,e.errorGeneric);return t},getSpeechToken:()=>s(()=>r.post(`${a}/speech/token`,void 0,{headers:u}))}};export{n as ChatApiError,g as createChatClient,f as newIdempotencyKey};
1
+ import"./contract.js";import{decodeChatConversationSummaryPage as e,decodeChatConversationView as t}from"./decode/messages.js";import{ChatDecodeError as n,array as r,arrayBuffer as i}from"./decode/primitives.js";import{decodeChatProfileView as a}from"./decode/profile.js";import{decodeChatActionView as o,decodeChatAttachment as s,decodeChatOpenTicket as c,decodeChatSpeechToken as l}from"./decode/replies.js";import{asRecord as u,isRecord as d}from"./guards.js";import{DEFAULT_CHAT_LABELS as f}from"./labels.js";import{runtime as p}from"./runtime.js";import{createStreamReader as m}from"./stream.js";var h=class extends Error{code;status;resetsDateTimeUtc;errors;constructor(e,t,n,r=null,i=null){super(t),this.name=`ChatApiError`,this.code=e,this.status=n,this.resetsDateTimeUtc=r,this.errors=i}},g=e=>{if(!d(e))return null;let t={errors:e.errors};return typeof e.code==`string`&&(t.code=e.code),typeof e.detail==`string`&&(t.detail=e.detail),typeof e.resetsDateTimeUtc==`string`&&(t.resetsDateTimeUtc=e.resetsDateTimeUtc),t},_=e=>{if(typeof e==`string`)try{return g(JSON.parse(e))}catch{return null}return g(e)},v=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return null;let t={};for(let[n,r]of Object.entries(u(e)))Array.isArray(r)&&typeof r[0]==`string`&&(t[n]=r[0]);return Object.keys(t).length>0?t:null},y=(e,t)=>{let n=u(e);return!!t?.aborted||n.code===`ERR_CANCELED`||n.name===`CanceledError`||n.name===`AbortError`},b=(e,t)=>{if(e instanceof h)return e;if(y(e,t))return new h(`aborted`,`The request was cancelled.`);let n=u(e).response;if(!n)return new h(`network`,f.errorGeneric);let r=u(n),i=_(r.data),a=typeof i?.code==`string`&&i.code?i.code:`unknown`,o=typeof i?.detail==`string`&&i.detail?i.detail:f.errorGeneric,s=typeof i?.resetsDateTimeUtc==`string`?i.resetsDateTimeUtc:null;return new h(a,o,typeof r.status==`number`?r.status:void 0,s,v(i?.errors))},x=e=>{try{return e()}catch(e){throw e instanceof n?new h(`invalid-response`,f.errorGeneric):e}},S=async(e,t)=>{let n;try{n=(await e()).data}catch(e){throw b(e)}return x(()=>t(n,`response`))},C=()=>void 0,w=e=>{let t=u(u(e).event).target;if(d(t)&&typeof t.responseText==`string`&&!(typeof t.status==`number`&&(t.status<200||t.status>=300)))return t.responseText},T=()=>{let e=p.createFormData;if(!e)throw Error(`FormData is not available.`);return e()},E=e=>typeof u(e).uri==`string`,D=(e,t)=>{if(E(t)){e.append(`file`,t);return}let n=u(t).name;if(typeof n!=`string`||n===``)throw Error(`The file needs a name.`);e.append(`file`,t,n)},O=()=>{let e=p.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`},k=e=>{let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t},A=e=>{let t=``,n=null;return r=>{let i=(t+r).split(`
2
+ `);t=i.pop()??``;for(let t of i){let r=t.endsWith(`\r`)?t.slice(0,-1):t;if(!r.startsWith(`id:`))continue;let i=r.slice(3).replace(/^ /,``);if(!/^\d+$/.test(i))continue;let a=Number(i);(n===null||a>n)&&(n=a,e?.(a))}}},j=(n,{base:u})=>{if(typeof u!=`string`||u.trim()===``)throw TypeError(`createChatClient needs a base path, e.g. { base: "/api/assistant" }.`);let d=u.replace(/\/+$/,``),g={"Chat-Contract":`4`},_=e=>`${d}/conversations/${encodeURIComponent(e)}`,v=e=>`${d}/attachments/${encodeURIComponent(e)}`,y=e=>`${d}/actions/${encodeURIComponent(e)}`,x=/* @__PURE__ */ new Map,E=async e=>{let t=e===void 0?``:`?screen=${encodeURIComponent(e)}`;try{let e=await S(()=>n.get(`${d}/profile${t}`,{headers:g}),a);if(typeof e?.contractVersion!=`number`||e.contractVersion<4)throw new h(`assistant_outdated`,f.assistantOutdated);return e}catch(e){throw e instanceof h&&e.status===404?new h(`assistant_outdated`,f.assistantOutdated,404):e}},j=e=>{let t=e??``,n=x.get(t);return n||(n=E(e).catch(e=>{throw x.delete(t),e}),x.set(t,n)),n},M=async(e,t,r)=>{let i=m(r.onEvent),a=0,o=e=>{typeof e!=`string`||e.length<=a||(i.push(e.slice(a)),a=e.length)},s;try{s=await n.post(e,t,{responseType:`text`,headers:r.headers,...r.signal===void 0?{}:{signal:r.signal},onDownloadProgress:e=>o(w(e))})}catch(e){throw b(e,r.signal)}o(s.data),i.end();let c=i.failure;if(c)throw new h(c.code||`unknown`,c.message||f.errorGeneric);let l=i.last;if(!l)throw new h(`invalid-response`,f.errorGeneric,s.status);return l};return{getProfile:j,send:(e,t={})=>{let n=k({conversationId:e.conversationId,text:e.text,quickReplyId:e.quickReplyId,attachmentIds:e.attachmentIds&&e.attachmentIds.length>0?e.attachmentIds:void 0,replacesMessageId:e.replacesMessageId,pageContext:e.pageContext,captchaToken:e.captchaToken});return M(`${d}/messages`,n,{signal:t.signal,onEvent:t.onEvent,headers:{...g,Accept:`text/event-stream`,"Idempotency-Key":O()}})},answerInput:(e,t,n={})=>{let r=k({values:t.values,captchaToken:t.captchaToken,codes:t.codes,attribution:t.attribution});return M(`${d}/inputs/${encodeURIComponent(e)}`,r,{signal:n.signal,onEvent:n.onEvent,headers:{...g,Accept:`text/event-stream`,"Idempotency-Key":O()}})},confirmAction:e=>S(()=>n.post(`${y(e)}/confirm`,{},{headers:g}),o),rejectAction:(e,t)=>S(()=>n.post(`${y(e)}/reject`,t===void 0?{}:{reason:t},{headers:g}),o),listConversations:(t={})=>{let r=[];t.page!==void 0&&r.push(`page=${encodeURIComponent(String(t.page))}`),t.pageSize!==void 0&&r.push(`pageSize=${encodeURIComponent(String(t.pageSize))}`);let i=r.join(`&`),a=i?`${d}/conversations?${i}`:`${d}/conversations`;return S(()=>n.get(a,{headers:g}),e)},getConversation:(e,r)=>{let i=r===void 0?_(e):`${_(e)}?afterSequence=${r}`;return S(()=>n.get(i,{headers:g}),t)},renameConversation:async(e,t)=>{await S(()=>n.put(`${_(e)}/title`,{title:t},{headers:g}),C)},deleteConversation:async e=>{await S(()=>n.delete(_(e),{headers:g}),C)},rateMessage:async(e,t)=>{let r=typeof t.note==`string`?t.note.trim():``;await S(()=>n.put(`${d}/messages/${encodeURIComponent(e)}/rating`,{rating:t.rating,note:r||null},{headers:g}),C)},uploadAttachment:(e,t={})=>{let r=T();return D(r,e),S(()=>n.post(`${d}/attachments`,r.native,{headers:{...g,"Content-Type":`multipart/form-data`},timeout:3e5,...t.signal===void 0?{}:{signal:t.signal},onUploadProgress:({loaded:e,total:n})=>{t.onProgress&&n&&t.onProgress((e??0)/n)}}),s)},deleteAttachment:async e=>{await S(()=>n.delete(v(e),{headers:g}),C)},getAttachment:e=>S(()=>n.get(v(e),{headers:g,responseType:`arraybuffer`}),i),sendOtp:async(e,t)=>{await S(()=>n.post(`${d}/inputs/${encodeURIComponent(e)}/otp`,t,{headers:g}),C)},requestHandoff:(e,t={})=>{let n=typeof e.reason==`string`&&e.reason.trim()!==``?e.reason:void 0;return M(`${d}/handoff`,k({conversationId:e.conversationId,reason:n}),{signal:t.signal,onEvent:t.onEvent,headers:{...g,Accept:`text/event-stream`,"Idempotency-Key":O()}})},watchConversation:async(e,t)=>{let r=new p.AbortController,i=()=>r.abort();t.signal?.aborted&&r.abort(),t.signal?.addEventListener(`abort`,i);let a=!1,o=null,s=()=>{o!==null&&p.clearTimeout(o),o=p.setTimeout(()=>{a=!0,r.abort()},t.stallTimeoutMs??9e4)},c=A(t.onCursor),l=m(t.onEvent),u=0,d=e=>{if(typeof e!=`string`||e.length<=u)return;let t=e.slice(u);u=e.length,c(t),l.push(t),l.failure&&r.abort()},v={...g,Accept:`text/event-stream`};typeof t.afterSequence==`number`&&Number.isFinite(t.afterSequence)&&(v[`Last-Event-ID`]=String(t.afterSequence)),s();try{d((await n.get(`${_(e)}/events`,{headers:v,responseType:`text`,timeout:0,signal:r.signal,onDownloadProgress:e=>{let t=w(e);t!==void 0&&(s(),d(t))}})).data),c(`
3
+ `),l.end();let t=l.failure;if(t)throw new h(t.code||`unknown`,t.message||f.errorGeneric)}catch(e){if(t.signal?.aborted)return;let n=l.failure;throw n?new h(n.code||`unknown`,n.message||f.errorGeneric):a?new h(`stalled`,f.errorGeneric):b(e,r.signal)}finally{o!==null&&p.clearTimeout(o),t.signal?.removeEventListener(`abort`,i)}},sendTyping:async e=>{await S(()=>n.post(`${_(e)}/typing`,void 0,{headers:g}),C)},listOpenTickets:()=>S(()=>n.get(`${d}/tickets/open`,{headers:g}),r(c)),getSpeechToken:()=>S(()=>n.post(`${d}/speech/token`,void 0,{headers:g}),l)}};export{h as ChatApiError,j as createChatClient,O as newIdempotencyKey};
@@ -1 +1 @@
1
- import{ChatApiError as e}from"./client.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=20,r=n=>n instanceof e?{code:n.code,message:n.message||t.loadFailed,resetsDateTimeUtc:n.resetsDateTimeUtc}:{code:`unknown`,message:t.loadFailed,resetsDateTimeUtc:null},i=e=>{let t=e.client,i=e.pageSize??n,a=/* @__PURE__ */ new Set,o={items:[],totalCount:null,loading:!1,error:null,hasMore:!1},s=0,c=!1,l=e=>{if(!c){o={...o,...e};for(let e of a)e()}};return{getState:()=>o,subscribe:e=>(a.add(e),()=>{a.delete(e)}),load:async()=>{s+=1;let e=s;l({loading:!0,error:null});try{let n=await t.listConversations({page:1,pageSize:i});if(c||e!==s)return;l({items:n.items,totalCount:n.totalCount,hasMore:n.page<n.totalPages,loading:!1})}catch(t){if(c||e!==s)return;l({loading:!1,error:r(t)})}},loadMore:async()=>{if(o.loading||!o.hasMore)return;let e=s,n=Math.floor(o.items.length/i)+1;l({loading:!0,error:null});try{let r=await t.listConversations({page:n,pageSize:i});if(c||e!==s)return;let a=new Set(o.items.map(e=>e.publicId)),u=r.items.filter(e=>!a.has(e.publicId));l({items:[...o.items,...u],totalCount:r.totalCount,hasMore:r.page<r.totalPages,loading:!1})}catch(t){if(c||e!==s)return;l({loading:!1,error:r(t)})}},rename:async(e,n)=>{let r=n.trim();if(await t.renameConversation(e,r),c)return;let i=r.replace(/\s+/g,` `);l({items:o.items.map(t=>t.publicId===e?{...t,title:i}:t)})},remove:async e=>{await t.deleteConversation(e),c||l({items:o.items.filter(t=>t.publicId!==e),totalCount:o.totalCount===null?null:o.totalCount-1})},dispose:()=>{c=!0,a.clear()}}};export{i as createConversationList};
1
+ import{ChatApiError as e}from"./client.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=20,r=n=>n instanceof e?{code:n.code,message:n.message||t.loadFailed,resetsDateTimeUtc:n.resetsDateTimeUtc}:{code:`unknown`,message:t.loadFailed,resetsDateTimeUtc:null},i=e=>{let t=e.client,i=e.pageSize??n,a=/* @__PURE__ */ new Set,o={items:[],totalCount:null,loading:!1,error:null,hasMore:!1},s=0,c=!1,l=e=>{if(!c){o={...o,...e};for(let e of a)e()}};return{getState:()=>o,subscribe:e=>(a.add(e),()=>{a.delete(e)}),load:async()=>{s+=1;let e=s;l({loading:!0,error:null});try{let n=await t.listConversations({page:1,pageSize:i});if(c||e!==s)return;l({items:n.items,totalCount:n.totalCount,hasMore:n.page<n.totalPages||n.totalCountCapped&&n.items.length===i,loading:!1})}catch(t){if(c||e!==s)return;l({loading:!1,error:r(t)})}},loadMore:async()=>{if(o.loading||!o.hasMore)return;let e=s,n=Math.floor(o.items.length/i)+1;l({loading:!0,error:null});try{let r=await t.listConversations({page:n,pageSize:i});if(c||e!==s)return;let a=new Set(o.items.map(e=>e.publicId)),u=r.items.filter(e=>!a.has(e.publicId));l({items:[...o.items,...u],totalCount:r.totalCount,hasMore:r.page<r.totalPages||r.totalCountCapped&&r.items.length===i,loading:!1})}catch(t){if(c||e!==s)return;l({loading:!1,error:r(t)})}},rename:async(e,n)=>{let r=n.trim();if(await t.renameConversation(e,r),c)return;let i=r.replace(/\s+/g,` `);l({items:o.items.map(t=>t.publicId===e?{...t,title:i}:t)})},remove:async e=>{await t.deleteConversation(e),c||l({items:o.items.filter(t=>t.publicId!==e),totalCount:o.totalCount===null?null:o.totalCount-1})},dispose:()=>{c=!0,a.clear()}}};export{i as createConversationList};
@@ -0,0 +1 @@
1
+ import{allMembers as e}from"./primitives.js";var t=e()([`Pending`,`Confirmed`,`Rejected`,`Expired`,`Done`,`Failed`,`Repeat`]),n=e()([`Visitor`,`Customer`,`Assistant`,`Agent`,`Script`,`System`]),r=e()([`Off`,`FirstMessage`,`EveryInput`]),i=e()([`Bar`,`Line`,`Donut`]),a=e()([`Text`,`Integer`,`Decimal`,`MoneyMinor`,`Percent`,`Date`,`DateTimeUtc`]),o=e()([`Open`,`WaitingForAgent`,`WithAgent`,`Closed`]),s=e()([`Email`,`Phone`,`Name`,`Company`,`Text`,`LongText`,`Choice`,`MultiChoice`,`TimeSlot`,`File`,`Consent`]),c=e()([`None`,`Otp`]),l=e()([`Neutral`,`Positive`,`Caution`,`Negative`]),u=e()([`Requested`,`Waiting`,`Joined`,`Left`,`Ended`]),d=e()([`Open`,`Answered`,`Skipped`,`Expired`]),f=e()([`NeedsNewerApp`,`ActionLimitReached`,`ConversationContinued`,`AssistantUnavailable`,`OutOfTopic`,`ConversationTooLong`,`LeadAlreadyCaptured`]),p=e()([`Text`,`Sources`,`QuickReplies`,`InputRequest`,`Action`,`Notice`,`Table`,`Chart`,`Figures`,`RecordCard`,`Image`,`File`,`Ticket`,`Handoff`,`VoiceClip`]),m=e()([`Send`,`Open`,`Navigate`]),h=e()([`Inline`,`Composer`]),g=e()([`Default`,`Primary`,`Cta`]),_=e()([`Up`,`Down`]),v=e()([`messageStarted`,`partStarted`,`partDelta`,`partCompleted`,`messageReset`,`step`,`messageCompleted`,`conversationUpdated`,`typing`,`error`]);export{t as ChatActionStateValues,n as ChatAuthorKindValues,r as ChatCaptchaModeValues,i as ChatChartTypeValues,a as ChatColumnTypeValues,o as ChatConversationStateValues,s as ChatFieldTypeValues,c as ChatFieldVerificationValues,l as ChatFigureStatusValues,u as ChatHandoffStateValues,d as ChatInputRequestStateValues,f as ChatNoticeCodeValues,p as ChatPartKindValues,m as ChatQuickReplyActionValues,h as ChatQuickReplyPlacementValues,g as ChatQuickReplyVariantValues,_ as ChatRatingValues,v as ChatStreamEventNameValues};
@@ -0,0 +1 @@
1
+ import{ChatStreamEventNameValues as e}from"./enums.js";import{decodeChatAuthorKind as t,decodeChatConversationState as n,decodeChatMessageView as r}from"./messages.js";import{decodeChatPart as i}from"./parts.js";import{ChatDecodeError as a,field as o,nullable as s,number as c,record as l,string as u}from"./primitives.js";var d=t=>e.some(e=>e===t),f=(f,p)=>{if(!d(f))throw new a(`event`,`one of ${e.join(`, `)}`);let m=`event.${f}`,h=l(p,m);switch(f){case`messageStarted`:return{name:`messageStarted`,data:{message:o(h,`message`,r,m)}};case`partStarted`:return{name:`partStarted`,data:{messageId:o(h,`messageId`,u,m),index:o(h,`index`,c,m),part:o(h,`part`,i,m)}};case`partDelta`:return{name:`partDelta`,data:{messageId:o(h,`messageId`,u,m),index:o(h,`index`,c,m),text:o(h,`text`,u,m)}};case`partCompleted`:return{name:`partCompleted`,data:{messageId:o(h,`messageId`,u,m),index:o(h,`index`,c,m),part:o(h,`part`,i,m)}};case`messageReset`:return{name:`messageReset`,data:{messageId:o(h,`messageId`,u,m)}};case`step`:return{name:`step`,data:{messageId:o(h,`messageId`,u,m),label:o(h,`label`,u,m)}};case`messageCompleted`:return{name:`messageCompleted`,data:{message:o(h,`message`,r,m),messagesLeftToday:o(h,`messagesLeftToday`,s(c),m)}};case`conversationUpdated`:return{name:`conversationUpdated`,data:{conversationId:o(h,`conversationId`,u,m),state:o(h,`state`,n,m),title:o(h,`title`,u,m),continuesConversationId:o(h,`continuesConversationId`,s(u),m)}};case`typing`:return{name:`typing`,data:{authorKind:o(h,`authorKind`,t,m),displayName:o(h,`displayName`,s(u),m)}};case`error`:return{name:`error`,data:{code:o(h,`code`,u,m),message:o(h,`message`,u,m)}}}};export{f as decodeChatStreamEvent};
@@ -0,0 +1 @@
1
+ import{ChatStreamEventNameValues as e}from"./enums.js";import{decodeChatConversationView as t}from"./messages.js";import{array as n,field as r,number as i,oneOf as a,record as o,string as s,unknownValue as c}from"./primitives.js";import{decodeChatProfileView as l}from"./profile.js";import{decodeChatOpenTicket as u,decodeChatSpeechToken as d}from"./replies.js";var f=(e,t,n,i)=>e[t]===void 0?void 0:r(e,t,n,i),p=(t,n)=>{let i=o(t,n);return{event:r(i,`event`,a(e),n),data:r(i,`data`,c,n)}},m=(e,t)=>{let i=o(e,t),a={};for(let e of Object.keys(i))a[e]=r(i,e,n(s),t);return a},h=(e,t)=>{let n=o(e,t),a=f(n,`errors`,m,t),c=f(n,`resetsDateTimeUtc`,s,t);return{status:r(n,`status`,i,t),code:r(n,`code`,s,t),message:r(n,`message`,s,t),...a===void 0?{}:{errors:a},...c===void 0?{}:{resetsDateTimeUtc:c}}},g=(e,t)=>{let r=o(e,t),i=o(r.match,`${t}.match`),a=`${t}.match`,c=f(i,`text`,s,a),l=f(i,`quickReplyId`,s,a),u=f(i,`inputRequestId`,s,a),d=f(r,`events`,n(p),t),m=f(r,`problem`,h,t);return{match:{...c===void 0?{}:{text:c},...l===void 0?{}:{quickReplyId:l},...u===void 0?{}:{inputRequestId:u}},...d===void 0?{}:{events:d},...m===void 0?{}:{problem:m}}},_=(e,i=`fixture`)=>{let a=o(e,i),c=f(a,`openTickets`,n(u),i),m=f(a,`speechToken`,d,i),h=f(a,`handoffReplies`,n(g),i),_=f(a,`liveEvents`,n(p),i);return{id:r(a,`id`,s,i),title:r(a,`title`,s,i),profile:r(a,`profile`,l,i),conversation:r(a,`conversation`,t,i),turns:r(a,`turns`,n(g),i),...c===void 0?{}:{openTickets:c},...m===void 0?{}:{speechToken:m},...h===void 0?{}:{handoffReplies:h},..._===void 0?{}:{liveEvents:_}}};export{_ as decodeChatFixture};
@@ -0,0 +1 @@
1
+ import{ChatAuthorKindValues as e,ChatConversationStateValues as t,ChatRatingValues as n}from"./enums.js";import{decodeChatPart as r}from"./parts.js";import{array as i,boolean as a,field as o,nullable as s,number as c,oneOf as l,record as u,string as d}from"./primitives.js";var f=l(e),p=l(n),m=l(t),h=(e,t)=>{let n=u(e,t);return{kind:o(n,`kind`,f,t),displayName:o(n,`displayName`,s(d),t),avatarUrl:o(n,`avatarUrl`,s(d),t)}},g=(e,t)=>{let n=u(e,t);return{publicId:o(n,`publicId`,d,t),conversationId:o(n,`conversationId`,d,t),sequence:o(n,`sequence`,c,t),author:o(n,`author`,h,t),createdDateTimeUtc:o(n,`createdDateTimeUtc`,d,t),parts:o(n,`parts`,i(r),t),rating:o(n,`rating`,s(p),t),ratingNote:o(n,`ratingNote`,s(d),t)}},_=(e,t)=>{let n=u(e,t);return{publicId:o(n,`publicId`,d,t),title:o(n,`title`,d,t),state:o(n,`state`,m,t),continuesConversationId:o(n,`continuesConversationId`,s(d),t),messages:o(n,`messages`,i(g),t),hasEarlier:o(n,`hasEarlier`,a,t)}},v=(e,t)=>{let n=u(e,t);return{publicId:o(n,`publicId`,d,t),title:o(n,`title`,d,t),state:o(n,`state`,m,t),createdDateTimeUtc:o(n,`createdDateTimeUtc`,d,t),lastActivityDateTimeUtc:o(n,`lastActivityDateTimeUtc`,d,t)}},y=(e,t)=>{let n=u(e,t);return{items:o(n,`items`,i(v),t),page:o(n,`page`,c,t),pageSize:o(n,`pageSize`,c,t),totalCount:o(n,`totalCount`,c,t),totalPages:o(n,`totalPages`,c,t),totalCountCapped:o(n,`totalCountCapped`,a,t)}};export{h as decodeChatAuthor,f as decodeChatAuthorKind,m as decodeChatConversationState,v as decodeChatConversationSummary,y as decodeChatConversationSummaryPage,_ as decodeChatConversationView,g as decodeChatMessageView,p as decodeChatRating};
@@ -0,0 +1 @@
1
+ import{DEFAULT_CHAT_LABELS as e}from"../labels.js";import{ChatActionStateValues as t,ChatChartTypeValues as n,ChatColumnTypeValues as r,ChatFieldTypeValues as i,ChatFieldVerificationValues as a,ChatFigureStatusValues as o,ChatHandoffStateValues as s,ChatInputRequestStateValues as c,ChatNoticeCodeValues as l,ChatPartKindValues as u,ChatQuickReplyActionValues as d,ChatQuickReplyPlacementValues as f,ChatQuickReplyVariantValues as p}from"./enums.js";import{ChatDecodeError as m,array as h,boolean as g,field as _,nullable as v,number as y,oneOf as b,record as x,string as S,unionByKind as C}from"./primitives.js";var w=(e,t)=>{if(e===null||typeof e==`string`||typeof e==`number`)return e;throw new m(t,`text, a number or null`)},T=(e,t)=>{let n=x(e,t);return Object.fromEntries(Object.keys(n).map(e=>[e,S(n[e],`${t}.${e}`)]))},E=(e,t)=>{let n=x(e,t);return{marker:_(n,`marker`,y,t),title:_(n,`title`,S,t),reference:_(n,`reference`,S,t),url:_(n,`url`,v(S),t)}},D=(e,t)=>{let n=x(e,t);return{id:_(n,`id`,S,t),label:_(n,`label`,S,t)}},O=(e,t)=>{let n=x(e,t);return{id:_(n,`id`,S,t),startDateTimeUtc:_(n,`startDateTimeUtc`,S,t),endDateTimeUtc:_(n,`endDateTimeUtc`,S,t)}},k=(e,t)=>{let n=x(e,t);return{id:_(n,`id`,S,t),label:_(n,`label`,S,t),action:_(n,`action`,b(d),t),target:_(n,`target`,v(S),t),navigateAfterMs:_(n,`navigateAfterMs`,v(y),t),icon:_(n,`icon`,v(S),t),variant:_(n,`variant`,v(b(p)),t)}},A=(e,t)=>{let n=x(e,t);return{key:_(n,`key`,S,t),type:_(n,`type`,b(i),t),label:_(n,`label`,S,t),placeholder:_(n,`placeholder`,v(S),t),required:_(n,`required`,g,t),maxLength:_(n,`maxLength`,v(y),t),options:_(n,`options`,v(h(D)),t),slots:_(n,`slots`,v(h(O)),t),consentText:_(n,`consentText`,v(S),t),verify:_(n,`verify`,b(a),t),accept:_(n,`accept`,v(h(S)),t),secret:_(n,`secret`,g,t),validator:_(n,`validator`,v(S),t)}},j=(e,t)=>{let n=x(e,t);return{key:_(n,`key`,S,t),label:_(n,`label`,S,t),type:_(n,`type`,b(r),t)}},M=(e,t)=>{let n=x(e,t);return{label:_(n,`label`,S,t),value:_(n,`value`,y,t)}},N=(e,t)=>{let n=x(e,t);return{name:_(n,`name`,S,t),points:_(n,`points`,h(M),t)}},P=(e,t)=>{let n=x(e,t);return{label:_(n,`label`,S,t),value:_(n,`value`,y,t),unit:_(n,`unit`,v(S),t),status:_(n,`status`,b(o),t)}},F=(e,t)=>{let n=x(e,t);return{label:_(n,`label`,S,t),value:_(n,`value`,S,t),type:_(n,`type`,b(r),t)}},I=(e,t)=>{let n=x(e,t);return{route:_(n,`route`,S,t),params:_(n,`params`,T,t)}},L=(e,t)=>{let n=x(e,t);return{displayName:_(n,`displayName`,S,t),avatarUrl:_(n,`avatarUrl`,v(S),t)}},R=C(u,{Text:(e,t)=>{let n=x(e,t);return{kind:`Text`,text:_(n,`text`,S,t)}},Sources:(e,t)=>{let n=x(e,t);return{kind:`Sources`,sources:_(n,`sources`,h(E),t)}},QuickReplies:(e,t)=>{let n=x(e,t);return{kind:`QuickReplies`,replies:_(n,`replies`,h(k),t),placement:_(n,`placement`,b(f),t)}},InputRequest:(e,t)=>{let n=x(e,t);return{kind:`InputRequest`,requestId:_(n,`requestId`,S,t),title:_(n,`title`,v(S),t),fields:_(n,`fields`,h(A),t),submitLabel:_(n,`submitLabel`,S,t),state:_(n,`state`,b(c),t),answeredSummary:_(n,`answeredSummary`,v(S),t),allowTyped:_(n,`allowTyped`,g,t),cancellable:_(n,`cancellable`,g,t)}},Action:(e,n)=>{let r=x(e,n);return{kind:`Action`,actionId:_(r,`actionId`,S,n),actionKind:_(r,`actionKind`,S,n),title:_(r,`title`,S,n),lines:_(r,`lines`,h(S),n),state:_(r,`state`,b(t),n),decidedDateTimeUtc:_(r,`decidedDateTimeUtc`,v(S),n),note:_(r,`note`,v(S),n),consentText:_(r,`consentText`,v(S),n),confirmLabel:_(r,`confirmLabel`,v(S),n),rejectLabel:_(r,`rejectLabel`,v(S),n),editFields:_(r,`editFields`,v(h(D)),n)}},Notice:(e,t)=>{let n=x(e,t);return{kind:`Notice`,code:_(n,`code`,b(l),t),text:_(n,`text`,S,t)}},Table:(e,t)=>{let n=x(e,t);return{kind:`Table`,title:_(n,`title`,v(S),t),columns:_(n,`columns`,h(j),t),rows:_(n,`rows`,h(h(w)),t),currency:_(n,`currency`,v(S),t)}},Chart:(e,t)=>{let r=x(e,t);return{kind:`Chart`,title:_(r,`title`,v(S),t),chartType:_(r,`chartType`,b(n),t),unit:_(r,`unit`,v(S),t),series:_(r,`series`,h(N),t)}},Figures:(e,t)=>{let n=x(e,t);return{kind:`Figures`,figures:_(n,`figures`,h(P),t)}},RecordCard:(e,t)=>{let n=x(e,t);return{kind:`RecordCard`,recordType:_(n,`recordType`,S,t),recordId:_(n,`recordId`,S,t),title:_(n,`title`,S,t),subtitle:_(n,`subtitle`,v(S),t),fields:_(n,`fields`,h(F),t),target:_(n,`target`,v(I),t)}},Image:(e,t)=>{let n=x(e,t);return{kind:`Image`,attachmentId:_(n,`attachmentId`,S,t),alt:_(n,`alt`,S,t),width:_(n,`width`,v(y),t),height:_(n,`height`,v(y),t)}},File:(e,t)=>{let n=x(e,t);return{kind:`File`,attachmentId:_(n,`attachmentId`,S,t),fileName:_(n,`fileName`,S,t),contentType:_(n,`contentType`,S,t),length:_(n,`length`,y,t)}},Ticket:(e,t)=>{let n=x(e,t);return{kind:`Ticket`,ticketId:_(n,`ticketId`,S,t),number:_(n,`number`,S,t),subject:_(n,`subject`,S,t),status:_(n,`status`,S,t)}},Handoff:(e,t)=>{let n=x(e,t);return{kind:`Handoff`,state:_(n,`state`,b(s),t),queuePosition:_(n,`queuePosition`,v(y),t),agent:_(n,`agent`,v(L),t)}},VoiceClip:(e,t)=>{let n=x(e,t);return{kind:`VoiceClip`,attachmentId:_(n,`attachmentId`,S,t),durationMs:_(n,`durationMs`,y,t),transcript:_(n,`transcript`,v(S),t)}}},()=>({kind:`Notice`,code:`NeedsNewerApp`,text:e.needsNewerApp}));export{M as decodeChatChartPoint,N as decodeChatChartSeries,P as decodeChatFigure,A as decodeChatInputField,D as decodeChatInputOption,R as decodeChatPart,L as decodeChatParticipant,k as decodeChatQuickReply,F as decodeChatRecordField,I as decodeChatRecordTarget,E as decodeChatSource,j as decodeChatTableColumn,O as decodeChatTimeSlot};
@@ -0,0 +1 @@
1
+ import{isRecord as e}from"../guards.js";var t=class extends Error{path;constructor(e,t){super(`Expected ${t} at ${e}.`),this.name=`ChatDecodeError`,this.path=e}},n=(n,r)=>{if(!e(n))throw new t(r,`an object`);return n},r=(e,t,n,r)=>n(e[t],`${r}.${t}`),i=(e,n)=>{if(typeof e!=`string`)throw new t(n,`a string`);return e},a=(e,n)=>{if(typeof e!=`number`||Number.isNaN(e))throw new t(n,`a number`);return e},o=(e,n)=>{if(typeof e!=`boolean`)throw new t(n,`true or false`);return e},s=(e,n)=>{if(!(e instanceof ArrayBuffer))throw new t(n,`binary data`);return e},c=e=>(t,n)=>t==null?null:e(t,n),l=e=>(n,r)=>{if(!Array.isArray(n))throw new t(r,`a list`);return n.map((t,n)=>e(t,`${r}[${n}]`))},u=()=>e=>e,d=e=>(n,r)=>{let i=e.find(e=>e===n);if(i===void 0)throw new t(r,`one of ${e.join(`, `)}`);return i},f=e=>e,p=(e,a,o)=>(s,c)=>{let l=r(n(s,c),`kind`,i,c);if(!(t=>e.some(e=>e===t))(l)){if(o)return o(l,c);throw new t(`${c}.kind`,`one of ${e.join(`, `)}`)}return a[l](s,c)};export{t as ChatDecodeError,u as allMembers,l as array,s as arrayBuffer,o as boolean,r as field,c as nullable,a as number,d as oneOf,n as record,i as string,p as unionByKind,f as unknownValue};
@@ -0,0 +1 @@
1
+ import{featureRecord as e}from"../profile.js";import{ChatCaptchaModeValues as t,ChatFieldTypeValues as n,ChatQuickReplyVariantValues as r}from"./enums.js";import{array as i,boolean as a,field as o,nullable as s,number as c,oneOf as l,record as u,string as d}from"./primitives.js";var f=l(r),p=l(t),m=l(n),h=(e,t)=>{let n=u(e,t);return{name:o(n,`name`,d,t),tagline:o(n,`tagline`,s(d),t),intro:o(n,`intro`,s(d),t)}},g=(e,t)=>{let n=u(e,t);return{privacyText:o(n,`privacyText`,s(d),t),privacyUrl:o(n,`privacyUrl`,s(d),t),assuranceText:o(n,`assuranceText`,s(d),t),disclaimer:o(n,`disclaimer`,s(d),t)}},_=(e,t)=>{let n=u(e,t);return{mode:o(n,`mode`,p,t),siteKey:o(n,`siteKey`,s(d),t),action:o(n,`action`,d,t)}},v=(e,t)=>{let n=u(e,t);return{maxMessageLength:o(n,`maxMessageLength`,c,t),maxAttachments:o(n,`maxAttachments`,c,t),maxFileBytes:o(n,`maxFileBytes`,c,t),contentTypes:o(n,`contentTypes`,i(d),t),maxRepliesPerConversation:o(n,`maxRepliesPerConversation`,s(c),t)}},y=(e,t)=>{let n=u(e,t);return{id:o(n,`id`,d,t),label:o(n,`label`,d,t),message:o(n,`message`,d,t),icon:o(n,`icon`,s(d),t),variant:o(n,`variant`,s(f),t)}},b=(e,t)=>{let n=u(e,t);return{pathPrefix:o(n,`pathPrefix`,d,t),greeting:o(n,`greeting`,s(d),t),starters:o(n,`starters`,s(i(y)),t)}},x=(e,t)=>{let n=u(e,t);return{kind:o(n,`kind`,d,t),text:o(n,`text`,d,t),delaySeconds:o(n,`delaySeconds`,c,t),scrollPercent:o(n,`scrollPercent`,s(c),t),pagesViewed:o(n,`pagesViewed`,s(c),t)}},S=(e,t)=>{let n=u(e,t);return{id:o(n,`id`,d,t),minTimeOnSiteSeconds:o(n,`minTimeOnSiteSeconds`,s(c),t),minScrollPercent:o(n,`minScrollPercent`,s(c),t),minPagesViewed:o(n,`minPagesViewed`,s(c),t),minServicesViewed:o(n,`minServicesViewed`,s(c),t),starters:o(n,`starters`,i(y),t),keepPageStarters:o(n,`keepPageStarters`,c,t)}},C=(e,t)=>{let n=u(e,t);return{servicePathPrefixes:o(n,`servicePathPrefixes`,i(d),t),maxStarters:o(n,`maxStarters`,c,t),recentServiceStarter:o(n,`recentServiceStarter`,s(d),t)}},w=(e,t)=>{let n=u(e,t);return{greeting:o(n,`greeting`,d,t),starters:o(n,`starters`,i(y),t),pageRules:o(n,`pageRules`,i(b),t),returningGreeting:o(n,`returningGreeting`,s(d),t),returningStarters:o(n,`returningStarters`,s(i(y)),t),nudge:o(n,`nudge`,s(x),t),rules:o(n,`rules`,s(i(S)),t),behaviour:o(n,`behaviour`,s(C),t)}},T=(e,t)=>{let n=u(e,t);return{open:o(n,`open`,a,t),sent:o(n,`sent`,a,t),reply:o(n,`reply`,a,t),vibrate:o(n,`vibrate`,a,t),vibrateMs:o(n,`vibrateMs`,c,t),volume:o(n,`volume`,c,t),muteControl:o(n,`muteControl`,a,t)}},E=(e,t)=>{let n=u(e,t);return{typingPause:o(n,`typingPause`,a,t),pauseBaseMs:o(n,`pauseBaseMs`,c,t),pausePerCharMs:o(n,`pausePerCharMs`,c,t),pauseMaxMs:o(n,`pauseMaxMs`,c,t),handoffPauseMs:o(n,`handoffPauseMs`,c,t),thinkingPhrases:o(n,`thinkingPhrases`,i(d),t),phraseIntervalMs:o(n,`phraseIntervalMs`,c,t)}},D=(e,t)=>{let n=u(e,t);return{peek:o(n,`peek`,a,t),peekSeconds:o(n,`peekSeconds`,c,t),hoverLabel:o(n,`hoverLabel`,s(d),t),hideWhileOpen:o(n,`hideWhileOpen`,a,t),liftAboveBanner:o(n,`liftAboveBanner`,a,t),liftAboveFooter:o(n,`liftAboveFooter`,a,t),stepAsideForMenus:o(n,`stepAsideForMenus`,a,t),switchOnDark:o(n,`switchOnDark`,a,t)}},O=(e,t)=>{let n=u(e,t);return{delaySeconds:o(n,`delaySeconds`,c,t),oncePerSession:o(n,`oncePerSession`,a,t),rememberDismissal:o(n,`rememberDismissal`,a,t),skipBelowWidthPx:o(n,`skipBelowWidthPx`,c,t),skipWhenFormTouched:o(n,`skipWhenFormTouched`,a,t),skipWhenCoversControl:o(n,`skipWhenCoversControl`,a,t),busyRetrySeconds:o(n,`busyRetrySeconds`,c,t),skipPathPrefixes:o(n,`skipPathPrefixes`,i(d),t)}},k=(e,t)=>{let n=u(e,t);return{motion:o(n,`motion`,a,t),sound:o(n,`sound`,T,t),pacing:o(n,`pacing`,E,t),launcher:o(n,`launcher`,D,t),autoOpen:o(n,`autoOpen`,O,t)}},A=(t,n)=>{let r=u(t,n),l=u(r.features,`${n}.features`);return{contractVersion:o(r,`contractVersion`,c,n),surface:o(r,`surface`,d,n),screen:o(r,`screen`,s(d),n),assistant:o(r,`assistant`,h,n),start:o(r,`start`,w,n),features:e(e=>o(l,e,a,`${n}.features`)),limits:o(r,`limits`,v,n),messagesLeftToday:o(r,`messagesLeftToday`,s(c),n),inputFieldTypes:o(r,`inputFieldTypes`,i(m),n),footer:o(r,`footer`,g,n),captcha:o(r,`captcha`,_,n),experience:o(r,`experience`,k,n),speechAvailable:o(r,`speechAvailable`,a,n)}};export{h as decodeChatAssistantCopy,O as decodeChatAutoOpenSettings,C as decodeChatBehaviourSettings,p as decodeChatCaptchaMode,_ as decodeChatCaptchaSettings,k as decodeChatExperienceSettings,m as decodeChatFieldType,g as decodeChatFooterCopy,D as decodeChatLauncherSettings,v as decodeChatLimits,x as decodeChatNudge,E as decodeChatPacingSettings,b as decodeChatPageRule,A as decodeChatProfileView,f as decodeChatQuickReplyVariant,T as decodeChatSoundSettings,w as decodeChatStartSettings,y as decodeChatStarter,S as decodeChatStarterRule};
@@ -0,0 +1 @@
1
+ import{ChatActionStateValues as e}from"./enums.js";import{field as t,nullable as n,number as r,oneOf as i,record as a,string as o}from"./primitives.js";var s=i(e),c=(e,n)=>{let r=a(e,n);return{token:t(r,`token`,o,n),region:t(r,`region`,o,n),expiresDateTimeUtc:t(r,`expiresDateTimeUtc`,o,n)}},l=(e,n)=>{let i=a(e,n);return{publicId:t(i,`publicId`,o,n),fileName:t(i,`fileName`,o,n),contentType:t(i,`contentType`,o,n),length:t(i,`length`,r,n)}},u=(e,n)=>{let r=a(e,n);return{ticketId:t(r,`ticketId`,o,n),number:t(r,`number`,o,n),subject:t(r,`subject`,o,n),status:t(r,`status`,o,n),updatedDateTimeUtc:t(r,`updatedDateTimeUtc`,o,n)}},d=(e,r)=>{let i=a(e,r);return{actionId:t(i,`actionId`,o,r),actionKind:t(i,`actionKind`,o,r),state:t(i,`state`,s,r),decidedDateTimeUtc:t(i,`decidedDateTimeUtc`,n(o),r),note:t(i,`note`,n(o),r)}};export{s as decodeChatActionState,d as decodeChatActionView,l as decodeChatAttachment,u as decodeChatOpenTicket,c as decodeChatSpeechToken};
package/dist/dictation.js CHANGED
@@ -1 +1 @@
1
- import{ChatSpeechError as e}from"./speech.js";var t=2e3,n=1e4,r=globalThis,i=e=>Object.freeze({status:e}),a={Idle:i(`Idle`),Listening:i(`Listening`),Blocked:i(`Blocked`),NotHeard:i(`NotHeard`),Failed:i(`Failed`),NoMicrophone:i(`NoMicrophone`),Unavailable:i(`Unavailable`)};function o(t){let{adapter:n}=t,i=t.silenceMs??2e3,o=t.noSpeechMs??1e4,s=/* @__PURE__ */ new Set,c=a.Idle,l=!1,u=0,d=!1,f=null,p=null,m=null,h=e=>{if(c.status!==e){c=a[e];for(let e of[...s])e()}},g=()=>{p!==null&&r.clearTimeout(p),m!==null&&r.clearTimeout(m),p=null,m=null},_=()=>{u+=1,g();let e=f;return f=null,e},v=e=>e===u,y=()=>{p!==null&&r.clearTimeout(p),p=r.setTimeout(()=>{p=null,S()},i)},b=()=>{m!==null&&r.clearTimeout(m),m=r.setTimeout(()=>{m=null,_()?.abort(),h(`NotHeard`)},o)},x=()=>{if(l||c.status===`Listening`)return;_()?.abort();let i=u;d=!1;let a=new r.AbortController;f=a,h(`Listening`),new Promise(e=>e(n.startDictation({language:t.language,signal:a.signal,onLevel:e=>{v(i)&&t.onLevel?.(e)},onStarted:()=>{v(i)&&!d&&n.streamsText&&b()},onText:(e,a)=>{v(i)&&(d=!0,m!==null&&(r.clearTimeout(m),m=null),n.streamsText&&y(),t.onText(e,a))}}))).then(()=>{if(!v(i))return;let e=d;_(),h(e?`Idle`:`NotHeard`)},t=>{v(i)&&(_(),h(t instanceof e&&(t.code===`Blocked`||t.code===`NoMicrophone`||t.code===`Unavailable`)?t.code:`Failed`))})},S=()=>{l||(_()?.abort(),h(`Idle`))};return{getState:()=>c,subscribe(e){return l?()=>void 0:(s.add(e),()=>{s.delete(e)})},start:()=>{l||x()},stop:S,toggle(){l||(c.status===`Listening`?S():x())},dispose(){l||(_()?.abort(),h(`Idle`),l=!0,s.clear())}}}export{n as DICTATION_NO_SPEECH_MS,t as DICTATION_SILENCE_MS,o as createDictation};
1
+ import{runtime as e}from"./runtime.js";import{ChatSpeechError as t}from"./speech.js";var n=2e3,r=1e4,i=e=>Object.freeze({status:e}),a={Idle:i(`Idle`),Listening:i(`Listening`),Blocked:i(`Blocked`),NotHeard:i(`NotHeard`),Failed:i(`Failed`),NoMicrophone:i(`NoMicrophone`),Unavailable:i(`Unavailable`)};function o(n){let{adapter:r}=n,i=n.silenceMs??2e3,o=n.noSpeechMs??1e4,s=/* @__PURE__ */ new Set,c=a.Idle,l=!1,u=0,d=!1,f=null,p=null,m=null,h=e=>{if(c.status!==e){c=a[e];for(let e of[...s])e()}},g=()=>{p!==null&&e.clearTimeout(p),m!==null&&e.clearTimeout(m),p=null,m=null},_=()=>{u+=1,g();let e=f;return f=null,e},v=e=>e===u,y=()=>{p!==null&&e.clearTimeout(p),p=e.setTimeout(()=>{p=null,S()},i)},b=()=>{m!==null&&e.clearTimeout(m),m=e.setTimeout(()=>{m=null,_()?.abort(),h(`NotHeard`)},o)},x=()=>{if(l||c.status===`Listening`)return;_()?.abort();let i=u;d=!1;let a=new e.AbortController;f=a,h(`Listening`),new Promise(t=>t(r.startDictation({...n.language===void 0?{}:{language:n.language},signal:a.signal,onLevel:e=>{v(i)&&n.onLevel?.(e)},onStarted:()=>{v(i)&&!d&&r.streamsText&&b()},onText:(t,a)=>{v(i)&&(d=!0,m!==null&&(e.clearTimeout(m),m=null),r.streamsText&&y(),n.onText(t,a))}}))).then(()=>{if(!v(i))return;let e=d;_(),h(e?`Idle`:`NotHeard`)},e=>{v(i)&&(_(),h(e instanceof t&&(e.code===`Blocked`||e.code===`NoMicrophone`||e.code===`Unavailable`)?e.code:`Failed`))})},S=()=>{l||(_()?.abort(),h(`Idle`))};return{getState:()=>c,subscribe(e){return l?()=>void 0:(s.add(e),()=>{s.delete(e)})},start:()=>{l||x()},stop:S,toggle(){l||(c.status===`Listening`?S():x())},dispose(){l||(_()?.abort(),h(`Idle`),l=!0,s.clear())}}}export{r as DICTATION_NO_SPEECH_MS,n as DICTATION_SILENCE_MS,o as createDictation};
package/dist/explain.js CHANGED
@@ -1 +1 @@
1
- var e=globalThis,t=(e,t)=>typeof e==`number`&&Number.isFinite(e)&&e>=0?e:t,n=e=>typeof e==`object`&&e?e:{},r=e=>{let t=n(e),r=n(n(t.response).data);return{capacity:t.code===`assistant_at_capacity`||r.code===`assistant_at_capacity`,resetsDateTimeUtc:typeof t.resetsDateTimeUtc==`string`?t.resetsDateTimeUtc:typeof r.resetsDateTimeUtc==`string`?r.resetsDateTimeUtc:null}};function i(n){let i=t(n.thinkingAfterMs,300),a=t(n.thinkingMinMs,500),o=t(n.slowAfterMs,8e3),s=t(n.timeoutMs,45e3),c=n.isEmpty??(e=>e==null),l=/* @__PURE__ */ new Set,u=e.navigator?.onLine===!1,d={state:u?`offline`:`idle`,answer:null,pillVisible:!1,resetsDateTimeUtc:null,offline:u},f=0,p=!1,m=null,h=null,g=null,_=null,v=null,y=0,b=e=>{if(Object.keys(e).some(t=>e[t]!==d[t])){d={...d,...e};for(let e of l)e()}},x=t=>(t!==null&&e.clearTimeout(t),null),S=()=>{f+=1,m?.abort(),m=null,h=x(h),g=x(g),_=x(_),v=x(v)},C=t=>{let n=f;if(m=null,g=x(g),_=x(_),d.pillVisible){let r=a-(Date.now()-y);if(r>0){v=e.setTimeout(()=>{v=null,n===f&&b({...t,pillVisible:!1})},r);return}}else h=x(h);b({...t,pillVisible:!1})},w=()=>{if(p||u)return;S();let t=f,a=new e.AbortController;m=a,b({state:`thinking`,answer:null,pillVisible:!1,resetsDateTimeUtc:null}),h=e.setTimeout(()=>{h=null,y=Date.now(),b({pillVisible:!0})},i),g=e.setTimeout(()=>{g=null,t===f&&d.state===`thinking`&&b({state:`slow`})},o),_=e.setTimeout(()=>{_=null,t===f&&(f+=1,a.abort(),C({state:`error`,answer:null,resetsDateTimeUtc:null}))},s),new Promise(e=>e(n.request(a.signal))).then(e=>{t===f&&C(c(e)?{state:`empty`,answer:null,resetsDateTimeUtc:null}:{state:`answered`,answer:e,resetsDateTimeUtc:null})},e=>{if(t!==f)return;let n=r(e);C(n.capacity?{state:`capacity`,answer:null,resetsDateTimeUtc:n.resetsDateTimeUtc}:{state:`error`,answer:null,resetsDateTimeUtc:null})})},T=()=>{p||(S(),b({state:u?`offline`:`idle`,answer:null,pillVisible:!1,resetsDateTimeUtc:null}))},E=()=>{u=!0,b(d.state===`idle`||d.state===`offline`?{offline:!0,state:`offline`}:{offline:!0})},D=()=>{u=!1,b(d.state===`offline`?{offline:!1,state:`idle`}:{offline:!1})};return typeof e.addEventListener==`function`&&(e.addEventListener(`offline`,E),e.addEventListener(`online`,D)),{getSnapshot:()=>d,subscribe:e=>p?()=>void 0:(l.add(e),()=>{l.delete(e)}),ask:w,reset:T,dispose:()=>{p||(T(),p=!0,typeof e.removeEventListener==`function`&&(e.removeEventListener(`offline`,E),e.removeEventListener(`online`,D)),l.clear())}}}export{i as createExplain};
1
+ import{asRecord as e}from"./guards.js";import{runtime as t}from"./runtime.js";var n=(e,t)=>typeof e==`number`&&Number.isFinite(e)&&e>=0?e:t,r=t=>{let n=e(t),r=e(e(n.response).data);return{capacity:n.code===`assistant_at_capacity`||r.code===`assistant_at_capacity`,resetsDateTimeUtc:typeof n.resetsDateTimeUtc==`string`?n.resetsDateTimeUtc:typeof r.resetsDateTimeUtc==`string`?r.resetsDateTimeUtc:null}};function i(i){let a=n(i.thinkingAfterMs,300),o=n(i.thinkingMinMs,500),s=n(i.slowAfterMs,8e3),c=n(i.timeoutMs,45e3),l=i.isEmpty??(e=>e==null),u=/* @__PURE__ */ new Set,d=t.navigator?.onLine===!1,f={state:d?`offline`:`idle`,answer:null,pillVisible:!1,resetsDateTimeUtc:null,offline:d},p=0,m=!1,h=null,g=null,_=null,v=null,y=null,b=0,x=t=>{if(Object.entries(t).some(([t,n])=>e(f)[t]!==n)){f={...f,...t};for(let e of u)e()}},S=e=>(e!==null&&t.clearTimeout(e),null),C=()=>{p+=1,h?.abort(),h=null,g=S(g),_=S(_),v=S(v),y=S(y)},w=e=>{let n=p;if(h=null,_=S(_),v=S(v),f.pillVisible){let r=o-(Date.now()-b);if(r>0){y=t.setTimeout(()=>{y=null,n===p&&x({...e,pillVisible:!1})},r);return}}else g=S(g);x({...e,pillVisible:!1})},T=()=>{if(m||d)return;C();let e=p,n=new t.AbortController;h=n,x({state:`thinking`,answer:null,pillVisible:!1,resetsDateTimeUtc:null}),g=t.setTimeout(()=>{g=null,b=Date.now(),x({pillVisible:!0})},a),_=t.setTimeout(()=>{_=null,e===p&&f.state===`thinking`&&x({state:`slow`})},s),v=t.setTimeout(()=>{v=null,e===p&&(p+=1,n.abort(),w({state:`error`,answer:null,resetsDateTimeUtc:null}))},c),new Promise(e=>e(i.request(n.signal))).then(t=>{e===p&&w(l(t)?{state:`empty`,answer:null,resetsDateTimeUtc:null}:{state:`answered`,answer:t,resetsDateTimeUtc:null})},t=>{if(e!==p)return;let n=r(t);w(n.capacity?{state:`capacity`,answer:null,resetsDateTimeUtc:n.resetsDateTimeUtc}:{state:`error`,answer:null,resetsDateTimeUtc:null})})},E=()=>{m||(C(),x({state:d?`offline`:`idle`,answer:null,pillVisible:!1,resetsDateTimeUtc:null}))},D=()=>{d=!0,x(f.state===`idle`||f.state===`offline`?{offline:!0,state:`offline`}:{offline:!0})},O=()=>{d=!1,x(f.state===`offline`?{offline:!1,state:`idle`}:{offline:!1})};return typeof t.addEventListener==`function`&&(t.addEventListener(`offline`,D),t.addEventListener(`online`,O)),{getSnapshot:()=>f,subscribe:e=>m?()=>void 0:(u.add(e),()=>{u.delete(e)}),ask:T,reset:E,dispose:()=>{m||(E(),m=!0,typeof t.removeEventListener==`function`&&(t.removeEventListener(`offline`,D),t.removeEventListener(`online`,O)),u.clear())}}}export{i as createExplain};
package/dist/figures.js CHANGED
@@ -1 +1 @@
1
- var e=`×`,t=`[-+\\u2212]?\\d{1,3}`,n=/* @__PURE__ */ new Map([[`times`,e],[`cdot`,`·`],[`sum`,`∑`],[`leq`,`≤`],[`le`,`≤`],[`geq`,`≥`],[`ge`,`≥`],[`neq`,`≠`],[`approx`,`≈`],[`pm`,`±`],[`rightarrow`,`→`],[`to`,`→`],[`alpha`,`α`],[`beta`,`β`],[`gamma`,`γ`],[`delta`,`δ`],[`lambda`,`λ`],[`mu`,`μ`],[`pi`,`π`],[`rho`,`ρ`],[`sigma`,`σ`],[`tau`,`τ`],[`Delta`,`Δ`],[`Omega`,`Ω`]]),r=/\\\((.*?)\\\)|\\\[(.*?)\\\]|\$\$(.*?)\$\$/gs,i=/`[^`]+`/g,a=/([_^])(\{[^}]*\}|[A-Za-z0-9])/g,o=e=>`(?<${e}>\\{\\s*${t}\\s*\\}|\\(\\s*${t}\\s*\\)|${t})`,s=`(?<tensMantissa>\\d+(?:\\.\\d+)?) *[xX*] *10 ?\\^ ?${o(`tensExp`)}`,c=`\\b10 ?\\^ ?${o(`powExp`)}`,l=`(?<![A-Za-z0-9_.#-])(?<etoken>\\d+(?:\\.\\d+)?[eE]${t})(?![A-Za-z0-9_.-])`,u=RegExp(`${s}|${c}|${l}|(?<![A-Za-z0-9_])(?<symLetter>[A-Za-z])_(?<symSub>[A-Za-z0-9]+)(?<symPrime>')?(?![A-Za-z0-9_])`,`g`),d=e=>e.replace(/\\(?:left|right)\b/g,``).replace(/\\(?:text|mathrm|mathbf|mathit|operatorname)\{([^{}]*)\}/g,`$1`).replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g,`($1)/($2)`).replace(/\\sqrt\{([^{}]*)\}/g,`√($1)`).replace(/\\[,;:! ]/g,` `).replace(/\\([A-Za-z]+)/g,(e,t)=>n.get(t)??t),f=e=>{let t=e.replace(/^[{(]\s*/,``).replace(/\s*[})]$/,``).trim().replace(/\u2212/g,`-`),n=``;return t.startsWith(`-`)?(n=`-`,t=t.slice(1)):t.startsWith(`+`)&&(t=t.slice(1)),t=t.replace(/^0+(?=\d)/,``),t===`0`?`0`:n+t},p=t=>{if(!Number.isFinite(t))return[{kind:`text`,text:String(t)}];if(t===0)return[{kind:`text`,text:`0`}];if(t<0)return[{kind:`text`,text:`-`},...p(-t)];let n=Math.floor(Math.log10(t)),r=t/10**n;Number(r.toFixed(2))>=10&&(r/=10,n+=1);let i=Math.abs(r-Math.round(r))<1e-9?String(Math.round(r)):String(Number(r.toFixed(2)));return n===0?[{kind:`text`,text:i}]:[{kind:`text`,text:`${i} ${e} 10`},{kind:`sup`,text:String(n)}]},m=(e,t)=>{let n=t.replace(/[{}]/g,``);n!==``&&e.push({kind:`text`,text:n})},h=e=>{let t=[],n=0;for(let r of e.matchAll(a)){let i=r.index??0;m(t,e.slice(n,i));let a=r[2].startsWith(`{`)?r[2].slice(1,-1):r[2];t.push({kind:r[1]===`_`?`sub`:`sup`,text:a}),n=i+r[0].length}return m(t,e.slice(n)),t},g=t=>{let n=[],r=0;for(let i of t.matchAll(u)){let a=i.index??0;a>r&&n.push({kind:`text`,text:t.slice(r,a)});let o=i.groups??{};o.tensMantissa===void 0?o.powExp===void 0?o.etoken===void 0?(n.push({kind:`text`,text:o.symLetter??``}),n.push({kind:`sub`,text:o.symSub??``}),o.symPrime!==void 0&&n.push({kind:`text`,text:`'`})):n.push(...p(Number(o.etoken.replace(/\u2212/g,`-`)))):(n.push({kind:`text`,text:`10`}),n.push({kind:`sup`,text:f(o.powExp)})):(n.push({kind:`text`,text:`${o.tensMantissa} ${e} 10`}),n.push({kind:`sup`,text:f(o.tensExp??``)})),r=a+i[0].length}return r<t.length&&n.push({kind:`text`,text:t.slice(r)}),n},_=e=>{let t=[],n=0;for(let r of e.matchAll(i)){let i=r.index??0;t.push(...g(e.slice(n,i))),t.push({kind:`text`,text:r[0]}),n=i+r[0].length}return t.push(...g(e.slice(n))),t},v=e=>{let t=[];for(let n of e){if(n.text===``)continue;let e=t.at(-1);n.kind===`text`&&e?.kind===`text`?t[t.length-1]={kind:`text`,text:e.text+n.text}:t.push(n)}return t};function y(e){if(typeof e!=`string`||e===``)return[];let t=[],n=0;for(let i of e.matchAll(r)){let r=i.index??0;t.push(..._(e.slice(n,r)));let a=i[1]??i[2]??i[3]??``;t.push(...h(d(a))),n=r+i[0].length}return t.push(..._(e.slice(n))),v(t)}function b(e){return y(e).map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``)}function x(e){return Number.isFinite(e)&&e!==0&&Math.abs(e)<.001?p(e):Number.isFinite(e)?[{kind:`text`,text:new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:10}).format(e)}]:[{kind:`text`,text:String(e)}]}export{x as formatFigure,y as toFigureRuns,b as toFigureText};
1
+ var e=`×`,t=`[-+\\u2212]?\\d{1,3}`,n=/* @__PURE__ */ new Map([[`times`,e],[`cdot`,`·`],[`sum`,`∑`],[`leq`,`≤`],[`le`,`≤`],[`geq`,`≥`],[`ge`,`≥`],[`neq`,`≠`],[`approx`,`≈`],[`pm`,`±`],[`rightarrow`,`→`],[`to`,`→`],[`alpha`,`α`],[`beta`,`β`],[`gamma`,`γ`],[`delta`,`δ`],[`lambda`,`λ`],[`mu`,`μ`],[`pi`,`π`],[`rho`,`ρ`],[`sigma`,`σ`],[`tau`,`τ`],[`Delta`,`Δ`],[`Omega`,`Ω`]]),r=/\\\((.*?)\\\)|\\\[(.*?)\\\]|\$\$(.*?)\$\$/gs,i=/`[^`]+`/g,a=/([_^])(\{[^}]*\}|[A-Za-z0-9])/g,o=e=>`(?<${e}>\\{\\s*${t}\\s*\\}|\\(\\s*${t}\\s*\\)|${t})`,s=`(?<tensMantissa>\\d+(?:\\.\\d+)?) *[xX*] *10 ?\\^ ?${o(`tensExp`)}`,c=`\\b10 ?\\^ ?${o(`powExp`)}`,l=`(?<![A-Za-z0-9_.#-])(?<etoken>\\d+(?:\\.\\d+)?[eE]${t})(?![A-Za-z0-9_.-])`,u=RegExp(`${s}|${c}|${l}|(?<![A-Za-z0-9_])(?<symLetter>[A-Za-z])_(?<symSub>[A-Za-z0-9]+)(?<symPrime>')?(?![A-Za-z0-9_])`,`g`),d=e=>e.replace(/\\(?:left|right)\b/g,``).replace(/\\(?:text|mathrm|mathbf|mathit|operatorname)\{([^{}]*)\}/g,`$1`).replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g,`($1)/($2)`).replace(/\\sqrt\{([^{}]*)\}/g,`√($1)`).replace(/\\[,;:! ]/g,` `).replace(/\\([A-Za-z]+)/g,(e,t)=>n.get(t)??t),f=e=>{let t=e.replace(/^[{(]\s*/,``).replace(/\s*[})]$/,``).trim().replace(/\u2212/g,`-`),n=``;return t.startsWith(`-`)?(n=`-`,t=t.slice(1)):t.startsWith(`+`)&&(t=t.slice(1)),t=t.replace(/^0+(?=\d)/,``),t===`0`?`0`:n+t},p=t=>{if(!Number.isFinite(t))return[{kind:`text`,text:String(t)}];if(t===0)return[{kind:`text`,text:`0`}];if(t<0)return[{kind:`text`,text:`-`},...p(-t)];let n=Math.floor(Math.log10(t)),r=t/10**n;Number(r.toFixed(2))>=10&&(r/=10,n+=1);let i=Math.abs(r-Math.round(r))<1e-9?String(Math.round(r)):String(Number(r.toFixed(2)));return n===0?[{kind:`text`,text:i}]:[{kind:`text`,text:`${i} ${e} 10`},{kind:`sup`,text:String(n)}]},m=(e,t)=>{let n=t.replace(/[{}]/g,``);n!==``&&e.push({kind:`text`,text:n})},h=e=>{let t=[],n=0;for(let r of e.matchAll(a)){let{index:i}=r,[,a,o]=r;if(i===void 0||a===void 0||o===void 0)throw Error(`figure script match is incomplete in "${e}"`);m(t,e.slice(n,i));let s=o.startsWith(`{`)?o.slice(1,-1):o;t.push({kind:a===`_`?`sub`:`sup`,text:s}),n=i+r[0].length}return m(t,e.slice(n)),t},g=t=>{let n=[],r=0;for(let i of t.matchAll(u)){let a=i.index??0;a>r&&n.push({kind:`text`,text:t.slice(r,a)});let o=i.groups??{};o.tensMantissa===void 0?o.powExp===void 0?o.etoken===void 0?(n.push({kind:`text`,text:o.symLetter??``}),n.push({kind:`sub`,text:o.symSub??``}),o.symPrime!==void 0&&n.push({kind:`text`,text:`'`})):n.push(...p(Number(o.etoken.replace(/\u2212/g,`-`)))):(n.push({kind:`text`,text:`10`}),n.push({kind:`sup`,text:f(o.powExp)})):(n.push({kind:`text`,text:`${o.tensMantissa} ${e} 10`}),n.push({kind:`sup`,text:f(o.tensExp??``)})),r=a+i[0].length}return r<t.length&&n.push({kind:`text`,text:t.slice(r)}),n},_=e=>{let t=[],n=0;for(let r of e.matchAll(i)){let i=r.index??0;t.push(...g(e.slice(n,i))),t.push({kind:`text`,text:r[0]}),n=i+r[0].length}return t.push(...g(e.slice(n))),t},v=e=>{let t=[];for(let n of e){if(n.text===``)continue;let e=t.at(-1);n.kind===`text`&&e?.kind===`text`?t[t.length-1]={kind:`text`,text:e.text+n.text}:t.push(n)}return t};function y(e){if(typeof e!=`string`||e===``)return[];let t=[],n=0;for(let i of e.matchAll(r)){let r=i.index??0;t.push(..._(e.slice(n,r)));let a=i[1]??i[2]??i[3]??``;t.push(...h(d(a))),n=r+i[0].length}return t.push(..._(e.slice(n))),v(t)}function b(e){return y(e).map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``)}function x(e){return Number.isFinite(e)&&e!==0&&Math.abs(e)<.001?p(e):Number.isFinite(e)?[{kind:`text`,text:new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:10}).format(e)}]:[{kind:`text`,text:String(e)}]}export{x as formatFigure,y as toFigureRuns,b as toFigureText};
@@ -1 +1 @@
1
- import{ChatApiError as e}from"./client.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=`2026-11-04T09:00:00+00:00`,r=e=>JSON.parse(JSON.stringify(e)),i=e=>typeof e==`object`&&e?e:{},a=(e,t)=>typeof e==`string`&&e!==``?e:t,o=e=>{if(!e)return null;let t={};for(let[n,r]of Object.entries(e))r.length>0&&(t[n]=r[0]);return t},s=(e,t)=>Object.keys(e.match).every(n=>{let r=t[n];return r===void 0?!1:e.match[n]===`*`||r===e.match[n]}),c=(n,r)=>{let i=n.turns.find(e=>s(e,r));if(!i)throw new e(`no_fixture_reply`,t.errorGeneric);return i},l=t=>{throw new e(t.code,t.message,t.status,null,o(t.errors))},u=o=>{let s=r(o.conversation),u=[],d=r(o.handoffReplies??[]),f=0,p=!1,m=!1,h=0,g=0,_=()=>s.messages.reduce((e,t)=>Math.max(e,t.sequence),0)+1,v=n=>{if(m||n!==s.publicId)throw new e(`conversation_not_found`,t.errorGeneric,404)},y=e=>{for(let t=s.messages.length-1;t>=0;--t)for(let n of s.messages[t].parts){if(n.kind!==`QuickReplies`)continue;let t=n.replies.find(t=>t.id===e);if(t)return t.label}},b=e=>{s={...s,messages:[...s.messages,e]}},x=async(n,r)=>{let o=null;for(let s of n){if(await Promise.resolve(),r?.signal?.aborted)throw new e(`aborted`,`The request was cancelled.`);if(s.event===`error`){let n=i(s.data);throw new e(a(n.code,`unknown`),a(n.message,t.errorGeneric))}if(s.event===`messageCompleted`){let e=i(s.data).message;b(e),o=e}r?.onEvent?.({name:s.event,data:s.data})}if(!o)throw new e(`invalid-response`,t.errorGeneric);return o},S=(e,t)=>{let n=!1;return s={...s,messages:s.messages.map(r=>({...r,parts:r.parts.map(r=>e(r)?(n=!0,t(r)):r)}))},n},C=e=>{for(let t of s.messages)for(let n of t.parts)if(n.kind===`Action`&&n.actionId===e)return n},w=(n,r,i)=>{let a=C(n);if(!a)throw new e(`action_not_found`,t.errorGeneric,404);let o=(/* @__PURE__ */ new Date()).toISOString();return S(e=>e.kind===`Action`&&e.actionId===n,e=>({...e,state:r,decidedDateTimeUtc:o,note:i})),{actionId:n,actionKind:a.actionKind,state:r,decidedDateTimeUtc:o,note:i}};return{getProfile:async()=>r(o.profile),send:async(e,t)=>{let n=e.quickReplyId?y(e.quickReplyId):void 0,r=e.text??n??``,i=c(o,{text:r,quickReplyId:e.quickReplyId??void 0});return i.problem?l(i.problem):(h+=1,b({publicId:`fixture-visitor-${h}`,conversationId:s.publicId,sequence:_(),author:{kind:`Visitor`,displayName:null,avatarUrl:null},createdDateTimeUtc:(/* @__PURE__ */ new Date()).toISOString(),parts:r===``?[]:[{kind:`Text`,text:r}],rating:null,ratingNote:null}),x(i.events??[],t))},answerInput:async(e,t,n)=>{let r=c(o,{inputRequestId:e});return r.problem?l(r.problem):(S(t=>t.kind===`InputRequest`&&t.requestId===e,e=>({...e,state:`Answered`,answeredSummary:null})),x(r.events??[],n))},confirmAction:async e=>w(e,`Done`,null),rejectAction:async(e,t)=>w(e,`Rejected`,t??null),listConversations:async(e={})=>{let t=e.page??1,r=e.pageSize??20,i=m||t>1?[]:[{publicId:s.publicId,title:s.title,state:s.state,createdDateTimeUtc:s.messages[0]?.createdDateTimeUtc??n,lastActivityDateTimeUtc:s.messages[s.messages.length-1]?.createdDateTimeUtc??n}];return{items:i,page:t,pageSize:r,totalCount:i.length,totalPages:1}},getConversation:async(e,t)=>{v(e);let n=t===void 0?s.messages:s.messages.filter(e=>e.sequence>t);return r({...s,messages:n,hasEarlier:!1})},renameConversation:async(e,t)=>{v(e),s={...s,title:t}},deleteConversation:async e=>{v(e),m=!0},rateMessage:async(n,r)=>{let i=typeof r.note==`string`&&r.note.trim()?r.note.trim():null;if(!s.messages.some(e=>e.publicId===n))throw new e(`message_not_found`,t.errorGeneric,404);s={...s,messages:s.messages.map(e=>e.publicId===n?{...e,rating:r.rating,ratingNote:i}:e)}},uploadAttachment:async e=>{g+=1;let t=i(e);return{publicId:`fixture-file-${g}`,fileName:a(t.name,``),contentType:a(t.type,``),length:typeof t.size==`number`?t.size:0}},deleteAttachment:async()=>void 0,getAttachment:async()=>/* @__PURE__ */ new ArrayBuffer(0),sendOtp:async()=>void 0,requestHandoff:async(n,r)=>{let i=d[f];if(!i)throw new e(`no_fixture_reply`,t.errorGeneric);return f+=1,i.problem?l(i.problem):x(i.events??[],r)},watchConversation:async(n,r)=>{let s=p?[]:o.liveEvents??[];p=!0;for(let n of s){if(await Promise.resolve(),r.signal?.aborted)return;if(n.event===`error`){let r=i(n.data);throw new e(a(r.code,`unknown`),a(r.message,t.errorGeneric))}if(r.onEvent({name:n.event,data:n.data}),n.event===`messageCompleted`){let e=i(i(n.data).message).sequence;typeof e==`number`&&r.onCursor?.(e)}}await new Promise(e=>{r.signal?.aborted?e():r.signal?.addEventListener(`abort`,()=>e())})},sendTyping:async e=>{u.push(e)},listOpenTickets:async()=>r(o.openTickets??[]),getSpeechToken:async()=>r(o.speechToken??{token:`fixture-token`,region:`fixture`,expiresDateTimeUtc:`2999-01-01T00:00:00Z`}),typingCalls:u}};export{u as createFixtureClient};
1
+ import{ChatApiError as e}from"./client.js";import{decodeChatStreamEvent as t}from"./decode/events.js";import{decodeChatConversationView as n}from"./decode/messages.js";import{array as r}from"./decode/primitives.js";import{decodeChatProfileView as i}from"./decode/profile.js";import{decodeChatOpenTicket as a,decodeChatSpeechToken as o}from"./decode/replies.js";import{asRecord as s}from"./guards.js";import{DEFAULT_CHAT_LABELS as c}from"./labels.js";var l=`2026-11-04T09:00:00+00:00`,u=r(a),d=(e,t)=>typeof e==`string`&&e!==``?e:t,f=e=>{if(!e)return null;let t={};for(let[n,r]of Object.entries(e)){let e=r[0];e!==void 0&&(t[n]=e)}return t},p=(e,t)=>Object.entries(e.match).every(([e,n])=>{let r=s(t)[e];return r===void 0?!1:n===`*`||r===n}),m=(t,n)=>{let r=t.turns.find(e=>p(e,n));if(!r)throw new e(`no_fixture_reply`,c.errorGeneric);return r},h=t=>{throw new e(t.code,t.message,t.status,null,f(t.errors))},g=r=>{let a=n(r.conversation,`fixture.conversation`),f=[],p=r.handoffReplies??[],g=0,_=!1,v=!1,y=0,b=0,x=()=>a.messages.reduce((e,t)=>Math.max(e,t.sequence),0)+1,S=t=>{if(v||t!==a.publicId)throw new e(`conversation_not_found`,c.errorGeneric,404)},C=e=>{for(let t=a.messages.length-1;t>=0;--t)for(let n of a.messages[t]?.parts??[]){if(n.kind!==`QuickReplies`)continue;let t=n.replies.find(t=>t.id===e);if(t)return t.label}},w=e=>{a={...a,messages:[...a.messages,e]}},T=async(n,r)=>{let i=null;for(let a of n){if(await Promise.resolve(),r?.signal?.aborted)throw new e(`aborted`,`The request was cancelled.`);let n=t(a.event,a.data);if(n.name===`error`)throw new e(n.data.code,n.data.message);n.name===`messageCompleted`&&(w(n.data.message),i=n.data.message),r?.onEvent?.(n)}if(!i)throw new e(`invalid-response`,c.errorGeneric);return i},E=(e,t)=>{let n=!1;return a={...a,messages:a.messages.map(r=>({...r,parts:r.parts.map(r=>e(r)?(n=!0,t(r)):r)}))},n},D=e=>{for(let t of a.messages)for(let n of t.parts)if(n.kind===`Action`&&n.actionId===e)return n},O=(t,n,r)=>{let i=D(t);if(!i)throw new e(`action_not_found`,c.errorGeneric,404);let a=(/* @__PURE__ */ new Date()).toISOString();return E(e=>e.kind===`Action`&&e.actionId===t,e=>e.kind===`Action`?{...e,state:n,decidedDateTimeUtc:a,note:r}:e),{actionId:t,actionKind:i.actionKind,state:n,decidedDateTimeUtc:a,note:r}};return{getProfile:async()=>i(r.profile,`fixture.profile`),send:async(e,t)=>{let n=e.quickReplyId?C(e.quickReplyId):void 0,i=e.text??n??``,o=m(r,{text:i,quickReplyId:e.quickReplyId??void 0});return o.problem?h(o.problem):(y+=1,w({publicId:`fixture-visitor-${y}`,conversationId:a.publicId,sequence:x(),author:{kind:`Visitor`,displayName:null,avatarUrl:null},createdDateTimeUtc:(/* @__PURE__ */ new Date()).toISOString(),parts:i===``?[]:[{kind:`Text`,text:i}],rating:null,ratingNote:null}),T(o.events??[],t))},answerInput:async(e,t,n)=>{let i=m(r,{inputRequestId:e});return i.problem?h(i.problem):(E(t=>t.kind===`InputRequest`&&t.requestId===e,e=>e.kind===`InputRequest`?{...e,state:`Answered`,answeredSummary:null}:e),T(i.events??[],n))},confirmAction:async e=>O(e,`Done`,null),rejectAction:async(e,t)=>O(e,`Rejected`,t??null),listConversations:async(e={})=>{let t=e.page??1,n=e.pageSize??20,r=v||t>1?[]:[{publicId:a.publicId,title:a.title,state:a.state,createdDateTimeUtc:a.messages[0]?.createdDateTimeUtc??l,lastActivityDateTimeUtc:a.messages[a.messages.length-1]?.createdDateTimeUtc??l}];return{items:r,page:t,pageSize:n,totalCount:r.length,totalPages:1,totalCountCapped:!1}},getConversation:async(e,t)=>{S(e);let r=t===void 0?a.messages:a.messages.filter(e=>e.sequence>t);return n({...a,messages:r,hasEarlier:!1},`conversation`)},renameConversation:async(e,t)=>{S(e),a={...a,title:t}},deleteConversation:async e=>{S(e),v=!0},rateMessage:async(t,n)=>{let r=typeof n.note==`string`&&n.note.trim()?n.note.trim():null;if(!a.messages.some(e=>e.publicId===t))throw new e(`message_not_found`,c.errorGeneric,404);a={...a,messages:a.messages.map(e=>e.publicId===t?{...e,rating:n.rating,ratingNote:r}:e)}},uploadAttachment:async e=>{b+=1;let t=s(e);return{publicId:`fixture-file-${b}`,fileName:d(t.name,``),contentType:d(t.type,``),length:typeof t.size==`number`?t.size:0}},deleteAttachment:async()=>void 0,getAttachment:async()=>/* @__PURE__ */ new ArrayBuffer(0),sendOtp:async()=>void 0,requestHandoff:async(t,n)=>{let r=p[g];if(!r)throw new e(`no_fixture_reply`,c.errorGeneric);return g+=1,r.problem?h(r.problem):T(r.events??[],n)},watchConversation:async(n,i)=>{let a=_?[]:r.liveEvents??[];_=!0;for(let n of a){if(await Promise.resolve(),i.signal?.aborted)return;let r=t(n.event,n.data);if(r.name===`error`)throw new e(r.data.code,r.data.message);i.onEvent(r),r.name===`messageCompleted`&&i.onCursor?.(r.data.message.sequence)}await new Promise(e=>{i.signal?.aborted?e():i.signal?.addEventListener(`abort`,()=>e())})},sendTyping:async e=>{f.push(e)},listOpenTickets:async()=>u(r.openTickets??[],`fixture.openTickets`),getSpeechToken:async()=>o(r.speechToken??{token:`fixture-token`,region:`fixture`,expiresDateTimeUtc:`2999-01-01T00:00:00Z`},`fixture.speechToken`),typingCalls:f}};export{g as createFixtureClient};
package/dist/guards.js ADDED
@@ -0,0 +1 @@
1
+ var e=e=>typeof e==`object`&&!!e&&!Array.isArray(e),t=t=>e(t)?t:{};export{t as asRecord,e as isRecord};
package/dist/handoff.js CHANGED
@@ -1 +1 @@
1
- var e=/^https?:\/\/([^@/?#:]+)(?::\d+)?(?=[/?#]|$)/i;function t(t,n){if(typeof t!=`string`||t===``||/[\t\n\r]/.test(t))return!1;if(t[0]===`/`)return t[1]!==`/`&&t[1]!==`\\`;if(n===void 0||n.length===0)return!1;let r=e.exec(t);if(r===null)return!1;let i=r[1].toLowerCase();return n.some(e=>e.toLowerCase()===i)}export{t as isHandoffTarget};
1
+ var e=/^https?:\/\/([^@/?#:]+)(?::\d+)?(?=[/?#]|$)/i;function t(t,n){if(typeof t!=`string`||t===``||/[\t\n\r]/.test(t))return!1;if(t[0]===`/`)return t[1]!==`/`&&t[1]!==`\\`;if(n===void 0||n.length===0)return!1;let r=e.exec(t);if(r===null)return!1;let i=r[1];if(i===void 0)return!1;let a=i.toLowerCase();return n.some(e=>e.toLowerCase()===a)}export{t as isHandoffTarget};
@@ -0,0 +1 @@
1
+ import{emptyFeatures as e}from"./profile.js";var t=()=>()=>void 0,n=Object.freeze({profile:null,profileError:null,features:Object.freeze(e()),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,open:!1,muted:!1,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffPause:!1,handoffContactRequestId:null,openTickets:[],draft:null}),r=()=>void 0,i=()=>Promise.resolve(),a=()=>/* @__PURE__ */ Error(`The chat session has not started.`),o={get client(){throw a()},getState:()=>n,subscribe:t,load:i,submit:i,chooseQuickReply:i,answerInput:()=>Promise.reject(a()),sendOtp:i,confirmAction:i,rejectAction:i,stop:r,retry:i,regenerate:i,startEdit:r,cancelEdit:r,attach:i,removeAttachment:i,openConversation:i,resumeLast:i,newConversation:r,rate:i,open:r,close:r,setMuted:r,skipField:i,cancelLead:i,editLeadField:i,requestHandoff:i,notifyTyping:r,setLiveActive:r,resumeLive:r,beginHandoff:r,endHandoffPause:r,consumeDraft:r,loadAttachmentUrl:()=>Promise.reject(a()),reset:r,dispose:r};export{o as IDLE_CHAT_SESSION,n as IDLE_CHAT_STATE};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{sniffAudioType as e}from"./audioType.js";import{ChatApiError as t,createChatClient as n,newIdempotencyKey as r}from"./client.js";import{CHAT_CONTRACT_VERSION as i,CHAT_HANDOFF_REQUEST_ID as a}from"./contract.js";import{createConversationList as o}from"./conversationList.js";import{DICTATION_NO_SPEECH_MS as s,DICTATION_SILENCE_MS as c,createDictation as l}from"./dictation.js";import{createExplain as u}from"./explain.js";import{formatFigure as d,toFigureRuns as f,toFigureText as p}from"./figures.js";import{createFixtureClient as m}from"./fixtureClient.js";import{formatChatDate as h,formatChatDateTime as g,formatChatDay as _,formatChatValue as v,formatFileSize as y,messagePlainText as b}from"./format.js";import{isHandoffTarget as x}from"./handoff.js";import{DEFAULT_CHAT_LABELS as S,mergeLabels as C}from"./labels.js";import{defaultChatLook as w,mergeLook as T}from"./look.js";import{pacingDelayMs as E}from"./pacing.js";import{CHAT_FEATURES as D,LOADER_STYLES as O,emptyFeatures as k,loaderView as A,resolveFeatures as j,resolveNudge as M,resolveStart as N,showsCaptchaNote as P}from"./profile.js";import{createChatSession as F,createTurnApi as I,handoffSettledIds as L}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as R,ChatSpeechError as z,createSpeechTokenSource as B}from"./speech.js";import{humanizeService as V,selectStarters as H}from"./starters.js";import{createSseParser as U,createStreamReader as W}from"./stream.js";import{buildTranscript as G,transcriptToText as K}from"./transcript.js";import{formatClipTime as q,voiceClipBars as J}from"./voiceClip.js";export{i as CHAT_CONTRACT_VERSION,D as CHAT_FEATURES,a as CHAT_HANDOFF_REQUEST_ID,R as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,z as ChatSpeechError,S as DEFAULT_CHAT_LABELS,s as DICTATION_NO_SPEECH_MS,c as DICTATION_SILENCE_MS,O as LOADER_STYLES,G as buildTranscript,n as createChatClient,F as createChatSession,o as createConversationList,l as createDictation,u as createExplain,m as createFixtureClient,B as createSpeechTokenSource,U as createSseParser,W as createStreamReader,I as createTurnApi,w as defaultChatLook,k as emptyFeatures,h as formatChatDate,g as formatChatDateTime,_ as formatChatDay,v as formatChatValue,q as formatClipTime,d as formatFigure,y as formatFileSize,L as handoffSettledIds,V as humanizeService,x as isHandoffTarget,A as loaderView,C as mergeLabels,T as mergeLook,b as messagePlainText,r as newIdempotencyKey,E as pacingDelayMs,j as resolveFeatures,M as resolveNudge,N as resolveStart,H as selectStarters,P as showsCaptchaNote,e as sniffAudioType,f as toFigureRuns,p as toFigureText,K as transcriptToText,J as voiceClipBars};
1
+ import{sniffAudioType as e}from"./audioType.js";import{ChatApiError as t,createChatClient as n,newIdempotencyKey as r}from"./client.js";import{ChatDecodeError as i}from"./decode/primitives.js";import{CHAT_CONTRACT_VERSION as a,CHAT_HANDOFF_REQUEST_ID as o}from"./contract.js";import{decodeChatPart as s}from"./decode/parts.js";import{decodeChatConversationView as c,decodeChatMessageView as l}from"./decode/messages.js";import{createConversationList as u}from"./conversationList.js";import{decodeChatProfileView as d}from"./decode/profile.js";import{decodeChatStreamEvent as f}from"./decode/events.js";import{DICTATION_NO_SPEECH_MS as p,DICTATION_SILENCE_MS as m,createDictation as h}from"./dictation.js";import{createExplain as g}from"./explain.js";import{formatFigure as _,toFigureRuns as v,toFigureText as y}from"./figures.js";import{decodeChatFixture as b}from"./decode/fixture.js";import{createFixtureClient as x}from"./fixtureClient.js";import{formatChatDate as S,formatChatDateTime as C,formatChatDay as w,formatChatValue as T,formatFileSize as E,messagePlainText as D}from"./format.js";import{isHandoffTarget as O}from"./handoff.js";import{IDLE_CHAT_SESSION as k,IDLE_CHAT_STATE as A}from"./idleSession.js";import{DEFAULT_CHAT_LABELS as j,mergeLabels as M}from"./labels.js";import{defaultChatLook as N,mergeLook as P}from"./look.js";import{pacingDelayMs as F}from"./pacing.js";import{CHAT_FEATURES as I,LOADER_STYLES as L,emptyFeatures as R,featureRecord as z,loaderView as B,resolveFeatures as V,resolveNudge as H,resolveStart as U,showsCaptchaNote as W}from"./profile.js";import{createChatSession as G,createTurnApi as K,handoffSettledIds as q}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as J,ChatSpeechError as Y,createSpeechTokenSource as X}from"./speech.js";import{humanizeService as Z,selectStarters as Q}from"./starters.js";import{createSseParser as $,createStreamReader as ee}from"./stream.js";import{buildTranscript as te,transcriptToText as ne}from"./transcript.js";import{formatClipTime as re,voiceClipBars as ie}from"./voiceClip.js";export{a as CHAT_CONTRACT_VERSION,I as CHAT_FEATURES,o as CHAT_HANDOFF_REQUEST_ID,J as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,i as ChatDecodeError,Y as ChatSpeechError,j as DEFAULT_CHAT_LABELS,p as DICTATION_NO_SPEECH_MS,m as DICTATION_SILENCE_MS,k as IDLE_CHAT_SESSION,A as IDLE_CHAT_STATE,L as LOADER_STYLES,te as buildTranscript,n as createChatClient,G as createChatSession,u as createConversationList,h as createDictation,g as createExplain,x as createFixtureClient,X as createSpeechTokenSource,$ as createSseParser,ee as createStreamReader,K as createTurnApi,c as decodeChatConversationView,b as decodeChatFixture,l as decodeChatMessageView,s as decodeChatPart,d as decodeChatProfileView,f as decodeChatStreamEvent,N as defaultChatLook,R as emptyFeatures,z as featureRecord,S as formatChatDate,C as formatChatDateTime,w as formatChatDay,T as formatChatValue,re as formatClipTime,_ as formatFigure,E as formatFileSize,q as handoffSettledIds,Z as humanizeService,O as isHandoffTarget,B as loaderView,M as mergeLabels,P as mergeLook,D as messagePlainText,r as newIdempotencyKey,F as pacingDelayMs,V as resolveFeatures,H as resolveNudge,U as resolveStart,Q as selectStarters,W as showsCaptchaNote,e as sniffAudioType,v as toFigureRuns,y as toFigureText,ne as transcriptToText,ie as voiceClipBars};
package/dist/live.js CHANGED
@@ -1 +1 @@
1
- import{ChatApiError as e}from"./client.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=globalThis,r=/* @__PURE__ */ new Set([`stalled`,`network`,`invalid-response`,`stream_ended`]),i=t=>t instanceof e?r.has(t.code)?!0:t.status===408||t.status===429||t.status!==void 0&&t.status>=500:!1;function a(r){let a=r.baseDelayMs??1e3,o=r.maxDelayMs??3e4,s=r.maxFailedAttempts??10,c=!1,l=null,u=null,d=null,f=0,p=0,m=0,h=e=>new Promise(t=>{d=t,u=n.setTimeout(()=>{u=null,d=null,t()},e)});return(async()=>{for(;!c;){if(m>0&&(await r.beforeReconnect().catch(()=>void 0),c))return;r.onStatus(`Connecting`);let u=new n.AbortController;l=u;let d=!1,g=!1,_=null,v=()=>{c||(d=!0,f=0,p=0,g||(g=!0,r.onStatus(`Live`)))};try{await r.watch(r.getCursor(),u.signal,v)}catch(e){if(c)return;if(!i(e)){r.onError(e),r.onStatus(`Lost`);return}_=e}if(c)return;l=null;let y=Math.min(o,a*2**p);if(d||(f+=1,p+=1),f>=s){r.onError(_??new e(`connection_lost`,t.errorGeneric)),r.onStatus(`Lost`);return}await h(y),m+=1}})().catch(e=>r.onError(e)),{stop(){c||(c=!0,l?.abort(),l=null,u!==null&&(n.clearTimeout(u),u=null),d?.(),d=null)}}}export{a as startLiveConnection};
1
+ import{ChatApiError as e}from"./client.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";import{runtime as n}from"./runtime.js";var r=/* @__PURE__ */ new Set([`stalled`,`network`,`invalid-response`,`stream_ended`]),i=t=>t instanceof e?r.has(t.code)?!0:t.status===408||t.status===429||t.status!==void 0&&t.status>=500:!1;function a(r){let a=r.baseDelayMs??1e3,o=r.maxDelayMs??3e4,s=r.maxFailedAttempts??10,c=!1,l=null,u=null,d=null,f=0,p=0,m=0,h=e=>new Promise(t=>{d=t,u=n.setTimeout(()=>{u=null,d=null,t()},e)});return(async()=>{for(;!c;){if(m>0&&(await Promise.allSettled([r.beforeReconnect()]),c))return;r.onStatus(`Connecting`);let u=new n.AbortController;l=u;let d=!1,g=!1,_=null,v=()=>{c||(d=!0,f=0,p=0,g||(g=!0,r.onStatus(`Live`)))};try{await r.watch(r.getCursor(),u.signal,v)}catch(e){if(c)return;if(!i(e)){r.onError(e),r.onStatus(`Lost`);return}_=e}if(c)return;l=null;let y=Math.min(o,a*2**p);if(d||(f+=1,p+=1),f>=s){r.onError(_??new e(`connection_lost`,t.errorGeneric)),r.onStatus(`Lost`);return}await h(y),m+=1}})().catch(e=>r.onError(e)),{stop(){c||(c=!0,l?.abort(),l=null,u!==null&&(n.clearTimeout(u),u=null),d?.(),d=null)}}}export{a as startLiveConnection};
package/dist/profile.js CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_CHAT_LABELS as e}from"./labels.js";var t=Object.freeze(/* @__PURE__ */ `VisitorChat.Starters.Nudges.ResumeLast.OpenTickets.History.Rename.Delete.SuggestedReplies.Stop.Retry.Edit.Regenerate.Sources.Rating.Copy.Share.Print.Attachments.RichAnswers.InputRequests.LeadCapture.Booking.Scripts.AiAnswers.HumanHandoff.Dictation.ReadAloud.VoiceClips.Sounds.AutoOpen.BehaviourStarters.LeadShortcuts.LeadRecap.FigureText.LinkHandoff.Explain.PanelSwitch`.split(`.`)),n=()=>{let e={};for(let n of t)e[n]=!1;return e},r=(e,n)=>{let r={};for(let i of t)r[i]=e.features[i]===!0&&n?.[i]!==!1;return Object.freeze(r)},i=(e,t)=>e===`/`||t===e||t.startsWith(`${e}/`),a=(e,{pathname:t,returning:n})=>{let r=e.start,a=r.greeting,o=r.starters;n&&(a=r.returningGreeting??a,o=r.returningStarters??o);let s=null;for(let e of r.pageRules)i(e.pathPrefix,t)&&(s===null||e.pathPrefix.length>s.pathPrefix.length)&&(s=e);return s&&(a=s.greeting??a,o=s.starters??o),{greeting:a,starters:o}},o=(e,t)=>t.Nudges&&e.start.nudge?e.start.nudge:null,s=e=>e.captcha.mode!==`Off`&&typeof e.captcha.siteKey==`string`&&e.captcha.siteKey!==``,c=[`Steps`,`Phrases`,`Orb`,`Skeleton`],l=(t,n,r,i)=>{let a=r.length>0?r:[e.thinking],o=a[(i%a.length+a.length)%a.length],s=n.length>0?n[n.length-1]:void 0;return t===`Phrases`?{label:o,steps:[],activeIndex:-1}:t===`Steps`?{label:s??o,steps:n.length>0?[...n]:[o],activeIndex:n.length>0?n.length-1:0}:{label:s??o,steps:[],activeIndex:-1}};export{t as CHAT_FEATURES,c as LOADER_STYLES,n as emptyFeatures,l as loaderView,r as resolveFeatures,o as resolveNudge,a as resolveStart,s as showsCaptchaNote};
1
+ import{allMembers as e}from"./decode/primitives.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=Object.freeze(e()(/* @__PURE__ */ `VisitorChat.Starters.Nudges.ResumeLast.OpenTickets.History.Rename.Delete.SuggestedReplies.Stop.Retry.Edit.Regenerate.Sources.Rating.Copy.Share.Print.Attachments.RichAnswers.InputRequests.LeadCapture.Booking.Scripts.AiAnswers.HumanHandoff.Dictation.ReadAloud.VoiceClips.Sounds.AutoOpen.BehaviourStarters.LeadShortcuts.LeadRecap.FigureText.LinkHandoff.Explain.PanelSwitch`.split(`.`))),r=e=>({VisitorChat:e(`VisitorChat`),Starters:e(`Starters`),Nudges:e(`Nudges`),ResumeLast:e(`ResumeLast`),OpenTickets:e(`OpenTickets`),History:e(`History`),Rename:e(`Rename`),Delete:e(`Delete`),SuggestedReplies:e(`SuggestedReplies`),Stop:e(`Stop`),Retry:e(`Retry`),Edit:e(`Edit`),Regenerate:e(`Regenerate`),Sources:e(`Sources`),Rating:e(`Rating`),Copy:e(`Copy`),Share:e(`Share`),Print:e(`Print`),Attachments:e(`Attachments`),RichAnswers:e(`RichAnswers`),InputRequests:e(`InputRequests`),LeadCapture:e(`LeadCapture`),Booking:e(`Booking`),Scripts:e(`Scripts`),AiAnswers:e(`AiAnswers`),HumanHandoff:e(`HumanHandoff`),Dictation:e(`Dictation`),ReadAloud:e(`ReadAloud`),VoiceClips:e(`VoiceClips`),Sounds:e(`Sounds`),AutoOpen:e(`AutoOpen`),BehaviourStarters:e(`BehaviourStarters`),LeadShortcuts:e(`LeadShortcuts`),LeadRecap:e(`LeadRecap`),FigureText:e(`FigureText`),LinkHandoff:e(`LinkHandoff`),Explain:e(`Explain`),PanelSwitch:e(`PanelSwitch`)}),i=()=>r(()=>!1),a=(e,t)=>Object.freeze(r(n=>e.features[n]===!0&&t?.[n]!==!1)),o=(e,t)=>e===`/`||t===e||t.startsWith(`${e}/`),s=(e,{pathname:t,returning:n})=>{let r=e.start,i=r.greeting,a=r.starters;n&&(i=r.returningGreeting??i,a=r.returningStarters??a);let s=null;for(let e of r.pageRules)o(e.pathPrefix,t)&&(s===null||e.pathPrefix.length>s.pathPrefix.length)&&(s=e);return s&&(i=s.greeting??i,a=s.starters??a),{greeting:i,starters:a}},c=(e,t)=>t.Nudges&&e.start.nudge?e.start.nudge:null,l=e=>e.captcha.mode!==`Off`&&typeof e.captcha.siteKey==`string`&&e.captcha.siteKey!==``,u=[`Steps`,`Phrases`,`Orb`,`Skeleton`],d=(e,n,r,i)=>{let a=r.length>0?r:[t.thinking],o=a[(i%a.length+a.length)%a.length];if(o===void 0)throw Error(`loader phrase index out of range for rotation ${i}`);let s=n.length>0?n[n.length-1]:void 0;return e===`Phrases`?{label:o,steps:[],activeIndex:-1}:e===`Steps`?{label:s??o,steps:n.length>0?[...n]:[o],activeIndex:n.length>0?n.length-1:0}:{label:s??o,steps:[],activeIndex:-1}};export{n as CHAT_FEATURES,u as LOADER_STYLES,i as emptyFeatures,r as featureRecord,d as loaderView,a as resolveFeatures,c as resolveNudge,s as resolveStart,l as showsCaptchaNote};
@@ -0,0 +1 @@
1
+ var e=(e,t)=>Reflect.get(e,t),t=e=>typeof e==`object`&&!!e||typeof e==`function`,n=(n,r)=>t(n)&&typeof e(n,r)==`function`,r=(t,n,r)=>{let i=e(t,n);if(typeof i!=`function`)throw Error(`${n} is not available on this host.`);return Reflect.apply(i,t,r)},i=(n,r)=>{let i=e(globalThis,n);if(typeof i!=`function`)throw Error(`${n} is not available on this host.`);let a=Reflect.construct(i,r);if(!t(a))throw Error(`${n} did not construct an object.`);return a},a=r=>t(r)&&typeof e(r,`aborted`)==`boolean`&&n(r,`addEventListener`)&&n(r,`removeEventListener`),o=class{signal;#e;constructor(){let t=i(`AbortController`,[]),n=e(t,`signal`);if(!a(n))throw Error(`AbortController made no usable signal.`);this.#e=t,this.signal=n}abort(){r(this.#e,`abort`,[])}},s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=1,u=(e,t,n)=>{let i=l++;return e.set(i,r(globalThis,t,n(i))),i},d=(e,t,n)=>{if(!e.has(n))return;let i=e.get(n);e.delete(n),r(globalThis,t,[i])},f=e=>n(globalThis,e)?(t,n)=>{r(globalThis,e,[t,n])}:void 0,p={AbortController:o,setTimeout:(e,t)=>u(s,`setTimeout`,n=>[()=>{s.delete(n),e()},t]),clearTimeout:e=>d(s,`clearTimeout`,e),get requestAnimationFrame(){if(n(globalThis,`requestAnimationFrame`))return e=>u(c,`requestAnimationFrame`,t=>[()=>{c.delete(t),e()}])},get cancelAnimationFrame(){if(n(globalThis,`cancelAnimationFrame`))return e=>d(c,`cancelAnimationFrame`,e)},get navigator(){let n=e(globalThis,`navigator`);if(!t(n))return;let r=e(n,`onLine`);return typeof r==`boolean`?{onLine:r}:{}},get addEventListener(){return f(`addEventListener`)},get removeEventListener(){return f(`removeEventListener`)},get location(){let n=e(globalThis,`location`);if(!t(n))return;let r=e(n,`pathname`);return typeof r==`string`?{pathname:r}:{}},get createFormData(){if(typeof e(globalThis,`FormData`)==`function`)return()=>{let e=i(`FormData`,[]);return{native:e,append:(t,n,i)=>{r(e,`append`,i===void 0?[t,n]:[t,n,i])}}}},get createObjectUrl(){let a=e(globalThis,`URL`);if(typeof e(globalThis,`Blob`)==`function`&&n(a,`createObjectURL`)&&t(a))return e=>{let t=r(a,`createObjectURL`,[i(`Blob`,[[e]])]);if(typeof t!=`string`)throw Error(`createObjectURL returned no URL.`);return t}},get revokeObjectUrl(){let i=e(globalThis,`URL`);if(t(i)&&n(i,`revokeObjectURL`))return e=>{r(i,`revokeObjectURL`,[e])}},get crypto(){let i=e(globalThis,`crypto`);if(t(i)&&n(i,`randomUUID`))return{randomUUID:()=>{let e=r(i,`randomUUID`,[]);if(typeof e!=`string`)throw Error(`randomUUID returned no string.`);return e}}}};export{p as runtime};
package/dist/session.js CHANGED
@@ -1,3 +1,3 @@
1
- import{ChatApiError as e}from"./client.js";import"./contract.js";import{messagePlainText as t}from"./format.js";import{DEFAULT_CHAT_LABELS as n,mergeLabels as r}from"./labels.js";import{startLiveConnection as i}from"./live.js";import{pacingDelayMs as a}from"./pacing.js";import{emptyFeatures as o,resolveFeatures as s,resolveStart as c}from"./profile.js";import{selectStarters as l}from"./starters.js";var u=globalThis,ee=5e3,te=3e3,ne=300,re=1200,ie=e=>{if(u.requestAnimationFrame&&u.cancelAnimationFrame){let t=u.requestAnimationFrame(()=>e());return()=>u.cancelAnimationFrame?.(t)}let t=u.setTimeout(e,16);return()=>u.clearTimeout(t)},d=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:{},f=e=>{let t=d(e);return{code:typeof t.code==`string`&&t.code?t.code:`unknown`,message:typeof t.message==`string`&&t.message?t.message:n.errorGeneric,resetsDateTimeUtc:typeof t.resetsDateTimeUtc==`string`?t.resetsDateTimeUtc:null}},ae=(e,t)=>({id:e.publicId,author:e.author,createdDateTimeUtc:e.createdDateTimeUtc,parts:e.parts,sequence:e.sequence,rating:e.rating,ratingNote:e.ratingNote,streaming:!1,stored:!0,restored:t}),oe=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)},se=(e,t)=>{for(let n=e.length-1;n>=0;--n)if(t(e[n]))return n;return-1},ce=e=>e.flatMap(e=>e.kind===`Text`?[e.text]:[]).join(`
1
+ import{ChatApiError as e}from"./client.js";import"./contract.js";import{messagePlainText as t}from"./format.js";import{asRecord as n}from"./guards.js";import{DEFAULT_CHAT_LABELS as r,mergeLabels as i}from"./labels.js";import{startLiveConnection as a}from"./live.js";import{pacingDelayMs as o}from"./pacing.js";import{emptyFeatures as s,resolveFeatures as ee,resolveStart as c}from"./profile.js";import{runtime as l}from"./runtime.js";import{selectStarters as te}from"./starters.js";var ne=5e3,re=3e3,ie=300,ae=1200,oe=e=>{if(l.requestAnimationFrame&&l.cancelAnimationFrame){let t=l.requestAnimationFrame(()=>e());return()=>l.cancelAnimationFrame?.(t)}let t=l.setTimeout(e,16);return()=>l.clearTimeout(t)},u=e=>{let t=n(e);return{code:typeof t.code==`string`&&t.code?t.code:`unknown`,message:typeof t.message==`string`&&t.message?t.message:r.errorGeneric,resetsDateTimeUtc:typeof t.resetsDateTimeUtc==`string`?t.resetsDateTimeUtc:null}},d=(e,t)=>({id:e.publicId,author:e.author,createdDateTimeUtc:e.createdDateTimeUtc,parts:e.parts,sequence:e.sequence,rating:e.rating,ratingNote:e.ratingNote,streaming:!1,stored:!0,restored:t}),se=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)},ce=(e,t)=>{for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&t(r))return n}return-1},le=e=>e.flatMap(e=>e.kind===`Text`?[e.text]:[]).join(`
2
2
 
3
- `),p=e=>e.flatMap(e=>e.kind===`File`?[{publicId:e.attachmentId,fileName:e.fileName,contentType:e.contentType,length:e.length}]:[]),le=e=>{let t=d(e);return{fileName:typeof t.name==`string`?t.name:``,contentType:typeof t.type==`string`?t.type:``,length:typeof t.size==`number`?t.size:null}},ue=(e,t)=>e.length===t.length&&e.every((e,n)=>e.id===t[n].id&&e.label===t[n].label&&e.message===t[n].message),de=e=>{for(let t of e){if(!t.startsWith(`Enquiry type:`))continue;let e=t.slice(13).trim();return e===``?null:e}return null},fe=e=>e.some(e=>e.kind===`Handoff`)?null:e.find(e=>e.kind===`InputRequest`)?.requestId??null,pe=(e,t)=>e.some(e=>e.parts.some(e=>e.kind===`InputRequest`&&e.requestId===t&&(e.state===`Skipped`||e.state===`Expired`))),me=(e,t)=>{if(t!==`WithAgent`)return null;for(let t=e.length-1;t>=0;--t){let n=e[t];for(let e=n.parts.length-1;e>=0;--e){let t=n.parts[e];if(t.kind===`Handoff`){if(t.state===`Left`||t.state===`Ended`)return null;if(t.state===`Joined`&&t.agent)return t.agent}}if(n.author.kind===`Agent`)return{displayName:n.author.displayName??``,avatarUrl:n.author.avatarUrl}}return null},he=(e,t)=>{(e.cursor===null||t>e.cursor)&&(e.cursor=t)},ge=(e,t)=>{let n=[];e!==``&&n.push({kind:`Text`,text:e});for(let e of t)n.push({kind:`File`,attachmentId:e.publicId,fileName:e.fileName,contentType:e.contentType,length:e.length});return n},_e=e=>{let t=ce(e.parts);return{wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:null,attachments:p(e.parts)}},ve=e=>({profile:null,profileError:null,features:o(),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,open:!1,muted:e?.get(`wchat:muted`)===`1`,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffContactRequestId:null,handoffPause:!1,openTickets:[],draft:null}),m=(o,p)=>{let m=r(p.labels),ye=p.schedule??ie,h=p.prefs,g=/* @__PURE__ */ new Set,_=ve(h),v=0,y=null,b=null,be=0,xe=0,Se=null,x=null,S=/* @__PURE__ */ new Map,Ce=/* @__PURE__ */ new Set,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Set,T=/* @__PURE__ */ new Map,E={name:null,email:null,phone:null},D=/* @__PURE__ */ new Set,O=null,k=null,A=null,j=null,M=null,we=!0,Te=!1,Ee=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new Map,P=Promise.resolve(),F=0,De=()=>p.pathname?.()??u.location?.pathname??`/`,Oe=()=>p.reducedMotion?.()===!0||_.profile?.experience.motion===!1,I=()=>_.streaming||_.thinking,ke=e=>{if(!e.profile)return{...e,greeting:null,starters:[]};let t=De(),n=e.lastConversation!==null,r=c(e.profile,{pathname:t,returning:n}).greeting,i=l(e.profile.start,{pathname:t,returning:n,behaviour:p.behaviour?.()??null,behaviourStarters:e.features.BehaviourStarters});return{...e,greeting:r,starters:ue(e.starters,i)?e.starters:i}},L=()=>{O!==null&&(u.clearTimeout(O),O=null)},R=()=>{A!==null&&(u.clearTimeout(A),A=null)},Ae=e=>e.flatMap(e=>e.parts.flatMap(e=>e.kind===`Action`&&e.actionKind===`ChatLeadCapture`&&e.state===`Done`?[{actionId:e.actionId,leadType:de(e.lines)}]:[])),z=()=>{E.name=null,E.email=null,E.phone=null,D.clear()},je=e=>{for(let t of Ae(e))D.add(t.actionId)},Me=()=>{for(let e of Ae(_.messages))D.has(e.actionId)||(D.add(e.actionId),p.onEvent?.(`leadSubmitted`,{conversationId:_.conversationId,fields:{name:E.name,email:E.email,phone:E.phone},leadType:e.leadType}))},Ne=(e,t)=>{let n=_.messages.flatMap(e=>e.parts).find(t=>t.kind===`InputRequest`&&t.requestId===e);if(n)for(let e of n.fields){let n=t[e.key];typeof n==`string`&&n.trim()!==``&&(e.type===`Email`?E.email=n.trim():e.type===`Phone`?E.phone=n.trim():(e.type===`Name`||e.key.toLowerCase()===`name`)&&(E.name=n.trim()))}},B=e=>{let t=M;t!==null&&(M=null,t.handle?.stop(),e!==null&&H({live:e}))},Pe=()=>!Te&&we&&_.features.HumanHandoff&&_.conversationId!==null&&(_.conversationState===`WaitingForAgent`||_.conversationState===`WithAgent`),V=()=>{if(!Pe()){M!==null&&B(`Off`);return}let e=_.conversationId;if(e===null||M!==null&&M.conversationId===e)return;B(null);let t={conversationId:e,cursor:null,handle:null};M=t;let n=i({watch:(n,r,i)=>o.watchConversation(e,{afterSequence:n,signal:r,onCursor:e=>he(t,e),onEvent:e=>{i(),M===t&&(e.name===`messageCompleted`&&he(t,e.data.message.sequence),X(e,`live`,()=>M===t))}}),beforeReconnect:()=>Z(),getCursor:()=>{let e=t.cursor;for(let t of _.messages)t.sequence!==null&&(e===null||t.sequence>e)&&(e=t.sequence);return e},onStatus:e=>{M===t&&_.live!==e&&H({live:e})},onError:e=>K(e)});t.handle=n,M!==t&&n.stop()},H=e=>{let t={..._,...e};_.conversationState===`WithAgent`&&t.conversationState!==`WithAgent`&&t.agentTyping!==null&&(L(),t.agentTyping=null),(e.messages!==void 0||e.conversationState!==void 0)&&(t.agent=me(t.messages,t.conversationState)),e.messages!==void 0&&t.handoffContactRequestId!==null&&pe(t.messages,t.handoffContactRequestId)&&(t.handoffContactRequestId=null),_=ke(t);for(let e of g)e();e.messages!==void 0&&Me(),V()},U=(e,t)=>H({attachments:_.attachments.map(n=>n.key===e?{...n,...t}:n)}),W=()=>{if(S.size===0)return;let e=[...S.values()];S.clear(),H({messages:_.messages.map(t=>{let n=e.filter(e=>e.messageId===t.id);if(n.length===0)return t;let r=t.parts.map((e,t)=>{let r=n.filter(e=>e.index===t).map(e=>e.text).join(``);return e.kind===`Text`&&r!==``?{...e,text:e.text+r}:e});return{...t,parts:r}})})},G=()=>{S.clear(),b?.(),b=null},Fe=(e,t,n)=>{let r=`${e}#${t}`,i=S.get(r);S.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),b||=ye(()=>{b=null,W()})},Ie=()=>{W(),v+=1,y?.abort(),y=null},K=e=>{if(p.onError)p.onError(e);else throw e},q=()=>{for(let e of T.values())e.abort();T.clear();for(let e of w){let t=C.get(e);t&&o.deleteAttachment(t.publicId).catch(K)}w.clear(),C.clear()},Le=e=>{let t=C.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Re=async(e,t)=>{let n=new u.AbortController;T.set(e,n);let r;try{r=await o.uploadAttachment(t,{signal:n.signal,onProgress:t=>{T.get(e)===n&&U(e,{progress:t})}})}catch{T.get(e)===n&&(T.delete(e),U(e,{status:`Failed`,progress:null,error:m.attachmentFailed}));return}T.get(e)===n?(T.delete(e),C.set(e,r),w.add(e),U(e,{status:`Ready`,progress:null})):o.deleteAttachment(r.publicId).catch(K)},ze=e=>{let t={...d(p.pageContext?.()),path:De(),behaviour:p.behaviour?.()??null};return e&&(t.attribution=p.attribution?.()??null),t},Be=async()=>{let t=_.profile?.captcha;if(!t||!p.getCaptchaToken||t.mode===`Off`&&!t.siteKey)return null;let n;try{n=await p.getCaptchaToken(t.action)}catch(t){throw p.onError?.(t),new e(`captcha_unavailable`,m.captchaUnavailable)}if(!n)throw new e(`captcha_unavailable`,m.captchaUnavailable);return n},Ve=(e,t,n)=>{let r=oe(_.messages,ae(e,!1));H(n?{messages:r,messagesLeftToday:t??_.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},He=e=>{let n=_.profile?.experience.pacing;return!n||Ce.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:a(t(e.parts),n,Oe())},Ue=(e,t,n,r,i)=>{F+=1,H({pending:{typing:!0,authorKind:e.author.kind}}),P=P.then(()=>new Promise(e=>u.setTimeout(e,n))).then(()=>{--F,r()&&Ve(e,t,i),F===0&&H({pending:null})})},We=(e,t,n)=>{let r=[...e];return r[t]=n,r},J=(e,t)=>_.messages.map(n=>n.id===e?t(n):n),Y=e=>_.messages.some(t=>t.id===e),Ge=()=>{L(),_.agentTyping!==null&&H({agentTyping:null})},Ke=e=>{L(),O=u.setTimeout(()=>{O=null,H({agentTyping:null})},ee),H({agentTyping:{displayName:e}})},X=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)Ce.add(e.data.messageId),Fe(e.data.messageId,e.data.index,e.data.text);else switch(W(),e.name){case`messageStarted`:{let t=e.data.message;if(t.author.kind===`Agent`&&Ge(),Y(t.publicId))break;H({messages:[..._.messages,{id:t.publicId,author:t.author,createdDateTimeUtc:t.createdDateTimeUtc,parts:[...t.parts],sequence:t.sequence,rating:t.rating,ratingNote:t.ratingNote,streaming:!0,stored:!1,restored:!1}]});break}case`partStarted`:{let{messageId:t,index:n,part:i}=e.data;if(!Y(t))break;H({messages:J(t,e=>({...e,parts:We(e.parts,n,i)})),...r?{thinking:!1}:{}});break}case`partCompleted`:{let{messageId:t,index:n,part:r}=e.data;if(!Y(t))break;H({messages:J(t,e=>({...e,parts:We(e.parts,n,r)}))});break}case`messageReset`:{let{messageId:t}=e.data;if(!Y(t))break;for(let e of[...S.keys()])S.get(e)?.messageId===t&&S.delete(e);H({messages:J(t,e=>({...e,parts:[]})),...r?{thinking:!0,steps:[]}:{}});break}case`step`:{if(!r)break;let t=e.data.label;_.steps[_.steps.length-1]!==t&&H({steps:[..._.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&Ge();let a=He(t);a>0||F>0?Ue(t,i,a,n,r):Ve(t,i,r);break}case`conversationUpdated`:{let t=e.data;H({conversationId:t.conversationId,conversationState:t.state,title:t.title,continuesConversationId:t.continuesConversationId});break}case`typing`:e.data.authorKind===`Agent`&&Ke(e.data.displayName)}},Z=async()=>{let e=_.conversationId;if(e===null)return;let t=v;try{let n=await o.getConversation(e);if(t!==v)return;let r=new Set(_.messages.filter(e=>e.restored).map(e=>e.id));H({messages:n.messages.map(e=>ae(e,r.has(e.publicId))),title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){K(e)}},Q=async(e,t,n)=>{let r=v,i=new u.AbortController,a=()=>r===v&&!i.signal.aborted;y=i;let s=_.conversationId===null;be+=1;let c={id:`local-${be}`,author:{kind:`Visitor`,displayName:null,avatarUrl:null},createdDateTimeUtc:(/* @__PURE__ */ new Date()).toISOString(),parts:ge(e.displayText,e.attachments),sequence:null,rating:null,ratingNote:null,streaming:!1,stored:!1,restored:!1};n&&(w.clear(),C.clear()),H({messages:[...t,c],thinking:!0,streaming:!0,steps:[],turnError:null,stopped:!1,...n?{editing:null,attachments:[]}:{}});try{let t=await Be();await o.send({conversationId:_.conversationId,text:e.wireText,quickReplyId:e.quickReplyId,attachmentIds:e.attachments.map(e=>e.publicId),replacesMessageId:e.replacesMessageId,pageContext:ze(s),captchaToken:t},{signal:i.signal,onEvent:e=>X(e,`turn`,a)})}catch(e){if(W(),!a())return;let t=f(e);H({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,turnError:t,...t.code===`daily_limit`?{messagesLeftToday:0}:{},...t.code===`conversation_not_found`?{conversationId:null}:{}});return}finally{y===i&&(y=null)}if(await P,!a())return;W(),H({thinking:!1,streaming:!1}),await Z();let l=_.conversationId;s&&l!==null&&l!==Se&&(Se=l,p.onEvent?.(`chatStarted`,{conversationId:l}))},qe=e=>H({messages:_.messages.map(t=>({...t,parts:t.parts.map(t=>t.kind===`Action`&&t.actionId===e.actionId?{...t,state:e.state,decidedDateTimeUtc:e.decidedDateTimeUtc,note:e.note}:t)}))}),Je=async()=>{try{H({openTickets:await o.listOpenTickets()})}catch(e){K(e)}},Ye=async()=>{try{let e=await o.listConversations({page:1,pageSize:1});H({lastConversation:e.items[0]??null})}catch(e){K(e)}},Xe=async()=>{let e;try{e=await o.getProfile(p.screen)}catch(e){H({profileError:f(e)});return}let t=s(e,p.narrow);H({profile:e,profileError:null,features:t,messagesLeftToday:e.messagesLeftToday}),t.OpenTickets&&Je(),t.ResumeLast&&t.History&&Ye(),p.conversationId&&await dt(p.conversationId)},Ze=()=>(x||=Xe(),x),Qe=async e=>{let t=typeof e==`string`?e.trim():``,n=_.attachments.filter(e=>e.status===`Ready`);if(t===``&&n.length===0||_.streaming||_.attachments.some(e=>e.status===`Uploading`))return;let r=_.messages,i=null;if(_.editing){let e=_.messages.findIndex(e=>e.id===_.editing?.messageId),t=_.messages[e];if(!t?.stored)return;i=t.id,r=_.messages.slice(0,e)}let a=n.map(e=>Le(e.key));await Q({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,attachments:a},r,!0)},$e=async e=>{e.action!==`Send`||I()||(e.id===`handoff.request`&&_.features.HumanHandoff&&_.conversationId!==null&&!_.handoffPending?await $():await Q({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,attachments:[]},_.messages,!1))},et=async(e,t)=>{let n=await Be();await o.sendOtp(e,{...t,captchaToken:n})},tt=async(t,n,r=null)=>{if(_.streaming)return{ok:!1,errors:{},message:m.errorGeneric};let i=v,a=new u.AbortController,s=()=>i===v&&!a.signal.aborted;y=a,Ne(t,n);let c=t===_.handoffContactRequestId;H({streaming:!0,thinking:!0});try{let e=await Be();await o.answerInput(t,{values:n,codes:r,captchaToken:e,attribution:p.attribution?.()??null},{signal:a.signal,onEvent:e=>X(e,`turn`,s)})}catch(t){return W(),H({thinking:!1,streaming:!1}),a.signal.aborted?{ok:!1,errors:{},message:m.errorGeneric}:t instanceof e&&t.code===`validation_failed`?{ok:!1,errors:t.errors??{},message:t.message}:t instanceof e&&t.code===`input_request_closed`?(await Z(),{ok:!1,errors:{},message:t.message}):{ok:!1,errors:{},message:f(t).message}}finally{y===a&&(y=null)}return await P,s()&&(W(),H({thinking:!1,streaming:!1}),p.onEvent?.(`inputSubmitted`,{requestId:t}),await Z(),c&&(H({handoffContactRequestId:null}),await $().catch(K))),{ok:!0}},nt=async e=>{let t=await o.confirmAction(e);qe(t),p.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Z()},rt=async(e,t)=>{qe(await o.rejectAction(e,t)),await Z()},it=()=>{if(!_.streaming)return;G();let e=y;y=null,e?.abort(),H({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,stopped:!0,steps:[],pending:null})},at=async()=>{if(_.streaming||_.turnError===null&&!_.stopped)return;let e=se(_.messages,e=>e.author.kind===`Visitor`);e<0||await Q(_e(_.messages[e]),_.messages.slice(0,e),!1)},ot=async()=>{if(I())return;let e=se(_.messages,e=>e.author.kind===`Visitor`&&e.stored);if(e<0)return;let t=_.messages[e];await Q({..._e(t),replacesMessageId:t.id},_.messages.slice(0,e),!1)},st=e=>{let t=_.messages.find(t=>t.id===e);t?.stored&&t.author.kind===`Visitor`&&(q(),H({editing:{messageId:e,text:ce(t.parts)},attachments:[]}))},ct=()=>{_.editing&&(q(),H({editing:null,attachments:[]}))},lt=async e=>{let t=_.profile;if(!t||!_.features.Attachments)return;let n=t.limits,r=n.maxAttachments-_.attachments.filter(e=>e.status!==`Failed`).length,i=[],a=[];for(let t of e){let e=le(t);xe+=1;let o=`file-${xe}`,s={key:o,fileName:e.fileName,contentType:e.contentType,length:e.length??0};r<=0?i.push({...s,status:`Failed`,progress:null,error:m.attachmentLimit(n.maxAttachments)}):e.length!==null&&e.length>n.maxFileBytes||!n.contentTypes.includes(e.contentType)?i.push({...s,status:`Failed`,progress:null,error:m.attachmentFailed}):(--r,i.push({...s,status:`Uploading`,progress:0,error:null}),a.push({key:o,file:t}))}H({attachments:[..._.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Re(e,t)))},ut=async e=>{let t=T.get(e);t&&(T.delete(e),t.abort());let n=w.has(e)?C.get(e):void 0;n&&await o.deleteAttachment(n.publicId),w.delete(e),C.delete(e),H({attachments:_.attachments.filter(t=>t.key!==e)})};async function dt(e){Ie();let t=v;H({messages:[],conversationId:null,loadError:null,loading:!0,editing:null,thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1});try{let n=await o.getConversation(e);if(t!==v)return;let r=n.messages.map(e=>ae(e,!0));z(),je(r),H({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==v)return;H({loadError:f(e)})}finally{t===v&&H({loading:!1})}}let ft=async()=>{let e=_.lastConversation;e&&await dt(e.publicId)},pt=()=>{q(),Ie(),G(),z(),H({messages:[],conversationId:null,title:null,conversationState:`Open`,continuesConversationId:null,loadError:null,loading:!1,editing:null,attachments:[],thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1,pending:null}),_.features.OpenTickets&&Je()},mt=(e,t,n)=>{H({messages:J(e,e=>({...e,rating:t,ratingNote:n}))})},ht=async(e,t,n)=>{let r=_.messages.find(t=>t.id===e);if(!r?.stored)throw Error(`Only a stored reply can be rated.`);let i={rating:r.rating,ratingNote:r.ratingNote},a=typeof n==`string`&&n.trim()?n.trim():null;mt(e,t,a);try{await o.rateMessage(e,{rating:t,note:a})}catch(t){throw mt(e,i.rating,i.ratingNote),t}p.onEvent?.(`rated`,{messageId:e,rating:t})},gt=e=>{let t=_.open,n=e?.trigger??`manual`,r=e?.draft,i={open:!0};typeof r==`string`&&r.trim()!==``&&(i.draft=r),!t&&n===`auto`&&h?.set(`wchat:auto-opened`,`1`),H(i),t||p.onEvent?.(`chatOpened`,{layout:p.layout??null,trigger:n})},_t=e=>{_.open&&(h?.set(`wchat:dismissed`,`1`),H({open:!1}),p.onEvent?.(`chatClosed`,{layout:p.layout??null,reason:e}))},vt=e=>{h?.set(`wchat:muted`,e?`1`:`0`),H({muted:e}),p.onEvent?.(`chatSoundToggled`,{muted:e})},yt=async e=>{I()||(e===_.handoffContactRequestId&&H({handoffContactRequestId:null}),p.onEvent?.(`chatLeadSkipped`,{requestId:e}),await Q({wireText:null,displayText:m.skip,quickReplyId:`lead.skip`,replacesMessageId:null,attachments:[]},_.messages,!1))},bt=async()=>{I()||(p.onEvent?.(`chatLeadCancelled`,{}),await Q({wireText:null,displayText:m.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,attachments:[]},_.messages,!1))},xt=async(e,t)=>{I()||_.messages.some(t=>t.parts.some(t=>t.kind===`Action`&&t.actionId===e))&&await Q({wireText:null,displayText:m.editSomething,quickReplyId:`lead.edit:${t}`,replacesMessageId:null,attachments:[]},_.messages,!1)},$=async t=>{if(!_.features.HumanHandoff)throw new e(`chat_feature_off`,n.errorGeneric,403);let r=_.conversationId;if(r===null)throw new e(`conversation_required`,n.errorGeneric);if(_.streaming||_.handoffPending)throw new e(`busy`,n.errorGeneric);let i=new u.AbortController;j=i,H({handoffPending:!0}),p.onEvent?.(`chatHandoffRequested`,{conversationId:r});let a=null;try{a=fe((await o.requestHandoff({conversationId:r,reason:t??null},{signal:i.signal,onEvent:e=>X(e,`handoff`,()=>!i.signal.aborted)})).parts)}catch(e){throw H({messages:_.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{j===i&&(j=null)}H({handoffPending:!1,handoffContactRequestId:a}),await Z(),p.onEvent?.(`chatHandoff`,{destination:`person`})},St=()=>{let e=_.conversationId;if(!_.features.HumanHandoff||e===null||_.conversationState!==`WithAgent`)return;let t=Date.now();k!==null&&t-k<te||(k=t,o.sendTyping(e).catch(()=>void 0))},Ct=e=>{we=e,V()},wt=()=>{_.live===`Lost`&&Pe()&&(B(null),V())},Tt=e=>{if(p.reducedMotion?.()===!0)return ne;let t=e.navigateAfterMs;if(typeof t==`number`&&Number.isFinite(t)&&t>=0)return t;let n=_.profile?.experience.pacing.handoffPauseMs;return typeof n==`number`&&Number.isFinite(n)?n:re},Et=()=>{R(),_.handoffPause&&H({handoffPause:!1})};return{client:o,getState:()=>_,subscribe:e=>(g.add(e),x||Ze(),()=>{g.delete(e)}),load:Ze,submit:Qe,chooseQuickReply:$e,answerInput:tt,sendOtp:et,confirmAction:nt,rejectAction:rt,stop:it,retry:at,regenerate:ot,startEdit:st,cancelEdit:ct,attach:lt,removeAttachment:ut,openConversation:dt,resumeLast:ft,newConversation:pt,rate:ht,open:gt,close:_t,setMuted:vt,skipField:yt,cancelLead:bt,editLeadField:xt,requestHandoff:$,notifyTyping:St,setLiveActive:Ct,resumeLive:wt,beginHandoff:(e,t)=>{_.handoffPause||(H({handoffPause:!0}),p.onEvent?.(`chatHandoff`,{destination:e.id}),A=u.setTimeout(()=>{A=null;try{t()}catch(e){Et(),K(e)}},Tt(e)))},endHandoffPause:Et,consumeDraft:()=>{_.draft!==null&&H({draft:null})},loadAttachmentUrl:t=>{let n=N.get(t);if(n)return n;let r=(async()=>{let n=u.Blob,r=u.URL;if(!n||typeof r?.createObjectURL!=`function`)throw new e(`unsupported`,m.errorGeneric);let i=await o.getAttachment(t);if(Te)throw new e(`aborted`,m.errorGeneric);let a=r.createObjectURL(new n([i]));return Ee.add(a),a})();return N.set(t,r),r.catch(()=>{N.get(t)===r&&N.delete(t)}),r},reset:()=>{q(),G(),Ie(),x=null,P=Promise.resolve(),F=0,Ce.clear(),Se=null,z(),L(),R(),H(ve(h))},dispose:()=>{g.clear(),Te=!0,v+=1;let e=y;y=null,e?.abort(),j?.abort(),j=null,R(),L(),B(null),q(),G();for(let e of Ee)u.URL?.revokeObjectURL?.(e);Ee.clear(),N.clear(),H({attachments:[],editing:null,agentTyping:null})}}},ye=e=>{let t=-1;for(let n=e.length-1;n>=0;--n)if(e[n].parts.some(e=>e.kind===`Handoff`)){t=n;break}let n=/* @__PURE__ */ new Set;for(let r=0;r<t;r+=1)n.add(e[r].id);return n},h=(e,t)=>({get features(){return e.getState().features},labels:t.labels,get isLast(){let n=e.getState().messages;return n[n.length-1]?.id===t.messageId},get busy(){let t=e.getState();return t.streaming||t.thinking},get handoffPause(){return e.getState().handoffPause},get handoffSettled(){return ye(e.getState().messages).has(t.messageId)},chooseQuickReply(t){e.chooseQuickReply(t)},skipInput(t){e.skipField(t)},cancelLead(){e.cancelLead()},answerInput:(t,n,r)=>e.answerInput(t,n,r),uploadInputFile:async(t,n)=>(await e.client.uploadAttachment(t,n?{onProgress:n}:{})).publicId,sendOtp:(t,n)=>e.sendOtp(t,n),confirmAction:t=>e.confirmAction(t),rejectAction:(t,n)=>e.rejectAction(t,n),requestHandoff:t=>e.requestHandoff(t),beginHandoff:(t,n)=>e.beginHandoff(t,n),readAttachment:t=>e.client.getAttachment(t),loadAttachmentUrl:t=>e.loadAttachmentUrl(t),...t.openAttachment?{openAttachment:t.openAttachment}:{},...t.openRecord?{openRecord:t.openRecord}:{},...t.openTicket?{openTicket:t.openTicket}:{},...t.attachmentUrl?{attachmentUrl:t.attachmentUrl}:{},...t.handoffHosts?{handoffHosts:t.handoffHosts}:{},...t.openCitation?{openCitation:t.openCitation}:{},...t.isCitation?{isCitation:t.isCitation}:{},...t.openTarget?{openTarget:t.openTarget}:{},...t.onNavigate?{onNavigate:t.onNavigate}:{}});export{m as createChatSession,h as createTurnApi,ye as handoffSettledIds};
3
+ `),f=e=>e.flatMap(e=>e.kind===`File`?[{publicId:e.attachmentId,fileName:e.fileName,contentType:e.contentType,length:e.length}]:[]),ue=e=>{let t=n(e);return{fileName:typeof t.name==`string`?t.name:``,contentType:typeof t.type==`string`?t.type:``,length:typeof t.size==`number`?t.size:null}},de=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&e.id===r.id&&e.label===r.label&&e.message===r.message}),fe=e=>{for(let t of e){if(!t.startsWith(`Enquiry type:`))continue;let e=t.slice(13).trim();return e===``?null:e}return null},pe=e=>e.some(e=>e.kind===`Handoff`)?null:e.find(e=>e.kind===`InputRequest`)?.requestId??null,me=(e,t)=>e.some(e=>e.parts.some(e=>e.kind===`InputRequest`&&e.requestId===t&&(e.state===`Skipped`||e.state===`Expired`))),he=(e,t)=>{if(t!==`WithAgent`)return null;for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0){for(let e=n.parts.length-1;e>=0;--e){let t=n.parts[e];if(t?.kind===`Handoff`){if(t.state===`Left`||t.state===`Ended`)return null;if(t.state===`Joined`&&t.agent)return t.agent}}if(n.author.kind===`Agent`)return{displayName:n.author.displayName??``,avatarUrl:n.author.avatarUrl}}}return null},ge=(e,t)=>{(e.cursor===null||t>e.cursor)&&(e.cursor=t)},_e=(e,t)=>{let n=[];e!==``&&n.push({kind:`Text`,text:e});for(let e of t)n.push({kind:`File`,attachmentId:e.publicId,fileName:e.fileName,contentType:e.contentType,length:e.length});return n},ve=e=>{let t=le(e.parts);return{wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:null,attachments:f(e.parts)}},ye=e=>({profile:null,profileError:null,features:s(),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,open:!1,muted:e?.get(`wchat:muted`)===`1`,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffContactRequestId:null,handoffPause:!1,openTickets:[],draft:null}),p=(s,f)=>{let p=i(f.labels),be=f.schedule??oe,m=f.prefs,h=/* @__PURE__ */ new Set,g=ye(m),_=0,v=null,y=null,xe=0,Se=0,Ce=null,b=null,x=/* @__PURE__ */ new Map,S=/* @__PURE__ */ new Set,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Set,T=/* @__PURE__ */ new Map,E={name:null,email:null,phone:null},D=/* @__PURE__ */ new Set,O=null,k=null,A=null,j=null,M=null,we=!0,Te=!1,N=/* @__PURE__ */ new Set,P=/* @__PURE__ */ new Map,F=Promise.resolve(),I=0,Ee=()=>f.pathname?.()??l.location?.pathname??`/`,De=()=>f.reducedMotion?.()===!0||g.profile?.experience.motion===!1,L=()=>g.streaming||g.thinking,Oe=e=>{if(!e.profile)return{...e,greeting:null,starters:[]};let t=Ee(),n=e.lastConversation!==null,r=c(e.profile,{pathname:t,returning:n}).greeting,i=te(e.profile.start,{pathname:t,returning:n,behaviour:f.behaviour?.()??null,behaviourStarters:e.features.BehaviourStarters});return{...e,greeting:r,starters:de(e.starters,i)?e.starters:i}},R=()=>{O!==null&&(l.clearTimeout(O),O=null)},ke=()=>{A!==null&&(l.clearTimeout(A),A=null)},Ae=e=>e.flatMap(e=>e.parts.flatMap(e=>e.kind===`Action`&&e.actionKind===`ChatLeadCapture`&&e.state===`Done`?[{actionId:e.actionId,leadType:fe(e.lines)}]:[])),je=()=>{E.name=null,E.email=null,E.phone=null,D.clear()},Me=e=>{for(let t of Ae(e))D.add(t.actionId)},Ne=()=>{for(let e of Ae(g.messages))D.has(e.actionId)||(D.add(e.actionId),f.onEvent?.(`leadSubmitted`,{conversationId:g.conversationId,fields:{name:E.name,email:E.email,phone:E.phone},leadType:e.leadType}))},Pe=(e,t)=>{let n=g.messages.flatMap(e=>e.parts).find(t=>t.kind===`InputRequest`&&t.requestId===e);if(n)for(let e of n.fields){let n=t[e.key];typeof n==`string`&&n.trim()!==``&&(e.type===`Email`?E.email=n.trim():e.type===`Phone`?E.phone=n.trim():(e.type===`Name`||e.key.toLowerCase()===`name`)&&(E.name=n.trim()))}},z=e=>{let t=M;t!==null&&(M=null,t.handle?.stop(),e!==null&&V({live:e}))},Fe=()=>!Te&&we&&g.features.HumanHandoff&&g.conversationId!==null&&(g.conversationState===`WaitingForAgent`||g.conversationState===`WithAgent`),B=()=>{if(!Fe()){M!==null&&z(`Off`);return}let e=g.conversationId;if(e===null||M!==null&&M.conversationId===e)return;z(null);let t={conversationId:e,cursor:null,handle:null};M=t;let n=a({watch:(n,r,i)=>s.watchConversation(e,{afterSequence:n,signal:r,onCursor:e=>ge(t,e),onEvent:e=>{i(),M===t&&(e.name===`messageCompleted`&&ge(t,e.data.message.sequence),Z(e,`live`,()=>M===t))}}),beforeReconnect:()=>Q(),getCursor:()=>{let e=t.cursor;for(let t of g.messages)t.sequence!==null&&(e===null||t.sequence>e)&&(e=t.sequence);return e},onStatus:e=>{M===t&&g.live!==e&&V({live:e})},onError:e=>K(e)});t.handle=n,M!==t&&n.stop()},V=e=>{let t={...g,...e};g.conversationState===`WithAgent`&&t.conversationState!==`WithAgent`&&t.agentTyping!==null&&(R(),t.agentTyping=null),(e.messages!==void 0||e.conversationState!==void 0)&&(t.agent=he(t.messages,t.conversationState)),e.messages!==void 0&&t.handoffContactRequestId!==null&&me(t.messages,t.handoffContactRequestId)&&(t.handoffContactRequestId=null),g=Oe(t);for(let e of h)e();e.messages!==void 0&&Ne(),B()},H=(e,t)=>V({attachments:g.attachments.map(n=>n.key===e?{...n,...t}:n)}),U=()=>{if(x.size===0)return;let e=[...x.values()];x.clear(),V({messages:g.messages.map(t=>{let n=e.filter(e=>e.messageId===t.id);if(n.length===0)return t;let r=t.parts.map((e,t)=>{let r=n.filter(e=>e.index===t).map(e=>e.text).join(``);return e.kind===`Text`&&r!==``?{...e,text:e.text+r}:e});return{...t,parts:r}})})},W=()=>{x.clear(),y?.(),y=null},Ie=(e,t,n)=>{let r=`${e}#${t}`,i=x.get(r);x.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),y||=be(()=>{y=null,U()})},G=()=>{U(),_+=1,v?.abort(),v=null},K=e=>{if(f.onError)f.onError(e);else throw e},q=()=>{for(let e of T.values())e.abort();T.clear();for(let e of w){let t=C.get(e);t&&s.deleteAttachment(t.publicId).catch(K)}w.clear(),C.clear()},Le=e=>{let t=C.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Re=async(e,t)=>{let n=new l.AbortController;T.set(e,n);let r;try{r=await s.uploadAttachment(t,{signal:n.signal,onProgress:t=>{T.get(e)===n&&H(e,{progress:t})}})}catch{T.get(e)===n&&(T.delete(e),H(e,{status:`Failed`,progress:null,error:p.attachmentFailed}));return}T.get(e)===n?(T.delete(e),C.set(e,r),w.add(e),H(e,{status:`Ready`,progress:null})):s.deleteAttachment(r.publicId).catch(K)},ze=e=>{let t={...n(f.pageContext?.()),path:Ee(),behaviour:f.behaviour?.()??null};return e&&(t.attribution=f.attribution?.()??null),t},J=async()=>{let t=g.profile?.captcha;if(!t||!f.getCaptchaToken||t.mode===`Off`&&!t.siteKey)return null;let n;try{n=await f.getCaptchaToken(t.action)}catch(t){throw f.onError?.(t),new e(`captcha_unavailable`,p.captchaUnavailable)}if(!n)throw new e(`captcha_unavailable`,p.captchaUnavailable);return n},Be=(e,t,n)=>{let r=se(g.messages,d(e,!1));V(n?{messages:r,messagesLeftToday:t??g.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},Ve=e=>{let n=g.profile?.experience.pacing;return!n||S.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:o(t(e.parts),n,De())},He=(e,t,n,r,i)=>{I+=1,V({pending:{typing:!0,authorKind:e.author.kind}}),F=F.then(()=>new Promise(e=>l.setTimeout(e,n))).then(()=>{--I,r()&&Be(e,t,i),I===0&&V({pending:null})})},Ue=(e,t,n)=>{let r=[...e];return r[t]=n,r},Y=(e,t)=>g.messages.map(n=>n.id===e?t(n):n),X=e=>g.messages.some(t=>t.id===e),We=()=>{R(),g.agentTyping!==null&&V({agentTyping:null})},Ge=e=>{R(),O=l.setTimeout(()=>{O=null,V({agentTyping:null})},ne),V({agentTyping:{displayName:e}})},Z=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)S.add(e.data.messageId),Ie(e.data.messageId,e.data.index,e.data.text);else switch(U(),e.name){case`messageStarted`:{let t=e.data.message;if(t.author.kind===`Agent`&&We(),X(t.publicId))break;V({messages:[...g.messages,{id:t.publicId,author:t.author,createdDateTimeUtc:t.createdDateTimeUtc,parts:[...t.parts],sequence:t.sequence,rating:t.rating,ratingNote:t.ratingNote,streaming:!0,stored:!1,restored:!1}]});break}case`partStarted`:{let{messageId:t,index:n,part:i}=e.data;if(!X(t))break;V({messages:Y(t,e=>({...e,parts:Ue(e.parts,n,i)})),...r?{thinking:!1}:{}});break}case`partCompleted`:{let{messageId:t,index:n,part:r}=e.data;if(!X(t))break;V({messages:Y(t,e=>({...e,parts:Ue(e.parts,n,r)}))});break}case`messageReset`:{let{messageId:t}=e.data;if(!X(t))break;for(let e of[...x.keys()])x.get(e)?.messageId===t&&x.delete(e);V({messages:Y(t,e=>({...e,parts:[]})),...r?{thinking:!0,steps:[]}:{}});break}case`step`:{if(!r)break;let t=e.data.label;g.steps[g.steps.length-1]!==t&&V({steps:[...g.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&We();let a=Ve(t);a>0||I>0?He(t,i,a,n,r):Be(t,i,r);break}case`conversationUpdated`:{let t=e.data;V({conversationId:t.conversationId,conversationState:t.state,title:t.title,continuesConversationId:t.continuesConversationId});break}case`typing`:e.data.authorKind===`Agent`&&Ge(e.data.displayName)}},Q=async()=>{let e=g.conversationId;if(e===null)return;let t=_;try{let n=await s.getConversation(e);if(t!==_)return;let r=new Set(g.messages.filter(e=>e.restored).map(e=>e.id));V({messages:n.messages.map(e=>d(e,r.has(e.publicId))),title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){K(e)}},$=async(e,t,n)=>{let r=_,i=new l.AbortController,a=()=>r===_&&!i.signal.aborted;v=i;let o=g.conversationId===null;xe+=1;let ee={id:`local-${xe}`,author:{kind:`Visitor`,displayName:null,avatarUrl:null},createdDateTimeUtc:(/* @__PURE__ */ new Date()).toISOString(),parts:_e(e.displayText,e.attachments),sequence:null,rating:null,ratingNote:null,streaming:!1,stored:!1,restored:!1};n&&(w.clear(),C.clear()),V({messages:[...t,ee],thinking:!0,streaming:!0,steps:[],turnError:null,stopped:!1,...n?{editing:null,attachments:[]}:{}});try{let t=await J();await s.send({conversationId:g.conversationId,text:e.wireText,quickReplyId:e.quickReplyId,attachmentIds:e.attachments.map(e=>e.publicId),replacesMessageId:e.replacesMessageId,pageContext:ze(o),captchaToken:t},{signal:i.signal,onEvent:e=>Z(e,`turn`,a)})}catch(e){if(U(),!a())return;let t=u(e);V({messages:g.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,turnError:t,...t.code===`daily_limit`?{messagesLeftToday:0}:{},...t.code===`conversation_not_found`?{conversationId:null}:{}});return}finally{v===i&&(v=null)}if(await F,!a())return;U(),V({thinking:!1,streaming:!1}),await Q();let c=g.conversationId;o&&c!==null&&c!==Ce&&(Ce=c,f.onEvent?.(`chatStarted`,{conversationId:c}))},Ke=e=>V({messages:g.messages.map(t=>({...t,parts:t.parts.map(t=>t.kind===`Action`&&t.actionId===e.actionId?{...t,state:e.state,decidedDateTimeUtc:e.decidedDateTimeUtc,note:e.note}:t)}))}),qe=async()=>{try{V({openTickets:await s.listOpenTickets()})}catch(e){K(e)}},Je=async()=>{try{let e=await s.listConversations({page:1,pageSize:1});V({lastConversation:e.items[0]??null})}catch(e){K(e)}},Ye=async()=>{let e;try{e=await s.getProfile(f.screen)}catch(e){V({profileError:u(e)});return}let t=ee(e,f.narrow);V({profile:e,profileError:null,features:t,messagesLeftToday:e.messagesLeftToday}),t.OpenTickets&&qe(),t.ResumeLast&&t.History&&Je(),f.conversationId&&await ut(f.conversationId)},Xe=()=>(b||=Ye(),b),Ze=async e=>{let t=typeof e==`string`?e.trim():``,n=g.attachments.filter(e=>e.status===`Ready`);if(t===``&&n.length===0||g.streaming||g.attachments.some(e=>e.status===`Uploading`))return;let r=g.messages,i=null;if(g.editing){let e=g.messages.findIndex(e=>e.id===g.editing?.messageId),t=g.messages[e];if(!t?.stored)return;i=t.id,r=g.messages.slice(0,e)}let a=n.map(e=>Le(e.key));await $({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,attachments:a},r,!0)},Qe=async e=>{e.action!==`Send`||L()||(e.id===`handoff.request`&&g.features.HumanHandoff&&g.conversationId!==null&&!g.handoffPending?await xt():await $({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,attachments:[]},g.messages,!1))},$e=async(e,t)=>{let n=await J();await s.sendOtp(e,{...t,captchaToken:n})},et=async(t,n,r=null)=>{if(g.streaming)return{ok:!1,errors:{},message:p.errorGeneric};let i=_,a=new l.AbortController,o=()=>i===_&&!a.signal.aborted;v=a,Pe(t,n);let ee=t===g.handoffContactRequestId;V({streaming:!0,thinking:!0});try{let e=await J();await s.answerInput(t,{values:n,codes:r,captchaToken:e,attribution:f.attribution?.()??null},{signal:a.signal,onEvent:e=>Z(e,`turn`,o)})}catch(t){return U(),V({thinking:!1,streaming:!1}),a.signal.aborted?{ok:!1,errors:{},message:p.errorGeneric}:t instanceof e&&t.code===`validation_failed`?{ok:!1,errors:t.errors??{},message:t.message}:t instanceof e&&t.code===`input_request_closed`?(await Q(),{ok:!1,errors:{},message:t.message}):{ok:!1,errors:{},message:u(t).message}}finally{v===a&&(v=null)}return await F,o()&&(U(),V({thinking:!1,streaming:!1}),f.onEvent?.(`inputSubmitted`,{requestId:t}),await Q(),ee&&(V({handoffContactRequestId:null}),await xt().catch(K))),{ok:!0}},tt=async e=>{let t=await s.confirmAction(e);Ke(t),f.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Q()},nt=async(e,t)=>{Ke(await s.rejectAction(e,t)),await Q()},rt=()=>{if(!g.streaming)return;W();let e=v;v=null,e?.abort(),V({messages:g.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,stopped:!0,steps:[],pending:null})},it=async()=>{if(g.streaming||g.turnError===null&&!g.stopped)return;let e=ce(g.messages,e=>e.author.kind===`Visitor`),t=g.messages[e];t!==void 0&&await $(ve(t),g.messages.slice(0,e),!1)},at=async()=>{if(L())return;let e=ce(g.messages,e=>e.author.kind===`Visitor`&&e.stored),t=g.messages[e];t!==void 0&&await $({...ve(t),replacesMessageId:t.id},g.messages.slice(0,e),!1)},ot=e=>{let t=g.messages.find(t=>t.id===e);t?.stored&&t.author.kind===`Visitor`&&(q(),V({editing:{messageId:e,text:le(t.parts)},attachments:[]}))},st=()=>{g.editing&&(q(),V({editing:null,attachments:[]}))},ct=async e=>{let t=g.profile;if(!t||!g.features.Attachments)return;let n=t.limits,r=n.maxAttachments-g.attachments.filter(e=>e.status!==`Failed`).length,i=[],a=[];for(let t of e){let e=ue(t);Se+=1;let o=`file-${Se}`,s={key:o,fileName:e.fileName,contentType:e.contentType,length:e.length??0};r<=0?i.push({...s,status:`Failed`,progress:null,error:p.attachmentLimit(n.maxAttachments)}):e.length!==null&&e.length>n.maxFileBytes||!n.contentTypes.includes(e.contentType)?i.push({...s,status:`Failed`,progress:null,error:p.attachmentFailed}):(--r,i.push({...s,status:`Uploading`,progress:0,error:null}),a.push({key:o,file:t}))}V({attachments:[...g.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Re(e,t)))},lt=async e=>{let t=T.get(e);t&&(T.delete(e),t.abort());let n=w.has(e)?C.get(e):void 0;n&&await s.deleteAttachment(n.publicId),w.delete(e),C.delete(e),V({attachments:g.attachments.filter(t=>t.key!==e)})};async function ut(e){G();let t=_;V({messages:[],conversationId:null,loadError:null,loading:!0,editing:null,thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1});try{let n=await s.getConversation(e);if(t!==_)return;let r=n.messages.map(e=>d(e,!0));je(),Me(r),V({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==_)return;V({loadError:u(e)})}finally{t===_&&V({loading:!1})}}let dt=async()=>{let e=g.lastConversation;e&&await ut(e.publicId)},ft=()=>{q(),G(),W(),je(),V({messages:[],conversationId:null,title:null,conversationState:`Open`,continuesConversationId:null,loadError:null,loading:!1,editing:null,attachments:[],thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1,pending:null}),g.features.OpenTickets&&qe()},pt=(e,t,n)=>{V({messages:Y(e,e=>({...e,rating:t,ratingNote:n}))})},mt=async(e,t,n)=>{let r=g.messages.find(t=>t.id===e);if(!r?.stored)throw Error(`Only a stored reply can be rated.`);let i={rating:r.rating,ratingNote:r.ratingNote},a=typeof n==`string`&&n.trim()?n.trim():null;pt(e,t,a);try{await s.rateMessage(e,{rating:t,note:a})}catch(t){throw pt(e,i.rating,i.ratingNote),t}f.onEvent?.(`rated`,{messageId:e,rating:t})},ht=e=>{let t=g.open,n=e?.trigger??`manual`,r=e?.draft,i={open:!0};typeof r==`string`&&r.trim()!==``&&(i.draft=r),!t&&n===`auto`&&m?.set(`wchat:auto-opened`,`1`),V(i),t||f.onEvent?.(`chatOpened`,{layout:f.layout??null,trigger:n})},gt=e=>{g.open&&(m?.set(`wchat:dismissed`,`1`),V({open:!1}),f.onEvent?.(`chatClosed`,{layout:f.layout??null,reason:e}))},_t=e=>{m?.set(`wchat:muted`,e?`1`:`0`),V({muted:e}),f.onEvent?.(`chatSoundToggled`,{muted:e})},vt=async e=>{L()||(e===g.handoffContactRequestId&&V({handoffContactRequestId:null}),f.onEvent?.(`chatLeadSkipped`,{requestId:e}),await $({wireText:null,displayText:p.skip,quickReplyId:`lead.skip`,replacesMessageId:null,attachments:[]},g.messages,!1))},yt=async()=>{L()||(f.onEvent?.(`chatLeadCancelled`,{}),await $({wireText:null,displayText:p.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,attachments:[]},g.messages,!1))},bt=async(e,t)=>{L()||g.messages.some(t=>t.parts.some(t=>t.kind===`Action`&&t.actionId===e))&&await $({wireText:null,displayText:p.editSomething,quickReplyId:`lead.edit:${t}`,replacesMessageId:null,attachments:[]},g.messages,!1)},xt=async t=>{if(!g.features.HumanHandoff)throw new e(`chat_feature_off`,r.errorGeneric,403);let n=g.conversationId;if(n===null)throw new e(`conversation_required`,r.errorGeneric);if(g.streaming||g.handoffPending)throw new e(`busy`,r.errorGeneric);let i=new l.AbortController;j=i,V({handoffPending:!0}),f.onEvent?.(`chatHandoffRequested`,{conversationId:n});let a=null;try{a=pe((await s.requestHandoff({conversationId:n,reason:t??null},{signal:i.signal,onEvent:e=>Z(e,`handoff`,()=>!i.signal.aborted)})).parts)}catch(e){throw V({messages:g.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{j===i&&(j=null)}V({handoffPending:!1,handoffContactRequestId:a}),await Q(),f.onEvent?.(`chatHandoff`,{destination:`person`})},St=()=>{let e=g.conversationId;if(!g.features.HumanHandoff||e===null||g.conversationState!==`WithAgent`)return;let t=Date.now();k!==null&&t-k<re||(k=t,Promise.allSettled([s.sendTyping(e)]))},Ct=e=>{we=e,B()},wt=()=>{g.live===`Lost`&&Fe()&&(z(null),B())},Tt=e=>{if(f.reducedMotion?.()===!0)return ie;let t=e.navigateAfterMs;if(typeof t==`number`&&Number.isFinite(t)&&t>=0)return t;let n=g.profile?.experience.pacing.handoffPauseMs;return typeof n==`number`&&Number.isFinite(n)?n:ae},Et=()=>{ke(),g.handoffPause&&V({handoffPause:!1})};return{client:s,getState:()=>g,subscribe:e=>(h.add(e),b||Xe(),()=>{h.delete(e)}),load:Xe,submit:Ze,chooseQuickReply:Qe,answerInput:et,sendOtp:$e,confirmAction:tt,rejectAction:nt,stop:rt,retry:it,regenerate:at,startEdit:ot,cancelEdit:st,attach:ct,removeAttachment:lt,openConversation:ut,resumeLast:dt,newConversation:ft,rate:mt,open:ht,close:gt,setMuted:_t,skipField:vt,cancelLead:yt,editLeadField:bt,requestHandoff:xt,notifyTyping:St,setLiveActive:Ct,resumeLive:wt,beginHandoff:(e,t)=>{g.handoffPause||(V({handoffPause:!0}),f.onEvent?.(`chatHandoff`,{destination:e.id}),A=l.setTimeout(()=>{A=null;try{t()}catch(e){Et(),K(e)}},Tt(e)))},endHandoffPause:Et,consumeDraft:()=>{g.draft!==null&&V({draft:null})},loadAttachmentUrl:t=>{let n=P.get(t);if(n)return n;let r=(async()=>{let n=l.createObjectUrl;if(!n)throw new e(`unsupported`,p.errorGeneric);let r=await s.getAttachment(t);if(Te)throw new e(`aborted`,p.errorGeneric);let i=n(r);return N.add(i),i})();return P.set(t,r),r.catch(()=>{P.get(t)===r&&P.delete(t)}),r},reset:()=>{q(),W(),G(),b=null,F=Promise.resolve(),I=0,S.clear(),Ce=null,je(),R(),ke(),V(ye(m))},dispose:()=>{h.clear(),Te=!0,_+=1;let e=v;v=null,e?.abort(),j?.abort(),j=null,ke(),R(),z(null),q(),W();let t=l.revokeObjectUrl;for(let e of N)t?.(e);N.clear(),P.clear(),V({attachments:[],editing:null,agentTyping:null})}}},be=e=>{let t=-1;for(let n=e.length-1;n>=0;--n)if(e[n]?.parts.some(e=>e.kind===`Handoff`)){t=n;break}let n=/* @__PURE__ */ new Set;for(let r=0;r<t;r+=1){let t=e[r]?.id;t!==void 0&&n.add(t)}return n},m=(e,t)=>({get features(){return e.getState().features},labels:t.labels,get isLast(){let n=e.getState().messages;return n[n.length-1]?.id===t.messageId},get busy(){let t=e.getState();return t.streaming||t.thinking},get handoffPause(){return e.getState().handoffPause},get handoffSettled(){return be(e.getState().messages).has(t.messageId)},chooseQuickReply(t){e.chooseQuickReply(t)},skipInput(t){e.skipField(t)},cancelLead(){e.cancelLead()},answerInput:(t,n,r)=>e.answerInput(t,n,r),uploadInputFile:async(t,n)=>(await e.client.uploadAttachment(t,n?{onProgress:n}:{})).publicId,sendOtp:(t,n)=>e.sendOtp(t,n),confirmAction:t=>e.confirmAction(t),rejectAction:(t,n)=>e.rejectAction(t,n),requestHandoff:t=>e.requestHandoff(t),beginHandoff:(t,n)=>e.beginHandoff(t,n),readAttachment:t=>e.client.getAttachment(t),loadAttachmentUrl:t=>e.loadAttachmentUrl(t),...t.openAttachment?{openAttachment:t.openAttachment}:{},...t.openRecord?{openRecord:t.openRecord}:{},...t.openTicket?{openTicket:t.openTicket}:{},...t.attachmentUrl?{attachmentUrl:t.attachmentUrl}:{},...t.handoffHosts?{handoffHosts:t.handoffHosts}:{},...t.openCitation?{openCitation:t.openCitation}:{},...t.isCitation?{isCitation:t.isCitation}:{},...t.openTarget?{openTarget:t.openTarget}:{},...t.onNavigate?{onNavigate:t.onNavigate}:{}});export{p as createChatSession,m as createTurnApi,be as handoffSettledIds};
package/dist/stream.js CHANGED
@@ -1,7 +1,7 @@
1
- var e=e=>{let t=``,n=t=>{let n=`message`,r=[];for(let e of t.split(`
1
+ import{decodeChatStreamEvent as e}from"./decode/events.js";import{ChatDecodeError as t}from"./decode/primitives.js";var n=e=>{let t=``,n=t=>{let n=`message`,r=[];for(let e of t.split(`
2
2
  `)){if(e===``||e.startsWith(`:`))continue;let t=e.indexOf(`:`),i=t===-1?e:e.slice(0,t),a=t===-1?``:e.slice(t+1);a.startsWith(` `)&&(a=a.slice(1)),i===`event`?n=a:i===`data`&&r.push(a)}if(r.length===0)return;let i;try{i=JSON.parse(r.join(`
3
- `))}catch{e({name:`error`,data:{code:`invalid-response`,message:null}});return}e({name:n,data:i})};return{push(e){if(!e)return;t=(t+e).replace(/\r\n/g,`
3
+ `))}catch{e({name:`error`,data:{code:`invalid-response`,message:``}});return}e({name:n,data:i})};return{push(e){if(!e)return;t=(t+e).replace(/\r\n/g,`
4
4
  `).replace(/\r(?!$)/g,`
5
5
  `);let r=t.split(`
6
6
 
7
- `);t=r.pop()??``;for(let e of r)n(e)},end(){let e=t.replace(/\r$/,``);t=``,e.trim()&&n(e)}}},t=/* @__PURE__ */ new Set([`messageStarted`,`partStarted`,`partDelta`,`partCompleted`,`messageReset`,`step`,`messageCompleted`,`conversationUpdated`,`typing`,`error`]),n=e=>typeof e==`object`&&e?e:{},r=r=>{let i=null,a=null,o=e(({name:e,data:o})=>{if(a||!t.has(e))return;if(e===`error`){let e=n(o);a={code:typeof e.code==`string`?e.code:``,message:typeof e.message==`string`?e.message:``};return}let s={name:e,data:o};s.name===`messageCompleted`&&(i=s.data.message),r?.(s)});return{push:e=>o.push(e),end:()=>o.end(),get last(){return i},get failure(){return a}}};export{e as createSseParser,r as createStreamReader};
7
+ `);t=r.pop()??``;for(let e of r)n(e)},end(){let e=t.replace(/\r$/,``);t=``,e.trim()&&n(e)}}},r=r=>{let i=null,a=null,o=n(({name:n,data:o})=>{if(a)return;let s;try{s=e(n,o)}catch(e){if(!(e instanceof t))throw e;a={code:`invalid-response`,message:``};return}s.name===`error`?a={code:s.data.code,message:s.data.message}:(s.name===`messageCompleted`&&(i=s.data.message),r?.(s))});return{push:e=>o.push(e),end:()=>o.end(),get last(){return i},get failure(){return a}}};export{n as createSseParser,r as createStreamReader};
@@ -1,4 +1,4 @@
1
- import{formatFigure as e,toFigureText as t}from"./figures.js";import{formatChatDate as n,formatChatValue as r,formatFileSize as i,messagePlainText as a}from"./format.js";var o=e=>e;function s(e){return e!=null&&e.trim()!==``}function c(e){return{kind:`paragraph`,text:e}}function l(e){return e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e!==``).map(c)}function u(e){return e.url!==null&&(e.url.startsWith(`http://`)||e.url.startsWith(`https://`))?`${e.title} (${e.url})`:e.title}function d(e,t){return t===null?e:`${e??``} (${t})`.trim()}function f(e){let t=[],n=/* @__PURE__ */ new Set,i=e.map(e=>{let r=/* @__PURE__ */ new Map;for(let i of e.points)r.set(i.label,i.value),n.has(i.label)||(n.add(i.label),t.push(i.label));return r});return t.map(e=>[e,...i.map(t=>{let n=t.get(e);return n===void 0?``:r(n,`Decimal`,null)})])}function p(e){return e.map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``)}function m(t){return Math.abs(t)<.001&&t!==0?p(e(t)):r(t,`Decimal`,null)}function h(e,t){switch(e.kind){case`Text`:case`Notice`:return l(a([e]));case`Sources`:return e.sources.length===0?[]:[c(t.sources),{kind:`list`,ordered:!0,items:e.sources.map(u)}];case`QuickReplies`:case`Handoff`:return[];case`InputRequest`:return e.state!==`Answered`||!s(e.answeredSummary)?[]:[c(e.title===null?e.answeredSummary:`${e.title}: ${e.answeredSummary}`)];case`Action`:{let t=[c(e.title)];return e.lines.length>0&&t.push({kind:`list`,ordered:!1,items:[...e.lines]}),t}case`Table`:return[{kind:`table`,title:e.title,head:e.columns.map(e=>e.label),rows:e.rows.map(t=>e.columns.map((n,i)=>r(t[i],n.type,e.currency)))}];case`Chart`:return e.series.length===0?[]:[{kind:`table`,title:d(e.title,e.unit),head:[``,...e.series.map(e=>e.name)],rows:f(e.series)}];case`Figures`:return e.figures.length===0?[]:[{kind:`table`,title:null,head:[],rows:e.figures.map(e=>[e.label,m(e.value)+(s(e.unit)?` ${e.unit}`:``)])}];case`RecordCard`:{let t=[c(e.subtitle===null?e.title:`${e.title} ${e.subtitle}`)];return e.fields.length>0&&t.push({kind:`table`,title:null,head:[],rows:e.fields.map(e=>[e.label,r(e.value,e.type,null)])}),t}case`Image`:return s(e.alt)?[c(e.alt)]:[];case`File`:return[c(`${e.fileName} (${i(e.length)})`)];case`Ticket`:return[c(`${e.number} ${e.subject}`)];case`VoiceClip`:return s(e.transcript)?[c(e.transcript)]:[];default:return[]}}function g(e,t){switch(e.kind){case`paragraph`:return{kind:`paragraph`,text:t(e.text)};case`list`:return{kind:`list`,ordered:e.ordered,items:e.items.map(e=>t(e))};case`table`:return{kind:`table`,title:e.title===null?null:t(e.title),head:e.head.map(e=>t(e)),rows:e.rows.map(e=>e.map(e=>t(e)))}}}function _(e,t,n){switch(e.kind){case`Visitor`:case`Customer`:return t.you;case`Agent`:return s(e.displayName)?e.displayName:t.agent;case`Assistant`:case`Script`:return s(e.displayName)?e.displayName:s(n)?n:t.assistant;case`System`:throw Error(`A System message has no speaker: buildTranscript skips it.`)}}function v(e,r){let i=r.figureText?t:o,a=[],c=null;for(let t of e){if(t.streaming||t.author.kind===`System`)continue;let e=t.parts.flatMap(e=>h(e,r.labels)).map(e=>g(e,i));e.length!==0&&(a.push({speaker:_(t.author,r.labels,r.assistantName),blocks:e}),c===null&&(c=n(t.createdDateTimeUtc)))}return{title:s(r.title)?r.title:r.labels.untitled,dateText:c,entries:a}}function y(e){switch(e.kind){case`paragraph`:return[e.text];case`list`:return e.items.map((t,n)=>e.ordered?`${n+1}. ${t}`:`- ${t}`);case`table`:{let t=[];e.title!==null&&t.push(e.title),e.head.length>0&&t.push(e.head.join(` | `));for(let n of e.rows)t.push(n.join(` | `));return t}}}function b(e,t){let n=[];t.heading&&n.push([e.title,...e.dateText===null?[]:[e.dateText]].join(`
1
+ import{formatFigure as e,toFigureText as t}from"./figures.js";import{formatChatDate as n,formatChatValue as r,formatFileSize as i,messagePlainText as a}from"./format.js";var o=e=>e;function s(e){return e!=null&&e.trim()!==``}function c(e){return{kind:`paragraph`,text:e}}function l(e){return e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e!==``).map(c)}function u(e){return e.url!==null&&(e.url.startsWith(`http://`)||e.url.startsWith(`https://`))?`${e.title} (${e.url})`:e.title}function d(e,t){return t===null?e:`${e??``} (${t})`.trim()}function f(e){let t=[],n=/* @__PURE__ */ new Set,i=e.map(e=>{let r=/* @__PURE__ */ new Map;for(let i of e.points)r.set(i.label,i.value),n.has(i.label)||(n.add(i.label),t.push(i.label));return r});return t.map(e=>[e,...i.map(t=>{let n=t.get(e);return n===void 0?``:r(n,`Decimal`,null)})])}function p(e){return e.map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``)}function m(t){return Math.abs(t)<.001&&t!==0?p(e(t)):r(t,`Decimal`,null)}function h(e,t){switch(e.kind){case`Text`:case`Notice`:return l(a([e]));case`Sources`:return e.sources.length===0?[]:[c(t.sources),{kind:`list`,ordered:!0,items:e.sources.map(u)}];case`QuickReplies`:case`Handoff`:return[];case`InputRequest`:return e.state!==`Answered`||!s(e.answeredSummary)?[]:[c(e.title===null?e.answeredSummary:`${e.title}: ${e.answeredSummary}`)];case`Action`:{let t=[c(e.title)];return e.lines.length>0&&t.push({kind:`list`,ordered:!1,items:[...e.lines]}),t}case`Table`:return[{kind:`table`,title:e.title,head:e.columns.map(e=>e.label),rows:e.rows.map(t=>e.columns.map((n,i)=>r(t[i]??null,n.type,e.currency)))}];case`Chart`:return e.series.length===0?[]:[{kind:`table`,title:d(e.title,e.unit),head:[``,...e.series.map(e=>e.name)],rows:f(e.series)}];case`Figures`:return e.figures.length===0?[]:[{kind:`table`,title:null,head:[],rows:e.figures.map(e=>[e.label,m(e.value)+(s(e.unit)?` ${e.unit}`:``)])}];case`RecordCard`:{let t=[c(e.subtitle===null?e.title:`${e.title} ${e.subtitle}`)];return e.fields.length>0&&t.push({kind:`table`,title:null,head:[],rows:e.fields.map(e=>[e.label,r(e.value,e.type,null)])}),t}case`Image`:return s(e.alt)?[c(e.alt)]:[];case`File`:return[c(`${e.fileName} (${i(e.length)})`)];case`Ticket`:return[c(`${e.number} ${e.subject}`)];case`VoiceClip`:return s(e.transcript)?[c(e.transcript)]:[];default:return[]}}function g(e,t){switch(e.kind){case`paragraph`:return{kind:`paragraph`,text:t(e.text)};case`list`:return{kind:`list`,ordered:e.ordered,items:e.items.map(e=>t(e))};case`table`:return{kind:`table`,title:e.title===null?null:t(e.title),head:e.head.map(e=>t(e)),rows:e.rows.map(e=>e.map(e=>t(e)))}}}function _(e,t,n){switch(e.kind){case`Visitor`:case`Customer`:return t.you;case`Agent`:return s(e.displayName)?e.displayName:t.agent;case`Assistant`:case`Script`:return s(e.displayName)?e.displayName:s(n)?n:t.assistant;case`System`:throw Error(`A System message has no speaker: buildTranscript skips it.`)}}function v(e,r){let i=r.figureText?t:o,a=[],c=null;for(let t of e){if(t.streaming||t.author.kind===`System`)continue;let e=t.parts.flatMap(e=>h(e,r.labels)).map(e=>g(e,i));e.length!==0&&(a.push({speaker:_(t.author,r.labels,r.assistantName),blocks:e}),c===null&&(c=n(t.createdDateTimeUtc)))}return{title:s(r.title)?r.title:r.labels.untitled,dateText:c,entries:a}}function y(e){switch(e.kind){case`paragraph`:return[e.text];case`list`:return e.items.map((t,n)=>e.ordered?`${n+1}. ${t}`:`- ${t}`);case`table`:{let t=[];e.title!==null&&t.push(e.title),e.head.length>0&&t.push(e.head.join(` | `));for(let n of e.rows)t.push(n.join(` | `));return t}}}function b(e,t){let n=[];t.heading&&n.push([e.title,...e.dateText===null?[]:[e.dateText]].join(`
2
2
  `));for(let r of e.entries){let e=t.speakers?[`${r.speaker}:`]:[];for(let t of r.blocks)e.push(...y(t));n.push(e.join(`
3
3
  `))}return n.join(`
4
4
 
@@ -451,7 +451,9 @@ export interface ChatSendRequest {
451
451
  pageContext: unknown;
452
452
  captchaToken: string | null;
453
453
  }
454
- export type ChatSendInput = Partial<ChatSendRequest>;
454
+ export type ChatSendInput = {
455
+ [K in keyof ChatSendRequest]?: ChatSendRequest[K] | undefined;
456
+ };
455
457
  export interface ChatInputAnswer {
456
458
  values: Record<string, string>;
457
459
  captchaToken?: string | null;
@@ -601,6 +603,8 @@ export interface PagedDataObject<T> {
601
603
  pageSize: number;
602
604
  totalCount: number;
603
605
  totalPages: number;
606
+ /** True when the server stopped counting at its cap, so totalCount is a floor and more pages may follow totalPages. */
607
+ totalCountCapped: boolean;
604
608
  }
605
609
  export interface ChatHttpRequestConfig {
606
610
  headers?: Record<string, string>;
@@ -0,0 +1,19 @@
1
+ import type { ChatActionState, ChatAuthorKind, ChatCaptchaMode, ChatChartType, ChatColumnType, ChatConversationState, ChatFieldType, ChatFieldVerification, ChatFigureStatus, ChatHandoffState, ChatInputRequestState, ChatNoticeCode, ChatPartKind, ChatQuickReplyAction, ChatQuickReplyPlacement, ChatQuickReplyVariant, ChatRating, ChatStreamEventName } from "../contract";
2
+ export declare const ChatActionStateValues: readonly ChatActionState[];
3
+ export declare const ChatAuthorKindValues: readonly ChatAuthorKind[];
4
+ export declare const ChatCaptchaModeValues: readonly ChatCaptchaMode[];
5
+ export declare const ChatChartTypeValues: readonly ChatChartType[];
6
+ export declare const ChatColumnTypeValues: readonly ChatColumnType[];
7
+ export declare const ChatConversationStateValues: readonly ChatConversationState[];
8
+ export declare const ChatFieldTypeValues: readonly ChatFieldType[];
9
+ export declare const ChatFieldVerificationValues: readonly ChatFieldVerification[];
10
+ export declare const ChatFigureStatusValues: readonly ChatFigureStatus[];
11
+ export declare const ChatHandoffStateValues: readonly ChatHandoffState[];
12
+ export declare const ChatInputRequestStateValues: readonly ChatInputRequestState[];
13
+ export declare const ChatNoticeCodeValues: readonly ChatNoticeCode[];
14
+ export declare const ChatPartKindValues: readonly ChatPartKind[];
15
+ export declare const ChatQuickReplyActionValues: readonly ChatQuickReplyAction[];
16
+ export declare const ChatQuickReplyPlacementValues: readonly ChatQuickReplyPlacement[];
17
+ export declare const ChatQuickReplyVariantValues: readonly ChatQuickReplyVariant[];
18
+ export declare const ChatRatingValues: readonly ChatRating[];
19
+ export declare const ChatStreamEventNameValues: readonly ChatStreamEventName[];
@@ -0,0 +1,3 @@
1
+ import type { ChatStreamEvent } from "../contract";
2
+ /** One server-sent event, checked against the contract; an event name the contract does not know is refused. */
3
+ export declare const decodeChatStreamEvent: (name: string, data: unknown) => ChatStreamEvent;
@@ -0,0 +1,3 @@
1
+ import type { ChatFixture } from "../fixtureClient";
2
+ /** Reads a fixture conversation file (`fixtures/conversations/*.json`) into the shape the fixture client plays. */
3
+ export declare const decodeChatFixture: (value: unknown, path?: string) => ChatFixture;
@@ -0,0 +1,6 @@
1
+ export { decodeChatStreamEvent } from "./events";
2
+ export { decodeChatFixture } from "./fixture";
3
+ export { decodeChatConversationView, decodeChatMessageView } from "./messages";
4
+ export { decodeChatPart } from "./parts";
5
+ export { ChatDecodeError } from "./primitives";
6
+ export { decodeChatProfileView } from "./profile";
@@ -0,0 +1,10 @@
1
+ import type { ChatAuthor, ChatAuthorKind, ChatConversationState, ChatConversationSummary, ChatConversationView, ChatMessageView, ChatRating, PagedDataObject } from "../contract";
2
+ import { type Decoder } from "./primitives";
3
+ export declare const decodeChatAuthorKind: Decoder<ChatAuthorKind>;
4
+ export declare const decodeChatRating: Decoder<ChatRating>;
5
+ export declare const decodeChatConversationState: Decoder<ChatConversationState>;
6
+ export declare const decodeChatAuthor: Decoder<ChatAuthor>;
7
+ export declare const decodeChatMessageView: Decoder<ChatMessageView>;
8
+ export declare const decodeChatConversationView: Decoder<ChatConversationView>;
9
+ export declare const decodeChatConversationSummary: Decoder<ChatConversationSummary>;
10
+ export declare const decodeChatConversationSummaryPage: Decoder<PagedDataObject<ChatConversationSummary>>;
@@ -0,0 +1,15 @@
1
+ import type { ChatChartPoint, ChatChartSeries, ChatFigure, ChatInputField, ChatInputOption, ChatPart, ChatParticipant, ChatQuickReply, ChatRecordField, ChatRecordTarget, ChatSource, ChatTableColumn, ChatTimeSlot } from "../contract";
2
+ import { type Decoder } from "./primitives";
3
+ export declare const decodeChatSource: Decoder<ChatSource>;
4
+ export declare const decodeChatInputOption: Decoder<ChatInputOption>;
5
+ export declare const decodeChatTimeSlot: Decoder<ChatTimeSlot>;
6
+ export declare const decodeChatQuickReply: Decoder<ChatQuickReply>;
7
+ export declare const decodeChatInputField: Decoder<ChatInputField>;
8
+ export declare const decodeChatTableColumn: Decoder<ChatTableColumn>;
9
+ export declare const decodeChatChartPoint: Decoder<ChatChartPoint>;
10
+ export declare const decodeChatChartSeries: Decoder<ChatChartSeries>;
11
+ export declare const decodeChatFigure: Decoder<ChatFigure>;
12
+ export declare const decodeChatRecordField: Decoder<ChatRecordField>;
13
+ export declare const decodeChatRecordTarget: Decoder<ChatRecordTarget>;
14
+ export declare const decodeChatParticipant: Decoder<ChatParticipant>;
15
+ export declare const decodeChatPart: Decoder<ChatPart>;
@@ -0,0 +1,35 @@
1
+ /** Reads one wire value at `path` into its contract type, or throws ChatDecodeError naming the path. */
2
+ export type Decoder<T> = (value: unknown, path: string) => T;
3
+ export declare class ChatDecodeError extends Error {
4
+ readonly path: string;
5
+ constructor(path: string, expected: string);
6
+ }
7
+ export declare const record: (value: unknown, path: string) => Record<string, unknown>;
8
+ export declare const field: <T>(source: Record<string, unknown>, key: string, decode: Decoder<T>, path: string) => T;
9
+ export declare const string: Decoder<string>;
10
+ export declare const number: Decoder<number>;
11
+ export declare const boolean: Decoder<boolean>;
12
+ export declare const arrayBuffer: Decoder<ArrayBuffer>;
13
+ /** The wire sends null for an absent value; a missing key is read the same way. */
14
+ export declare const nullable: <T>(decode: Decoder<T>) => Decoder<T | null>;
15
+ export declare const array: <T>(decode: Decoder<T>) => Decoder<T[]>;
16
+ /**
17
+ * The full member list of a contract union, written once in `enums.ts`. The compiler refuses a list that
18
+ * misses a member (the `missing` property names it) or adds one the union lacks.
19
+ */
20
+ export declare const allMembers: <U extends string>() => <const T extends readonly U[]>(values: T & ([Exclude<U, T[number]>] extends [never] ? unknown : {
21
+ readonly missing: Exclude<U, T[number]>;
22
+ })) => readonly U[];
23
+ /** One member of a closed string union; `values` comes from `allMembers`, so it matches the contract. */
24
+ export declare const oneOf: <U extends string>(values: readonly U[]) => Decoder<U>;
25
+ /** A plain JSON value the contract types as unknown (page context, figure data); passed through unread. */
26
+ export declare const unknownValue: Decoder<unknown>;
27
+ /**
28
+ * A union discriminated by `kind`. A kind the map does not know goes to `unknownKind` when one is given
29
+ * (a newer server's part kind renders as a Notice), and is refused otherwise.
30
+ */
31
+ export declare const unionByKind: <const K extends readonly string[], U extends {
32
+ kind: K[number];
33
+ }>(kinds: K, decoders: { [Kind in K[number]]: Decoder<Extract<U, {
34
+ kind: Kind;
35
+ }>>; }, unknownKind?: (kind: string, path: string) => U) => Decoder<U>;
@@ -0,0 +1,21 @@
1
+ import type { ChatAssistantCopy, ChatAutoOpenSettings, ChatBehaviourSettings, ChatCaptchaMode, ChatCaptchaSettings, ChatExperienceSettings, ChatFieldType, ChatFooterCopy, ChatLauncherSettings, ChatLimits, ChatNudge, ChatPacingSettings, ChatPageRule, ChatProfileView, ChatQuickReplyVariant, ChatSoundSettings, ChatStarter, ChatStarterRule, ChatStartSettings } from "../contract";
2
+ import type { Decoder } from "./primitives";
3
+ export declare const decodeChatQuickReplyVariant: Decoder<ChatQuickReplyVariant>;
4
+ export declare const decodeChatCaptchaMode: Decoder<ChatCaptchaMode>;
5
+ export declare const decodeChatFieldType: Decoder<ChatFieldType>;
6
+ export declare const decodeChatAssistantCopy: Decoder<ChatAssistantCopy>;
7
+ export declare const decodeChatFooterCopy: Decoder<ChatFooterCopy>;
8
+ export declare const decodeChatCaptchaSettings: Decoder<ChatCaptchaSettings>;
9
+ export declare const decodeChatLimits: Decoder<ChatLimits>;
10
+ export declare const decodeChatStarter: Decoder<ChatStarter>;
11
+ export declare const decodeChatPageRule: Decoder<ChatPageRule>;
12
+ export declare const decodeChatNudge: Decoder<ChatNudge>;
13
+ export declare const decodeChatStarterRule: Decoder<ChatStarterRule>;
14
+ export declare const decodeChatBehaviourSettings: Decoder<ChatBehaviourSettings>;
15
+ export declare const decodeChatStartSettings: Decoder<ChatStartSettings>;
16
+ export declare const decodeChatSoundSettings: Decoder<ChatSoundSettings>;
17
+ export declare const decodeChatPacingSettings: Decoder<ChatPacingSettings>;
18
+ export declare const decodeChatLauncherSettings: Decoder<ChatLauncherSettings>;
19
+ export declare const decodeChatAutoOpenSettings: Decoder<ChatAutoOpenSettings>;
20
+ export declare const decodeChatExperienceSettings: Decoder<ChatExperienceSettings>;
21
+ export declare const decodeChatProfileView: Decoder<ChatProfileView>;
@@ -0,0 +1,7 @@
1
+ import type { ChatActionState, ChatActionView, ChatAttachment, ChatOpenTicket, ChatSpeechToken } from "../contract";
2
+ import type { Decoder } from "./primitives";
3
+ export declare const decodeChatActionState: Decoder<ChatActionState>;
4
+ export declare const decodeChatSpeechToken: Decoder<ChatSpeechToken>;
5
+ export declare const decodeChatAttachment: Decoder<ChatAttachment>;
6
+ export declare const decodeChatOpenTicket: Decoder<ChatOpenTicket>;
7
+ export declare const decodeChatActionView: Decoder<ChatActionView>;
@@ -1,4 +1,4 @@
1
1
  import type { ChatFigureRun } from "./contract";
2
- export declare function toFigureRuns(text: string): ChatFigureRun[];
2
+ export declare function toFigureRuns(text: string | null | undefined): ChatFigureRun[];
3
3
  export declare function toFigureText(text: string): string;
4
4
  export declare function formatFigure(value: number): ChatFigureRun[];
@@ -0,0 +1,3 @@
1
+ export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
2
+ /** The value's own fields, or none when it is not a plain object; a read of a missing field is then undefined. */
3
+ export declare const asRecord: (value: unknown) => Record<string, unknown>;
@@ -0,0 +1,3 @@
1
+ import type { ChatSession, ChatSessionState } from "./session";
2
+ export declare const IDLE_CHAT_STATE: ChatSessionState;
3
+ export declare const IDLE_CHAT_SESSION: ChatSession;
@@ -2,12 +2,14 @@ export * from "./audioType";
2
2
  export * from "./client";
3
3
  export * from "./contract";
4
4
  export * from "./conversationList";
5
+ export * from "./decode";
5
6
  export * from "./dictation";
6
7
  export * from "./explain";
7
8
  export * from "./figures";
8
9
  export * from "./fixtureClient";
9
10
  export * from "./format";
10
11
  export * from "./handoff";
12
+ export * from "./idleSession";
11
13
  export * from "./labels";
12
14
  export * from "./look";
13
15
  export * from "./pacing";
@@ -1,5 +1,7 @@
1
1
  import type { ChatFeature, ChatNudge, ChatProfileView, ChatStarter } from "./contract";
2
2
  export declare const CHAT_FEATURES: readonly ChatFeature[];
3
+ /** One value per feature; the literal names every ChatFeature, so the compiler refuses a missing or extra key. */
4
+ export declare const featureRecord: (value: (feature: ChatFeature) => boolean) => Record<ChatFeature, boolean>;
3
5
  export declare const emptyFeatures: () => Record<ChatFeature, boolean>;
4
6
  export declare const resolveFeatures: (profile: ChatProfileView, narrow?: Partial<Record<ChatFeature, boolean>>) => Readonly<Record<ChatFeature, boolean>>;
5
7
  export declare const resolveStart: (profile: ChatProfileView, { pathname, returning }: {
@@ -0,0 +1,35 @@
1
+ import type { ChatAbortSignal } from "./contract";
2
+ export interface AbortControllerLike {
3
+ readonly signal: ChatAbortSignal;
4
+ abort(): void;
5
+ }
6
+ export interface FormDataLike {
7
+ append(name: string, value: unknown, fileName?: string): void;
8
+ }
9
+ /** A host FormData: `append` writes into it, and `native` is the host object the request sends. */
10
+ export interface HostFormData extends FormDataLike {
11
+ readonly native: unknown;
12
+ }
13
+ /** The host globals the engine uses, each read and checked when called. Optional ones are absent on some hosts. */
14
+ export interface EngineRuntime {
15
+ AbortController: new () => AbortControllerLike;
16
+ setTimeout: (callback: () => void, ms: number) => number;
17
+ clearTimeout: (id: number) => void;
18
+ requestAnimationFrame?: ((callback: () => void) => number) | undefined;
19
+ cancelAnimationFrame?: ((id: number) => void) | undefined;
20
+ navigator?: {
21
+ onLine?: boolean;
22
+ } | undefined;
23
+ addEventListener?: ((type: string, listener: () => void) => void) | undefined;
24
+ removeEventListener?: ((type: string, listener: () => void) => void) | undefined;
25
+ location?: {
26
+ pathname?: string;
27
+ } | undefined;
28
+ createFormData?: (() => HostFormData) | undefined;
29
+ createObjectUrl?: ((bytes: ArrayBuffer) => string) | undefined;
30
+ revokeObjectUrl?: ((url: string) => void) | undefined;
31
+ crypto?: {
32
+ randomUUID?: () => string;
33
+ } | undefined;
34
+ }
35
+ export declare const runtime: EngineRuntime;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/chat-core",
3
- "version": "0.141.0",
3
+ "version": "0.142.0",
4
4
  "description": "The headless Webority Chat engine: the client over the chat routes, the session state machine over message parts, the stream reader, profile resolution with screen narrowing, the default English labels and a fixture client for sandboxes and tests. No DOM and no UI.",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "type": "module",
@@ -26,13 +26,13 @@
26
26
  },
27
27
  "sideEffects": false,
28
28
  "peerDependencies": {
29
- "@webority/markdown-core": "^0.149.0"
29
+ "@webority/markdown-core": "^0.150.0"
30
30
  },
31
31
  "devDependencies": {
32
- "@webority/markdown-core": "0.149.0",
32
+ "@webority/markdown-core": "0.150.0",
33
33
  "typescript": "^7.0.2",
34
- "vite": "^8.0.12",
35
- "vitest": "5.0.1"
34
+ "vite": "^8.3.6",
35
+ "vitest": "5.1.0"
36
36
  },
37
37
  "scripts": {
38
38
  "build": "vite build && tsc -p tsconfig.json",