@holaboss/client 0.2.0-beta.3 → 0.2.0-beta.30

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/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  'use client'
2
- var F=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(e,t)=>{for(var a in t)F(e,a,{get:t[a],enumerable:!0})},te=(e,t,a,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of X(t))!Z.call(e,n)&&n!==a&&F(e,n,{get:()=>t[n],enumerable:!(s=Q(t,n))||s.enumerable});return e};var re=e=>te(F({},"__esModule",{value:!0}),e);var pe={};ee(pe,{Chat:()=>G,HolaProvider:()=>q,PortalConflict:()=>v,createApiTransport:()=>z,createHolaClient:()=>K,createPortalData:()=>V,createWidgetTransport:()=>O,mergeMessage:()=>L,textDeltaOf:()=>I,thinkingDeltaOf:()=>R,toolEventOf:()=>E,useArtifactUrl:()=>k,useChat:()=>U,useHolaClient:()=>A,useThread:()=>Y});module.exports=re(pe);var W=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},I=e=>{let t=W(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},R=e=>{let t=W(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},E=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="tool_execution_start"&&t.toolCallId?{phase:"start",id:t.toolCallId,name:t.toolName}:t.type==="tool_execution_end"&&t.toolCallId?{phase:"end",id:t.toolCallId,isError:t.isError}:null};var oe=/^ /,C=e=>{if(e&&typeof e=="object"){let t=e,a=typeof t.error=="string"?t.error:"request_failed";return typeof t.retryable=="boolean"?{error:a,retryable:t.retryable}:{error:a}}return{error:"request_failed"}},se=e=>{let t="message",a=[];for(let s of e.split(`
3
- `))s.startsWith(":")||(s.startsWith("event:")?t=s.slice(6).trim():s.startsWith("data:")&&a.push(s.slice(5).replace(oe,"")));return a.length>0?{event:t,data:a.join(`
4
- `)}:null},ne=(e,t,a)=>{let s;try{s=JSON.parse(e.data)}catch{return}if(e.event==="session"){let n=s.sessionId;n&&(a(n),t.onSession?.(n));return}if(e.event==="turn_event"){t.onEvent?.(s);let n=I(s);n&&t.onText?.(n);let d=R(s);d&&t.onThinking?.(d);let r=E(s);r&&t.onTool?.(r);return}if(e.event==="chat_completed"){let n=s;a(n.sessionId),t.onComplete?.(n);return}e.event==="chat_error"&&t.onError?.(C(s))},h=async(e,t)=>{let a=await fetch(e,{headers:t});if(!a.ok)throw new Error(`hola: request failed (${a.status})`);return await a.json()},j=async e=>{let t=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body});if(!t.ok)throw new Error(`hola: message failed (${t.status})`);return await t.json()},N=async(e,t,a,s)=>{let n=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body,signal:s});if(!(n.ok&&n.body)){t.onError?.({error:`stream_failed_${n.status}`});return}let d=n.body.getReader(),r=new TextDecoder,o="",l=()=>{let c=o.indexOf(`
2
+ var ee=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var pt=(e,t)=>{for(var n in t)ee(e,n,{get:t[n],enumerable:!0})},ct=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ut(t))!dt.call(e,s)&&s!==n&&ee(e,s,{get:()=>t[s],enumerable:!(r=lt(t,s))||r.enumerable});return e};var mt=e=>ct(ee({},"__esModule",{value:!0}),e);var Bt={};pt(Bt,{Chat:()=>Oe,CreditRefused:()=>E,GRID_COLS:()=>oe,GRID_MAX_COLS:()=>se,GRID_MAX_ROWS:()=>ie,HolaProvider:()=>$e,PortalConflict:()=>M,QUOTE_BALANCE_LABEL:()=>Ce,QUOTE_DEPOSIT_LABEL:()=>ke,bandOfKind:()=>$,bandOfType:()=>ae,buyRequestText:()=>nt,cellValue:()=>Se,createApiTransport:()=>Ee,createHolaClient:()=>Fe,createPortalCredits:()=>je,createPortalData:()=>Ge,createPortalShop:()=>Qe,createWidgetTransport:()=>z,deliverableCellText:()=>he,deliverableStatus:()=>fe,deriveFields:()=>ne,emptyTableResponses:()=>F,facetValues:()=>tt,footprintOf:()=>le,footprintWith:()=>J,formatDeliverableDate:()=>Te,groupDeliverableVersions:()=>Y,includesFor:()=>et,inferSpec:()=>re,isDeliverableChecked:()=>xe,mergeMessage:()=>De,modeOf:()=>ze,money:()=>_,normalizeDeliverableColType:()=>Z,normalizeDeliverableItem:()=>X,orderBilling:()=>Ve,parseDashboardSpec:()=>me,parseDeliverableItems:()=>ge,parseDeliverableTable:()=>be,parseTableResponses:()=>we,placeWidgets:()=>K,priceFor:()=>Xe,priceLabel:()=>Re,publishedVersionOf:()=>ye,quantityRange:()=>Ze,quoteSchedule:()=>Be,renderModel:()=>ce,setResponse:()=>ve,setTableReview:()=>Pe,shelfPriceLabel:()=>Ke,shelfProblem:()=>rt,splitLayout:()=>ue,textDeltaOf:()=>L,thinkingDeltaOf:()=>U,toolEventOf:()=>q,totalFor:()=>Ye,useArtifactUrl:()=>B,useChat:()=>G,useCredits:()=>ot,useHolaClient:()=>j,useShop:()=>st,useThread:()=>at});module.exports=mt(Bt);var Ie=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},L=e=>{let t=Ie(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},U=e=>{let t=Ie(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},q=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="tool_execution_start"&&t.toolCallId?{phase:"start",id:t.toolCallId,name:t.toolName}:t.type==="tool_execution_end"&&t.toolCallId?{phase:"end",id:t.toolCallId,isError:t.isError}:null};var gt=/^ /,w=e=>{if(e&&typeof e=="object"){let t=e,n=typeof t.error=="string"?t.error:"request_failed";return typeof t.retryable=="boolean"?{error:n,retryable:t.retryable}:{error:n}}return{error:"request_failed"}},ft=e=>{let t="message",n=[];for(let r of e.split(`
3
+ `))r.startsWith(":")||(r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&n.push(r.slice(5).replace(gt,"")));return n.length>0?{event:t,data:n.join(`
4
+ `)}:null},yt=(e,t,n)=>{let r;try{r=JSON.parse(e.data)}catch{return}if(e.event==="session"){let s=r.sessionId;s&&(n(s),t.onSession?.(s));return}if(e.event==="turn_event"){t.onEvent?.(r);let s=L(r);s&&t.onText?.(s);let i=U(r);i&&t.onThinking?.(i);let o=q(r);o&&t.onTool?.(o);return}if(e.event==="chat_completed"){let s=r;n(s.sessionId),t.onComplete?.(s);return}e.event==="chat_error"&&t.onError?.(w(r))},P=async(e,t)=>{let n=await fetch(e,{headers:t});if(!n.ok)throw new Error(`hola: request failed (${n.status})`);return await n.json()},Ae=async e=>{let t=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body});if(!t.ok)throw new Error(`hola: message failed (${t.status})`);return await t.json()},He=async(e,t,n,r)=>{let s=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body,signal:r});if(!(s.ok&&s.body)){t.onError?.({error:`stream_failed_${s.status}`});return}let i=s.body.getReader(),o=new TextDecoder,a="",l=()=>{let d=a.indexOf(`
5
5
 
6
- `);for(;c!==-1;){let b=o.slice(0,c);o=o.slice(c+2);let u=se(b);u&&ne(u,t,a),c=o.indexOf(`
6
+ `);for(;d!==-1;){let p=a.slice(0,d);a=a.slice(d+2);let f=ft(p);f&&yt(f,t,n),d=a.indexOf(`
7
7
 
8
- `)}},i=async()=>{let c=await d.read();if(!c.done)return o+=r.decode(c.value,{stream:!0}),l(),i()};await i()};var ae=/\/+$/,S="/api/v1/end-user",z=e=>{let t=e.baseUrl.replace(ae,""),a=()=>typeof e.token=="function"?e.token():e.token,s=r=>e.project?`${r}project=${encodeURIComponent(e.project)}`:"",n=async()=>({"content-type":"application/json",authorization:`Bearer ${await a()}`}),d=async r=>{let o=await fetch(`${t}${S}/chat${s("?")}`,{method:"POST",headers:await n(),body:JSON.stringify({message:r})});if(!o.ok)throw new Error(`hola: message failed (${o.status})`);return{reply:(await o.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>h(`${t}${S}/chat/info${s("?")}`,await n()),sendMessage:d,streamMessage:async(r,o)=>{try{let l=await d(r);o.onText?.(l.reply),o.onComplete?.(l)}catch(l){o.onError?.(C(l))}},subscribe:(r,o)=>{let l=o?.since??"0",i=!1,c,b=o?.intervalMs??3e3,u=async()=>{try{let g=await h(`${t}${S}/chat/thread?since=${encodeURIComponent(l)}${s("&")}`,await n());for(let m of g.messages)r.onMessage(m);l=g.cursor}catch(g){r.onError?.(C(g))}i||(c=setTimeout(u,b))},p=()=>{i=!0,c&&clearTimeout(c)};return o?.signal?.addEventListener("abort",p),c=setTimeout(u,0),p},requestHuman:async()=>{await fetch(`${t}${S}/chat/request-human${s("?")}`,{method:"POST",headers:await n(),body:"{}"})}}};var $=require("react"),k=(e,t)=>{let[a,s]=(0,$.useState)("");return(0,$.useEffect)(()=>{if(!e){s("");return}let n=Uint8Array.from(atob(e),r=>r.charCodeAt(0)),d=URL.createObjectURL(new Blob([n],{type:t}));return s(d),()=>URL.revokeObjectURL(d)},[e,t]),a};var D=require("react");var M=require("react"),B=require("react/jsx-runtime"),J=(0,M.createContext)(null),q=({client:e,children:t})=>(0,B.jsx)(J.Provider,{value:e,children:t}),A=()=>{let e=(0,M.useContext)(J);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};var w=require("react"),U=e=>{let[t,a]=(0,w.useState)([]),[s,n]=(0,w.useState)(""),[d,r]=(0,w.useState)(!1),[o,l]=(0,w.useState)(null),i=(0,w.useRef)(0),c=(0,w.useCallback)(()=>{let u=i.current;return i.current+=1,u},[]);(0,w.useEffect)(()=>{let u=!0;return e.getInfo().then(p=>{u&&p.greeting&&a([{id:c(),role:"assistant",text:p.greeting}])}).catch(()=>{}),()=>{u=!1}},[e,c]);let b=(0,w.useCallback)(()=>{let u=s.trim();if(!u||d)return;n(""),l(null),r(!0);let p=c(),g=c();a(f=>[...f,{id:p,role:"user",text:u},{id:g,role:"assistant",text:"",streaming:!0}]);let m=f=>{a(H=>H.map(_=>_.id===g?f(_):_))};e.streamMessage(u,{onText:f=>m(H=>({...H,text:H.text+f})),onComplete:f=>{m(H=>({...H,text:f.reply||H.text,artifacts:f.artifacts,streaming:!1})),r(!1)},onError:f=>{m(H=>({...H,streaming:!1})),l(f.error),r(!1)}}).catch(f=>{m(H=>({...H,streaming:!1})),l(f instanceof Error?f.message:"stream_failed"),r(!1)})},[s,d,e,c]);return{messages:t,input:s,setInput:n,send:b,sending:d,error:o}};var y=require("react/jsx-runtime"),T={root:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:14,color:"#111827"},log:{flex:1,overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:8},user:{alignSelf:"flex-end",background:"#111827",color:"#ffffff",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},assistant:{alignSelf:"flex-start",background:"#f1f1f4",color:"#111827",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},artifacts:{display:"flex",flexDirection:"column",gap:6,marginTop:6},image:{maxHeight:220,borderRadius:8,border:"1px solid #e5e7eb"},link:{color:"#2563eb",textDecoration:"underline",wordBreak:"break-all"},error:{color:"#b91c1c",padding:"4px 12px",fontSize:13},form:{display:"flex",gap:8,borderTop:"1px solid #e5e7eb",padding:8},input:{flex:1,border:"1px solid #d1d5db",borderRadius:8,padding:"8px 10px",fontSize:14,outline:"none"},button:{border:"none",background:"#111827",color:"#ffffff",borderRadius:8,padding:"8px 14px",fontSize:14,cursor:"pointer"}},ie=({artifact:e})=>{let t=k(e.dataBase64??"",e.mimeType),a=e.url??t;return a?e.mimeType.startsWith("image/")?(0,y.jsx)("a",{href:a,rel:"noopener noreferrer",target:"_blank",children:(0,y.jsx)("img",{alt:e.filename,src:a,style:T.image})}):(0,y.jsx)("a",{download:e.filename,href:a,style:T.link,children:e.filename}):null},G=()=>{let e=A(),{messages:t,input:a,setInput:s,send:n,sending:d,error:r}=U(e),o=(0,D.useRef)(null);(0,D.useEffect)(()=>{let i=o.current;i&&(i.scrollTop=i.scrollHeight)},[t]);let l=i=>{i.preventDefault(),n()};return(0,y.jsxs)("div",{style:T.root,children:[(0,y.jsx)("div",{ref:o,style:T.log,children:t.map(i=>(0,y.jsxs)("div",{style:i.role==="user"?T.user:T.assistant,children:[i.text||(i.streaming?"\u2026":""),i.artifacts&&i.artifacts.length>0?(0,y.jsx)("div",{style:T.artifacts,children:i.artifacts.map(c=>(0,y.jsx)(ie,{artifact:c},c.filename))}):null]},i.id))}),r?(0,y.jsx)("div",{style:T.error,children:r}):null,(0,y.jsxs)("form",{onSubmit:l,style:T.form,children:[(0,y.jsx)("input",{"aria-label":"Message",onChange:i=>s(i.target.value),placeholder:"Type a message\u2026",style:T.input,value:a}),(0,y.jsx)("button",{disabled:d||a.trim().length===0,style:T.button,type:"submit",children:"Send"})]})]})};var le=/\/+$/,O=e=>{let t=e.sessionId,a=e.baseUrl.replace(le,""),s=r=>`${a}/endpoint/${encodeURIComponent(e.token)}${r}`,n={"content-type":"application/json"},d=(r,o)=>({url:s(r),headers:n,body:JSON.stringify({message:o,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>h(s("/config"),{}),sendMessage:async r=>{let o=await j(d("/message",r));return t=o.sessionId,o},streamMessage:(r,o,l)=>N(d("/message/stream",r),o,i=>{t=i},l),subscribe:(r,o)=>{let l=o?.since??"0",i=!1,c,b=o?.intervalMs??3e3,u=async()=>{let g=t;if(g)try{let m=await h(s(`/messages?session=${encodeURIComponent(g)}&since=${encodeURIComponent(l)}`),{});for(let f of m.messages)r.onMessage(f);l=m.cursor}catch(m){r.onError?.(C(m))}i||(c=setTimeout(u,b))},p=()=>{i=!0,c&&clearTimeout(c)};return o?.signal?.addEventListener("abort",p),c=setTimeout(u,0),p},requestHuman:async()=>{t&&await fetch(s("/request-human"),{method:"POST",headers:n,body:JSON.stringify({sessionId:t})})}}};var K=e=>"transport"in e?e.transport:O(e);var ce=/\/+$/,P="/api/v1/end-user",v=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function de(e){let t="";for(let s=0;s<e.length;s+=32768)t+=String.fromCharCode(...e.subarray(s,s+32768));return btoa(t)}var V=e=>{let t=e.baseUrl.replace(ce,""),a=()=>typeof e.token=="function"?e.token():e.token,s=async()=>({"content-type":"application/json",authorization:`Bearer ${await a()}`}),n=async(r,o)=>{try{let l=await fetch(`${t}${P}${r}`,{method:o.method,headers:await s(),...o.body===void 0?{}:{body:JSON.stringify(o.body)}});if(l.status===409){let i=await l.json().catch(()=>({}));throw new v(i.message??"Someone else saved this first.")}if(!l.ok){let i=await l.text().catch(()=>""),c=`${o.method} ${r} \u2192 ${String(l.status)}`;try{let b=JSON.parse(i);b.message&&(c=b.message)}catch{c=i?`${c}: ${i}`:c}throw C(new Error(c))}return await l.json()}catch(l){throw C(l)}},d=r=>`/tables/${encodeURIComponent(r)}`;return{listTables:async()=>(await h(`${t}${P}/tables`,await s())).tables,listRows:async(r,o)=>await h(`${t}${P}${d(r)}/rows?limit=${String(o??100)}`,await s()),insertRow:async(r,o)=>{let{rowIds:l}=await n(`${d(r)}/rows`,{method:"POST",body:{rows:[o]}}),i=l[0];if(!i)throw C(new Error("The row was not created."));return i},patchRow:async(r,o,l)=>(await n(`${d(r)}/rows/${encodeURIComponent(o)}`,{method:"PATCH",body:l})).updated,deleteRow:async(r,o)=>(await n(`/${encodeURIComponent(r)}/${encodeURIComponent(o)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await h(`${t}${P}/tables/files/rows?limit=200`,await s())).rows.map(o=>({id:o.rowId,filename:String(o.data.filename??""),source:String(o.data.source??"client"),campaign:String(o.data.campaign??""),size:typeof o.data.size=="number"?o.data.size:0,createdAt:o.createdAt})),uploadFile:async(r,o)=>{let l=new Uint8Array(await r.arrayBuffer());return await n("/files",{method:"POST",body:{filename:r.name,mime:r.type||"application/octet-stream",data:de(l),...o===void 0?{}:{message:o}}})},fileLink:async r=>await h(`${t}${P}/files/${encodeURIComponent(r)}/url`,await s()),deleteFile:async r=>(await n(`/files/${encodeURIComponent(r)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await h(`${t}${P}/documents`,await s())).documents,readDocument:async r=>(await h(`${t}${P}/documents/${encodeURIComponent(r)}`,await s())).document,saveDocument:async(r,o)=>await n(`/documents/${encodeURIComponent(r)}`,{method:"PATCH",body:o})}};var x=require("react");function L(e,t){return e.some(s=>s.id===t.id)?e:[...t.author==="client"?e.filter(s=>!(s.pending&&s.author==="client"&&s.text===t.text)):e,t]}var Y=(e,t)=>{let[a,s]=(0,x.useState)([]),[n,d]=(0,x.useState)(""),[r,o]=(0,x.useState)(!1),[l,i]=(0,x.useState)(null),c=(0,x.useRef)(0),b=t?.pollMs??2e3;(0,x.useEffect)(()=>{let p=!0;return e.getInfo().then(g=>{p&&g.greeting&&s(m=>m.length===0?[{id:"greeting",cursor:"",author:"agent",text:g.greeting}]:m)}).catch(()=>{}),()=>{p=!1}},[e]),(0,x.useEffect)(()=>e.subscribe?.({onMessage:p=>s(g=>L(g,p)),onError:p=>i(p.error)},{intervalMs:b}),[e,b]);let u=(0,x.useCallback)(()=>{let p=n.trim();if(!p||r)return;d(""),i(null),o(!0),c.current+=1;let g={id:`pending-${c.current}`,cursor:"",author:"client",text:p,pending:!0};s(m=>[...m,g]),e.sendMessage(p).then(()=>o(!1)).catch(m=>{i(m instanceof Error?m.message:"send_failed"),o(!1)})},[n,r,e]);return{messages:a,input:n,setInput:d,send:u,sending:r,error:l}};0&&(module.exports={Chat,HolaProvider,PortalConflict,createApiTransport,createHolaClient,createPortalData,createWidgetTransport,mergeMessage,textDeltaOf,thinkingDeltaOf,toolEventOf,useArtifactUrl,useChat,useHolaClient,useThread});
8
+ `)}},u=async()=>{let d=await i.read();if(!d.done)return a+=o.decode(d.value,{stream:!0}),l(),u()};await u()};var bt=/\/+$/,te="/api/v1/end-user",Ee=e=>{let t=e.baseUrl.replace(bt,""),n=()=>typeof e.token=="function"?e.token():e.token,r=o=>e.project?`${o}project=${encodeURIComponent(e.project)}`:"",s=async()=>({"content-type":"application/json",authorization:`Bearer ${await n()}`}),i=async o=>{let a=await fetch(`${t}${te}/chat${r("?")}`,{method:"POST",headers:await s(),body:JSON.stringify({message:o})});if(!a.ok)throw new Error(`hola: message failed (${a.status})`);return{reply:(await a.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>P(`${t}${te}/chat/info${r("?")}`,await s()),sendMessage:i,streamMessage:async(o,a)=>{try{let l=await i(o);a.onText?.(l.reply),a.onComplete?.(l)}catch(l){a.onError?.(w(l))}},subscribe:(o,a)=>{let l=a?.since??"0",u=!1,d,p=a?.intervalMs??3e3,f=typeof document<"u",c=()=>f&&document.visibilityState==="hidden",m=!1,y=()=>{if(!u){if(c()){m=!0;return}d=setTimeout(b,p)}},b=async()=>{try{let x=await P(`${t}${te}/chat/thread?since=${encodeURIComponent(l)}${r("&")}`,await s());for(let I of x.messages)o.onMessage(I);l=x.cursor,o.onHealthy?.()}catch(x){o.onError?.(w(x))}y()},R=()=>{u||!m||c()||(m=!1,d&&clearTimeout(d),d=setTimeout(b,0))};f&&document.addEventListener("visibilitychange",R);let g=()=>{u=!0,d&&clearTimeout(d),f&&document.removeEventListener("visibilitychange",R)};return a?.signal?.addEventListener("abort",g),d=setTimeout(b,0),g}}};var N=require("react"),B=(e,t)=>{let[n,r]=(0,N.useState)("");return(0,N.useEffect)(()=>{if(!e){r("");return}let s=Uint8Array.from(atob(e),o=>o.charCodeAt(0)),i=URL.createObjectURL(new Blob([s],{type:t}));return r(i),()=>URL.revokeObjectURL(i)},[e,t]),n};var Q=require("react");var V=require("react"),We=require("react/jsx-runtime"),Me=(0,V.createContext)(null),$e=({client:e,children:t})=>(0,We.jsx)(Me.Provider,{value:e,children:t}),j=()=>{let e=(0,V.useContext)(Me);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};var S=require("react"),G=e=>{let[t,n]=(0,S.useState)([]),[r,s]=(0,S.useState)(""),[i,o]=(0,S.useState)(!1),[a,l]=(0,S.useState)(null),u=(0,S.useRef)(0),d=(0,S.useRef)(null);(0,S.useEffect)(()=>()=>d.current?.abort(),[]);let p=(0,S.useCallback)(()=>{let c=u.current;return u.current+=1,c},[]);(0,S.useEffect)(()=>{let c=!0;return e.getInfo().then(m=>{c&&m.greeting&&n([{id:p(),role:"assistant",text:m.greeting}])}).catch(()=>{}),()=>{c=!1}},[e,p]);let f=(0,S.useCallback)(()=>{let c=r.trim();if(!c||i)return;s(""),l(null),o(!0);let m=p(),y=p();n(g=>[...g,{id:m,role:"user",text:c},{id:y,role:"assistant",text:"",streaming:!0}]);let b=g=>{n(x=>x.map(I=>I.id===y?g(I):I))},R=new AbortController;d.current=R,e.streamMessage(c,{onText:g=>b(x=>({...x,text:x.text+g})),onComplete:g=>{b(x=>({...x,text:g.reply||x.text,artifacts:g.artifacts,streaming:!1})),o(!1)},onError:g=>{b(x=>({...x,streaming:!1})),l(g.error),o(!1)}},R.signal).catch(g=>{b(x=>({...x,streaming:!1})),l(g instanceof Error?g.message:"stream_failed"),o(!1)}).finally(()=>{o(!1),b(g=>g.streaming?{...g,streaming:!1}:g)})},[r,i,e,p]);return{messages:t,input:r,setInput:s,send:f,sending:i,error:a}};var v=require("react/jsx-runtime"),k={root:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:14,color:"#111827"},log:{flex:1,overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:8},user:{alignSelf:"flex-end",background:"#111827",color:"#ffffff",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},assistant:{alignSelf:"flex-start",background:"#f1f1f4",color:"#111827",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},artifacts:{display:"flex",flexDirection:"column",gap:6,marginTop:6},image:{maxHeight:220,borderRadius:8,border:"1px solid #e5e7eb"},link:{color:"#2563eb",textDecoration:"underline",wordBreak:"break-all"},error:{color:"#b91c1c",padding:"4px 12px",fontSize:13},form:{display:"flex",gap:8,borderTop:"1px solid #e5e7eb",padding:8},input:{flex:1,border:"1px solid #d1d5db",borderRadius:8,padding:"8px 10px",fontSize:14,outline:"none"},button:{border:"none",background:"#111827",color:"#ffffff",borderRadius:8,padding:"8px 14px",fontSize:14,cursor:"pointer"}},ht=({artifact:e})=>{let t=B(e.dataBase64??"",e.mimeType),n=e.url??t;return n?e.mimeType.startsWith("image/")?(0,v.jsx)("a",{href:n,rel:"noopener noreferrer",target:"_blank",children:(0,v.jsx)("img",{alt:e.filename,src:n,style:k.image})}):(0,v.jsx)("a",{download:e.filename,href:n,style:k.link,children:e.filename}):null},Oe=()=>{let e=j(),{messages:t,input:n,setInput:r,send:s,sending:i,error:o}=G(e),a=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let u=a.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let l=u=>{u.preventDefault(),s()};return(0,v.jsxs)("div",{style:k.root,children:[(0,v.jsx)("div",{ref:a,style:k.log,children:t.map(u=>(0,v.jsxs)("div",{style:u.role==="user"?k.user:k.assistant,children:[u.text||(u.streaming?"\u2026":""),u.artifacts&&u.artifacts.length>0?(0,v.jsx)("div",{style:k.artifacts,children:u.artifacts.map(d=>(0,v.jsx)(ht,{artifact:d},d.filename))}):null]},u.id))}),o?(0,v.jsx)("div",{style:k.error,children:o}):null,(0,v.jsxs)("form",{onSubmit:l,style:k.form,children:[(0,v.jsx)("input",{"aria-label":"Message",onChange:u=>r(u.target.value),placeholder:"Type a message\u2026",style:k.input,value:n}),(0,v.jsx)("button",{disabled:i||n.trim().length===0,style:k.button,type:"submit",children:"Send"})]})]})};var xt=/\/+$/,z=e=>{let t=e.sessionId,n=e.baseUrl.replace(xt,""),r=o=>`${n}/endpoint/${encodeURIComponent(e.token)}${o}`,s={"content-type":"application/json"},i=(o,a)=>({url:r(o),headers:s,body:JSON.stringify({message:a,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>P(r("/config"),{}),sendMessage:async o=>{let a=await Ae(i("/message",o));return t=a.sessionId,a},streamMessage:(o,a,l)=>He(i("/message/stream",o),a,u=>{t=u},l),subscribe:(o,a)=>{let l=a?.since??"0",u=!1,d,p=a?.intervalMs??3e3,f=async()=>{let m=t;if(m)try{let y=await P(r(`/messages?session=${encodeURIComponent(m)}&since=${encodeURIComponent(l)}`),{});for(let b of y.messages)o.onMessage(b);l=y.cursor,o.onHealthy?.()}catch(y){o.onError?.(w(y))}u||(d=setTimeout(f,p))},c=()=>{u=!0,d&&clearTimeout(d)};return a?.signal?.addEventListener("abort",c),d=setTimeout(f,0),c}}};var Fe=e=>"transport"in e?e.transport:z(e);var wt=/^https?:\/\//i,St=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,vt=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function Pt(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(wt.test(e))return"url";if(St.test(e))return"date"}return"text"}function ne(e){let t=[],n=new Map;for(let r of e)for(let[s,i]of Object.entries(r.data??{})){if(i==null)continue;let o=n.get(s);o||(o=new Map,n.set(s,o),t.push(s));let a=Pt(i);o.set(a,(o.get(a)??0)+1)}return t.map(r=>{let s=n.get(r)??new Map,i="text",o=-1;for(let[a,l]of s)l>o&&(o=l,i=a);return{key:r,label:vt(r),type:i}})}var Tt=e=>typeof e=="number"?e:Number(e)||0,_e=e=>/rate|position|rank|score|percent|avg/i.test(e),kt=/posted|published|sent|completed|shipped|launched|_at/i,Ct=new Set(["service","order","end_user_id"]);function re(e,t){let n=e.filter(l=>!Ct.has(l.key)),r=n.filter(l=>l.type==="number").slice(0,3),s=n.find(l=>l.key==="status")??n.find(l=>l.type==="select"),i=n.find(l=>l.type==="date"&&kt.test(l.key))??n.find(l=>l.type==="date"),o=n.filter(l=>l.type==="number"&&!_e(l.key)).map(l=>({field:l,total:t.reduce((u,d)=>u+Tt(d.data[l.key]),0)})).sort((l,u)=>u.total-l.total).find(l=>l.total>0)?.field??null,a=[{type:"stat",label:"Items",agg:"count"}];for(let l of r){let u=_e(l.key);a.push({type:"stat",metric:l.key,agg:u?"avg":"sum",label:u?`Avg ${l.label.toLowerCase()}`:l.label})}return i&&a.push({type:"line",x:i.key,y:o?.key,agg:"sum",title:o?`${o.label} by day`:"Items by day"}),s&&a.push({type:"donut",groupBy:s.key,title:s.label}),a.push({type:"table",columns:n.map(l=>l.key)}),{version:1,widgets:a}}var oe=6,se=6,ie=4,Le={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:2}},Rt=e=>Math.max(1,Math.min(6,Math.round(e))),Dt=e=>Math.max(1,Math.min(4,Math.round(e)));function $(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function ae(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function le(e){return Le[e]}function J(e,t,n){let r=Le[e];return{w:t===void 0?r.w:Rt(t),h:n===void 0?r.h:Dt(n)}}function K(e){let t=[],n=[],r=(o,a,l,u)=>{if(o<0||o+l>6)return!1;for(let d=0;d<u;d+=1){let p=n[a+d];if(p){for(let f=0;f<l;f+=1)if(p[o+f])return!1}}return!0},s=(o,a,l,u)=>{for(let d=0;d<u;d+=1){let p=n[a+d]??[];for(let f=0;f<l;f+=1)p[o+f]=!0;n[a+d]=p}},i=(o,a)=>{for(let l=0;;l+=1)for(let u=0;u+o<=6;u+=1)if(r(u,l,o,a))return{gx:u,gy:l}};for(let o of e){let a=J($(o.kind),o.w,o.h),u=o.gx!==void 0&&o.gy!==void 0&&r(o.gx,o.gy,a.w,a.h)&&o.gx!==void 0&&o.gy!==void 0?{gx:o.gx,gy:o.gy}:i(a.w,a.h);s(u.gx,u.gy,a.w,a.h),t.push({widget:o,gx:u.gx,gy:u.gy,w:a.w,h:a.h})}return t}function ue(e){let t=[],n=[];for(let r of e)$(r.kind)==="block"?n.push(r):t.push(r);return{tiles:K(t),blocks:n}}var Ue=new Set(["service","order","end_user_id"]),de=e=>typeof e=="number"?e:Number(e)||0,qe=e=>e==null?"":String(e);function pe(e,t){if(e==="count")return t.length;if(t.length===0)return 0;if(e==="last")return t[t.length-1]??0;if(e==="min")return Math.min(...t);if(e==="max")return Math.max(...t);let n=t.reduce((r,s)=>r+s,0);return e==="avg"?Math.round(n/t.length*100)/100:n}function It(e,t,n,r){let s=new Map;for(let i of e){let o=new Date(qe(i.data[t]));if(Number.isNaN(o.getTime()))continue;let a=o.toISOString().slice(0,10),l=s.get(a)??[];l.push(n?de(i.data[n]):1),s.set(a,l)}return[...s.entries()].sort((i,o)=>i[0]<o[0]?-1:1).map(([i,o])=>({label:new Date(`${i}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:n?pe(r,o):o.length}))}function At(e,t,n,r="sum"){let s=new Map;for(let i of e){let o=qe(i.data[t]).trim();if(!o)continue;let a=s.get(o)??[];a.push(n?de(i.data[n]):1),s.set(o,a)}return[...s.entries()].map(([i,o])=>({label:i,value:n?pe(r,o):o.length})).sort((i,o)=>o.value-i.value)}function Ht(e,t,n,r){switch(e.type){case"stat":{let s=e.metric?t.get(e.metric):void 0;if(e.metric&&!s)return null;if(!s)return{kind:"stat",label:e.label??"Items",value:r.length};let i=r.map(o=>de(o.data[s.key]));return{kind:"stat",label:e.label??s.label,value:pe(e.agg??"sum",i)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let s=It(r,e.x,e.y,e.agg??"sum");return s.length<2?null:{kind:"series",draw:e.type,title:e.title??"By day",points:s}}case"donut":{if(!t.has(e.groupBy))return null;let s=At(r,e.groupBy,e.metric,e.agg??"sum");return s.length===0?null:{kind:"donut",title:e.title??t.get(e.groupBy)?.label??"Breakdown",points:s}}case"table":{let s=e.columns?e.columns.map(i=>t.get(i)).filter(i=>i!==void 0&&!Ue.has(i.key)):n;return s.length===0?null:{kind:"table",title:e.title,columns:s,rows:r}}case"text":return{kind:"text",title:e.title,body:e.body};default:return null}}function ce(e,t,n,r={}){let s=new Map,i=l=>({byKey:new Map(l.fields.map(u=>[u.key,u])),cols:l.fields.filter(u=>!Ue.has(u.key)),rows:l.rows}),o=i({fields:t,rows:n});for(let[l,u]of Object.entries(r))s.set(l,i(u));let a=[];for(let l of e.widgets){let u=l.type==="text"?void 0:l.source,d=u?s.get(u):o;if(!d)continue;let p=Ht(l,d.byKey,d.cols,d.rows);p&&a.push({...p,w:l.w,h:l.h,gx:l.gx,gy:l.gy})}return a}var Et=new Set(["sum","avg","count","min","max","last"]),Ne=e=>typeof e=="string"&&Et.has(e)?e:void 0,h=e=>typeof e=="string"&&e!==""?e:void 0,W=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,O=e=>typeof e=="number"&&e>=1?Math.min(4,Math.round(e)):void 0,D=e=>typeof e=="number"&&e>=0?Math.round(e):void 0;function Mt(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"stat":return{type:"stat",source:h(t.source),label:h(t.label),metric:h(t.metric)??h(t.column),agg:Ne(t.agg),w:W(t.w),h:O(t.h),gx:D(t.gx),gy:D(t.gy)};case"line":case"bar":{let n=h(t.x);return n?{type:t.type,source:h(t.source),title:h(t.title),x:n,y:h(t.y)??h(t.column),agg:Ne(t.agg),w:W(t.w),h:O(t.h),gx:D(t.gx),gy:D(t.gy)}:null}case"donut":{let n=h(t.groupBy)??h(t.column);return n?{type:"donut",source:h(t.source),title:h(t.title),groupBy:n,w:W(t.w),h:O(t.h),gx:D(t.gx),gy:D(t.gy)}:null}case"table":{let n=Array.isArray(t.columns)?t.columns.filter(r=>typeof r=="string"):void 0;return{type:"table",source:h(t.source),title:h(t.title),columns:n,w:W(t.w),h:O(t.h),gx:D(t.gx),gy:D(t.gy)}}case"text":{let n=h(t.body);return n?{type:"text",title:h(t.title),body:n,w:W(t.w),h:O(t.h),gx:D(t.gx),gy:D(t.gy)}:null}default:return null}}function me(e){let t=e;if(typeof e=="string"){if(e.trim()==="")return null;try{t=JSON.parse(e)}catch{return null}}if(typeof t!="object"||t===null)return null;let n=t.widgets;if(!Array.isArray(n))return null;let r=n.map(Mt).filter(i=>i!==null);if(r.length===0)return null;let s=t.version;return{version:typeof s=="number"?s:1,title:h(t.title),widgets:r}}function X(e){if(typeof e=="string")return e?{kind:"file",value:e}:null;if(e&&typeof e=="object"){let t=e,n=typeof t.value=="string"?t.value:"",r=t.kind==="link"||t.kind==="text"||t.kind==="table"?t.kind:"file",s=typeof t.v=="number"&&t.v>=1?Math.floor(t.v):void 0;return n?{kind:r,value:n,...s?{v:s}:{}}:null}return null}function Y(e){let t=new Map;for(let n of e){let r=n.v??1,s=t.get(r)??[];s.push(n),t.set(r,s)}return[...t.entries()].sort(([n],[r])=>n-r).map(([n,r])=>({v:n,items:r}))}function ge(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(X).filter(s=>s!==null)}catch{}let n=String(e.file??"");return n?[{kind:"file",value:n}]:[]}function fe(e,t,n,r=""){let i=Y(e).find(a=>a.v===t)?.items??[],o=i.filter(a=>a.kind==="file").map(a=>n.get(a.value)??"");return i.some(a=>a.kind==="table")&&o.push(r),o.length===0||o.some(a=>a==="")?"awaiting":o.some(a=>a==="revise")?"revise":"accepted"}function ye(e){return Number(e.published_version)||0}function Z(e){return e==="number"||e==="date"||e==="boolean"||e==="select"||e==="url"?e:e==="link"?"url":e==="checkbox"?"boolean":"text"}function be(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let n=t.columns.map((i,o)=>({key:typeof i.key=="string"&&i.key?i.key:typeof i.id=="string"&&i.id?i.id:`column_${o+1}`,label:typeof i.label=="string"?i.label:"",type:Z(i.type),...i.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((i,o)=>({id:typeof i.id=="string"&&i.id?i.id:`row_${o}`,cells:i.cells&&typeof i.cells=="object"?i.cells:{}})),s=typeof t.name=="string"?t.name:void 0;return{columns:n,rows:r,...s?{name:s}:{}}}}catch{}return null}function he(e){return e==null?"":String(e)}function xe(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function F(){return{cells:{},verdict:"",comment:""}}function we(e){if(typeof e!="string"||e.trim()==="")return F();try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t;return{cells:n.cells&&typeof n.cells=="object"?n.cells:n,verdict:n.verdict==="accepted"||n.verdict==="revise"?n.verdict:"",comment:typeof n.comment=="string"?n.comment:""}}}catch{}return F()}function Se(e,t,n){if(e.clientEditable){let r=n.cells[t.id];if(r&&e.key in r)return r[e.key]}return t.cells[e.key]}function ve(e,t,n,r){return{...e,cells:{...e.cells,[t]:{...e.cells[t]??{},[n]:r}}}}function Pe(e,t,n){return{...e,verdict:t,comment:n}}function Te(e){let t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var E=class extends Error{code;status;constructor(t,n,r){super(n),this.name="CreditRefused",this.code=t,this.status=r}},$t=/\/+$/,Wt="/api/v1/end-user",ke="Pre-payment",Ce="After-payment";function Be(e,t){if(e<=0)return[];let n=t&&typeof t.upfront=="number"&&Number.isFinite(t.upfront)?Math.max(0,Math.min(t.upfront,e)):e,r=Math.round((e-n)*100)/100,s=[];return n>0&&s.push({label:ke,amount:n}),r>0&&s.push({label:Ce,amount:r}),s}var Ve=(e,t,n)=>{let r=t.filter(l=>l.order===n),s=r.reduce((l,u)=>l+u.amount,0),i=r.filter(l=>l.status==="paid").reduce((l,u)=>l+u.amount,0),o=e.value>0,a=s>0?s-i:e.value-i;return{value:e.value,priced:o,billed:s,paid:i,due:Math.max(0,a),lines:[...r].sort((l,u)=>l.status!==u.status?l.status==="due"?-1:1:(l.dueDate||l.paidAt).localeCompare(u.dueDate||u.paidAt)),awaitingPayment:o&&i<=0}},je=e=>{let t=e.baseUrl.replace($t,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async(s,i={method:"GET"})=>{try{let o=await fetch(`${t}${Wt}${s}`,{method:i.method,headers:{"content-type":"application/json",authorization:`Bearer ${await n()}`},...i.body===void 0?{}:{body:JSON.stringify(i.body)}});if(!o.ok){let a=await o.json().catch(()=>({}));throw new E(a.error??"request_failed",a.message??`${i.method} ${s} \u2192 ${String(o.status)}`,o.status)}return await o.json()}catch(o){throw o instanceof E?o:w(o)}};return{wallet:()=>r("/credits"),history:()=>r("/credits/history"),topup:s=>r("/credits/checkout",{method:"POST",body:{packId:s}}),checkout:s=>r("/shop/checkout",{method:"POST",body:s}),payments:()=>r("/payments"),paymentMethods:()=>r("/payment-methods"),markPaymentSent:(s,i)=>r(`/payments/${encodeURIComponent(s)}/sent`,{method:"POST",body:{reference:i??""}}),inquiryQuote:s=>r(`/inquiries/${encodeURIComponent(s)}/quote`),acceptInquiry:(s,i)=>r(`/inquiries/${encodeURIComponent(s)}/accept`,{method:"POST",body:{version:i}}),enquire:(s,i,o)=>r("/shop/enquire",{method:"POST",body:{productId:s,answers:i,name:o??""}})}};var Ot=/\/+$/,H="/api/v1/end-user",M=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function Ft(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var Ge=e=>{let t=e.baseUrl.replace(Ot,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await n()}`}),s=async(o,a)=>{try{let l=await fetch(`${t}${H}${o}`,{method:a.method,headers:await r(),...a.body===void 0?{}:{body:JSON.stringify(a.body)}});if(l.status===409){let u=await l.json().catch(()=>({}));throw new M(u.message??"Someone else saved this first.")}if(!l.ok){let u=await l.text().catch(()=>""),d=`${a.method} ${o} \u2192 ${String(l.status)}`;try{let p=JSON.parse(u);p.message&&(d=p.message)}catch{d=u?`${d}: ${u}`:d}throw w({error:d})}return await l.json()}catch(l){throw l instanceof M?l:w(l)}},i=o=>`/tables/${encodeURIComponent(o)}`;return{listTables:async()=>(await P(`${t}${H}/tables`,await r())).tables,listRows:async(o,a)=>await P(`${t}${H}${i(o)}/rows?limit=${String(a??100)}`,await r()),insertRow:async(o,a)=>{let{rowIds:l}=await s(`${i(o)}/rows`,{method:"POST",body:{rows:[a]}}),u=l[0];if(!u)throw w(new Error("The row was not created."));return u},patchRow:async(o,a,l)=>(await s(`${i(o)}/rows/${encodeURIComponent(a)}`,{method:"PATCH",body:l})).updated,deleteRow:async(o,a)=>(await s(`/${encodeURIComponent(o)}/${encodeURIComponent(a)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await P(`${t}${H}/tables/files/rows?limit=200`,await r())).rows.map(a=>({id:a.rowId,filename:String(a.data.filename??""),source:String(a.data.source??"client"),campaign:String(a.data.campaign??""),size:typeof a.data.size=="number"?a.data.size:0,createdAt:a.createdAt})),uploadFile:async(o,a)=>{let l=new Uint8Array(await o.arrayBuffer());return await s("/files",{method:"POST",body:{filename:o.name,mime:o.type||"application/octet-stream",data:Ft(l),...a===void 0?{}:{message:a}}})},fileLink:async o=>await P(`${t}${H}/files/${encodeURIComponent(o)}/url`,await r()),deleteFile:async o=>(await s(`/files/${encodeURIComponent(o)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await P(`${t}${H}/documents`,await r())).documents,readDocument:async o=>(await P(`${t}${H}/documents/${encodeURIComponent(o)}`,await r())).document,saveDocument:async(o,a)=>await s(`/documents/${encodeURIComponent(o)}`,{method:"PATCH",body:a})}};var _t=/\/+$/,Lt="/api/v1/end-user",Qe=e=>{let t=e.baseUrl.replace(_t,""),n=async(r,s)=>{let i;try{i=await fetch(`${t}${Lt}${r}`,s===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)})}catch(o){throw w(o)}if(i.status===429)throw w({error:"rate_limited",retryable:!0});if(!i.ok)throw w({error:`shop_request_failed_${String(i.status)}`});try{return await i.json()}catch(o){throw w(o)}};return{listProducts:async()=>{let r=await n(`/shop/products?publishable_key=${encodeURIComponent(e.publishableKey)}`);return{products:r.products.map(s=>({...s,currency:typeof s.currency=="string"?s.currency:""})),truncated:r.truncated===!0,enquiryForm:Array.isArray(r.enquiryForm)?r.enquiryForm:[]}},apply:async r=>await n("/shop/apply",{publishable_key:e.publishableKey,name:r.name,email:r.email,...r.phone?{phone:r.phone}:{},...r.message?{message:r.message}:{},...r.productId?{productId:r.productId}:{}})}};var Ut=new Set(["buy","ask"]);function ze(e){return Ut.has(e.mode)?e.mode:"ask"}var qt={kind:"quoted"};function _(e,t){if(!t)return e.toLocaleString();if(t.toLowerCase()==="credits")return`${e.toLocaleString()} ${e===1?"credit":"credits"}`;let n=Number.isInteger(e)?0:2;try{return new Intl.NumberFormat(void 0,{style:"currency",currency:t,minimumFractionDigits:n,maximumFractionDigits:n}).format(e)}catch{return`${t} ${e.toLocaleString()}`}}function Je(e,t){let n=/^[a-z]+$/i.test(t)&&!t.endsWith("s")?"s":"";return`${e.toLocaleString()} ${t}${n}`}function Re(e,t){return e.kind==="quoted"?"Priced on enquiry":e.kind==="flat"?_(e.price,t):`${_(e.unitPrice,t)} per ${e.unitStep===1?e.unit:Je(e.unitStep,e.unit)}`}function Ke(e){let t=e.currency,n=e.pricing;if(n.kind!=="variants")return Re(n,t);let r=n.variants.map(s=>s.price).filter(s=>typeof s=="number");return r.length>0?`From ${_(Math.min(...r),t)}`:"Priced on enquiry"}function Xe(e,t){if(e.kind!=="variants")return e;let n=e.variants.find(r=>r.name===t);return typeof n?.price=="number"?{kind:"flat",price:n.price}:qt}function Ye(e,t){return e.kind==="flat"?e.price:e.kind==="per_unit"?e.unitPrice*Math.ceil(t/Math.max(e.unitStep,1)):null}function Ze(e,t){let n=t.kind==="per_unit"?Math.max(t.unitStep,1):1;return{min:Math.max(e.minQty??n,n),max:e.maxQty??null,step:n}}function et(e,t){let n=e.variants?.find(r=>r.name===t);return n&&n.includes.length>0?n.includes:e.includes}function tt(e,t){let n=[];for(let r of e){let s=t(r).trim();s&&!n.includes(s)&&n.push(s)}return n}function nt(e,t,n,r){let s=t?`${e.name} \u2014 ${t}`:e.name,i=n.kind==="per_unit"?`, ${Je(r,n.unit)}`:"";return`I'd like to buy ${s}${i}. How do I go ahead?`}function rt(e){return e?(e&&typeof e=="object"&&"error"in e?String(e.error):"")==="rate_limited"?"That's a lot of looking at once \u2014 give it a moment, then reload.":"The shop isn't loading right now. Please try again shortly.":null}var A=require("react"),ot=e=>{let[t,n]=(0,A.useState)(null),[r,s]=(0,A.useState)(!0),[i,o]=(0,A.useState)(null),a=(0,A.useCallback)(async()=>{try{n(await e.wallet()),o(null)}catch{o("Couldn't read your balance just now.")}finally{s(!1)}},[e]),l=(0,A.useCallback)(()=>{a().catch(()=>{})},[a]);return(0,A.useEffect)(()=>(l(),window.addEventListener("focus",l),()=>{window.removeEventListener("focus",l)}),[l]),{wallet:t,loading:r,failure:i,refresh:l}};var C=require("react"),Nt=e=>e&&typeof e=="object"&&typeof e.error=="string"?e.error:e instanceof Error?e.message:"shop_unavailable",st=e=>{let[t,n]=(0,C.useState)([]),[r,s]=(0,C.useState)([]),[i,o]=(0,C.useState)(!1),[a,l]=(0,C.useState)(!0),[u,d]=(0,C.useState)(null),[p,f]=(0,C.useState)(0);(0,C.useEffect)(()=>{let m=!0;return l(!0),e.listProducts().then(y=>{m&&(n(y.products),s(y.enquiryForm),o(y.truncated),d(null))}).catch(y=>{m&&d(Nt(y))}).finally(()=>{m&&l(!1)}),()=>{m=!1}},[e,p]);let c=(0,C.useCallback)(()=>f(m=>m+1),[]);return{products:t,enquiryForm:r,truncated:i,loading:a,error:u,reload:c}};var T=require("react"),it="greeting";function De(e,t){if(e.some(i=>i.id===t.id))return e;let n=e.filter(i=>i.id!==it),r=i=>i.author==="client"==(t.author==="client");return[...n.filter(i=>!(i.pending&&r(i)&&i.text===t.text)),t]}var at=(e,t)=>{let[n,r]=(0,T.useState)([]),[s,i]=(0,T.useState)(""),[o,a]=(0,T.useState)(!1),[l,u]=(0,T.useState)(null),d=(0,T.useRef)(0),p=t?.pollMs??2e3;(0,T.useEffect)(()=>{let c=!0;return e.getInfo().then(m=>{c&&m.greeting&&r(y=>y.length===0?[{id:it,cursor:"",author:"agent",text:m.greeting}]:y)}).catch(()=>{}),()=>{c=!1}},[e]),(0,T.useEffect)(()=>e.subscribe?.({onMessage:c=>r(m=>De(m,c)),onError:c=>u(c.error),onHealthy:()=>u(null)},{intervalMs:p}),[e,p]);let f=(0,T.useCallback)(()=>{let c=s.trim();if(!c||o)return;i(""),u(null),a(!0),d.current+=1;let m=`pending-${d.current}`,y={id:m,cursor:"",author:"client",text:c,pending:!0};r(b=>[...b,y]),e.sendMessage(c).then(b=>{a(!1),b.reply.trim()&&r(g=>g.some(I=>!I.pending&&I.author!=="client"&&I.text===b.reply)?g:(d.current+=1,[...g,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:b.reply,pending:!0}]))}).catch(b=>{u(b instanceof Error?b.message:"send_failed"),a(!1),r(R=>R.filter(g=>g.id!==m)),i(R=>R||c)})},[s,o,e]);return{messages:n,input:s,setInput:i,send:f,sending:o,error:l}};0&&(module.exports={Chat,CreditRefused,GRID_COLS,GRID_MAX_COLS,GRID_MAX_ROWS,HolaProvider,PortalConflict,QUOTE_BALANCE_LABEL,QUOTE_DEPOSIT_LABEL,bandOfKind,bandOfType,buyRequestText,cellValue,createApiTransport,createHolaClient,createPortalCredits,createPortalData,createPortalShop,createWidgetTransport,deliverableCellText,deliverableStatus,deriveFields,emptyTableResponses,facetValues,footprintOf,footprintWith,formatDeliverableDate,groupDeliverableVersions,includesFor,inferSpec,isDeliverableChecked,mergeMessage,modeOf,money,normalizeDeliverableColType,normalizeDeliverableItem,orderBilling,parseDashboardSpec,parseDeliverableItems,parseDeliverableTable,parseTableResponses,placeWidgets,priceFor,priceLabel,publishedVersionOf,quantityRange,quoteSchedule,renderModel,setResponse,setTableReview,shelfPriceLabel,shelfProblem,splitLayout,textDeltaOf,thinkingDeltaOf,toolEventOf,totalFor,useArtifactUrl,useChat,useCredits,useHolaClient,useShop,useThread});