@docgenlab.com/chat-widget 0.4.2 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +12 -0
- package/dist/index.js +561 -463
- package/dist/index.js.map +1 -1
- package/dist/index.umd.cjs +6 -6
- package/dist/index.umd.cjs.map +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
(function(I,
|
|
1
|
+
(function(I,K){typeof exports=="object"&&typeof module!="undefined"?K(exports,require("react-dom/client"),require("react")):typeof define=="function"&&define.amd?define(["exports","react-dom/client","react"],K):(I=typeof globalThis!="undefined"?globalThis:I||self,K(I.DocGenLab={},I.ReactDOM,I.React))})(this,function(I,K,d){"use strict";function Ue(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const l in t)if(l!=="default"){const r=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(n,l,r.get?r:{enumerable:!0,get:()=>t[l]})}}return n.default=t,Object.freeze(n)}const e=Ue(d),$="/api/v1/public/kb",se="dgl-visitor-id";function ce(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const l=Math.random()*16|0;return(n==="x"?l:l&3|8).toString(16)})}function Le(){try{let t=localStorage.getItem(se);return t||(t=ce(),localStorage.setItem(se,t)),t}catch(t){return ce()}}class $e{constructor(n){this.agentKey=n.agentKey,this.baseUrl=n.apiBaseUrl.replace(/\/+$/,""),this.visitorId=n.endUserId?`user:${n.endUserId}`:Le(),this.endUserHash=n.endUserHash}headers(n){const l={"X-DocGenLab-Key":this.agentKey,"X-DocGenLab-Visitor-Id":this.visitorId,...n||{}};return this.endUserHash&&(l["X-DocGenLab-User-Hash"]=this.endUserHash),l}async getAgent(){const n=await fetch(`${this.baseUrl}${$}/agent`,{method:"GET",headers:this.headers()});if(!n.ok)throw new Error(`getAgent failed: ${n.status}`);return n.json()}async listConversations(){const n=`${this.baseUrl}${$}/conversations`,l=await fetch(n,{headers:this.headers()});if(!l.ok)throw new Error(`listConversations failed: ${l.status}`);return l.json()}async getConversation(n){const l=`${this.baseUrl}${$}/conversations/${encodeURIComponent(n)}`,r=await fetch(l,{headers:this.headers()});if(!r.ok)throw new Error(`getConversation failed: ${r.status}`);return r.json()}async getTicketCardState(n){const l=`${this.baseUrl}${$}/conversations/${encodeURIComponent(n)}/ticket-card`,r=await fetch(l,{headers:this.headers()});if(!r.ok)throw new Error(`getTicketCardState failed: ${r.status}`);return r.json()}async uploadImage(n){const l=new FormData;l.append("file",n);const r=await fetch(`${this.baseUrl}${$}/chat-image`,{method:"POST",headers:this.headers(),body:l});if(!r.ok){let o=`${r.status} ${r.statusText}`;try{const c=await r.json();o=(c==null?void 0:c.detail)||o}catch(c){}throw new Error(o)}return(await r.json()).image_path}async fetchImage(n){const l=`${this.baseUrl}${$}/chat-image?path=${encodeURIComponent(n)}&key=${encodeURIComponent(this.agentKey)}`,r=await fetch(l,{method:"GET",headers:{"X-DocGenLab-Visitor-Id":this.visitorId}});if(!r.ok)throw new Error(`fetchImage failed: ${r.status}`);const a=await r.blob();return URL.createObjectURL(a)}async raiseTicket(n,l){const r=`${this.baseUrl}${$}/conversations/${encodeURIComponent(n)}/raise-ticket`,a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","X-DocGenLab-Key":this.agentKey,"X-DocGenLab-Visitor-Id":this.visitorId,...this.endUserHash?{"X-DocGenLab-User-Hash":this.endUserHash}:{}},body:JSON.stringify(l)});if(!a.ok){let o=`raiseTicket failed: ${a.status}`;try{o=(await a.json()).detail||o}catch(c){}throw new Error(o)}return a.json()}async listTickets(n){const l=n?`?conversation_id=${encodeURIComponent(n)}`:"",r=`${this.baseUrl}${$}/tickets${l}`,a=await fetch(r,{headers:{"X-DocGenLab-Key":this.agentKey,"X-DocGenLab-Visitor-Id":this.visitorId}});if(!a.ok)throw new Error(`listTickets failed: ${a.status}`);return a.json()}async getTicket(n,l=!1){const r=`${this.baseUrl}${$}/tickets/${encodeURIComponent(n)}${l?"?refresh=1":""}`,a=await fetch(r,{headers:{"X-DocGenLab-Key":this.agentKey,"X-DocGenLab-Visitor-Id":this.visitorId}});if(!a.ok)throw new Error(`getTicket failed: ${a.status}`);return a.json()}async fetchSourceFrame(n,l){const r=`${this.baseUrl}${$}/sources/${encodeURIComponent(n)}/frame?path=${encodeURIComponent(l)}&key=${encodeURIComponent(this.agentKey)}`,a=await fetch(r,{method:"GET",headers:{"X-DocGenLab-Visitor-Id":this.visitorId}});if(!a.ok)throw new Error(`fetchSourceFrame failed: ${a.status}`);const o=await a.blob();return URL.createObjectURL(o)}streamChat(n,l){const r=new AbortController;return(async()=>{try{const a=await fetch(`${this.baseUrl}${$}/chat`,{method:"POST",signal:r.signal,headers:this.headers({"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(n)});if(!a.ok||!a.body){let g=`${a.status} ${a.statusText}`;try{const E=await a.json();g=(E==null?void 0:E.detail)||g}catch(E){}l({type:"error",error:g});return}const o=a.body.getReader(),c=new TextDecoder;let i="";for(;;){const{value:g,done:E}=await o.read();if(E)break;i+=c.decode(g,{stream:!0});let x;for(;(x=i.indexOf(`
|
|
2
2
|
|
|
3
|
-
`))!==-1;){const y=i.slice(0,w);i=i.slice(w+2);const b=y.trim();if(b.startsWith("data:"))try{const C=JSON.parse(b.slice(5).trim());r(C)}catch(C){}}}}catch(a){(a==null?void 0:a.name)!=="AbortError"&&r({type:"error",error:(a==null?void 0:a.message)||String(a)})}})(),()=>l.abort()}}const O={apiBaseUrl:"https://api.docgenlab.com",position:"bottom-right",primary:"#4F46E5",primaryText:"#FFFFFF",radius:"14px",fontFamily:'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',greeting:"How can I help you today?",greetingSub:"Ask anything about your uploaded documents. I'll only answer from what's in the knowledge base."};function G(t){var ke,Ee,ye,ve,Ne,we,xe,_e;const n=t.apiBaseUrl||O.apiBaseUrl,r=t.enableImageUpload!==!1,l=d.useRef(null),a=`${t.agentKey}::${t.endUserId||""}::${t.endUserHash||""}`,o=d.useRef("");(!l.current||o.current!==a)&&(l.current=new Ce({agentKey:t.agentKey,apiBaseUrl:n,endUserId:t.endUserId,endUserHash:t.endUserHash}),o.current=a);const s=l.current,[i,m]=d.useState(null),[h,w]=d.useState(null),y=(i==null?void 0:i.widget_config)||{},b={position:t.position||y.position||O.position,primary:((ke=t.theme)==null?void 0:ke.primary)||y.primary_color||O.primary,primaryText:((Ee=t.theme)==null?void 0:Ee.primaryText)||y.primary_text_color||O.primaryText,radius:((ye=t.theme)==null?void 0:ye.radius)||y.radius||O.radius,fontFamily:((ve=t.theme)==null?void 0:ve.fontFamily)||O.fontFamily,greeting:t.greeting||y.greeting||O.greeting,agentName:t.agentName||y.agent_name||(i==null?void 0:i.name)||"Assistant",agentAvatarUrl:t.agentAvatarUrl||y.agent_avatar_url||void 0,launcherAvatarUrl:y.launcher_avatar_url||void 0,hideBranding:(we=(Ne=t.hideBranding)!=null?Ne:y.hide_branding)!=null?we:!1,openOnLoad:(_e=(xe=t.openOnLoad)!=null?xe:y.open_on_load)!=null?_e:!1},C={"--dgl-primary":b.primary,"--dgl-primary-text":b.primaryText,"--dgl-radius":b.radius,"--dgl-font":b.fontFamily},[_,F]=d.useState(b.openOnLoad),[S,K]=d.useState(!1),[E,L]=d.useState([]),[X,J]=d.useState(""),[M,V]=d.useState(!1),[W,Q]=d.useState(null),[ge,Z]=d.useState(null),[T,ee]=d.useState(null),[Y,te]=d.useState(!1),fe=d.useRef(null),ae=d.useRef(null),q=d.useRef(""),z=d.useRef(null),[ne,le]=d.useState([]),[Ze,he]=d.useState(!1);d.useEffect(()=>{!_||i||s.getAgent().then(u=>{var k;m(u),(k=t.onReady)==null||k.call(t,u)}).catch(u=>{var k;w(u.message),(k=t.onError)==null||k.call(t,u.message)})},[_,i,s,t]),d.useEffect(()=>{if(!_||t.disableTicketing)return;let u=!1;return s.listTickets().then(k=>{u||le(k)}).catch(()=>{}),()=>{u=!0}},[_,s,t.disableTicketing]),d.useEffect(()=>{if(!_)return;const u=`dgl-chat:${t.agentKey}`,k=localStorage.getItem(u);if(!k)return;let x=!1;return(async()=>{try{const[v,p]=await Promise.all([s.getConversation(k),s.getTicketCardState(k).catch(()=>null)]);if(x)return;const c=[];for(const U of v.messages||[])U.role==="user"?c.push({id:U.id,role:"user",content:U.content||"",imagePath:U.image_path||void 0}):U.role==="assistant"&&c.push({id:U.id,role:"assistant",content:U.content||"",citations:U.retrieved_chunks||void 0});if(p&&p.kind&&c.length){let U=-1;for(let g=c.length-1;g>=0;g--)if(c[g].role==="assistant"){U=g;break}if(U>=0){const g=c[U];p.kind==="offer"&&p.conversation_id&&p.connector_type&&p.connector_name?g.ticketOffer={conversationId:p.conversation_id,connectorType:p.connector_type,connectorName:p.connector_name}:p.kind==="existing"&&p.ticket_id&&p.status?g.ticketExisting={ticketId:p.ticket_id,externalNumber:p.external_ticket_number||null,externalUrl:p.external_url||null,status:p.status}:p.kind==="created"&&p.ticket_id&&(g.ticketCreated={id:p.ticket_id,externalNumber:p.external_ticket_number||null,externalUrl:p.external_url||null})}}Q(k),L(c)}catch(v){localStorage.removeItem(u)}})(),()=>{x=!0}},[t.agentKey,s,_]),d.useEffect(()=>{W&&localStorage.setItem(`dgl-chat:${t.agentKey}`,W)},[W,t.agentKey]),d.useEffect(()=>{z.current&&(z.current.scrollTop=z.current.scrollHeight)},[E]);const pe=d.useCallback(()=>{T&&URL.revokeObjectURL(T),Z(null),ee(null)},[T]),be=d.useCallback(u=>{if(!u.type.startsWith("image/"))return;const k=10*1024*1024;u.size>k||(T&&URL.revokeObjectURL(T),Z(u),ee(URL.createObjectURL(u)))},[T]),et=async u=>{var p;if(u.preventDefault(),!X.trim()||M||Y)return;const k=X.trim();let x,v;if(ge){try{te(!0),x=await s.uploadImage(ge)}catch(c){(p=t.onError)==null||p.call(t,(c==null?void 0:c.message)||"Image upload failed"),te(!1);return}te(!1),v=T||void 0}J(""),q.current="",L(c=>[...c,{role:"user",content:k,imagePath:x,imagePreviewUrl:v},{role:"assistant",content:"",streaming:!0}]),V(!0),Z(null),ee(null),ae.current=s.streamChat({message:k,conversation_id:W||void 0,image_path:x},c=>{var U;if(c.type==="conversation")Q(c.conversation_id);else if(c.type==="token"){q.current+=c.content;const g=q.current;L(f=>f.map((N,at)=>at===f.length-1&&N.role==="assistant"?{...N,content:g}:N))}else if(c.type==="citations")L(g=>g.map((f,N)=>N===g.length-1&&f.role==="assistant"?{...f,citations:c.citations}:f));else if(c.type==="refused")q.current=c.content,L(g=>g.map((f,N)=>N===g.length-1&&f.role==="assistant"?{...f,content:c.content,refused:!0}:f));else if(c.type==="ticket_offer"){if(t.disableTicketing)return;L(g=>g.map((f,N)=>N===g.length-1&&f.role==="assistant"?{...f,ticketOffer:{conversationId:c.conversation_id,connectorType:c.connector_type,connectorName:c.connector_name}}:f))}else if(c.type==="ticket_existing"){if(t.disableTicketing)return;L(g=>g.map((f,N)=>N===g.length-1&&f.role==="assistant"?{...f,ticketExisting:{ticketId:c.ticket_id,externalNumber:c.external_ticket_number,externalUrl:c.external_url,status:c.status}}:f))}else c.type==="ticket_status_card"?L(g=>g.map((f,N)=>N===g.length-1&&f.role==="assistant"?{...f,ticketStatus:{ticketId:c.ticket_id,externalNumber:c.external_number,externalUrl:c.external_url,status:c.status,title:c.title,priority:c.priority,lastUpdate:c.last_update,assignedTo:c.assigned_to,createdAt:c.created_at}}:f)):c.type==="done"?(L(g=>g.map((f,N)=>N===g.length-1&&f.role==="assistant"?{...f,streaming:!1,id:c.message_id,cacheHit:c.cache_hit}:f)),V(!1)):c.type==="error"&&(L(g=>g.map((f,N)=>N===g.length-1&&f.role==="assistant"?{...f,content:`Error: ${c.error}`,streaming:!1,refused:!0}:f)),V(!1),(U=t.onError)==null||U.call(t,c.error))})},tt=()=>{ae.current&&ae.current(),L([]),Q(null),V(!1),localStorage.removeItem(`dgl-chat:${t.agentKey}`),pe()};return e.createElement("div",{className:`dgl-root dgl-pos-${b.position}`,style:C},_&&e.createElement("div",{className:`dgl-panel ${S?"dgl-panel-expanded":""}`},e.createElement("div",{className:"dgl-header"},e.createElement("div",{className:"dgl-header-info"},b.agentAvatarUrl?e.createElement("img",{src:b.agentAvatarUrl,alt:"",className:"dgl-avatar"}):e.createElement("div",{className:"dgl-avatar dgl-avatar-fallback dgl-avatar-fallback-light"},b.agentName.slice(0,1).toUpperCase()),e.createElement("div",{className:"dgl-header-text"},e.createElement("div",{className:"dgl-title"},b.agentName),(i==null?void 0:i.org_name)&&e.createElement("div",{className:"dgl-subtitle"},i.org_name))),e.createElement("div",{className:"dgl-header-actions"},!t.disableTicketing&&ne.length>0&&e.createElement("button",{type:"button",onClick:()=>he(!0),className:"dgl-tix-btn",title:"Your tickets","aria-label":"Your tickets"},D(),e.createElement("span",null,"Tickets"),e.createElement("span",{className:"dgl-tix-btn-badge"},ne.length)),e.createElement("button",{type:"button",onClick:tt,className:"dgl-icon-btn",title:"New chat","aria-label":"New chat"},Ve()),e.createElement("button",{type:"button",onClick:()=>K(u=>!u),className:"dgl-icon-btn dgl-hide-on-mobile",title:S?"Restore size":"Expand view","aria-label":S?"Restore size":"Expand view"},S?Je():ze()),e.createElement("button",{type:"button",onClick:()=>F(!1),className:"dgl-icon-btn",title:"Close","aria-label":"Close"},H()))),Ze&&e.createElement(Ge,{tickets:ne,onClose:()=>he(!1),onRefresh:async()=>{try{const u=await s.listTickets();le(u)}catch(u){}}}),e.createElement("div",{className:"dgl-messages",ref:z},E.length===0&&!h&&e.createElement("div",{className:"dgl-empty"},e.createElement("div",{className:"dgl-empty-icon"},de()),e.createElement("div",{className:"dgl-empty-text"},b.greeting),e.createElement("div",{className:"dgl-empty-sub"},(i==null?void 0:i.description)||O.greetingSub)),h&&e.createElement("div",{className:"dgl-error"},"Couldn't load the assistant: ",h),E.map((u,k)=>e.createElement(Le,{key:k,message:u,client:s,isLast:k===E.length-1,agentAvatarUrl:b.agentAvatarUrl,onPickFollowup:x=>{J(x)},defaultEmail:t.endUserEmail,defaultPhone:t.endUserPhone,conversationId:W||void 0,onTicketCreated:(x,v)=>{L(p=>p.map(c=>c===x?{...c,ticketOffer:void 0,ticketExisting:void 0,ticketCreated:{id:v.id,externalNumber:v.external_ticket_number,externalUrl:v.external_url}}:c)),le(p=>[v,...p.filter(c=>c.id!==v.id)])}}))),e.createElement("form",{className:"dgl-composer",onSubmit:et},T&&e.createElement("div",{className:"dgl-staged-image"},e.createElement("img",{src:T,alt:"attachment"}),e.createElement("button",{type:"button",onClick:pe,className:"dgl-staged-remove","aria-label":"Remove image"},H())),e.createElement("div",{className:"dgl-composer-row"},r&&e.createElement(e.Fragment,null,e.createElement("button",{type:"button",className:"dgl-icon-btn",onClick:()=>{var u;return(u=fe.current)==null?void 0:u.click()},disabled:M||Y,title:"Attach image","aria-label":"Attach image"},qe()),e.createElement("input",{ref:fe,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",style:{display:"none"},onChange:u=>{var x;const k=(x=u.target.files)==null?void 0:x[0];k&&be(k),u.target&&(u.target.value="")}})),e.createElement("input",{className:"dgl-input",value:X,onChange:u=>J(u.target.value),placeholder:M?"Thinking…":T?"Describe what to know about this image…":"Type your question…",disabled:M,onPaste:u=>{var x;if(!r)return;const k=Array.from(((x=u.clipboardData)==null?void 0:x.items)||[]).find(v=>v.kind==="file"&&v.type.startsWith("image/"));if(k){const v=k.getAsFile();v&&(u.preventDefault(),be(v))}}}),e.createElement("button",{type:"submit",className:"dgl-send-btn",disabled:!X.trim()||M||Y,"aria-label":"Send"},M||Y?R():Ye())),!b.hideBranding&&e.createElement("div",{className:"dgl-branding"},"Powered by ",e.createElement("a",{href:"https://docgenlab.com",target:"_blank",rel:"noopener noreferrer"},"DocGenLab")))),e.createElement("button",{type:"button",className:"dgl-launcher",onClick:()=>F(u=>!u),"aria-label":_?"Close chat":"Open chat"},_?Xe():b.launcherAvatarUrl?e.createElement("img",{src:b.launcherAvatarUrl,alt:"",className:"dgl-launcher-avatar"}):Re()))}function Le({message:t,client:n,isLast:r,agentAvatarUrl:l,onPickFollowup:a,defaultEmail:o,defaultPhone:s,conversationId:i,onTicketCreated:m}){var y;if(t.role==="user")return e.createElement("div",{className:"dgl-msg dgl-msg-user"},e.createElement("div",{className:"dgl-bubble dgl-bubble-user"},(t.imagePath||t.imagePreviewUrl)&&e.createElement($e,{client:n,imagePath:t.imagePath,previewUrl:t.imagePreviewUrl}),t.content));const h=je(t.content),w=t.streaming?[]:Be(t.content);return e.createElement("div",{className:"dgl-msg dgl-msg-assistant"},l?e.createElement("img",{src:l,className:"dgl-avatar",alt:""}):e.createElement("div",{className:"dgl-avatar dgl-avatar-fallback"},de()),e.createElement("div",{className:"dgl-msg-body"},t.refused?e.createElement("div",{className:"dgl-refused"},h):t.ticketStatus?e.createElement(We,{ticket:t.ticketStatus}):e.createElement("div",{className:"dgl-assistant-text"},t.streaming&&!h?e.createElement(De,null):e.createElement(e.Fragment,null,Ae(h),t.streaming&&e.createElement("span",{className:"dgl-typing-cursor"},"▍"))),!t.streaming&&!t.refused&&!!((y=t.citations)!=null&&y.length)&&!t.ticketStatus&&e.createElement(Te,{citations:t.citations,client:n}),!t.streaming&&!t.ticketStatus&&t.ticketCreated?e.createElement(Pe,{created:t.ticketCreated}):!t.streaming&&!t.ticketStatus&&t.ticketExisting?e.createElement(Ke,{existing:t.ticketExisting,client:n,conversationId:i,defaultEmail:o,defaultPhone:s,onNewTicketRaised:b=>m==null?void 0:m(t,b)}):!t.streaming&&!t.ticketStatus&&t.ticketOffer?e.createElement(Me,{client:n,offer:t.ticketOffer,defaultEmail:o,defaultPhone:s,onCreated:b=>m==null?void 0:m(t,b)}):null,w.length>0&&e.createElement(Ie,{suggestions:w,onPick:a})))}function Ie({suggestions:t,onPick:n}){return e.createElement("div",{className:"dgl-followups"},e.createElement("div",{className:"dgl-followups-label"},"Continue exploring"),e.createElement("div",{className:"dgl-followups-list"},t.map((r,l)=>e.createElement("button",{key:l,type:"button",className:"dgl-followup-chip",onClick:()=>n(r)},r))))}function $e({client:t,imagePath:n,previewUrl:r}){const[l,a]=d.useState(r||null),[o,s]=d.useState(!1);return d.useEffect(()=>{if(r||!n)return;let i=null;return t.fetchImage(n).then(m=>{i=m,a(m)}).catch(()=>a(null)),()=>{i&&URL.revokeObjectURL(i)}},[t,n,r]),d.useEffect(()=>{if(!o)return;const i=h=>{h.key==="Escape"&&s(!1)};window.addEventListener("keydown",i);const m=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{window.removeEventListener("keydown",i),document.body.style.overflow=m}},[o]),l?e.createElement(e.Fragment,null,e.createElement("button",{type:"button",onClick:()=>s(!0),className:"dgl-user-image-btn","aria-label":"View image"},e.createElement("img",{src:l,className:"dgl-user-image",alt:"attached"})),o&&e.createElement("div",{className:"dgl-lightbox",role:"dialog","aria-modal":"true",onClick:()=>s(!1)},e.createElement("button",{type:"button",className:"dgl-lightbox-close",onClick:i=>{i.stopPropagation(),s(!1)},"aria-label":"Close image"},H()),e.createElement("img",{src:l,className:"dgl-lightbox-img",alt:"attached",onClick:i=>i.stopPropagation()}))):null}function Te({citations:t,client:n}){const r={};for(const i of t){const m=r[i.source_id];(!m||i.score>m.score)&&(r[i.source_id]=i)}const l=Object.values(r).sort((i,m)=>m.score-i.score).slice(0,3),a=Object.keys(r).length-l.length;if(!l.length)return null;const[o,s]=d.useState(null);return e.createElement("div",{className:"dgl-citations"},l.map(i=>e.createElement(Oe,{key:i.chunk_id,citation:i,client:n,isOpen:o===i.chunk_id,onToggle:()=>s(o===i.chunk_id?null:i.chunk_id)})),a>0&&e.createElement("span",{className:"dgl-citation-more"},"+",a," more"))}function Oe({citation:t,client:n,isOpen:r,onToggle:l}){const a=t,o=!!a.frame_path,s=a.heading?`${a.heading}${a.subheading?" › "+a.subheading:""}`:null,i=a.start_seconds!=null?`${Math.floor(a.start_seconds/60)}:${String(a.start_seconds%60).padStart(2,"0")}`:null;return e.createElement("span",{className:"dgl-citation-wrap"},e.createElement("button",{type:"button",className:`dgl-citation ${r?"dgl-citation-open":""}`,onClick:l,title:a.snippet||""},o&&e.createElement("span",{className:"dgl-citation-icon"},"▶"),a.source_name,i&&e.createElement("span",{className:"dgl-citation-stamp"}," · ",i),a.page&&e.createElement("span",{className:"dgl-citation-stamp"}," · p",a.page)),r&&e.createElement("div",{className:"dgl-citation-popover"},a.frame_path&&e.createElement(Fe,{client:n,sourceId:a.source_id,framePath:a.frame_path}),s&&e.createElement("div",{className:"dgl-citation-breadcrumb"},s),a.snippet&&e.createElement("div",{className:"dgl-citation-snippet"},a.snippet)))}function Fe({client:t,sourceId:n,framePath:r}){const[l,a]=d.useState(null);return d.useEffect(()=>{let o=null;return t.fetchSourceFrame(n,r).then(s=>{o=s,a(s)}).catch(()=>a(null)),()=>{o&&URL.revokeObjectURL(o)}},[t,n,r]),l?e.createElement("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"dgl-citation-frame-link"},e.createElement("img",{src:l,alt:"",className:"dgl-citation-frame"})):e.createElement("div",{className:"dgl-citation-frame-loading"})}function Be(t){const n=t.match(/<followups>([\s\S]*?)<\/followups>/i);return n?n[1].split(`
|
|
4
|
-
`).map(
|
|
3
|
+
`))!==-1;){const N=i.slice(0,x);i=i.slice(x+2);const y=N.trim();if(y.startsWith("data:"))try{const L=JSON.parse(y.slice(5).trim());l(L)}catch(L){}}}}catch(a){(a==null?void 0:a.name)!=="AbortError"&&l({type:"error",error:(a==null?void 0:a.message)||String(a)})}})(),()=>r.abort()}}const oe="0.5.1",O={apiBaseUrl:"https://api.docgenlab.com",position:"bottom-right",primary:"#4F46E5",primaryText:"#FFFFFF",radius:"14px",fontFamily:'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',greeting:"How can I help you today?",greetingSub:"Ask anything about your uploaded documents. I'll only answer from what's in the knowledge base."};function H(t){var ye,ve,Ne,we,xe,_e,Ce,Se;const n=t.apiBaseUrl||O.apiBaseUrl,l=t.enableImageUpload!==!1,r=d.useRef(null),a=`${t.agentKey}::${t.endUserId||""}::${t.endUserHash||""}`,o=d.useRef("");(!r.current||o.current!==a)&&(r.current=new $e({agentKey:t.agentKey,apiBaseUrl:n,endUserId:t.endUserId,endUserHash:t.endUserHash}),o.current=a);const c=r.current,[i,g]=d.useState(null),[E,x]=d.useState(null),N=(i==null?void 0:i.widget_config)||{},y={position:t.position||N.position||O.position,primary:((ye=t.theme)==null?void 0:ye.primary)||N.primary_color||O.primary,primaryText:((ve=t.theme)==null?void 0:ve.primaryText)||N.primary_text_color||O.primaryText,radius:((Ne=t.theme)==null?void 0:Ne.radius)||N.radius||O.radius,fontFamily:((we=t.theme)==null?void 0:we.fontFamily)||O.fontFamily,greeting:t.greeting||N.greeting||O.greeting,agentName:t.agentName||N.agent_name||(i==null?void 0:i.name)||"Assistant",agentAvatarUrl:t.agentAvatarUrl||N.agent_avatar_url||void 0,launcherAvatarUrl:N.launcher_avatar_url||void 0,hideBranding:(_e=(xe=t.hideBranding)!=null?xe:N.hide_branding)!=null?_e:!1,openOnLoad:(Se=(Ce=t.openOnLoad)!=null?Ce:N.open_on_load)!=null?Se:!1},L={"--dgl-primary":y.primary,"--dgl-primary-text":y.primaryText,"--dgl-radius":y.radius,"--dgl-font":y.fontFamily},[_,F]=d.useState(y.openOnLoad),[S,G]=d.useState(!1),[v,U]=d.useState([]),[V,Z]=d.useState(""),[D,X]=d.useState(!1),[M,Y]=d.useState(null),[he,ee]=d.useState(null),[T,te]=d.useState(null),[z,ae]=d.useState(!1),pe=d.useRef(null),ne=d.useRef(null),q=d.useRef(""),J=d.useRef(null),[le,re]=d.useState([]),[nt,ke]=d.useState(!1),[lt,ie]=d.useState(!1),[rt,it]=d.useState([]);d.useEffect(()=>{!_||i||c.getAgent().then(m=>{var h;g(m),(h=t.onReady)==null||h.call(t,m)}).catch(m=>{var h;x(m.message),(h=t.onError)==null||h.call(t,m.message)})},[_,i,c,t]),d.useEffect(()=>{if(!_||t.disableTicketing)return;let m=!1;return c.listTickets().then(h=>{m||re(h)}).catch(()=>{}),()=>{m=!0}},[_,c,t.disableTicketing]),d.useEffect(()=>{if(!_)return;const m=`dgl-chat:${t.agentKey}`,h=localStorage.getItem(m);if(!h)return;let f=!1;return(async()=>{try{const[b,u]=await Promise.all([c.getConversation(h),c.getTicketCardState(h).catch(()=>null)]);if(f)return;const s=[];for(const C of b.messages||[])C.role==="user"?s.push({id:C.id,role:"user",content:C.content||"",imagePath:C.image_path||void 0}):C.role==="assistant"&&s.push({id:C.id,role:"assistant",content:C.content||"",citations:C.retrieved_chunks||void 0});if(u&&u.kind&&s.length){let C=-1;for(let p=s.length-1;p>=0;p--)if(s[p].role==="assistant"){C=p;break}if(C>=0){const p=s[C];u.kind==="offer"&&u.conversation_id&&u.connector_type&&u.connector_name?p.ticketOffer={conversationId:u.conversation_id,connectorType:u.connector_type,connectorName:u.connector_name}:u.kind==="existing"&&u.ticket_id&&u.status?p.ticketExisting={ticketId:u.ticket_id,externalNumber:u.external_ticket_number||null,externalUrl:u.external_url||null,status:u.status}:u.kind==="created"&&u.ticket_id&&(p.ticketCreated={id:u.ticket_id,externalNumber:u.external_ticket_number||null,externalUrl:u.external_url||null})}}Y(h),U(s)}catch(b){localStorage.removeItem(m)}})(),()=>{f=!0}},[t.agentKey,c,_]),d.useEffect(()=>{M&&localStorage.setItem(`dgl-chat:${t.agentKey}`,M)},[M,t.agentKey]),d.useEffect(()=>{J.current&&(J.current.scrollTop=J.current.scrollHeight)},[v]);const Ee=d.useCallback(()=>{T&&URL.revokeObjectURL(T),ee(null),te(null)},[T]),be=d.useCallback(m=>{if(!m.type.startsWith("image/"))return;const h=10*1024*1024;m.size>h||(T&&URL.revokeObjectURL(T),ee(m),te(URL.createObjectURL(m)))},[T]),st=async m=>{var u;if(m.preventDefault(),!V.trim()||D||z)return;const h=V.trim();let f,b;if(he){try{ae(!0),f=await c.uploadImage(he)}catch(s){(u=t.onError)==null||u.call(t,(s==null?void 0:s.message)||"Image upload failed"),ae(!1);return}ae(!1),b=T||void 0}Z(""),q.current="",U(s=>[...s,{role:"user",content:h,imagePath:f,imagePreviewUrl:b},{role:"assistant",content:"",streaming:!0}]),X(!0),ee(null),te(null),ne.current=c.streamChat({message:h,conversation_id:M||void 0,image_path:f},s=>{var C;if(s.type==="conversation")Y(s.conversation_id);else if(s.type==="token"){q.current+=s.content;const p=q.current;U(k=>k.map((w,ot)=>ot===k.length-1&&w.role==="assistant"?{...w,content:p}:w))}else if(s.type==="citations")U(p=>p.map((k,w)=>w===p.length-1&&k.role==="assistant"?{...k,citations:s.citations}:k));else if(s.type==="refused")q.current=s.content,U(p=>p.map((k,w)=>w===p.length-1&&k.role==="assistant"?{...k,content:s.content,refused:!0}:k));else if(s.type==="ticket_offer"){if(t.disableTicketing)return;U(p=>p.map((k,w)=>w===p.length-1&&k.role==="assistant"?{...k,ticketOffer:{conversationId:s.conversation_id,connectorType:s.connector_type,connectorName:s.connector_name}}:k))}else if(s.type==="ticket_existing"){if(t.disableTicketing)return;U(p=>p.map((k,w)=>w===p.length-1&&k.role==="assistant"?{...k,ticketExisting:{ticketId:s.ticket_id,externalNumber:s.external_ticket_number,externalUrl:s.external_url,status:s.status}}:k))}else s.type==="ticket_status_card"?U(p=>p.map((k,w)=>w===p.length-1&&k.role==="assistant"?{...k,ticketStatus:{ticketId:s.ticket_id,externalNumber:s.external_number,externalUrl:s.external_url,status:s.status,title:s.title,priority:s.priority,lastUpdate:s.last_update,assignedTo:s.assigned_to,createdAt:s.created_at}}:k)):s.type==="done"?(U(p=>p.map((k,w)=>w===p.length-1&&k.role==="assistant"?{...k,streaming:!1,id:s.message_id,cacheHit:s.cache_hit}:k)),X(!1)):s.type==="error"&&(U(p=>p.map((k,w)=>w===p.length-1&&k.role==="assistant"?{...k,content:`Error: ${s.error}`,streaming:!1,refused:!0}:k)),X(!1),(C=t.onError)==null||C.call(t,s.error))})},ct=()=>{ne.current&&ne.current(),U([]),Y(null),X(!1),localStorage.removeItem(`dgl-chat:${t.agentKey}`),Ee()};return e.createElement("div",{className:`dgl-root dgl-pos-${y.position}`,style:L},_&&e.createElement("div",{className:`dgl-panel ${S?"dgl-panel-expanded":""}`},e.createElement("div",{className:"dgl-header"},e.createElement("div",{className:"dgl-header-info"},y.agentAvatarUrl?e.createElement("img",{src:y.agentAvatarUrl,alt:"",className:"dgl-avatar"}):e.createElement("div",{className:"dgl-avatar dgl-avatar-fallback dgl-avatar-fallback-light"},y.agentName.slice(0,1).toUpperCase()),e.createElement("div",{className:"dgl-header-text"},e.createElement("div",{className:"dgl-title"},y.agentName),(i==null?void 0:i.org_name)&&e.createElement("div",{className:"dgl-subtitle"},i.org_name))),e.createElement("div",{className:"dgl-header-actions"},e.createElement("button",{type:"button",onClick:async()=>{ie(!0);try{const m=await c.listConversations();it(m)}catch(m){}},className:"dgl-icon-btn",title:"All chats","aria-label":"All chats"},at()),!t.disableTicketing&&e.createElement("button",{type:"button",onClick:()=>ke(!0),className:"dgl-icon-btn dgl-icon-btn-with-badge",title:"Your tickets","aria-label":"Your tickets"},P(),le.length>0&&e.createElement("span",{className:"dgl-icon-badge"},le.length)),e.createElement("button",{type:"button",onClick:ct,className:"dgl-icon-btn",title:"New chat","aria-label":"New chat"},qe()),e.createElement("button",{type:"button",onClick:()=>G(m=>!m),className:"dgl-icon-btn dgl-hide-on-mobile",title:S?"Restore size":"Expand view","aria-label":S?"Restore size":"Expand view"},S?et():Ze()),e.createElement("button",{type:"button",onClick:()=>F(!1),className:"dgl-icon-btn",title:"Close","aria-label":"Close"},W()))),lt&&e.createElement(Ve,{chats:rt,currentConvId:M,onClose:()=>ie(!1),onPick:async m=>{if(ie(!1),m!==M)try{const[h,f]=await Promise.all([c.getConversation(m),c.getTicketCardState(m).catch(()=>null)]),b=[];for(const u of h.messages||[])u.role==="user"?b.push({id:u.id,role:"user",content:u.content||"",imagePath:u.image_path||void 0}):u.role==="assistant"&&b.push({id:u.id,role:"assistant",content:u.content||"",citations:u.retrieved_chunks||void 0});if(f&&f.kind&&b.length){for(let u=b.length-1;u>=0;u--)if(b[u].role==="assistant"){const s=b[u];f.kind==="offer"&&f.conversation_id&&f.connector_type&&f.connector_name?s.ticketOffer={conversationId:f.conversation_id,connectorType:f.connector_type,connectorName:f.connector_name}:f.kind==="existing"&&f.ticket_id&&f.status?s.ticketExisting={ticketId:f.ticket_id,externalNumber:f.external_ticket_number||null,externalUrl:f.external_url||null,status:f.status}:f.kind==="created"&&f.ticket_id&&(s.ticketCreated={id:f.ticket_id,externalNumber:f.external_ticket_number||null,externalUrl:f.external_url||null});break}}Y(m),U(b)}catch(h){}}}),nt&&e.createElement(Re,{tickets:le,onClose:()=>ke(!1),onRefresh:async()=>{try{const m=await c.listTickets(),h=new Set(["open","pending","in_progress","on_hold"]),f=m.filter(s=>h.has((s.status||"open").toLowerCase())),b=await Promise.all(f.map(s=>c.getTicket(s.id,!0).catch(()=>null))),u=new Map;b.forEach(s=>{s&&u.set(s.id,s)}),re(m.map(s=>u.get(s.id)||s))}catch(m){}}}),e.createElement("div",{className:"dgl-messages",ref:J},v.length===0&&!E&&e.createElement("div",{className:"dgl-empty"},e.createElement("div",{className:"dgl-empty-icon"},ue()),e.createElement("div",{className:"dgl-empty-text"},y.greeting),e.createElement("div",{className:"dgl-empty-sub"},(i==null?void 0:i.description)||O.greetingSub)),E&&e.createElement("div",{className:"dgl-error"},"Couldn't load the assistant: ",E),v.map((m,h)=>e.createElement(Ie,{key:h,message:m,client:c,isLast:h===v.length-1,agentAvatarUrl:y.agentAvatarUrl,onPickFollowup:f=>{Z(f)},defaultEmail:t.endUserEmail,defaultPhone:t.endUserPhone,conversationId:M||void 0,onTicketCreated:(f,b)=>{U(u=>u.map(s=>s===f?{...s,ticketOffer:void 0,ticketExisting:void 0,ticketCreated:{id:b.id,externalNumber:b.external_ticket_number,externalUrl:b.external_url}}:s)),re(u=>[b,...u.filter(s=>s.id!==b.id)])}}))),e.createElement("form",{className:"dgl-composer",onSubmit:st},T&&e.createElement("div",{className:"dgl-staged-image"},e.createElement("img",{src:T,alt:"attachment"}),e.createElement("button",{type:"button",onClick:Ee,className:"dgl-staged-remove","aria-label":"Remove image"},W())),e.createElement("div",{className:"dgl-composer-row"},l&&e.createElement(e.Fragment,null,e.createElement("button",{type:"button",className:"dgl-icon-btn",onClick:()=>{var m;return(m=pe.current)==null?void 0:m.click()},disabled:D||z,title:"Attach image","aria-label":"Attach image"},Qe()),e.createElement("input",{ref:pe,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",style:{display:"none"},onChange:m=>{var f;const h=(f=m.target.files)==null?void 0:f[0];h&&be(h),m.target&&(m.target.value="")}})),e.createElement("input",{className:"dgl-input",value:V,onChange:m=>Z(m.target.value),placeholder:D?"Thinking…":T?"Describe what to know about this image…":"Type your question…",disabled:D,onPaste:m=>{var f;if(!l)return;const h=Array.from(((f=m.clipboardData)==null?void 0:f.items)||[]).find(b=>b.kind==="file"&&b.type.startsWith("image/"));if(h){const b=h.getAsFile();b&&(m.preventDefault(),be(b))}}}),e.createElement("button",{type:"submit",className:"dgl-send-btn",disabled:!V.trim()||D||z,"aria-label":"Send"},D||z?R():Je())),!y.hideBranding&&e.createElement("div",{className:"dgl-branding"},"Powered by ",e.createElement("a",{href:"https://docgenlab.com",target:"_blank",rel:"noopener noreferrer"},"DocGenLab"),e.createElement("span",{className:"dgl-branding-version",title:`Widget version ${oe}`},"v",oe)))),e.createElement("button",{type:"button",className:"dgl-launcher",onClick:()=>F(m=>!m),"aria-label":_?"Close chat":"Open chat"},_?ze():y.launcherAvatarUrl?e.createElement("img",{src:y.launcherAvatarUrl,alt:"",className:"dgl-launcher-avatar"}):Ye()))}function Ie({message:t,client:n,isLast:l,agentAvatarUrl:r,onPickFollowup:a,defaultEmail:o,defaultPhone:c,conversationId:i,onTicketCreated:g}){var N;if(t.role==="user")return e.createElement("div",{className:"dgl-msg dgl-msg-user"},e.createElement("div",{className:"dgl-bubble dgl-bubble-user"},(t.imagePath||t.imagePreviewUrl)&&e.createElement(Oe,{client:n,imagePath:t.imagePath,previewUrl:t.imagePreviewUrl}),t.content));const E=Me(t.content),x=t.streaming?[]:Ae(t.content);return e.createElement("div",{className:"dgl-msg dgl-msg-assistant"},r?e.createElement("img",{src:r,className:"dgl-avatar",alt:""}):e.createElement("div",{className:"dgl-avatar dgl-avatar-fallback"},ue()),e.createElement("div",{className:"dgl-msg-body"},t.refused?e.createElement("div",{className:"dgl-refused"},E):t.ticketStatus?e.createElement(He,{ticket:t.ticketStatus}):e.createElement("div",{className:"dgl-assistant-text"},t.streaming&&!E?e.createElement(De,null):e.createElement(e.Fragment,null,Pe(E),t.streaming&&e.createElement("span",{className:"dgl-typing-cursor"},"▍"))),!t.streaming&&!t.refused&&!!((N=t.citations)!=null&&N.length)&&!t.ticketStatus&&e.createElement(Fe,{citations:t.citations,client:n}),!t.streaming&&!t.ticketStatus&&t.ticketCreated?e.createElement(We,{created:t.ticketCreated}):!t.streaming&&!t.ticketStatus&&t.ticketExisting?e.createElement(Ge,{existing:t.ticketExisting,client:n,conversationId:i,defaultEmail:o,defaultPhone:c,onNewTicketRaised:y=>g==null?void 0:g(t,y)}):!t.streaming&&!t.ticketStatus&&t.ticketOffer?e.createElement(Ke,{client:n,offer:t.ticketOffer,defaultEmail:o,defaultPhone:c,onCreated:y=>g==null?void 0:g(t,y)}):null,x.length>0&&e.createElement(Te,{suggestions:x,onPick:a})))}function Te({suggestions:t,onPick:n}){return e.createElement("div",{className:"dgl-followups"},e.createElement("div",{className:"dgl-followups-label"},"Continue exploring"),e.createElement("div",{className:"dgl-followups-list"},t.map((l,r)=>e.createElement("button",{key:r,type:"button",className:"dgl-followup-chip",onClick:()=>n(l)},l))))}function Oe({client:t,imagePath:n,previewUrl:l}){const[r,a]=d.useState(l||null),[o,c]=d.useState(!1);return d.useEffect(()=>{if(l||!n)return;let i=null;return t.fetchImage(n).then(g=>{i=g,a(g)}).catch(()=>a(null)),()=>{i&&URL.revokeObjectURL(i)}},[t,n,l]),d.useEffect(()=>{if(!o)return;const i=E=>{E.key==="Escape"&&c(!1)};window.addEventListener("keydown",i);const g=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{window.removeEventListener("keydown",i),document.body.style.overflow=g}},[o]),r?e.createElement(e.Fragment,null,e.createElement("button",{type:"button",onClick:()=>c(!0),className:"dgl-user-image-btn","aria-label":"View image"},e.createElement("img",{src:r,className:"dgl-user-image",alt:"attached"})),o&&e.createElement("div",{className:"dgl-lightbox",role:"dialog","aria-modal":"true",onClick:()=>c(!1)},e.createElement("button",{type:"button",className:"dgl-lightbox-close",onClick:i=>{i.stopPropagation(),c(!1)},"aria-label":"Close image"},W()),e.createElement("img",{src:r,className:"dgl-lightbox-img",alt:"attached",onClick:i=>i.stopPropagation()}))):null}function Fe({citations:t,client:n}){const l={};for(const i of t){const g=l[i.source_id];(!g||i.score>g.score)&&(l[i.source_id]=i)}const r=Object.values(l).sort((i,g)=>g.score-i.score).slice(0,3),a=Object.keys(l).length-r.length;if(!r.length)return null;const[o,c]=d.useState(null);return e.createElement("div",{className:"dgl-citations"},r.map(i=>e.createElement(Be,{key:i.chunk_id,citation:i,client:n,isOpen:o===i.chunk_id,onToggle:()=>c(o===i.chunk_id?null:i.chunk_id)})),a>0&&e.createElement("span",{className:"dgl-citation-more"},"+",a," more"))}function Be({citation:t,client:n,isOpen:l,onToggle:r}){const a=t,o=!!a.frame_path,c=a.heading?`${a.heading}${a.subheading?" › "+a.subheading:""}`:null,i=a.start_seconds!=null?`${Math.floor(a.start_seconds/60)}:${String(a.start_seconds%60).padStart(2,"0")}`:null;return e.createElement("span",{className:"dgl-citation-wrap"},e.createElement("button",{type:"button",className:`dgl-citation ${l?"dgl-citation-open":""}`,onClick:r,title:a.snippet||""},o&&e.createElement("span",{className:"dgl-citation-icon"},"▶"),a.source_name,i&&e.createElement("span",{className:"dgl-citation-stamp"}," · ",i),a.page&&e.createElement("span",{className:"dgl-citation-stamp"}," · p",a.page)),l&&e.createElement("div",{className:"dgl-citation-popover"},a.frame_path&&e.createElement(je,{client:n,sourceId:a.source_id,framePath:a.frame_path}),c&&e.createElement("div",{className:"dgl-citation-breadcrumb"},c),a.snippet&&e.createElement("div",{className:"dgl-citation-snippet"},a.snippet)))}function je({client:t,sourceId:n,framePath:l}){const[r,a]=d.useState(null);return d.useEffect(()=>{let o=null;return t.fetchSourceFrame(n,l).then(c=>{o=c,a(c)}).catch(()=>a(null)),()=>{o&&URL.revokeObjectURL(o)}},[t,n,l]),r?e.createElement("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"dgl-citation-frame-link"},e.createElement("img",{src:r,alt:"",className:"dgl-citation-frame"})):e.createElement("div",{className:"dgl-citation-frame-loading"})}function Ae(t){const n=t.match(/<followups>([\s\S]*?)<\/followups>/i);return n?n[1].split(`
|
|
4
|
+
`).map(l=>l.trim()).map(l=>l.replace(/^[-*•\d.)\s"']+|["']$/g,"").trim()).filter(l=>l.length>=4&&l.length<=120).slice(0,3):[]}function Me(t){const n=/\s*I\s+(don'?t|do not)\s+have\s+(?:specific|enough|that|the|any)?\s*information\s+on\s+(?:this|that)[^.]*?\.(?:\s*Please\s+(?:contact|reach\s*out\s+to)\s+(?:your\s+)?(?:support|admin)[^.]*?\.)?/gi,l=/\n*<followups>[\s\S]*?(<\/followups>|$)/gi,r=t.replace(l,""),a=r.replace(n,"").trim();return(r.trim().length>0&&a.length<20?t:t.replace(n,"")).replace(/\n*<followups>[\s\S]*?(<\/followups>|$)/gi,"").replace(/\s*\[\s*Section:[^\]]*\]?/gi,"").replace(/\s*\[\s*doc:[^\]]*\]?/gi,"").replace(/\s*\[\s*(?:document|doc|source|ref|reference)[^\]]*\]?/gi,"").replace(/\s*\[\s*(?:p\.?\s*)?\d+(?:\s*[,–-]\s*\d+)*\s*\]/gi,"").replace(/[,;]?\s*doc:\s*[0-9a-fA-F][0-9a-fA-F-]{6,}\]?/gi,"").replace(/[,;]\s*(?:\d+|doc:?\s*[0-9a-fA-F-]+)\s*\]?/gi,"").replace(/([\w%])\s*\]/g,"$1").replace(/\s+([,.;:!?])/g,"$1").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
5
5
|
|
|
6
|
-
`).trim()}function
|
|
7
|
-
`);if(a.every(
|
|
8
|
-
`).map((s,i,m)=>e.createElement(e.Fragment,{key:i},se(s),i<m.length-1&&e.createElement("br",null))))})}function se(t){const n=/(`[^`]+`|\*\*[^*\n]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^)]+\))/g;return t.split(n).map((l,a)=>{if(!l)return null;if(l.startsWith("`")&&l.endsWith("`"))return e.createElement("code",{key:a,className:"dgl-md-code"},l.slice(1,-1));if(l.startsWith("**")&&l.endsWith("**"))return e.createElement("strong",{key:a},l.slice(2,-2));if(l.startsWith("*")&&l.endsWith("*")&&l.length>2)return e.createElement("em",{key:a},l.slice(1,-1));const o=l.match(/^\[([^\]]+)\]\(([^)]+)\)$/);return o?e.createElement("a",{key:a,href:o[2],target:"_blank",rel:"noopener noreferrer",className:"dgl-md-link"},o[1]):e.createElement(e.Fragment,{key:a},l)})}function De(){return e.createElement("span",{className:"dgl-thinking"},e.createElement("span",{className:"dgl-thinking-dot"}),e.createElement("span",{className:"dgl-thinking-dot"}),e.createElement("span",{className:"dgl-thinking-dot"}))}const B={open:{label:"Open",stripe:"linear-gradient(90deg,#3b82f6,#6366f1)",iconBg:"#3b82f6",pillBg:"#dbeafe",pillFg:"#1e40af"},in_progress:{label:"In progress",stripe:"linear-gradient(90deg,#8b5cf6,#d946ef)",iconBg:"#8b5cf6",pillBg:"#ede9fe",pillFg:"#5b21b6"},on_hold:{label:"On hold",stripe:"linear-gradient(90deg,#f59e0b,#f97316)",iconBg:"#f59e0b",pillBg:"#fef3c7",pillFg:"#92400e"},resolved:{label:"Resolved",stripe:"linear-gradient(90deg,#10b981,#14b8a6)",iconBg:"#10b981",pillBg:"#d1fae5",pillFg:"#065f46"},closed:{label:"Closed",stripe:"linear-gradient(90deg,#94a3b8,#64748b)",iconBg:"#64748b",pillBg:"#f1f5f9",pillFg:"#334155"},cancelled:{label:"Cancelled",stripe:"linear-gradient(90deg,#ef4444,#f43f5e)",iconBg:"#ef4444",pillBg:"#fee2e2",pillFg:"#991b1b"}},ce={low:{bg:"#f1f5f9",fg:"#475569"},medium:{bg:"#dbeafe",fg:"#1e40af"},high:{bg:"#fef3c7",fg:"#92400e"},urgent:{bg:"#fee2e2",fg:"#991b1b"}};function oe(t){if(!t)return"—";const n=new Date(t),r=Date.now()-n.getTime();if(Number.isNaN(r))return t;const l=Math.floor(r/6e4);if(l<1)return"just now";if(l<60)return`${l}m ago`;const a=Math.floor(l/60);if(a<24)return`${a}h ago`;const o=Math.floor(a/24);return o<7?`${o}d ago`:n.toLocaleDateString()}function Me({client:t,offer:n,defaultEmail:r,defaultPhone:l,onCreated:a}){const[o,s]=d.useState(r||""),[i,m]=d.useState(l||""),[h,w]=d.useState(!r),[y,b]=d.useState("medium"),[C,_]=d.useState(!1),[F,S]=d.useState(null),K=async()=>{if(!o.trim()){S("Email is required so the team can follow up.");return}_(!0),S(null);try{const E=await t.raiseTicket(n.conversationId,{consent:!0,end_user_email:o.trim(),end_user_phone:i.trim()||void 0,priority:y});a(E)}catch(E){S((E==null?void 0:E.message)||"Could not create ticket. Try again.")}finally{_(!1)}};return e.createElement("div",{className:"dgl-ticket-card"},e.createElement("div",{className:"dgl-ticket-card-stripe",style:{background:"linear-gradient(90deg,#6366f1,#8b5cf6)"}}),e.createElement("div",{className:"dgl-ticket-card-body"},e.createElement("div",{className:"dgl-ticket-card-head"},e.createElement("div",{className:"dgl-ticket-card-icon",style:{background:"linear-gradient(135deg,#6366f1,#8b5cf6,#ec4899)"}},D()),e.createElement("div",{className:"dgl-ticket-card-titles"},e.createElement("div",{className:"dgl-ticket-card-eyebrow"},"Support escalation"),e.createElement("div",{className:"dgl-ticket-card-title"},"Need a human to look at this?"))),e.createElement("div",{className:"dgl-ticket-card-desc"},"We'll summarise this chat and raise a ticket. Our team will follow up on the email below."),e.createElement("div",{className:"dgl-ticket-form-grid"},e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-field-label"},"Reply to"),h?e.createElement("input",{type:"email",className:"dgl-ticket-input",value:o,onChange:E=>s(E.target.value),onBlur:()=>o&&w(!1),placeholder:"you@example.com",autoFocus:!0}):e.createElement("button",{type:"button",className:"dgl-ticket-email-link",onClick:()=>w(!0),title:"Click to change"},o||"Set email"," ",e.createElement("span",{className:"dgl-ticket-email-change"},"(change)"))),e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-field-label"},"Priority"),e.createElement("select",{className:"dgl-ticket-input",value:y,onChange:E=>b(E.target.value)},e.createElement("option",{value:"low"},"Low"),e.createElement("option",{value:"medium"},"Medium"),e.createElement("option",{value:"high"},"High"),e.createElement("option",{value:"urgent"},"Urgent")))),F&&e.createElement("div",{className:"dgl-ticket-error"},F),e.createElement("div",{className:"dgl-ticket-card-footer"},e.createElement("span",{className:"dgl-ticket-hint"},"The bot writes the title + description from this chat."),e.createElement("button",{type:"button",className:"dgl-ticket-submit",onClick:K,disabled:C||!o.trim()},C?R():D(),e.createElement("span",null,C?"Submitting…":"Submit ticket")))))}function Pe({created:t}){const n=B.open;return e.createElement("div",{className:"dgl-ticket-card"},e.createElement("div",{className:"dgl-ticket-card-stripe",style:{background:"linear-gradient(90deg,#10b981,#14b8a6)"}}),e.createElement("div",{className:"dgl-ticket-card-body"},e.createElement("div",{className:"dgl-ticket-card-head"},e.createElement("div",{className:"dgl-ticket-card-icon",style:{background:"linear-gradient(135deg,#10b981,#14b8a6)"}},He()),e.createElement("div",{className:"dgl-ticket-card-titles"},e.createElement("div",{className:"dgl-ticket-card-eyebrow",style:{color:"#059669"}},"Ticket created"),e.createElement("div",{className:"dgl-ticket-card-title"},"#",t.externalNumber||t.id.slice(0,8))),t.externalUrl&&e.createElement("a",{className:"dgl-ticket-open-btn",href:t.externalUrl,target:"_blank",rel:"noopener noreferrer"},"Open")),e.createElement("div",{className:"dgl-ticket-pills"},e.createElement("span",{className:"dgl-ticket-pill",style:{background:n.pillBg,color:n.pillFg}},e.createElement("span",{className:"dgl-ticket-pill-dot",style:{background:n.iconBg}})," Open")),e.createElement("div",{className:"dgl-ticket-card-desc"},"Support team has been notified — they'll follow up directly on your email.")))}function Ke({existing:t,client:n,conversationId:r,defaultEmail:l,defaultPhone:a,onNewTicketRaised:o}){const s=B[t.status]||B.open,[i,m]=d.useState(!1),[h,w]=d.useState(l||""),[y,b]=d.useState("medium"),[C,_]=d.useState(!1),[F,S]=d.useState(null),K=async()=>{if(!h.trim()){S("Email is required so the team can follow up.");return}if(!r){S("Conversation not available yet.");return}_(!0),S(null);try{const E=await n.raiseTicket(r,{consent:!0,end_user_email:h.trim(),end_user_phone:a||void 0,priority:y,force_new:!0});o==null||o(E)}catch(E){S((E==null?void 0:E.message)||"Could not create ticket. Try again.")}finally{_(!1)}};return e.createElement("div",{className:"dgl-ticket-card"},e.createElement("div",{className:"dgl-ticket-card-stripe",style:{background:s.stripe}}),e.createElement("div",{className:"dgl-ticket-card-body"},e.createElement("div",{className:"dgl-ticket-card-head"},e.createElement("div",{className:"dgl-ticket-card-icon",style:{background:s.iconBg}},D()),e.createElement("div",{className:"dgl-ticket-card-titles"},e.createElement("div",{className:"dgl-ticket-card-eyebrow"},"We're already on it"),e.createElement("div",{className:"dgl-ticket-card-title"},"#",t.externalNumber||t.ticketId.slice(0,8))),t.externalUrl&&e.createElement("a",{className:"dgl-ticket-open-btn",href:t.externalUrl,target:"_blank",rel:"noopener noreferrer"},"Open")),e.createElement("div",{className:"dgl-ticket-pills"},e.createElement("span",{className:"dgl-ticket-pill",style:{background:s.pillBg,color:s.pillFg}},e.createElement("span",{className:"dgl-ticket-pill-dot",style:{background:s.iconBg}})," ",s.label)),e.createElement("div",{className:"dgl-ticket-card-desc"},"A ticket has already been raised for this conversation. Our team will follow up — no need to file another."),i?e.createElement("div",{className:"dgl-ticket-diff-form"},e.createElement("div",{className:"dgl-ticket-field-label",style:{marginTop:4}},"File a separate ticket for a new issue"),e.createElement("div",{className:"dgl-ticket-form-grid"},e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-field-label"},"Reply to"),e.createElement("input",{type:"email",className:"dgl-ticket-input",value:h,onChange:E=>w(E.target.value),placeholder:"you@example.com"})),e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-field-label"},"Priority"),e.createElement("select",{className:"dgl-ticket-input",value:y,onChange:E=>b(E.target.value)},e.createElement("option",{value:"low"},"Low"),e.createElement("option",{value:"medium"},"Medium"),e.createElement("option",{value:"high"},"High"),e.createElement("option",{value:"urgent"},"Urgent")))),F&&e.createElement("div",{className:"dgl-ticket-error"},F),e.createElement("div",{className:"dgl-ticket-card-footer"},e.createElement("button",{type:"button",className:"dgl-ticket-diff-cancel",onClick:()=>m(!1)},"Cancel"),e.createElement("button",{type:"button",className:"dgl-ticket-submit",onClick:K,disabled:C||!h.trim()},C?R():D(),e.createElement("span",null,C?"Submitting…":"Submit new ticket")))):e.createElement("button",{type:"button",className:"dgl-ticket-diff-link",onClick:()=>m(!0)},"Different issue? Raise new ticket →")))}function We({ticket:t}){const n=B[t.status]||B.open,r=ce[(t.priority||"medium").toLowerCase()]||ce.medium;return e.createElement("div",{className:"dgl-ticket-card"},e.createElement("div",{className:"dgl-ticket-card-stripe",style:{background:n.stripe}}),e.createElement("div",{className:"dgl-ticket-card-body"},e.createElement("div",{className:"dgl-ticket-card-head"},e.createElement("div",{className:"dgl-ticket-card-icon",style:{background:n.iconBg}},D()),e.createElement("div",{className:"dgl-ticket-card-titles"},e.createElement("div",{className:"dgl-ticket-card-eyebrow"},"Support ticket"),e.createElement("div",{className:"dgl-ticket-card-title"},"#",t.externalNumber||t.ticketId.slice(0,8))),t.externalUrl&&e.createElement("a",{className:"dgl-ticket-open-btn",href:t.externalUrl,target:"_blank",rel:"noopener noreferrer"},"Open")),e.createElement("div",{className:"dgl-ticket-pills"},e.createElement("span",{className:"dgl-ticket-pill",style:{background:n.pillBg,color:n.pillFg}},e.createElement("span",{className:"dgl-ticket-pill-dot",style:{background:n.iconBg}})," ",n.label),e.createElement("span",{className:"dgl-ticket-pill",style:{background:r.bg,color:r.fg}},t.priority||"medium"," priority")),t.title&&e.createElement("div",{className:"dgl-ticket-card-body-title"},t.title),e.createElement("div",{className:"dgl-ticket-meta-grid"},e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-meta-label"},"Last update"),e.createElement("div",{className:"dgl-ticket-meta-value"},oe(t.lastUpdate))),e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-meta-label"},"Assigned to"),e.createElement("div",{className:"dgl-ticket-meta-value"},t.assignedTo||"Unassigned")))))}function Ge({tickets:t,onClose:n,onRefresh:r}){const[l,a]=d.useState(!1);d.useEffect(()=>{const i=m=>{m.key==="Escape"&&n()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[n]);const o=async()=>{a(!0);try{await r()}finally{a(!1)}},s=[...t].sort((i,m)=>{const h=i.created_at?new Date(i.created_at).getTime():0;return(m.created_at?new Date(m.created_at).getTime():0)-h});return e.createElement("div",{className:"dgl-tix-modal-backdrop",onClick:n},e.createElement("div",{className:"dgl-tix-modal",onClick:i=>i.stopPropagation()},e.createElement("div",{className:"dgl-tix-modal-header"},e.createElement("div",null,e.createElement("div",{className:"dgl-tix-modal-title"},"Your tickets"),e.createElement("div",{className:"dgl-tix-modal-sub"},t.length===0?"No tickets yet":`${t.length} ticket${t.length===1?"":"s"} on this assistant`)),e.createElement("div",{style:{display:"flex",gap:4}},e.createElement("button",{type:"button",onClick:o,className:"dgl-icon-btn",title:"Refresh","aria-label":"Refresh tickets",disabled:l,style:{color:"#475569"}},l?R():Qe()),e.createElement("button",{type:"button",onClick:n,className:"dgl-icon-btn",title:"Close","aria-label":"Close",style:{color:"#475569"}},H()))),e.createElement("div",{className:"dgl-tix-modal-list"},s.length===0?e.createElement("div",{className:"dgl-tix-empty"},"You haven't raised any support tickets here yet. They'll show up here once you do."):s.map(i=>{const m=B[i.status]||B.open;return e.createElement("div",{key:i.id,className:"dgl-tix-row"},e.createElement("div",{className:"dgl-tix-row-head"},e.createElement("span",{className:"dgl-tix-row-num"},"#",i.external_ticket_number||i.id.slice(0,8)),e.createElement("span",{className:"dgl-ticket-pill",style:{background:m.pillBg,color:m.pillFg}},e.createElement("span",{className:"dgl-ticket-pill-dot",style:{background:m.iconBg}}),m.label),i.external_url&&e.createElement("a",{href:i.external_url,target:"_blank",rel:"noopener noreferrer",className:"dgl-ticket-open-btn",style:{marginLeft:"auto"}},"Open")),i.title&&e.createElement("div",{className:"dgl-tix-row-title"},i.title),e.createElement("div",{className:"dgl-tix-row-meta"},i.priority||"medium"," priority · raised ",oe(i.created_at)))}))))}function D(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("circle",{cx:"12",cy:"12",r:"10"}),e.createElement("circle",{cx:"12",cy:"12",r:"4"}),e.createElement("path",{d:"M4.93 4.93l4.24 4.24M14.83 14.83l4.24 4.24M14.83 9.17l4.24-4.24M14.83 9.17l3.53-3.53M4.93 19.07l4.24-4.24"}))}function He(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("path",{d:"M20 6L9 17l-5-5"}))}function Re(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"22",height:"22",fill:"currentColor"},e.createElement("path",{d:"M4 4h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H8l-4 4V6a2 2 0 0 1 2-2z"}))}function Xe(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"22",height:"22",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("polyline",{points:"6 9 12 15 18 9"}))}function H(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"}))}function Ve(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function Ye(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor"},e.createElement("path",{d:"M2 21l21-9L2 3v7l15 2-15 2z"}))}function qe(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.createElement("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),e.createElement("polyline",{points:"21 15 16 10 5 21"}))}function R(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",className:"dgl-spin",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"},e.createElement("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}))}function ze(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("polyline",{points:"15 3 21 3 21 9"}),e.createElement("polyline",{points:"9 21 3 21 3 15"}),e.createElement("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),e.createElement("line",{x1:"3",y1:"21",x2:"10",y2:"14"}))}function Je(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("polyline",{points:"4 14 10 14 10 20"}),e.createElement("polyline",{points:"20 10 14 10 14 4"}),e.createElement("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),e.createElement("line",{x1:"3",y1:"21",x2:"10",y2:"14"}))}function Qe(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("polyline",{points:"23 4 23 10 17 10"}),e.createElement("polyline",{points:"1 20 1 14 7 14"}),e.createElement("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"}))}function de(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"currentColor"},e.createElement("path",{d:"M12 2l2.39 6.95L21 11l-6.61 2.05L12 20l-2.39-6.95L3 11l6.61-2.05L12 2z"}))}let j=null,A=null;function me(t){if(typeof document=="undefined")throw new Error("DocGenLab.init() requires a browser environment.");if(j){j.render(d.createElement(G,t));return}A=document.createElement("div"),A.id="docgenlab-chat-widget-root",document.body.appendChild(A),j=P.createRoot(A),j.render(d.createElement(G,t))}function ue(){j&&(j.unmount(),j=null),A&&(A.remove(),A=null)}typeof window!="undefined"&&(window.DocGenLab={init:me,destroy:ue,DocGenLabChat:G}),I.DocGenLabChat=G,I.destroy=ue,I.init=me,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});
|
|
6
|
+
`).trim()}function Pe(t){return t.split(/\n{2,}/).map((l,r)=>{const a=l.split(`
|
|
7
|
+
`);if(a.every(c=>/^(\s*)([-*]|\d+\.)\s/.test(c))&&a.length>0){const c=/^\d+\./.test(a[0].trim()),i=a.map(E=>E.replace(/^\s*(?:[-*]|\d+\.)\s+/,"")),g=c?"ol":"ul";return e.createElement(g,{key:r,className:`dgl-md-list ${c?"dgl-md-ol":"dgl-md-ul"}`},i.map((E,x)=>e.createElement("li",{key:x},de(E))))}return e.createElement("p",{key:r,className:"dgl-md-p"},l.split(`
|
|
8
|
+
`).map((c,i,g)=>e.createElement(e.Fragment,{key:i},de(c),i<g.length-1&&e.createElement("br",null))))})}function de(t){const n=/(`[^`]+`|\*\*[^*\n]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^)]+\))/g;return t.split(n).map((r,a)=>{if(!r)return null;if(r.startsWith("`")&&r.endsWith("`"))return e.createElement("code",{key:a,className:"dgl-md-code"},r.slice(1,-1));if(r.startsWith("**")&&r.endsWith("**"))return e.createElement("strong",{key:a},r.slice(2,-2));if(r.startsWith("*")&&r.endsWith("*")&&r.length>2)return e.createElement("em",{key:a},r.slice(1,-1));const o=r.match(/^\[([^\]]+)\]\(([^)]+)\)$/);return o?e.createElement("a",{key:a,href:o[2],target:"_blank",rel:"noopener noreferrer",className:"dgl-md-link"},o[1]):e.createElement(e.Fragment,{key:a},r)})}function De(){return e.createElement("span",{className:"dgl-thinking"},e.createElement("span",{className:"dgl-thinking-dot"}),e.createElement("span",{className:"dgl-thinking-dot"}),e.createElement("span",{className:"dgl-thinking-dot"}))}const B={open:{label:"Open",stripe:"linear-gradient(90deg,#3b82f6,#6366f1)",iconBg:"#3b82f6",pillBg:"#dbeafe",pillFg:"#1e40af"},in_progress:{label:"In progress",stripe:"linear-gradient(90deg,#8b5cf6,#d946ef)",iconBg:"#8b5cf6",pillBg:"#ede9fe",pillFg:"#5b21b6"},on_hold:{label:"On hold",stripe:"linear-gradient(90deg,#f59e0b,#f97316)",iconBg:"#f59e0b",pillBg:"#fef3c7",pillFg:"#92400e"},resolved:{label:"Resolved",stripe:"linear-gradient(90deg,#10b981,#14b8a6)",iconBg:"#10b981",pillBg:"#d1fae5",pillFg:"#065f46"},closed:{label:"Closed",stripe:"linear-gradient(90deg,#94a3b8,#64748b)",iconBg:"#64748b",pillBg:"#f1f5f9",pillFg:"#334155"},cancelled:{label:"Cancelled",stripe:"linear-gradient(90deg,#ef4444,#f43f5e)",iconBg:"#ef4444",pillBg:"#fee2e2",pillFg:"#991b1b"}},me={low:{bg:"#f1f5f9",fg:"#475569"},medium:{bg:"#dbeafe",fg:"#1e40af"},high:{bg:"#fef3c7",fg:"#92400e"},urgent:{bg:"#fee2e2",fg:"#991b1b"}};function Q(t){if(!t)return"—";const n=new Date(t),l=Date.now()-n.getTime();if(Number.isNaN(l))return t;const r=Math.floor(l/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const a=Math.floor(r/60);if(a<24)return`${a}h ago`;const o=Math.floor(a/24);return o<7?`${o}d ago`:n.toLocaleDateString()}function Ke({client:t,offer:n,defaultEmail:l,defaultPhone:r,onCreated:a}){const[o,c]=d.useState(l||""),[i,g]=d.useState(r||""),[E,x]=d.useState(!l),[N,y]=d.useState("medium"),[L,_]=d.useState(!1),[F,S]=d.useState(null),G=async()=>{if(!o.trim()){S("Email is required so the team can follow up.");return}_(!0),S(null);try{const v=await t.raiseTicket(n.conversationId,{consent:!0,end_user_email:o.trim(),end_user_phone:i.trim()||void 0,priority:N});a(v)}catch(v){S((v==null?void 0:v.message)||"Could not create ticket. Try again.")}finally{_(!1)}};return e.createElement("div",{className:"dgl-ticket-card"},e.createElement("div",{className:"dgl-ticket-card-stripe",style:{background:"linear-gradient(90deg,#6366f1,#8b5cf6)"}}),e.createElement("div",{className:"dgl-ticket-card-body"},e.createElement("div",{className:"dgl-ticket-card-head"},e.createElement("div",{className:"dgl-ticket-card-icon",style:{background:"linear-gradient(135deg,#6366f1,#8b5cf6,#ec4899)"}},P()),e.createElement("div",{className:"dgl-ticket-card-titles"},e.createElement("div",{className:"dgl-ticket-card-eyebrow"},"Support escalation"),e.createElement("div",{className:"dgl-ticket-card-title"},"Need a human to look at this?"))),e.createElement("div",{className:"dgl-ticket-card-desc"},"We'll summarise this chat and raise a ticket. Our team will follow up on the email below."),e.createElement("div",{className:"dgl-ticket-form-grid"},e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-field-label"},"Reply to"),E?e.createElement("input",{type:"email",className:"dgl-ticket-input",value:o,onChange:v=>c(v.target.value),onBlur:()=>o&&x(!1),placeholder:"you@example.com",autoFocus:!0}):e.createElement("button",{type:"button",className:"dgl-ticket-email-link",onClick:()=>x(!0),title:"Click to change"},o||"Set email"," ",e.createElement("span",{className:"dgl-ticket-email-change"},"(change)"))),e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-field-label"},"Priority"),e.createElement("select",{className:"dgl-ticket-input",value:N,onChange:v=>y(v.target.value)},e.createElement("option",{value:"low"},"Low"),e.createElement("option",{value:"medium"},"Medium"),e.createElement("option",{value:"high"},"High"),e.createElement("option",{value:"urgent"},"Urgent")))),F&&e.createElement("div",{className:"dgl-ticket-error"},F),e.createElement("div",{className:"dgl-ticket-card-footer"},e.createElement("span",{className:"dgl-ticket-hint"},"The bot writes the title + description from this chat."),e.createElement("button",{type:"button",className:"dgl-ticket-submit",onClick:G,disabled:L||!o.trim()},L?R():P(),e.createElement("span",null,L?"Submitting…":"Submit ticket")))))}function We({created:t}){const n=B.open;return e.createElement("div",{className:"dgl-ticket-card"},e.createElement("div",{className:"dgl-ticket-card-stripe",style:{background:"linear-gradient(90deg,#10b981,#14b8a6)"}}),e.createElement("div",{className:"dgl-ticket-card-body"},e.createElement("div",{className:"dgl-ticket-card-head"},e.createElement("div",{className:"dgl-ticket-card-icon",style:{background:"linear-gradient(135deg,#10b981,#14b8a6)"}},Xe()),e.createElement("div",{className:"dgl-ticket-card-titles"},e.createElement("div",{className:"dgl-ticket-card-eyebrow",style:{color:"#059669"}},"Ticket created"),e.createElement("div",{className:"dgl-ticket-card-title"},"#",t.externalNumber||t.id.slice(0,8))),t.externalUrl&&e.createElement("a",{className:"dgl-ticket-open-btn",href:t.externalUrl,target:"_blank",rel:"noopener noreferrer"},"Open")),e.createElement("div",{className:"dgl-ticket-pills"},e.createElement("span",{className:"dgl-ticket-pill",style:{background:n.pillBg,color:n.pillFg}},e.createElement("span",{className:"dgl-ticket-pill-dot",style:{background:n.iconBg}})," Open")),e.createElement("div",{className:"dgl-ticket-card-desc"},"Support team has been notified — they'll follow up directly on your email.")))}function Ge({existing:t,client:n,conversationId:l,defaultEmail:r,defaultPhone:a,onNewTicketRaised:o}){const c=B[t.status]||B.open,[i,g]=d.useState(!1),[E,x]=d.useState(r||""),[N,y]=d.useState("medium"),[L,_]=d.useState(!1),[F,S]=d.useState(null),G=async()=>{if(!E.trim()){S("Email is required so the team can follow up.");return}if(!l){S("Conversation not available yet.");return}_(!0),S(null);try{const v=await n.raiseTicket(l,{consent:!0,end_user_email:E.trim(),end_user_phone:a||void 0,priority:N,force_new:!0});o==null||o(v)}catch(v){S((v==null?void 0:v.message)||"Could not create ticket. Try again.")}finally{_(!1)}};return e.createElement("div",{className:"dgl-ticket-card"},e.createElement("div",{className:"dgl-ticket-card-stripe",style:{background:c.stripe}}),e.createElement("div",{className:"dgl-ticket-card-body"},e.createElement("div",{className:"dgl-ticket-card-head"},e.createElement("div",{className:"dgl-ticket-card-icon",style:{background:c.iconBg}},P()),e.createElement("div",{className:"dgl-ticket-card-titles"},e.createElement("div",{className:"dgl-ticket-card-eyebrow"},"We're already on it"),e.createElement("div",{className:"dgl-ticket-card-title"},"#",t.externalNumber||t.ticketId.slice(0,8))),t.externalUrl&&e.createElement("a",{className:"dgl-ticket-open-btn",href:t.externalUrl,target:"_blank",rel:"noopener noreferrer"},"Open")),e.createElement("div",{className:"dgl-ticket-pills"},e.createElement("span",{className:"dgl-ticket-pill",style:{background:c.pillBg,color:c.pillFg}},e.createElement("span",{className:"dgl-ticket-pill-dot",style:{background:c.iconBg}})," ",c.label)),e.createElement("div",{className:"dgl-ticket-card-desc"},"A ticket has already been raised for this conversation. Our team will follow up — no need to file another."),i?e.createElement("div",{className:"dgl-ticket-diff-form"},e.createElement("div",{className:"dgl-ticket-field-label",style:{marginTop:4}},"File a separate ticket for a new issue"),e.createElement("div",{className:"dgl-ticket-form-grid"},e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-field-label"},"Reply to"),e.createElement("input",{type:"email",className:"dgl-ticket-input",value:E,onChange:v=>x(v.target.value),placeholder:"you@example.com"})),e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-field-label"},"Priority"),e.createElement("select",{className:"dgl-ticket-input",value:N,onChange:v=>y(v.target.value)},e.createElement("option",{value:"low"},"Low"),e.createElement("option",{value:"medium"},"Medium"),e.createElement("option",{value:"high"},"High"),e.createElement("option",{value:"urgent"},"Urgent")))),F&&e.createElement("div",{className:"dgl-ticket-error"},F),e.createElement("div",{className:"dgl-ticket-card-footer"},e.createElement("button",{type:"button",className:"dgl-ticket-diff-cancel",onClick:()=>g(!1)},"Cancel"),e.createElement("button",{type:"button",className:"dgl-ticket-submit",onClick:G,disabled:L||!E.trim()},L?R():P(),e.createElement("span",null,L?"Submitting…":"Submit new ticket")))):e.createElement("button",{type:"button",className:"dgl-ticket-diff-link",onClick:()=>g(!0)},"Different issue? Raise new ticket →")))}function He({ticket:t}){const n=B[t.status]||B.open,l=me[(t.priority||"medium").toLowerCase()]||me.medium;return e.createElement("div",{className:"dgl-ticket-card"},e.createElement("div",{className:"dgl-ticket-card-stripe",style:{background:n.stripe}}),e.createElement("div",{className:"dgl-ticket-card-body"},e.createElement("div",{className:"dgl-ticket-card-head"},e.createElement("div",{className:"dgl-ticket-card-icon",style:{background:n.iconBg}},P()),e.createElement("div",{className:"dgl-ticket-card-titles"},e.createElement("div",{className:"dgl-ticket-card-eyebrow"},"Support ticket"),e.createElement("div",{className:"dgl-ticket-card-title"},"#",t.externalNumber||t.ticketId.slice(0,8))),t.externalUrl&&e.createElement("a",{className:"dgl-ticket-open-btn",href:t.externalUrl,target:"_blank",rel:"noopener noreferrer"},"Open")),e.createElement("div",{className:"dgl-ticket-pills"},e.createElement("span",{className:"dgl-ticket-pill",style:{background:n.pillBg,color:n.pillFg}},e.createElement("span",{className:"dgl-ticket-pill-dot",style:{background:n.iconBg}})," ",n.label),e.createElement("span",{className:"dgl-ticket-pill",style:{background:l.bg,color:l.fg}},t.priority||"medium"," priority")),t.title&&e.createElement("div",{className:"dgl-ticket-card-body-title"},t.title),e.createElement("div",{className:"dgl-ticket-meta-grid"},e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-meta-label"},"Last update"),e.createElement("div",{className:"dgl-ticket-meta-value"},Q(t.lastUpdate))),e.createElement("div",null,e.createElement("div",{className:"dgl-ticket-meta-label"},"Assigned to"),e.createElement("div",{className:"dgl-ticket-meta-value"},t.assignedTo||"Unassigned")))))}function Re({tickets:t,onClose:n,onRefresh:l}){const[r,a]=d.useState(!1);d.useEffect(()=>{const i=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[n]);const o=async()=>{a(!0);try{await l()}finally{a(!1)}},c=[...t].sort((i,g)=>{const E=i.created_at?new Date(i.created_at).getTime():0;return(g.created_at?new Date(g.created_at).getTime():0)-E});return e.createElement("div",{className:"dgl-tix-modal-backdrop",onClick:n},e.createElement("div",{className:"dgl-tix-modal",onClick:i=>i.stopPropagation()},e.createElement("div",{className:"dgl-tix-modal-header"},e.createElement("div",null,e.createElement("div",{className:"dgl-tix-modal-title"},"Your tickets"),e.createElement("div",{className:"dgl-tix-modal-sub"},t.length===0?"No tickets yet":`${t.length} ticket${t.length===1?"":"s"} on this assistant`)),e.createElement("div",{style:{display:"flex",gap:4}},e.createElement("button",{type:"button",onClick:o,className:"dgl-icon-btn",title:"Refresh","aria-label":"Refresh tickets",disabled:r,style:{color:"#475569"}},r?R():tt()),e.createElement("button",{type:"button",onClick:n,className:"dgl-icon-btn",title:"Close","aria-label":"Close",style:{color:"#475569"}},W()))),e.createElement("div",{className:"dgl-tix-modal-list"},c.length===0?e.createElement("div",{className:"dgl-tix-empty"},"You haven't raised any support tickets here yet. They'll show up here once you do."):c.map(i=>{const g=B[i.status]||B.open;return e.createElement("div",{key:i.id,className:"dgl-tix-row"},e.createElement("div",{className:"dgl-tix-row-head"},e.createElement("span",{className:"dgl-tix-row-num"},"#",i.external_ticket_number||i.id.slice(0,8)),e.createElement("span",{className:"dgl-ticket-pill",style:{background:g.pillBg,color:g.pillFg}},e.createElement("span",{className:"dgl-ticket-pill-dot",style:{background:g.iconBg}}),g.label),i.external_url&&e.createElement("a",{href:i.external_url,target:"_blank",rel:"noopener noreferrer",className:"dgl-ticket-open-btn",style:{marginLeft:"auto"}},"Open")),i.title&&e.createElement("div",{className:"dgl-tix-row-title"},i.title),e.createElement("div",{className:"dgl-tix-row-meta"},i.priority||"medium"," priority · raised ",Q(i.created_at)))}))))}function Ve({chats:t,currentConvId:n,onClose:l,onPick:r}){return d.useEffect(()=>{const a=o=>{o.key==="Escape"&&l()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[l]),e.createElement("div",{className:"dgl-tix-modal-backdrop",onClick:l},e.createElement("div",{className:"dgl-tix-modal",onClick:a=>a.stopPropagation()},e.createElement("div",{className:"dgl-tix-modal-header"},e.createElement("div",null,e.createElement("div",{className:"dgl-tix-modal-title"},"Your chats"),e.createElement("div",{className:"dgl-tix-modal-sub"},t.length===0?"No conversations yet":`${t.length} conversation${t.length===1?"":"s"}`)),e.createElement("button",{type:"button",onClick:l,className:"dgl-icon-btn",title:"Close","aria-label":"Close",style:{color:"#475569"}},W())),e.createElement("div",{className:"dgl-tix-modal-list"},t.length===0?e.createElement("div",{className:"dgl-tix-empty"},"Your conversations with this assistant will show up here."):t.map(a=>{const o=a.id===n,c=a.title||a.preview||`Conversation ${a.id.slice(0,8)}`;return e.createElement("button",{key:a.id,type:"button",onClick:()=>r(a.id),className:`dgl-chat-row${o?" dgl-chat-row-current":""}`,title:o?"Current conversation":"Open this conversation"},e.createElement("div",{className:"dgl-chat-row-title"},c),e.createElement("div",{className:"dgl-chat-row-meta"},a.message_count," message",a.message_count===1?"":"s",a.updated_at?` · ${Q(a.updated_at)}`:"",o?" · current":""))}))))}function P(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("circle",{cx:"12",cy:"12",r:"10"}),e.createElement("circle",{cx:"12",cy:"12",r:"4"}),e.createElement("path",{d:"M4.93 4.93l4.24 4.24M14.83 14.83l4.24 4.24M14.83 9.17l4.24-4.24M14.83 9.17l3.53-3.53M4.93 19.07l4.24-4.24"}))}function Xe(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("path",{d:"M20 6L9 17l-5-5"}))}function Ye(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"22",height:"22",fill:"currentColor"},e.createElement("path",{d:"M4 4h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H8l-4 4V6a2 2 0 0 1 2-2z"}))}function ze(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"22",height:"22",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("polyline",{points:"6 9 12 15 18 9"}))}function W(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"}))}function qe(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function Je(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor"},e.createElement("path",{d:"M2 21l21-9L2 3v7l15 2-15 2z"}))}function Qe(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.createElement("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),e.createElement("polyline",{points:"21 15 16 10 5 21"}))}function R(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",className:"dgl-spin",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"},e.createElement("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}))}function Ze(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("polyline",{points:"15 3 21 3 21 9"}),e.createElement("polyline",{points:"9 21 3 21 3 15"}),e.createElement("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),e.createElement("line",{x1:"3",y1:"21",x2:"10",y2:"14"}))}function et(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("polyline",{points:"4 14 10 14 10 20"}),e.createElement("polyline",{points:"20 10 14 10 14 4"}),e.createElement("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),e.createElement("line",{x1:"3",y1:"21",x2:"10",y2:"14"}))}function tt(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("polyline",{points:"23 4 23 10 17 10"}),e.createElement("polyline",{points:"1 20 1 14 7 14"}),e.createElement("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"}))}function at(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},e.createElement("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}),e.createElement("line",{x1:"7",y1:"9",x2:"17",y2:"9"}),e.createElement("line",{x1:"7",y1:"13",x2:"13",y2:"13"}))}function ue(){return e.createElement("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"currentColor"},e.createElement("path",{d:"M12 2l2.39 6.95L21 11l-6.61 2.05L12 20l-2.39-6.95L3 11l6.61-2.05L12 2z"}))}let j=null,A=null;function ge(t){if(typeof document=="undefined")throw new Error("DocGenLab.init() requires a browser environment.");if(j){j.render(d.createElement(H,t));return}A=document.createElement("div"),A.id="docgenlab-chat-widget-root",document.body.appendChild(A),j=K.createRoot(A),j.render(d.createElement(H,t))}function fe(){j&&(j.unmount(),j=null),A&&(A.remove(),A=null)}typeof window!="undefined"&&(window.DocGenLab={init:ge,destroy:fe,DocGenLabChat:H}),I.DocGenLabChat=H,I.destroy=fe,I.init=ge,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});
|
|
9
9
|
//# sourceMappingURL=index.umd.cjs.map
|