@holaboss/client 0.2.0-beta.35 → 0.2.0-beta.36

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 pe=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var Ct=Object.prototype.hasOwnProperty;var Rt=(e,t)=>{for(var n in t)pe(e,n,{get:t[n],enumerable:!0})},Dt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of kt(t))!Ct.call(e,s)&&s!==n&&pe(e,s,{get:()=>t[s],enumerable:!(r=Pt(t,s))||r.enumerable});return e};var It=e=>Dt(pe({},"__esModule",{value:!0}),e);var un={};Rt(un,{Chat:()=>Je,CreditRefused:()=>M,DATE_FORMATS:()=>te,GRID_COLS:()=>fe,GRID_MAX_COLS:()=>ye,GRID_MAX_ROWS:()=>be,HolaProvider:()=>Qe,InsufficientCredits:()=>L,OPTION_TINTS:()=>se,PortalConflict:()=>O,QUOTE_BALANCE_LABEL:()=>de,QUOTE_DEPOSIT_LABEL:()=>ue,TIME_FORMATS:()=>ne,arrangedColumns:()=>Ae,bandOfKind:()=>H,bandOfType:()=>he,buyRequestText:()=>ht,cellValue:()=>_e,createApiTransport:()=>Ve,createHolaClient:()=>Ke,createPortalCredits:()=>at,createPortalData:()=>lt,createPortalShop:()=>ut,createWidgetTransport:()=>K,creditsOfMoney:()=>st,deliverableCellText:()=>ie,deliverableCellValues:()=>Ee,deliverableStatus:()=>Ce,deriveFields:()=>me,emptyTableResponses:()=>W,facetValues:()=>bt,footprintOf:()=>we,footprintWith:()=>X,formatDeliverableDate:()=>Le,groupDeliverableVersions:()=>ee,includesFor:()=>yt,inferSpec:()=>ge,isDeliverableChecked:()=>Oe,mergeMessage:()=>Ne,modeOf:()=>dt,money:()=>U,normalizeDeliverableColType:()=>re,normalizeDeliverableItem:()=>Z,optionTintIndex:()=>Me,orderBilling:()=>it,parseArrangement:()=>oe,parseDashboardSpec:()=>Pe,parseDeliverableItems:()=>ke,parseDeliverableTable:()=>Ie,parseTableResponses:()=>He,paymentAsked:()=>le,paymentPayMethods:()=>ot,placeWidgets:()=>Y,priceFor:()=>mt,priceLabel:()=>Ue,publishedVersionOf:()=>Re,quantityRange:()=>ft,quoteSchedule:()=>rt,renderModel:()=>Te,setResponse:()=>$e,setTableReview:()=>We,shelfPriceLabel:()=>ct,shelfProblem:()=>wt,shortenUrl:()=>Fe,splitLayout:()=>xe,textDeltaOf:()=>N,thinkingDeltaOf:()=>q,toolEventOf:()=>j,totalFor:()=>gt,useArtifactUrl:()=>V,useChat:()=>z,useCredits:()=>xt,useHolaClient:()=>Q,useShop:()=>St,useThread:()=>Tt});module.exports=It(un);var qe=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},N=e=>{let t=qe(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},q=e=>{let t=qe(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},j=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 At=/^ /,x=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"}},Mt=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(At,"")));return n.length>0?{event:t,data:n.join(`
4
- `)}:null},Ft=(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=N(r);s&&t.onText?.(s);let l=q(r);l&&t.onThinking?.(l);let o=j(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?.(x(r))},T=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()},je=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()},Be=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 l=s.body.getReader(),o=new TextDecoder,i="",a=()=>{let d=i.indexOf(`
2
+ var ce=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var Rt=Object.getOwnPropertyNames;var Dt=Object.prototype.hasOwnProperty;var It=(e,t)=>{for(var n in t)ce(e,n,{get:t[n],enumerable:!0})},At=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Rt(t))!Dt.call(e,s)&&s!==n&&ce(e,s,{get:()=>t[s],enumerable:!(r=Ct(t,s))||r.enumerable});return e};var Mt=e=>At(ce({},"__esModule",{value:!0}),e);var cn={};It(cn,{COLUMN_TYPES:()=>me,Chat:()=>Xe,CreditRefused:()=>M,DATE_FORMATS:()=>ne,GRID_COLS:()=>be,GRID_MAX_COLS:()=>he,GRID_MAX_ROWS:()=>we,HolaProvider:()=>Je,InsufficientCredits:()=>L,OPTION_TINTS:()=>ie,PortalConflict:()=>O,QUOTE_BALANCE_LABEL:()=>pe,QUOTE_DEPOSIT_LABEL:()=>de,TIME_FORMATS:()=>re,arrangedColumns:()=>Fe,bandOfKind:()=>H,bandOfType:()=>xe,buyRequestText:()=>xt,cellValue:()=>We,createApiTransport:()=>Ge,createHolaClient:()=>Ye,createPortalCredits:()=>ut,createPortalData:()=>dt,createPortalShop:()=>pt,createWidgetTransport:()=>X,creditsOfMoney:()=>at,deliverableCellText:()=>ae,deliverableCellValues:()=>He,deliverableStatus:()=>De,deriveFields:()=>fe,emptyTableResponses:()=>W,facetValues:()=>wt,footprintOf:()=>Te,footprintWith:()=>Y,formatDeliverableDate:()=>Ne,groupDeliverableVersions:()=>te,includesFor:()=>ht,inferSpec:()=>ye,isDeliverableChecked:()=>_e,mergeMessage:()=>je,modeOf:()=>ct,money:()=>U,normalizeColumnType:()=>N,normalizeDeliverableColType:()=>oe,normalizeDeliverableItem:()=>ee,optionTintIndex:()=>Ee,orderBilling:()=>lt,parseArrangement:()=>se,parseDashboardSpec:()=>Ce,parseDeliverableItems:()=>Re,parseDeliverableTable:()=>Me,parseTableResponses:()=>$e,paymentAsked:()=>ue,paymentPayMethods:()=>it,placeWidgets:()=>Z,priceFor:()=>ft,priceLabel:()=>qe,publishedVersionOf:()=>Ie,quantityRange:()=>bt,quoteSchedule:()=>st,renderModel:()=>ke,setResponse:()=>Le,setTableReview:()=>Ue,shelfPriceLabel:()=>gt,shelfProblem:()=>Tt,shortenUrl:()=>Oe,splitLayout:()=>Se,textDeltaOf:()=>q,thinkingDeltaOf:()=>j,toolEventOf:()=>B,totalFor:()=>yt,useArtifactUrl:()=>z,useChat:()=>J,useCredits:()=>St,useHolaClient:()=>Q,useShop:()=>vt,useThread:()=>kt});module.exports=Mt(cn);var me=["text","number","url","date","boolean","select","multi_select","file"],Ft={checkbox:"boolean",link:"url"};function N(e){return typeof e!="string"?"text":me.includes(e)?e:Ft[e]??"text"}var Be=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},q=e=>{let t=Be(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},j=e=>{let t=Be(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},B=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 Et=/^ /,x=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"}},Ot=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(Et,"")));return n.length>0?{event:t,data:n.join(`
4
+ `)}:null},Ht=(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=q(r);s&&t.onText?.(s);let l=j(r);l&&t.onThinking?.(l);let o=B(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?.(x(r))},v=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()},Ve=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()},ze=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 l=s.body.getReader(),o=new TextDecoder,i="",a=()=>{let d=i.indexOf(`
5
5
 
6
- `);for(;d!==-1;){let m=i.slice(0,d);i=i.slice(d+2);let p=Mt(m);p&&Ft(p,t,n),d=i.indexOf(`
6
+ `);for(;d!==-1;){let m=i.slice(0,d);i=i.slice(d+2);let p=Ot(m);p&&Ht(p,t,n),d=i.indexOf(`
7
7
 
8
- `)}},u=async()=>{let d=await l.read();if(!d.done)return i+=o.decode(d.value,{stream:!0}),a(),u()};await u()};var Et=/\/+$/,ce="/api/v1/end-user",Ve=e=>{let t=e.baseUrl.replace(Et,""),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()}`}),l=async o=>{let i=await fetch(`${t}${ce}/chat${r("?")}`,{method:"POST",headers:await s(),body:JSON.stringify({message:o})});if(!i.ok)throw new Error(`hola: message failed (${i.status})`);return{reply:(await i.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>T(`${t}${ce}/chat/info${r("?")}`,await s()),sendMessage:l,streamMessage:async(o,i)=>{try{let a=await l(o);i.onText?.(a.reply),i.onComplete?.(a)}catch(a){i.onError?.(x(a))}},subscribe:(o,i)=>{let a=i?.since??"0",u=!1,d,m=i?.intervalMs??3e3,p=typeof document<"u",c=()=>p&&document.visibilityState==="hidden",g=!1,y=()=>{if(!u){if(c()){g=!0;return}d=setTimeout(b,m)}},b=async()=>{try{let w=await T(`${t}${ce}/chat/thread?since=${encodeURIComponent(a)}${r("&")}`,await s());for(let I of w.messages)o.onMessage(I);a=w.cursor,o.onHealthy?.()}catch(w){o.onError?.(x(w))}y()},R=()=>{u||!g||c()||(g=!1,d&&clearTimeout(d),d=setTimeout(b,0))};p&&document.addEventListener("visibilitychange",R);let f=()=>{u=!0,d&&clearTimeout(d),p&&document.removeEventListener("visibilitychange",R)};return i?.signal?.addEventListener("abort",f),d=setTimeout(b,0),f}}};var B=require("react"),V=(e,t)=>{let[n,r]=(0,B.useState)("");return(0,B.useEffect)(()=>{if(!e){r("");return}let s=Uint8Array.from(atob(e),o=>o.charCodeAt(0)),l=URL.createObjectURL(new Blob([s],{type:t}));return r(l),()=>URL.revokeObjectURL(l)},[e,t]),n};var J=require("react");var G=require("react"),ze=require("react/jsx-runtime"),Ge=(0,G.createContext)(null),Qe=({client:e,children:t})=>(0,ze.jsx)(Ge.Provider,{value:e,children:t}),Q=()=>{let e=(0,G.useContext)(Ge);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};var S=require("react"),z=e=>{let[t,n]=(0,S.useState)([]),[r,s]=(0,S.useState)(""),[l,o]=(0,S.useState)(!1),[i,a]=(0,S.useState)(null),u=(0,S.useRef)(0),d=(0,S.useRef)(null);(0,S.useEffect)(()=>()=>d.current?.abort(),[]);let m=(0,S.useCallback)(()=>{let c=u.current;return u.current+=1,c},[]);(0,S.useEffect)(()=>{let c=!0;return e.getInfo().then(g=>{c&&g.greeting&&n([{id:m(),role:"assistant",text:g.greeting}])}).catch(()=>{}),()=>{c=!1}},[e,m]);let p=(0,S.useCallback)(()=>{let c=r.trim();if(!c||l)return;s(""),a(null),o(!0);let g=m(),y=m();n(f=>[...f,{id:g,role:"user",text:c},{id:y,role:"assistant",text:"",streaming:!0}]);let b=f=>{n(w=>w.map(I=>I.id===y?f(I):I))},R=new AbortController;d.current=R,e.streamMessage(c,{onText:f=>b(w=>({...w,text:w.text+f})),onComplete:f=>{b(w=>({...w,text:f.reply||w.text,artifacts:f.artifacts,streaming:!1})),o(!1)},onError:f=>{b(w=>({...w,streaming:!1})),a(f.error),o(!1)}},R.signal).catch(f=>{b(w=>({...w,streaming:!1})),a(f instanceof Error?f.message:"stream_failed"),o(!1)}).finally(()=>{o(!1),b(f=>f.streaming?{...f,streaming:!1}:f)})},[r,l,e,m]);return{messages:t,input:r,setInput:s,send:p,sending:l,error:i}};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"}},Ot=({artifact:e})=>{let t=V(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},Je=()=>{let e=Q(),{messages:t,input:n,setInput:r,send:s,sending:l,error:o}=z(e),i=(0,J.useRef)(null);(0,J.useEffect)(()=>{let u=i.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let a=u=>{u.preventDefault(),s()};return(0,v.jsxs)("div",{style:k.root,children:[(0,v.jsx)("div",{ref:i,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)(Ot,{artifact:d},d.filename))}):null]},u.id))}),o?(0,v.jsx)("div",{style:k.error,children:o}):null,(0,v.jsxs)("form",{onSubmit:a,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:l||n.trim().length===0,style:k.button,type:"submit",children:"Send"})]})]})};var Ht=/\/+$/,K=e=>{let t=e.sessionId,n=e.baseUrl.replace(Ht,""),r=o=>`${n}/endpoint/${encodeURIComponent(e.token)}${o}`,s={"content-type":"application/json"},l=(o,i)=>({url:r(o),headers:s,body:JSON.stringify({message:i,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>T(r("/config"),{}),sendMessage:async o=>{let i=await je(l("/message",o));return t=i.sessionId,i},streamMessage:(o,i,a)=>Be(l("/message/stream",o),i,u=>{t=u},a),subscribe:(o,i)=>{let a=i?.since??"0",u=!1,d,m=i?.intervalMs??3e3,p=async()=>{let g=t;if(g)try{let y=await T(r(`/messages?session=${encodeURIComponent(g)}&since=${encodeURIComponent(a)}`),{});for(let b of y.messages)o.onMessage(b);a=y.cursor,o.onHealthy?.()}catch(y){o.onError?.(x(y))}u||(d=setTimeout(p,m))},c=()=>{u=!0,d&&clearTimeout(d)};return i?.signal?.addEventListener("abort",c),d=setTimeout(p,0),c}}};var Ke=e=>"transport"in e?e.transport:K(e);var _t=/^https?:\/\//i,$t=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,Wt=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function Lt(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(_t.test(e))return"url";if($t.test(e))return"date"}return"text"}function me(e){let t=[],n=new Map,r=[...e].sort((s,l)=>String(s.rowId??"").localeCompare(String(l.rowId??"")));for(let s of r)for(let[l,o]of Object.entries(s.data??{})){if(o==null)continue;let i=n.get(l);i||(i=new Map,n.set(l,i),t.push(l));let a=Lt(o);i.set(a,(i.get(a)??0)+1)}return t.map(s=>{let l=n.get(s)??new Map,o="text",i=-1;for(let[a,u]of l)u>i&&(i=u,o=a);return{key:s,label:Wt(s),type:o}})}var Ut=e=>typeof e=="number"?e:Number(e)||0,Xe=e=>/rate|position|rank|score|percent|avg/i.test(e),Nt=/posted|published|sent|completed|shipped|launched|_at/i,qt=new Set(["service","order","end_user_id"]);function ge(e,t){let n=e.filter(a=>!qt.has(a.key)),r=n.filter(a=>a.type==="number").slice(0,3),s=n.find(a=>a.key==="status")??n.find(a=>a.type==="select"),l=n.find(a=>a.type==="date"&&Nt.test(a.key))??n.find(a=>a.type==="date"),o=n.filter(a=>a.type==="number"&&!Xe(a.key)).map(a=>({field:a,total:t.reduce((u,d)=>u+Ut(d.data[a.key]),0)})).sort((a,u)=>u.total-a.total).find(a=>a.total>0)?.field??null,i=[{type:"stat",label:"Items",agg:"count"}];for(let a of r){let u=Xe(a.key);i.push({type:"stat",metric:a.key,agg:u?"avg":"sum",label:u?`Avg ${a.label.toLowerCase()}`:a.label})}return l&&i.push({type:"line",x:l.key,y:o?.key,agg:"sum",title:o?`${o.label} by day`:"Items by day"}),s&&i.push({type:"donut",groupBy:s.key,title:s.label}),i.push({type:"table",columns:n.map(a=>a.key)}),{version:1,widgets:i}}var fe=6,ye=6,be=4,Ye={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:2}},jt=e=>Math.max(1,Math.min(6,Math.round(e))),Bt=e=>Math.max(1,Math.min(4,Math.round(e)));function H(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function he(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function we(e){return Ye[e]}function X(e,t,n){let r=Ye[e];return{w:t===void 0?r.w:jt(t),h:n===void 0?r.h:Bt(n)}}function Y(e){let t=[],n=[],r=(o,i,a,u)=>{if(o<0||o+a>6)return!1;for(let d=0;d<u;d+=1){let m=n[i+d];if(m){for(let p=0;p<a;p+=1)if(m[o+p])return!1}}return!0},s=(o,i,a,u)=>{for(let d=0;d<u;d+=1){let m=n[i+d]??[];for(let p=0;p<a;p+=1)m[o+p]=!0;n[i+d]=m}},l=(o,i)=>{for(let a=0;;a+=1)for(let u=0;u+o<=6;u+=1)if(r(u,a,o,i))return{gx:u,gy:a}};for(let o of e){let i=X(H(o.kind),o.w,o.h),u=o.gx!==void 0&&o.gy!==void 0&&r(o.gx,o.gy,i.w,i.h)&&o.gx!==void 0&&o.gy!==void 0?{gx:o.gx,gy:o.gy}:l(i.w,i.h);s(u.gx,u.gy,i.w,i.h),t.push({widget:o,gx:u.gx,gy:u.gy,w:i.w,h:i.h})}return t}function xe(e){let t=[],n=[];for(let r of e)H(r.kind)==="block"?n.push(r):t.push(r);return{tiles:Y(t),blocks:n}}var Ze=new Set(["service","order","end_user_id"]),Se=e=>typeof e=="number"?e:Number(e)||0,et=e=>e==null?"":String(e);function ve(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 Vt(e,t,n,r){let s=new Map;for(let l of e){let o=new Date(et(l.data[t]));if(Number.isNaN(o.getTime()))continue;let i=o.toISOString().slice(0,10),a=s.get(i)??[];a.push(n?Se(l.data[n]):1),s.set(i,a)}return[...s.entries()].sort((l,o)=>l[0]<o[0]?-1:1).map(([l,o])=>({label:new Date(`${l}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:n?ve(r,o):o.length}))}function Gt(e,t,n,r="sum"){let s=new Map;for(let l of e){let o=et(l.data[t]).trim();if(!o)continue;let i=s.get(o)??[];i.push(n?Se(l.data[n]):1),s.set(o,i)}return[...s.entries()].map(([l,o])=>({label:l,value:n?ve(r,o):o.length})).sort((l,o)=>o.value-l.value)}function Qt(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 l=r.map(o=>Se(o.data[s.key]));return{kind:"stat",label:e.label??s.label,value:ve(e.agg??"sum",l)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let s=Vt(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=Gt(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(l=>t.get(l)).filter(l=>l!==void 0&&!Ze.has(l.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 Te(e,t,n,r={}){let s=new Map,l=a=>({byKey:new Map(a.fields.map(u=>[u.key,u])),cols:a.fields.filter(u=>!Ze.has(u.key)),rows:a.rows}),o=l({fields:t,rows:n});for(let[a,u]of Object.entries(r))s.set(a,l(u));let i=[];for(let a of e.widgets){let u=a.type==="text"?void 0:a.source,d=u?s.get(u):o;if(!d)continue;let m=Qt(a,d.byKey,d.cols,d.rows);m&&i.push({...m,w:a.w,h:a.h,gx:a.gx,gy:a.gy})}return i}var zt=new Set(["sum","avg","count","min","max","last"]),tt=e=>typeof e=="string"&&zt.has(e)?e:void 0,h=e=>typeof e=="string"&&e!==""?e:void 0,_=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,$=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 Jt(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:tt(t.agg),w:_(t.w),h:$(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:tt(t.agg),w:_(t.w),h:$(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:_(t.w),h:$(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:_(t.w),h:$(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:_(t.w),h:$(t.h),gx:D(t.gx),gy:D(t.gy)}:null}default:return null}}function Pe(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(Jt).filter(l=>l!==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 Z(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 ee(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 ke(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(Z).filter(s=>s!==null)}catch{}let n=String(e.file??"");return n?[{kind:"file",value:n}]:[]}function Ce(e,t,n,r=""){let l=ee(e).find(i=>i.v===t)?.items??[],o=l.filter(i=>i.kind==="file").map(i=>n.get(i.value)??"");return l.some(i=>i.kind==="table")&&o.push(r),o.length===0||o.some(i=>i==="")?"awaiting":o.some(i=>i==="revise")?"revise":"accepted"}function Re(e){return Number(e.published_version)||0}var te=["short","medium","long","iso","relative"],ne=["none","12h","24h"];function re(e){return e==="number"||e==="date"||e==="boolean"||e==="select"||e==="multi_select"||e==="file"||e==="url"?e:e==="link"?"url":e==="checkbox"?"boolean":"text"}function Ie(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let n=t.columns.map((o,i)=>({key:typeof o.key=="string"&&o.key?o.key:typeof o.id=="string"&&o.id?o.id:`column_${i+1}`,label:typeof o.label=="string"?o.label:"",type:re(o.type),...(()=>{let a=Array.isArray(o.options)?[...new Set(o.options.map(u=>String(u).trim()).filter(u=>u!==""))]:[];return a.length>0?{options:a}:{}})(),...te.includes(o.dateFormat)?{dateFormat:o.dateFormat}:{},...ne.includes(o.timeFormat)?{timeFormat:o.timeFormat}:{},...o.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((o,i)=>({id:typeof o.id=="string"&&o.id?o.id:`row_${i}`,cells:o.cells&&typeof o.cells=="object"?o.cells:{}})),s=typeof t.name=="string"?t.name:void 0,l=oe(t.view);return{columns:n,rows:r,...s?{name:s}:{},...l?{view:l}:{}}}}catch{}return null}var E=e=>{if(!Array.isArray(e))return;let t=e.map(n=>String(n).trim()).filter(n=>n!=="");return t.length>0?t:void 0};function oe(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n={};if(t.widths&&typeof t.widths=="object"&&!Array.isArray(t.widths))for(let[l,o]of Object.entries(t.widths))typeof o=="number"&&Number.isFinite(o)&&o>0&&(n[l]=Math.round(o));let r=typeof t.frozen=="number"&&Number.isFinite(t.frozen)&&t.frozen>0?Math.floor(t.frozen):void 0,s={...E(t.hidden)?{hidden:E(t.hidden)}:{},...E(t.order)?{order:E(t.order)}:{},...E(t.wrap)?{wrap:E(t.wrap)}:{},...Object.keys(n).length>0?{widths:n}:{},...r?{frozen:r}:{}};return Object.keys(s).length>0?s:void 0}function Ae(e){let t=e.view;if(!t)return e.columns;let n=new Set(e.columns.map(i=>i.key)),r=new Set(t.hidden??[]),s=(t.order??[]).filter(i=>n.has(i)),l=e.columns.map(i=>i.key).filter(i=>!s.includes(i)),o=new Map(e.columns.map(i=>[i.key,i]));return[...s,...l].filter(i=>!r.has(i)).map(i=>o.get(i)).filter(i=>!!i)}var se=6;function Me(e){let t=e.trim().toLowerCase();if(t==="")return-1;let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return Math.abs(n)%se}function Fe(e){try{let t=new URL(e),n=t.pathname.split("/").filter(Boolean).pop()??"";return n===""?t.host:`${t.host}/\u2026/${n}`}catch{return e}}function ie(e){return e==null?"":String(e)}function Ee(e){let t=ie(e).trim();if(t==="")return[];try{let n=JSON.parse(t);if(Array.isArray(n))return n.map(r=>String(r).trim()).filter(r=>r!=="")}catch{}return t.split(",").map(n=>n.trim()).filter(n=>n!=="")}function Oe(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function W(){return{cells:{},verdict:"",comment:""}}function He(e){if(typeof e!="string"||e.trim()==="")return W();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 W()}function _e(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 $e(e,t,n,r){return{...e,cells:{...e.cells,[t]:{...e.cells[t]??{},[n]:r}}}}function We(e,t,n){return{...e,verdict:t,comment:n}}function Le(e,t="medium",n="none"){let r=new Date(/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00`:e);if(Number.isNaN(r.getTime()))return e;if(t==="iso"){let o=a=>String(a).padStart(2,"0"),i=`${r.getFullYear()}-${o(r.getMonth()+1)}-${o(r.getDate())}`;return n==="none"?i:`${i} ${o(r.getHours())}:${o(r.getMinutes())}`}if(t==="relative")return Xt(r);let s=t==="short"?{year:"numeric",month:"numeric",day:"numeric"}:t==="long"?{year:"numeric",month:"long",day:"numeric",weekday:"long"}:{year:"numeric",month:"short",day:"numeric"},l=n==="none"?{}:{hour:"numeric",minute:"2-digit",hour12:n==="12h"};return r.toLocaleString(void 0,{...s,...l})}var Kt=6e4,nt=36e5,De=864e5;function Xt(e){let t=e.getTime()-Date.now(),n=Math.abs(t);if(n>30*De)return e.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});let r=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});return n<nt?r.format(Math.round(t/Kt),"minute"):n<De?r.format(Math.round(t/nt),"hour"):r.format(Math.round(t/De),"day")}var M=class extends Error{code;status;constructor(t,n,r){super(n),this.name="CreditRefused",this.code=t,this.status=r}},L=class extends M{credits;balance;short;constructor(t,n){super("insufficient_credits",t,402),this.name="InsufficientCredits",this.credits=n.credits,this.balance=n.balance,this.short=n.short}},Yt=/\/+$/,Zt="/api/v1/end-user",ue="Pre-payment",de="After-payment";function rt(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:ue,amount:n}),r>0&&s.push({label:de,amount:r}),s}var le=e=>e.status!=="paid"&&e.asked!==!1,ot=(e,t)=>e.payMethods&&e.payMethods.length>0?[...e.payMethods]:[...t],st=(e,t)=>{let n=typeof t=="number"&&Number.isFinite(t)&&t>0?t:1;return!Number.isFinite(e)||e<=0?0:Math.ceil(e*n)},ae=e=>{let t=e.label.trim().toLowerCase();return t===ue.toLowerCase()?0:t===de.toLowerCase()?2:1},it=(e,t,n)=>{let r=t.filter(p=>p.order===n),s=p=>p.reduce((c,g)=>c+g.amount,0),l=s(r),o=s(r.filter(p=>p.status==="paid")),i=e.value>0,a=[...r].sort((p,c)=>ae(p)!==ae(c)?ae(p)-ae(c):(p.dueDate||p.paidAt).localeCompare(c.dueDate||c.paidAt)),u=a.filter(le),d=a.filter(p=>p.status!=="paid"&&!le(p)),m=l>0?s(u):e.value-o;return{value:e.value,priced:i,billed:l,paid:o,due:Math.max(0,m),scheduled:s(d),lines:a,asked:u,upcoming:d,awaitingPayment:i&&o<=0}},en=e=>{let{credits:t,balance:n,short:r}=e;return typeof t!="number"||typeof n!="number"||typeof r!="number"||!(Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r))?null:{credits:t,balance:n,short:r}},at=e=>{let t=e.baseUrl.replace(Yt,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async(s,l={method:"GET"})=>{try{let o=await fetch(`${t}${Zt}${s}`,{method:l.method,headers:{"content-type":"application/json",authorization:`Bearer ${await n()}`},...l.body===void 0?{}:{body:JSON.stringify(l.body)}});if(!o.ok){let i=await o.json().catch(()=>({})),a=i.message??`${l.method} ${s} \u2192 ${String(o.status)}`,u=en(i);throw o.status===402&&i.error==="insufficient_credits"&&u?new L(a,u):new M(i.error??"request_failed",a,o.status)}return await o.json()}catch(o){throw o instanceof M?o:x(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,l)=>r(`/payments/${encodeURIComponent(s)}/sent`,{method:"POST",body:{reference:l??""}}),payWithCredits:s=>r(`/payments/${encodeURIComponent(s)}/pay-with-credits`,{method:"POST",body:{}}),inquiryQuote:s=>r(`/inquiries/${encodeURIComponent(s)}/quote`),acceptInquiry:(s,l)=>r(`/inquiries/${encodeURIComponent(s)}/accept`,{method:"POST",body:{version:l}}),enquire:(s,l,o)=>r("/shop/enquire",{method:"POST",body:{productId:s,answers:l,name:o??""}})}};var tn=/\/+$/,F="/api/v1/end-user",O=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function nn(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var lt=e=>{let t=e.baseUrl.replace(tn,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await n()}`}),s=async(o,i)=>{try{let a=await fetch(`${t}${F}${o}`,{method:i.method,headers:await r(),...i.body===void 0?{}:{body:JSON.stringify(i.body)}});if(a.status===409){let u=await a.json().catch(()=>({}));throw new O(u.message??"Someone else saved this first.")}if(!a.ok){let u=await a.text().catch(()=>""),d=`${i.method} ${o} \u2192 ${String(a.status)}`;try{let m=JSON.parse(u);m.message&&(d=m.message)}catch{d=u?`${d}: ${u}`:d}throw x({error:d})}return await a.json()}catch(a){throw a instanceof O?a:x(a)}},l=o=>`/tables/${encodeURIComponent(o)}`;return{listTables:async()=>(await T(`${t}${F}/tables`,await r())).tables,listRows:async(o,i)=>await T(`${t}${F}${l(o)}/rows?limit=${String(i??100)}`,await r()),insertRow:async(o,i)=>{let{rowIds:a}=await s(`${l(o)}/rows`,{method:"POST",body:{rows:[i]}}),u=a[0];if(!u)throw x(new Error("The row was not created."));return u},patchRow:async(o,i,a)=>(await s(`${l(o)}/rows/${encodeURIComponent(i)}`,{method:"PATCH",body:a})).updated,deleteRow:async(o,i)=>(await s(`/${encodeURIComponent(o)}/${encodeURIComponent(i)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await T(`${t}${F}/tables/files/rows?limit=200`,await r())).rows.map(i=>({id:i.rowId,filename:String(i.data.filename??""),source:String(i.data.source??"client"),campaign:String(i.data.campaign??""),size:typeof i.data.size=="number"?i.data.size:0,createdAt:i.createdAt})),uploadFile:async(o,i)=>{let a=new Uint8Array(await o.arrayBuffer());return await s("/files",{method:"POST",body:{filename:o.name,mime:o.type||"application/octet-stream",data:nn(a),...i===void 0?{}:{message:i}}})},fileLink:async o=>await T(`${t}${F}/files/${encodeURIComponent(o)}/url`,await r()),deleteFile:async o=>(await s(`/files/${encodeURIComponent(o)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await T(`${t}${F}/documents`,await r())).documents,readDocument:async o=>(await T(`${t}${F}/documents/${encodeURIComponent(o)}`,await r())).document,saveDocument:async(o,i)=>await s(`/documents/${encodeURIComponent(o)}`,{method:"PATCH",body:i})}};var rn=/\/+$/,on="/api/v1/end-user",ut=e=>{let t=e.baseUrl.replace(rn,""),n=async(r,s)=>{let l;try{l=await fetch(`${t}${on}${r}`,s===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)})}catch(o){throw x(o)}if(l.status===429)throw x({error:"rate_limited",retryable:!0});if(!l.ok)throw x({error:`shop_request_failed_${String(l.status)}`});try{return await l.json()}catch(o){throw x(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 sn=new Set(["buy","ask"]);function dt(e){return sn.has(e.mode)?e.mode:"ask"}var an={kind:"quoted"};function U(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 pt(e,t){let n=/^[a-z]+$/i.test(t)&&!t.endsWith("s")?"s":"";return`${e.toLocaleString()} ${t}${n}`}function Ue(e,t){return e.kind==="quoted"?"Priced on enquiry":e.kind==="flat"?U(e.price,t):`${U(e.unitPrice,t)} per ${e.unitStep===1?e.unit:pt(e.unitStep,e.unit)}`}function ct(e){let t=e.currency,n=e.pricing;if(n.kind!=="variants")return Ue(n,t);let r=n.variants.map(s=>s.price).filter(s=>typeof s=="number");return r.length>0?`From ${U(Math.min(...r),t)}`:"Priced on enquiry"}function mt(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}:an}function gt(e,t){return e.kind==="flat"?e.price:e.kind==="per_unit"?e.unitPrice*Math.ceil(t/Math.max(e.unitStep,1)):null}function ft(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 yt(e,t){let n=e.variants?.find(r=>r.name===t);return n&&n.includes.length>0?n.includes:e.includes}function bt(e,t){let n=[];for(let r of e){let s=t(r).trim();s&&!n.includes(s)&&n.push(s)}return n}function ht(e,t,n,r){let s=t?`${e.name} \u2014 ${t}`:e.name,l=n.kind==="per_unit"?`, ${pt(r,n.unit)}`:"";return`I'd like to buy ${s}${l}. How do I go ahead?`}function wt(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"),xt=e=>{let[t,n]=(0,A.useState)(null),[r,s]=(0,A.useState)(!0),[l,o]=(0,A.useState)(null),i=(0,A.useCallback)(async()=>{try{n(await e.wallet()),o(null)}catch{o("Couldn't read your balance just now.")}finally{s(!1)}},[e]),a=(0,A.useCallback)(()=>{i().catch(()=>{})},[i]);return(0,A.useEffect)(()=>(a(),window.addEventListener("focus",a),()=>{window.removeEventListener("focus",a)}),[a]),{wallet:t,loading:r,failure:l,refresh:a}};var C=require("react"),ln=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)([]),[l,o]=(0,C.useState)(!1),[i,a]=(0,C.useState)(!0),[u,d]=(0,C.useState)(null),[m,p]=(0,C.useState)(0);(0,C.useEffect)(()=>{let g=!0;return a(!0),e.listProducts().then(y=>{g&&(n(y.products),s(y.enquiryForm),o(y.truncated),d(null))}).catch(y=>{g&&d(ln(y))}).finally(()=>{g&&a(!1)}),()=>{g=!1}},[e,m]);let c=(0,C.useCallback)(()=>p(g=>g+1),[]);return{products:t,enquiryForm:r,truncated:l,loading:i,error:u,reload:c}};var P=require("react"),vt="greeting";function Ne(e,t){if(e.some(l=>l.id===t.id))return e;let n=e.filter(l=>l.id!==vt),r=l=>l.author==="client"==(t.author==="client");return[...n.filter(l=>!(l.pending&&r(l)&&l.text===t.text)),t]}var Tt=(e,t)=>{let[n,r]=(0,P.useState)([]),[s,l]=(0,P.useState)(""),[o,i]=(0,P.useState)(!1),[a,u]=(0,P.useState)(null),d=(0,P.useRef)(0),m=t?.pollMs??2e3;(0,P.useEffect)(()=>{let c=!0;return e.getInfo().then(g=>{c&&g.greeting&&r(y=>y.length===0?[{id:vt,cursor:"",author:"agent",text:g.greeting}]:y)}).catch(()=>{}),()=>{c=!1}},[e]),(0,P.useEffect)(()=>e.subscribe?.({onMessage:c=>r(g=>Ne(g,c)),onError:c=>u(c.error),onHealthy:()=>u(null)},{intervalMs:m}),[e,m]);let p=(0,P.useCallback)(()=>{let c=s.trim();if(!c||o)return;l(""),u(null),i(!0),d.current+=1;let g=`pending-${d.current}`,y={id:g,cursor:"",author:"client",text:c,pending:!0};r(b=>[...b,y]),e.sendMessage(c).then(b=>{i(!1),b.reply.trim()&&r(f=>f.some(I=>!I.pending&&I.author!=="client"&&I.text===b.reply)?f:(d.current+=1,[...f,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:b.reply,pending:!0}]))}).catch(b=>{u(b instanceof Error?b.message:"send_failed"),i(!1),r(R=>R.filter(f=>f.id!==g)),l(R=>R||c)})},[s,o,e]);return{messages:n,input:s,setInput:l,send:p,sending:o,error:a}};0&&(module.exports={Chat,CreditRefused,DATE_FORMATS,GRID_COLS,GRID_MAX_COLS,GRID_MAX_ROWS,HolaProvider,InsufficientCredits,OPTION_TINTS,PortalConflict,QUOTE_BALANCE_LABEL,QUOTE_DEPOSIT_LABEL,TIME_FORMATS,arrangedColumns,bandOfKind,bandOfType,buyRequestText,cellValue,createApiTransport,createHolaClient,createPortalCredits,createPortalData,createPortalShop,createWidgetTransport,creditsOfMoney,deliverableCellText,deliverableCellValues,deliverableStatus,deriveFields,emptyTableResponses,facetValues,footprintOf,footprintWith,formatDeliverableDate,groupDeliverableVersions,includesFor,inferSpec,isDeliverableChecked,mergeMessage,modeOf,money,normalizeDeliverableColType,normalizeDeliverableItem,optionTintIndex,orderBilling,parseArrangement,parseDashboardSpec,parseDeliverableItems,parseDeliverableTable,parseTableResponses,paymentAsked,paymentPayMethods,placeWidgets,priceFor,priceLabel,publishedVersionOf,quantityRange,quoteSchedule,renderModel,setResponse,setTableReview,shelfPriceLabel,shelfProblem,shortenUrl,splitLayout,textDeltaOf,thinkingDeltaOf,toolEventOf,totalFor,useArtifactUrl,useChat,useCredits,useHolaClient,useShop,useThread});
8
+ `)}},u=async()=>{let d=await l.read();if(!d.done)return i+=o.decode(d.value,{stream:!0}),a(),u()};await u()};var _t=/\/+$/,ge="/api/v1/end-user",Ge=e=>{let t=e.baseUrl.replace(_t,""),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()}`}),l=async o=>{let i=await fetch(`${t}${ge}/chat${r("?")}`,{method:"POST",headers:await s(),body:JSON.stringify({message:o})});if(!i.ok)throw new Error(`hola: message failed (${i.status})`);return{reply:(await i.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>v(`${t}${ge}/chat/info${r("?")}`,await s()),sendMessage:l,streamMessage:async(o,i)=>{try{let a=await l(o);i.onText?.(a.reply),i.onComplete?.(a)}catch(a){i.onError?.(x(a))}},subscribe:(o,i)=>{let a=i?.since??"0",u=!1,d,m=i?.intervalMs??3e3,p=typeof document<"u",c=()=>p&&document.visibilityState==="hidden",g=!1,y=()=>{if(!u){if(c()){g=!0;return}d=setTimeout(b,m)}},b=async()=>{try{let w=await v(`${t}${ge}/chat/thread?since=${encodeURIComponent(a)}${r("&")}`,await s());for(let I of w.messages)o.onMessage(I);a=w.cursor,o.onHealthy?.()}catch(w){o.onError?.(x(w))}y()},R=()=>{u||!g||c()||(g=!1,d&&clearTimeout(d),d=setTimeout(b,0))};p&&document.addEventListener("visibilitychange",R);let f=()=>{u=!0,d&&clearTimeout(d),p&&document.removeEventListener("visibilitychange",R)};return i?.signal?.addEventListener("abort",f),d=setTimeout(b,0),f}}};var V=require("react"),z=(e,t)=>{let[n,r]=(0,V.useState)("");return(0,V.useEffect)(()=>{if(!e){r("");return}let s=Uint8Array.from(atob(e),o=>o.charCodeAt(0)),l=URL.createObjectURL(new Blob([s],{type:t}));return r(l),()=>URL.revokeObjectURL(l)},[e,t]),n};var K=require("react");var G=require("react"),Ke=require("react/jsx-runtime"),Qe=(0,G.createContext)(null),Je=({client:e,children:t})=>(0,Ke.jsx)(Qe.Provider,{value:e,children:t}),Q=()=>{let e=(0,G.useContext)(Qe);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};var T=require("react"),J=e=>{let[t,n]=(0,T.useState)([]),[r,s]=(0,T.useState)(""),[l,o]=(0,T.useState)(!1),[i,a]=(0,T.useState)(null),u=(0,T.useRef)(0),d=(0,T.useRef)(null);(0,T.useEffect)(()=>()=>d.current?.abort(),[]);let m=(0,T.useCallback)(()=>{let c=u.current;return u.current+=1,c},[]);(0,T.useEffect)(()=>{let c=!0;return e.getInfo().then(g=>{c&&g.greeting&&n([{id:m(),role:"assistant",text:g.greeting}])}).catch(()=>{}),()=>{c=!1}},[e,m]);let p=(0,T.useCallback)(()=>{let c=r.trim();if(!c||l)return;s(""),a(null),o(!0);let g=m(),y=m();n(f=>[...f,{id:g,role:"user",text:c},{id:y,role:"assistant",text:"",streaming:!0}]);let b=f=>{n(w=>w.map(I=>I.id===y?f(I):I))},R=new AbortController;d.current=R,e.streamMessage(c,{onText:f=>b(w=>({...w,text:w.text+f})),onComplete:f=>{b(w=>({...w,text:f.reply||w.text,artifacts:f.artifacts,streaming:!1})),o(!1)},onError:f=>{b(w=>({...w,streaming:!1})),a(f.error),o(!1)}},R.signal).catch(f=>{b(w=>({...w,streaming:!1})),a(f instanceof Error?f.message:"stream_failed"),o(!1)}).finally(()=>{o(!1),b(f=>f.streaming?{...f,streaming:!1}:f)})},[r,l,e,m]);return{messages:t,input:r,setInput:s,send:p,sending:l,error:i}};var S=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"}},$t=({artifact:e})=>{let t=z(e.dataBase64??"",e.mimeType),n=e.url??t;return n?e.mimeType.startsWith("image/")?(0,S.jsx)("a",{href:n,rel:"noopener noreferrer",target:"_blank",children:(0,S.jsx)("img",{alt:e.filename,src:n,style:k.image})}):(0,S.jsx)("a",{download:e.filename,href:n,style:k.link,children:e.filename}):null},Xe=()=>{let e=Q(),{messages:t,input:n,setInput:r,send:s,sending:l,error:o}=J(e),i=(0,K.useRef)(null);(0,K.useEffect)(()=>{let u=i.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let a=u=>{u.preventDefault(),s()};return(0,S.jsxs)("div",{style:k.root,children:[(0,S.jsx)("div",{ref:i,style:k.log,children:t.map(u=>(0,S.jsxs)("div",{style:u.role==="user"?k.user:k.assistant,children:[u.text||(u.streaming?"\u2026":""),u.artifacts&&u.artifacts.length>0?(0,S.jsx)("div",{style:k.artifacts,children:u.artifacts.map(d=>(0,S.jsx)($t,{artifact:d},d.filename))}):null]},u.id))}),o?(0,S.jsx)("div",{style:k.error,children:o}):null,(0,S.jsxs)("form",{onSubmit:a,style:k.form,children:[(0,S.jsx)("input",{"aria-label":"Message",onChange:u=>r(u.target.value),placeholder:"Type a message\u2026",style:k.input,value:n}),(0,S.jsx)("button",{disabled:l||n.trim().length===0,style:k.button,type:"submit",children:"Send"})]})]})};var Wt=/\/+$/,X=e=>{let t=e.sessionId,n=e.baseUrl.replace(Wt,""),r=o=>`${n}/endpoint/${encodeURIComponent(e.token)}${o}`,s={"content-type":"application/json"},l=(o,i)=>({url:r(o),headers:s,body:JSON.stringify({message:i,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>v(r("/config"),{}),sendMessage:async o=>{let i=await Ve(l("/message",o));return t=i.sessionId,i},streamMessage:(o,i,a)=>ze(l("/message/stream",o),i,u=>{t=u},a),subscribe:(o,i)=>{let a=i?.since??"0",u=!1,d,m=i?.intervalMs??3e3,p=async()=>{let g=t;if(g)try{let y=await v(r(`/messages?session=${encodeURIComponent(g)}&since=${encodeURIComponent(a)}`),{});for(let b of y.messages)o.onMessage(b);a=y.cursor,o.onHealthy?.()}catch(y){o.onError?.(x(y))}u||(d=setTimeout(p,m))},c=()=>{u=!0,d&&clearTimeout(d)};return i?.signal?.addEventListener("abort",c),d=setTimeout(p,0),c}}};var Ye=e=>"transport"in e?e.transport:X(e);var Lt=/^https?:\/\//i,Ut=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,Nt=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function qt(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(Lt.test(e))return"url";if(Ut.test(e))return"date"}return"text"}function fe(e){let t=[],n=new Map,r=[...e].sort((s,l)=>String(s.rowId??"").localeCompare(String(l.rowId??"")));for(let s of r)for(let[l,o]of Object.entries(s.data??{})){if(o==null)continue;let i=n.get(l);i||(i=new Map,n.set(l,i),t.push(l));let a=qt(o);i.set(a,(i.get(a)??0)+1)}return t.map(s=>{let l=n.get(s)??new Map,o="text",i=-1;for(let[a,u]of l)u>i&&(i=u,o=a);return{key:s,label:Nt(s),type:o}})}var jt=e=>typeof e=="number"?e:Number(e)||0,Ze=e=>/rate|position|rank|score|percent|avg/i.test(e),Bt=/posted|published|sent|completed|shipped|launched|_at/i,Vt=new Set(["service","order","end_user_id"]);function ye(e,t){let n=e.filter(a=>!Vt.has(a.key)),r=n.filter(a=>a.type==="number").slice(0,3),s=n.find(a=>a.key==="status")??n.find(a=>a.type==="select"),l=n.find(a=>a.type==="date"&&Bt.test(a.key))??n.find(a=>a.type==="date"),o=n.filter(a=>a.type==="number"&&!Ze(a.key)).map(a=>({field:a,total:t.reduce((u,d)=>u+jt(d.data[a.key]),0)})).sort((a,u)=>u.total-a.total).find(a=>a.total>0)?.field??null,i=[{type:"stat",label:"Items",agg:"count"}];for(let a of r){let u=Ze(a.key);i.push({type:"stat",metric:a.key,agg:u?"avg":"sum",label:u?`Avg ${a.label.toLowerCase()}`:a.label})}return l&&i.push({type:"line",x:l.key,y:o?.key,agg:"sum",title:o?`${o.label} by day`:"Items by day"}),s&&i.push({type:"donut",groupBy:s.key,title:s.label}),i.push({type:"table",columns:n.map(a=>a.key)}),{version:1,widgets:i}}var be=6,he=6,we=4,et={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:2}},zt=e=>Math.max(1,Math.min(6,Math.round(e))),Gt=e=>Math.max(1,Math.min(4,Math.round(e)));function H(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function xe(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function Te(e){return et[e]}function Y(e,t,n){let r=et[e];return{w:t===void 0?r.w:zt(t),h:n===void 0?r.h:Gt(n)}}function Z(e){let t=[],n=[],r=(o,i,a,u)=>{if(o<0||o+a>6)return!1;for(let d=0;d<u;d+=1){let m=n[i+d];if(m){for(let p=0;p<a;p+=1)if(m[o+p])return!1}}return!0},s=(o,i,a,u)=>{for(let d=0;d<u;d+=1){let m=n[i+d]??[];for(let p=0;p<a;p+=1)m[o+p]=!0;n[i+d]=m}},l=(o,i)=>{for(let a=0;;a+=1)for(let u=0;u+o<=6;u+=1)if(r(u,a,o,i))return{gx:u,gy:a}};for(let o of e){let i=Y(H(o.kind),o.w,o.h),u=o.gx!==void 0&&o.gy!==void 0&&r(o.gx,o.gy,i.w,i.h)&&o.gx!==void 0&&o.gy!==void 0?{gx:o.gx,gy:o.gy}:l(i.w,i.h);s(u.gx,u.gy,i.w,i.h),t.push({widget:o,gx:u.gx,gy:u.gy,w:i.w,h:i.h})}return t}function Se(e){let t=[],n=[];for(let r of e)H(r.kind)==="block"?n.push(r):t.push(r);return{tiles:Z(t),blocks:n}}var tt=new Set(["service","order","end_user_id"]),ve=e=>typeof e=="number"?e:Number(e)||0,nt=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 Qt(e,t,n,r){let s=new Map;for(let l of e){let o=new Date(nt(l.data[t]));if(Number.isNaN(o.getTime()))continue;let i=o.toISOString().slice(0,10),a=s.get(i)??[];a.push(n?ve(l.data[n]):1),s.set(i,a)}return[...s.entries()].sort((l,o)=>l[0]<o[0]?-1:1).map(([l,o])=>({label:new Date(`${l}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:n?Pe(r,o):o.length}))}function Jt(e,t,n,r="sum"){let s=new Map;for(let l of e){let o=nt(l.data[t]).trim();if(!o)continue;let i=s.get(o)??[];i.push(n?ve(l.data[n]):1),s.set(o,i)}return[...s.entries()].map(([l,o])=>({label:l,value:n?Pe(r,o):o.length})).sort((l,o)=>o.value-l.value)}function Kt(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 l=r.map(o=>ve(o.data[s.key]));return{kind:"stat",label:e.label??s.label,value:Pe(e.agg??"sum",l)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let s=Qt(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=Jt(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(l=>t.get(l)).filter(l=>l!==void 0&&!tt.has(l.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 ke(e,t,n,r={}){let s=new Map,l=a=>({byKey:new Map(a.fields.map(u=>[u.key,u])),cols:a.fields.filter(u=>!tt.has(u.key)),rows:a.rows}),o=l({fields:t,rows:n});for(let[a,u]of Object.entries(r))s.set(a,l(u));let i=[];for(let a of e.widgets){let u=a.type==="text"?void 0:a.source,d=u?s.get(u):o;if(!d)continue;let m=Kt(a,d.byKey,d.cols,d.rows);m&&i.push({...m,w:a.w,h:a.h,gx:a.gx,gy:a.gy})}return i}var Xt=new Set(["sum","avg","count","min","max","last"]),rt=e=>typeof e=="string"&&Xt.has(e)?e:void 0,h=e=>typeof e=="string"&&e!==""?e:void 0,_=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,$=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 Yt(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:rt(t.agg),w:_(t.w),h:$(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:rt(t.agg),w:_(t.w),h:$(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:_(t.w),h:$(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:_(t.w),h:$(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:_(t.w),h:$(t.h),gx:D(t.gx),gy:D(t.gy)}:null}default:return null}}function Ce(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(Yt).filter(l=>l!==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 ee(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 te(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 Re(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(ee).filter(s=>s!==null)}catch{}let n=String(e.file??"");return n?[{kind:"file",value:n}]:[]}function De(e,t,n,r=""){let l=te(e).find(i=>i.v===t)?.items??[],o=l.filter(i=>i.kind==="file").map(i=>n.get(i.value)??"");return l.some(i=>i.kind==="table")&&o.push(r),o.length===0||o.some(i=>i==="")?"awaiting":o.some(i=>i==="revise")?"revise":"accepted"}function Ie(e){return Number(e.published_version)||0}var ne=["short","medium","long","iso","relative"],re=["none","12h","24h"],oe=N;function Me(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let n=t.columns.map((o,i)=>({key:typeof o.key=="string"&&o.key?o.key:typeof o.id=="string"&&o.id?o.id:`column_${i+1}`,label:typeof o.label=="string"?o.label:"",type:oe(o.type),...(()=>{let a=Array.isArray(o.options)?[...new Set(o.options.map(u=>String(u).trim()).filter(u=>u!==""))]:[];return a.length>0?{options:a}:{}})(),...ne.includes(o.dateFormat)?{dateFormat:o.dateFormat}:{},...re.includes(o.timeFormat)?{timeFormat:o.timeFormat}:{},...o.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((o,i)=>({id:typeof o.id=="string"&&o.id?o.id:`row_${i}`,cells:o.cells&&typeof o.cells=="object"?o.cells:{}})),s=typeof t.name=="string"?t.name:void 0,l=se(t.view);return{columns:n,rows:r,...s?{name:s}:{},...l?{view:l}:{}}}}catch{}return null}var E=e=>{if(!Array.isArray(e))return;let t=e.map(n=>String(n).trim()).filter(n=>n!=="");return t.length>0?t:void 0};function se(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n={};if(t.widths&&typeof t.widths=="object"&&!Array.isArray(t.widths))for(let[l,o]of Object.entries(t.widths))typeof o=="number"&&Number.isFinite(o)&&o>0&&(n[l]=Math.round(o));let r=typeof t.frozen=="number"&&Number.isFinite(t.frozen)&&t.frozen>0?Math.floor(t.frozen):void 0,s={...E(t.hidden)?{hidden:E(t.hidden)}:{},...E(t.order)?{order:E(t.order)}:{},...E(t.wrap)?{wrap:E(t.wrap)}:{},...Object.keys(n).length>0?{widths:n}:{},...r?{frozen:r}:{}};return Object.keys(s).length>0?s:void 0}function Fe(e){let t=e.view;if(!t)return e.columns;let n=new Set(e.columns.map(i=>i.key)),r=new Set(t.hidden??[]),s=(t.order??[]).filter(i=>n.has(i)),l=e.columns.map(i=>i.key).filter(i=>!s.includes(i)),o=new Map(e.columns.map(i=>[i.key,i]));return[...s,...l].filter(i=>!r.has(i)).map(i=>o.get(i)).filter(i=>!!i)}var ie=6;function Ee(e){let t=e.trim().toLowerCase();if(t==="")return-1;let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return Math.abs(n)%ie}function Oe(e){try{let t=new URL(e),n=t.pathname.split("/").filter(Boolean).pop()??"";return n===""?t.host:`${t.host}/\u2026/${n}`}catch{return e}}function ae(e){return e==null?"":String(e)}function He(e){let t=ae(e).trim();if(t==="")return[];try{let n=JSON.parse(t);if(Array.isArray(n))return n.map(r=>String(r).trim()).filter(r=>r!=="")}catch{}return t.split(",").map(n=>n.trim()).filter(n=>n!=="")}function _e(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function W(){return{cells:{},verdict:"",comment:""}}function $e(e){if(typeof e!="string"||e.trim()==="")return W();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 W()}function We(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 Le(e,t,n,r){return{...e,cells:{...e.cells,[t]:{...e.cells[t]??{},[n]:r}}}}function Ue(e,t,n){return{...e,verdict:t,comment:n}}function Ne(e,t="medium",n="none"){let r=new Date(/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00`:e);if(Number.isNaN(r.getTime()))return e;if(t==="iso"){let o=a=>String(a).padStart(2,"0"),i=`${r.getFullYear()}-${o(r.getMonth()+1)}-${o(r.getDate())}`;return n==="none"?i:`${i} ${o(r.getHours())}:${o(r.getMinutes())}`}if(t==="relative")return en(r);let s=t==="short"?{year:"numeric",month:"numeric",day:"numeric"}:t==="long"?{year:"numeric",month:"long",day:"numeric",weekday:"long"}:{year:"numeric",month:"short",day:"numeric"},l=n==="none"?{}:{hour:"numeric",minute:"2-digit",hour12:n==="12h"};return r.toLocaleString(void 0,{...s,...l})}var Zt=6e4,ot=36e5,Ae=864e5;function en(e){let t=e.getTime()-Date.now(),n=Math.abs(t);if(n>30*Ae)return e.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});let r=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});return n<ot?r.format(Math.round(t/Zt),"minute"):n<Ae?r.format(Math.round(t/ot),"hour"):r.format(Math.round(t/Ae),"day")}var M=class extends Error{code;status;constructor(t,n,r){super(n),this.name="CreditRefused",this.code=t,this.status=r}},L=class extends M{credits;balance;short;constructor(t,n){super("insufficient_credits",t,402),this.name="InsufficientCredits",this.credits=n.credits,this.balance=n.balance,this.short=n.short}},tn=/\/+$/,nn="/api/v1/end-user",de="Pre-payment",pe="After-payment";function st(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:de,amount:n}),r>0&&s.push({label:pe,amount:r}),s}var ue=e=>e.status!=="paid"&&e.asked!==!1,it=(e,t)=>e.payMethods&&e.payMethods.length>0?[...e.payMethods]:[...t],at=(e,t)=>{let n=typeof t=="number"&&Number.isFinite(t)&&t>0?t:1;return!Number.isFinite(e)||e<=0?0:Math.ceil(e*n)},le=e=>{let t=e.label.trim().toLowerCase();return t===de.toLowerCase()?0:t===pe.toLowerCase()?2:1},lt=(e,t,n)=>{let r=t.filter(p=>p.order===n),s=p=>p.reduce((c,g)=>c+g.amount,0),l=s(r),o=s(r.filter(p=>p.status==="paid")),i=e.value>0,a=[...r].sort((p,c)=>le(p)!==le(c)?le(p)-le(c):(p.dueDate||p.paidAt).localeCompare(c.dueDate||c.paidAt)),u=a.filter(ue),d=a.filter(p=>p.status!=="paid"&&!ue(p)),m=l>0?s(u):e.value-o;return{value:e.value,priced:i,billed:l,paid:o,due:Math.max(0,m),scheduled:s(d),lines:a,asked:u,upcoming:d,awaitingPayment:i&&o<=0}},rn=e=>{let{credits:t,balance:n,short:r}=e;return typeof t!="number"||typeof n!="number"||typeof r!="number"||!(Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r))?null:{credits:t,balance:n,short:r}},ut=e=>{let t=e.baseUrl.replace(tn,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async(s,l={method:"GET"})=>{try{let o=await fetch(`${t}${nn}${s}`,{method:l.method,headers:{"content-type":"application/json",authorization:`Bearer ${await n()}`},...l.body===void 0?{}:{body:JSON.stringify(l.body)}});if(!o.ok){let i=await o.json().catch(()=>({})),a=i.message??`${l.method} ${s} \u2192 ${String(o.status)}`,u=rn(i);throw o.status===402&&i.error==="insufficient_credits"&&u?new L(a,u):new M(i.error??"request_failed",a,o.status)}return await o.json()}catch(o){throw o instanceof M?o:x(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,l)=>r(`/payments/${encodeURIComponent(s)}/sent`,{method:"POST",body:{reference:l??""}}),payWithCredits:s=>r(`/payments/${encodeURIComponent(s)}/pay-with-credits`,{method:"POST",body:{}}),inquiryQuote:s=>r(`/inquiries/${encodeURIComponent(s)}/quote`),acceptInquiry:(s,l)=>r(`/inquiries/${encodeURIComponent(s)}/accept`,{method:"POST",body:{version:l}}),enquire:(s,l,o)=>r("/shop/enquire",{method:"POST",body:{productId:s,answers:l,name:o??""}})}};var on=/\/+$/,F="/api/v1/end-user",O=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function sn(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var dt=e=>{let t=e.baseUrl.replace(on,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await n()}`}),s=async(o,i)=>{try{let a=await fetch(`${t}${F}${o}`,{method:i.method,headers:await r(),...i.body===void 0?{}:{body:JSON.stringify(i.body)}});if(a.status===409){let u=await a.json().catch(()=>({}));throw new O(u.message??"Someone else saved this first.")}if(!a.ok){let u=await a.text().catch(()=>""),d=`${i.method} ${o} \u2192 ${String(a.status)}`;try{let m=JSON.parse(u);m.message&&(d=m.message)}catch{d=u?`${d}: ${u}`:d}throw x({error:d})}return await a.json()}catch(a){throw a instanceof O?a:x(a)}},l=o=>`/tables/${encodeURIComponent(o)}`;return{listTables:async()=>(await v(`${t}${F}/tables`,await r())).tables,listRows:async(o,i)=>await v(`${t}${F}${l(o)}/rows?limit=${String(i??100)}`,await r()),insertRow:async(o,i)=>{let{rowIds:a}=await s(`${l(o)}/rows`,{method:"POST",body:{rows:[i]}}),u=a[0];if(!u)throw x(new Error("The row was not created."));return u},patchRow:async(o,i,a)=>(await s(`${l(o)}/rows/${encodeURIComponent(i)}`,{method:"PATCH",body:a})).updated,deleteRow:async(o,i)=>(await s(`/${encodeURIComponent(o)}/${encodeURIComponent(i)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await v(`${t}${F}/tables/files/rows?limit=200`,await r())).rows.map(i=>({id:i.rowId,filename:String(i.data.filename??""),source:String(i.data.source??"client"),campaign:String(i.data.campaign??""),size:typeof i.data.size=="number"?i.data.size:0,createdAt:i.createdAt})),uploadFile:async(o,i)=>{let a=new Uint8Array(await o.arrayBuffer());return await s("/files",{method:"POST",body:{filename:o.name,mime:o.type||"application/octet-stream",data:sn(a),...i===void 0?{}:{message:i}}})},fileLink:async o=>await v(`${t}${F}/files/${encodeURIComponent(o)}/url`,await r()),deleteFile:async o=>(await s(`/files/${encodeURIComponent(o)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await v(`${t}${F}/documents`,await r())).documents,readDocument:async o=>(await v(`${t}${F}/documents/${encodeURIComponent(o)}`,await r())).document,saveDocument:async(o,i)=>await s(`/documents/${encodeURIComponent(o)}`,{method:"PATCH",body:i})}};var an=/\/+$/,ln="/api/v1/end-user",pt=e=>{let t=e.baseUrl.replace(an,""),n=async(r,s)=>{let l;try{l=await fetch(`${t}${ln}${r}`,s===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)})}catch(o){throw x(o)}if(l.status===429)throw x({error:"rate_limited",retryable:!0});if(!l.ok)throw x({error:`shop_request_failed_${String(l.status)}`});try{return await l.json()}catch(o){throw x(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 un=new Set(["buy","ask"]);function ct(e){return un.has(e.mode)?e.mode:"ask"}var dn={kind:"quoted"};function U(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 mt(e,t){let n=/^[a-z]+$/i.test(t)&&!t.endsWith("s")?"s":"";return`${e.toLocaleString()} ${t}${n}`}function qe(e,t){return e.kind==="quoted"?"Priced on enquiry":e.kind==="flat"?U(e.price,t):`${U(e.unitPrice,t)} per ${e.unitStep===1?e.unit:mt(e.unitStep,e.unit)}`}function gt(e){let t=e.currency,n=e.pricing;if(n.kind!=="variants")return qe(n,t);let r=n.variants.map(s=>s.price).filter(s=>typeof s=="number");return r.length>0?`From ${U(Math.min(...r),t)}`:"Priced on enquiry"}function ft(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}:dn}function yt(e,t){return e.kind==="flat"?e.price:e.kind==="per_unit"?e.unitPrice*Math.ceil(t/Math.max(e.unitStep,1)):null}function bt(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 ht(e,t){let n=e.variants?.find(r=>r.name===t);return n&&n.includes.length>0?n.includes:e.includes}function wt(e,t){let n=[];for(let r of e){let s=t(r).trim();s&&!n.includes(s)&&n.push(s)}return n}function xt(e,t,n,r){let s=t?`${e.name} \u2014 ${t}`:e.name,l=n.kind==="per_unit"?`, ${mt(r,n.unit)}`:"";return`I'd like to buy ${s}${l}. How do I go ahead?`}function Tt(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"),St=e=>{let[t,n]=(0,A.useState)(null),[r,s]=(0,A.useState)(!0),[l,o]=(0,A.useState)(null),i=(0,A.useCallback)(async()=>{try{n(await e.wallet()),o(null)}catch{o("Couldn't read your balance just now.")}finally{s(!1)}},[e]),a=(0,A.useCallback)(()=>{i().catch(()=>{})},[i]);return(0,A.useEffect)(()=>(a(),window.addEventListener("focus",a),()=>{window.removeEventListener("focus",a)}),[a]),{wallet:t,loading:r,failure:l,refresh:a}};var C=require("react"),pn=e=>e&&typeof e=="object"&&typeof e.error=="string"?e.error:e instanceof Error?e.message:"shop_unavailable",vt=e=>{let[t,n]=(0,C.useState)([]),[r,s]=(0,C.useState)([]),[l,o]=(0,C.useState)(!1),[i,a]=(0,C.useState)(!0),[u,d]=(0,C.useState)(null),[m,p]=(0,C.useState)(0);(0,C.useEffect)(()=>{let g=!0;return a(!0),e.listProducts().then(y=>{g&&(n(y.products),s(y.enquiryForm),o(y.truncated),d(null))}).catch(y=>{g&&d(pn(y))}).finally(()=>{g&&a(!1)}),()=>{g=!1}},[e,m]);let c=(0,C.useCallback)(()=>p(g=>g+1),[]);return{products:t,enquiryForm:r,truncated:l,loading:i,error:u,reload:c}};var P=require("react"),Pt="greeting";function je(e,t){if(e.some(l=>l.id===t.id))return e;let n=e.filter(l=>l.id!==Pt),r=l=>l.author==="client"==(t.author==="client");return[...n.filter(l=>!(l.pending&&r(l)&&l.text===t.text)),t]}var kt=(e,t)=>{let[n,r]=(0,P.useState)([]),[s,l]=(0,P.useState)(""),[o,i]=(0,P.useState)(!1),[a,u]=(0,P.useState)(null),d=(0,P.useRef)(0),m=t?.pollMs??2e3;(0,P.useEffect)(()=>{let c=!0;return e.getInfo().then(g=>{c&&g.greeting&&r(y=>y.length===0?[{id:Pt,cursor:"",author:"agent",text:g.greeting}]:y)}).catch(()=>{}),()=>{c=!1}},[e]),(0,P.useEffect)(()=>e.subscribe?.({onMessage:c=>r(g=>je(g,c)),onError:c=>u(c.error),onHealthy:()=>u(null)},{intervalMs:m}),[e,m]);let p=(0,P.useCallback)(()=>{let c=s.trim();if(!c||o)return;l(""),u(null),i(!0),d.current+=1;let g=`pending-${d.current}`,y={id:g,cursor:"",author:"client",text:c,pending:!0};r(b=>[...b,y]),e.sendMessage(c).then(b=>{i(!1),b.reply.trim()&&r(f=>f.some(I=>!I.pending&&I.author!=="client"&&I.text===b.reply)?f:(d.current+=1,[...f,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:b.reply,pending:!0}]))}).catch(b=>{u(b instanceof Error?b.message:"send_failed"),i(!1),r(R=>R.filter(f=>f.id!==g)),l(R=>R||c)})},[s,o,e]);return{messages:n,input:s,setInput:l,send:p,sending:o,error:a}};0&&(module.exports={COLUMN_TYPES,Chat,CreditRefused,DATE_FORMATS,GRID_COLS,GRID_MAX_COLS,GRID_MAX_ROWS,HolaProvider,InsufficientCredits,OPTION_TINTS,PortalConflict,QUOTE_BALANCE_LABEL,QUOTE_DEPOSIT_LABEL,TIME_FORMATS,arrangedColumns,bandOfKind,bandOfType,buyRequestText,cellValue,createApiTransport,createHolaClient,createPortalCredits,createPortalData,createPortalShop,createWidgetTransport,creditsOfMoney,deliverableCellText,deliverableCellValues,deliverableStatus,deriveFields,emptyTableResponses,facetValues,footprintOf,footprintWith,formatDeliverableDate,groupDeliverableVersions,includesFor,inferSpec,isDeliverableChecked,mergeMessage,modeOf,money,normalizeColumnType,normalizeDeliverableColType,normalizeDeliverableItem,optionTintIndex,orderBilling,parseArrangement,parseDashboardSpec,parseDeliverableItems,parseDeliverableTable,parseTableResponses,paymentAsked,paymentPayMethods,placeWidgets,priceFor,priceLabel,publishedVersionOf,quantityRange,quoteSchedule,renderModel,setResponse,setTableReview,shelfPriceLabel,shelfProblem,shortenUrl,splitLayout,textDeltaOf,thinkingDeltaOf,toolEventOf,totalFor,useArtifactUrl,useChat,useCredits,useHolaClient,useShop,useThread});
package/dist/index.d.cts CHANGED
@@ -1,6 +1,15 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
 
4
+ declare const COLUMN_TYPES: readonly ["text", "number", "url", "date", "boolean", "select", "multi_select", "file"];
5
+ type ColumnType = (typeof COLUMN_TYPES)[number];
6
+ /** Read a stored type tolerantly.
7
+ *
8
+ * Anything unrecognised lands as `text`, which is the one type every value can be shown as. That
9
+ * is what makes widening this list a release rather than a breaking change: an older reader shows
10
+ * the raw value instead of the richer cell — degraded, not broken. */
11
+ declare function normalizeColumnType(t: unknown): ColumnType;
12
+
4
13
  /** A file the employee produced (image/video/audio/other). In-turn artifacts (a turn's
5
14
  * completion) carry inline `dataBase64`; thread artifacts (the receive channel) carry a `url`
6
15
  * reference (presigned/public). Exactly one of the two is present. */
@@ -162,7 +171,10 @@ declare const createHolaClient: (options: CreateHolaClientOptions) => HolaClient
162
171
  type PortalField = {
163
172
  key: string;
164
173
  label: string;
165
- type: "text" | "number" | "date" | "boolean" | "select" | "url";
174
+ /** The SHARED vocabulary see `column-type.ts`. This used to be its own six-member list, which
175
+ * is how `file` and `multi_select` reached a customer's App as types nothing was written to
176
+ * handle: a file column printed its storage id where a screenshot belonged. */
177
+ type: ColumnType;
166
178
  options?: string[];
167
179
  description?: string;
168
180
  };
@@ -548,14 +560,14 @@ tableVerdict?: "" | "accepted" | "revise"): DeliverableReviewState;
548
560
  * version the team delivered would auto-appear to the client before it was published. */
549
561
  declare function publishedVersionOf(data: Record<string, unknown>): number;
550
562
 
551
- /** A column type.
563
+ /** A deliverable column's type.
552
564
  *
553
- * KEPT IN STEP WITH THE SERVICE-SLICE VOCABULARY on purpose: this is the same primitive, authored
554
- * in the same grid with the same components, and a type the operator can pick on one and not the
555
- * other is a column that changes meaning depending on where it was made. Widening it is a release
556
- * a tenant App pins its copy of this package so the reader below stays tolerant and anything
557
- * it does not recognise still lands as `text` rather than throwing. */
558
- type DeliverableColType = "text" | "number" | "url" | "date" | "boolean" | "select" | "multi_select" | "file";
565
+ * THE SAME VOCABULARY a service slice uses, and now literally the same type — see `column-type.ts`
566
+ * for why it is defined once. This is the same primitive authored in the same grid with the same
567
+ * components, and a type the operator can pick on one surface and not the other is a column that
568
+ * changes meaning depending on where it was made. Kept as its own name because tenant Apps import
569
+ * it. */
570
+ type DeliverableColType = ColumnType;
559
571
  /** How much of a date to show. `relative` is the one that is not a format at all but an
560
572
  * interpretation — "3 days ago" — and it is the right default nowhere and the right answer often. */
561
573
  declare const DATE_FORMATS: readonly ["short", "medium", "long", "iso", "relative"];
@@ -614,7 +626,8 @@ type DeliverableTable = {
614
626
  view?: DeliverableArrangement;
615
627
  };
616
628
  /** Legacy tables used `link`/`checkbox`; the current vocabulary is `url`/`boolean`. */
617
- declare function normalizeDeliverableColType(t: unknown): DeliverableColType;
629
+ /** Read a stored column type tolerantly. The shared reader, under the name the Apps already use. */
630
+ declare const normalizeDeliverableColType: typeof normalizeColumnType;
618
631
  /** Parse a table item's JSON `value` into the grid model, tolerating the legacy id-keyed shape (its
619
632
  * columns carried `id` not `key`, so a legacy column keeps its cells by keying on that id). Returns
620
633
  * null when `value` is not a table payload. */
@@ -1671,4 +1684,4 @@ declare const useThread: (client: HolaClient, options?: {
1671
1684
  pollMs?: number;
1672
1685
  }) => UseThread;
1673
1686
 
1674
- export { type Agg, type ApiTransportConfig, type Band, type ChartView, Chat, type ChatMessage, type ChosenPrice, type CreateHolaClientOptions, type CreditEntry, type CreditHistory, type CreditPack, CreditRefused, type CreditTotals, type CreditWallet, type CustomerPayment, DATE_FORMATS, type DashboardLayout, type DashboardSpec, type DataSource, type DateFormat, type DeliverableArrangement, type DeliverableColType, type DeliverableColumn, type DeliverableItem, type DeliverableItemKind, type DeliverableReviewState, type DeliverableRow, type DeliverableTable, type DeliverableVersion, type DonutWidget, GRID_COLS, GRID_MAX_COLS, GRID_MAX_ROWS, type HolaArtifact, type HolaAuthor, type HolaClient, type HolaCompletion, type HolaEmployeeInfo, type HolaError, type HolaIdentity, type HolaMessage, HolaProvider, type HolaStreamHandlers, type HolaSubscribeHandlers, type HolaSubscribeOptions, type HolaToolEvent, type HolaTransport, type InquiryQuote, InsufficientCredits, OPTION_TINTS, type OrderBilling, type PaidWithCredits, type PendingTopup, type PlacedWidget, type Point, PortalConflict, type PortalCredits, type PortalData, type PortalDocument, type PortalDocumentSummary, type PortalField, type PortalFile, type PortalRow, type PortalRowAuthor, type PortalRowPage, type PortalShop, type PortalShopConfig, type PortalTable, type Purchased, QUOTE_BALANCE_LABEL, QUOTE_DEPOSIT_LABEL, type QuoteScheduleLine, type QuoteTerms, type QuotedLine, type ResolvedWidget, type SeriesWidget, type ShopApplication, type ShopApplyResult, type ShopFormField, type ShopInclusion, type ShopMode, type ShopPricing, type ShopProduct, type ShopShelf, type ShopVariant, type StatView, type StatWidget, TIME_FORMATS, type TableResponses, type TableReviewVerdict, type TableWidget, type TextWidget, type ThreadMessage, type TimeFormat, type TopupStarted, type TransferDetails, type UseChat, type UseCredits, type UseShop, type UseThread, type Widget, type WidgetTransportConfig, type WidgetType, arrangedColumns, bandOfKind, bandOfType, buyRequestText, cellValue, createApiTransport, createHolaClient, createPortalCredits, createPortalData, createPortalShop, createWidgetTransport, creditsOfMoney, deliverableCellText, deliverableCellValues, deliverableStatus, deriveFields, emptyTableResponses, facetValues, footprintOf, footprintWith, formatDeliverableDate, groupDeliverableVersions, includesFor, inferSpec, isDeliverableChecked, mergeMessage, modeOf, money, normalizeDeliverableColType, normalizeDeliverableItem, optionTintIndex, orderBilling, parseArrangement, parseDashboardSpec, parseDeliverableItems, parseDeliverableTable, parseTableResponses, paymentAsked, paymentPayMethods, placeWidgets, priceFor, priceLabel, publishedVersionOf, quantityRange, quoteSchedule, renderModel, setResponse, setTableReview, shelfPriceLabel, shelfProblem, shortenUrl, splitLayout, textDeltaOf, thinkingDeltaOf, toolEventOf, totalFor, useArtifactUrl, useChat, useCredits, useHolaClient, useShop, useThread };
1687
+ export { type Agg, type ApiTransportConfig, type Band, COLUMN_TYPES, type ChartView, Chat, type ChatMessage, type ChosenPrice, type ColumnType, type CreateHolaClientOptions, type CreditEntry, type CreditHistory, type CreditPack, CreditRefused, type CreditTotals, type CreditWallet, type CustomerPayment, DATE_FORMATS, type DashboardLayout, type DashboardSpec, type DataSource, type DateFormat, type DeliverableArrangement, type DeliverableColType, type DeliverableColumn, type DeliverableItem, type DeliverableItemKind, type DeliverableReviewState, type DeliverableRow, type DeliverableTable, type DeliverableVersion, type DonutWidget, GRID_COLS, GRID_MAX_COLS, GRID_MAX_ROWS, type HolaArtifact, type HolaAuthor, type HolaClient, type HolaCompletion, type HolaEmployeeInfo, type HolaError, type HolaIdentity, type HolaMessage, HolaProvider, type HolaStreamHandlers, type HolaSubscribeHandlers, type HolaSubscribeOptions, type HolaToolEvent, type HolaTransport, type InquiryQuote, InsufficientCredits, OPTION_TINTS, type OrderBilling, type PaidWithCredits, type PendingTopup, type PlacedWidget, type Point, PortalConflict, type PortalCredits, type PortalData, type PortalDocument, type PortalDocumentSummary, type PortalField, type PortalFile, type PortalRow, type PortalRowAuthor, type PortalRowPage, type PortalShop, type PortalShopConfig, type PortalTable, type Purchased, QUOTE_BALANCE_LABEL, QUOTE_DEPOSIT_LABEL, type QuoteScheduleLine, type QuoteTerms, type QuotedLine, type ResolvedWidget, type SeriesWidget, type ShopApplication, type ShopApplyResult, type ShopFormField, type ShopInclusion, type ShopMode, type ShopPricing, type ShopProduct, type ShopShelf, type ShopVariant, type StatView, type StatWidget, TIME_FORMATS, type TableResponses, type TableReviewVerdict, type TableWidget, type TextWidget, type ThreadMessage, type TimeFormat, type TopupStarted, type TransferDetails, type UseChat, type UseCredits, type UseShop, type UseThread, type Widget, type WidgetTransportConfig, type WidgetType, arrangedColumns, bandOfKind, bandOfType, buyRequestText, cellValue, createApiTransport, createHolaClient, createPortalCredits, createPortalData, createPortalShop, createWidgetTransport, creditsOfMoney, deliverableCellText, deliverableCellValues, deliverableStatus, deriveFields, emptyTableResponses, facetValues, footprintOf, footprintWith, formatDeliverableDate, groupDeliverableVersions, includesFor, inferSpec, isDeliverableChecked, mergeMessage, modeOf, money, normalizeColumnType, normalizeDeliverableColType, normalizeDeliverableItem, optionTintIndex, orderBilling, parseArrangement, parseDashboardSpec, parseDeliverableItems, parseDeliverableTable, parseTableResponses, paymentAsked, paymentPayMethods, placeWidgets, priceFor, priceLabel, publishedVersionOf, quantityRange, quoteSchedule, renderModel, setResponse, setTableReview, shelfPriceLabel, shelfProblem, shortenUrl, splitLayout, textDeltaOf, thinkingDeltaOf, toolEventOf, totalFor, useArtifactUrl, useChat, useCredits, useHolaClient, useShop, useThread };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,15 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
 
4
+ declare const COLUMN_TYPES: readonly ["text", "number", "url", "date", "boolean", "select", "multi_select", "file"];
5
+ type ColumnType = (typeof COLUMN_TYPES)[number];
6
+ /** Read a stored type tolerantly.
7
+ *
8
+ * Anything unrecognised lands as `text`, which is the one type every value can be shown as. That
9
+ * is what makes widening this list a release rather than a breaking change: an older reader shows
10
+ * the raw value instead of the richer cell — degraded, not broken. */
11
+ declare function normalizeColumnType(t: unknown): ColumnType;
12
+
4
13
  /** A file the employee produced (image/video/audio/other). In-turn artifacts (a turn's
5
14
  * completion) carry inline `dataBase64`; thread artifacts (the receive channel) carry a `url`
6
15
  * reference (presigned/public). Exactly one of the two is present. */
@@ -162,7 +171,10 @@ declare const createHolaClient: (options: CreateHolaClientOptions) => HolaClient
162
171
  type PortalField = {
163
172
  key: string;
164
173
  label: string;
165
- type: "text" | "number" | "date" | "boolean" | "select" | "url";
174
+ /** The SHARED vocabulary see `column-type.ts`. This used to be its own six-member list, which
175
+ * is how `file` and `multi_select` reached a customer's App as types nothing was written to
176
+ * handle: a file column printed its storage id where a screenshot belonged. */
177
+ type: ColumnType;
166
178
  options?: string[];
167
179
  description?: string;
168
180
  };
@@ -548,14 +560,14 @@ tableVerdict?: "" | "accepted" | "revise"): DeliverableReviewState;
548
560
  * version the team delivered would auto-appear to the client before it was published. */
549
561
  declare function publishedVersionOf(data: Record<string, unknown>): number;
550
562
 
551
- /** A column type.
563
+ /** A deliverable column's type.
552
564
  *
553
- * KEPT IN STEP WITH THE SERVICE-SLICE VOCABULARY on purpose: this is the same primitive, authored
554
- * in the same grid with the same components, and a type the operator can pick on one and not the
555
- * other is a column that changes meaning depending on where it was made. Widening it is a release
556
- * a tenant App pins its copy of this package so the reader below stays tolerant and anything
557
- * it does not recognise still lands as `text` rather than throwing. */
558
- type DeliverableColType = "text" | "number" | "url" | "date" | "boolean" | "select" | "multi_select" | "file";
565
+ * THE SAME VOCABULARY a service slice uses, and now literally the same type — see `column-type.ts`
566
+ * for why it is defined once. This is the same primitive authored in the same grid with the same
567
+ * components, and a type the operator can pick on one surface and not the other is a column that
568
+ * changes meaning depending on where it was made. Kept as its own name because tenant Apps import
569
+ * it. */
570
+ type DeliverableColType = ColumnType;
559
571
  /** How much of a date to show. `relative` is the one that is not a format at all but an
560
572
  * interpretation — "3 days ago" — and it is the right default nowhere and the right answer often. */
561
573
  declare const DATE_FORMATS: readonly ["short", "medium", "long", "iso", "relative"];
@@ -614,7 +626,8 @@ type DeliverableTable = {
614
626
  view?: DeliverableArrangement;
615
627
  };
616
628
  /** Legacy tables used `link`/`checkbox`; the current vocabulary is `url`/`boolean`. */
617
- declare function normalizeDeliverableColType(t: unknown): DeliverableColType;
629
+ /** Read a stored column type tolerantly. The shared reader, under the name the Apps already use. */
630
+ declare const normalizeDeliverableColType: typeof normalizeColumnType;
618
631
  /** Parse a table item's JSON `value` into the grid model, tolerating the legacy id-keyed shape (its
619
632
  * columns carried `id` not `key`, so a legacy column keeps its cells by keying on that id). Returns
620
633
  * null when `value` is not a table payload. */
@@ -1671,4 +1684,4 @@ declare const useThread: (client: HolaClient, options?: {
1671
1684
  pollMs?: number;
1672
1685
  }) => UseThread;
1673
1686
 
1674
- export { type Agg, type ApiTransportConfig, type Band, type ChartView, Chat, type ChatMessage, type ChosenPrice, type CreateHolaClientOptions, type CreditEntry, type CreditHistory, type CreditPack, CreditRefused, type CreditTotals, type CreditWallet, type CustomerPayment, DATE_FORMATS, type DashboardLayout, type DashboardSpec, type DataSource, type DateFormat, type DeliverableArrangement, type DeliverableColType, type DeliverableColumn, type DeliverableItem, type DeliverableItemKind, type DeliverableReviewState, type DeliverableRow, type DeliverableTable, type DeliverableVersion, type DonutWidget, GRID_COLS, GRID_MAX_COLS, GRID_MAX_ROWS, type HolaArtifact, type HolaAuthor, type HolaClient, type HolaCompletion, type HolaEmployeeInfo, type HolaError, type HolaIdentity, type HolaMessage, HolaProvider, type HolaStreamHandlers, type HolaSubscribeHandlers, type HolaSubscribeOptions, type HolaToolEvent, type HolaTransport, type InquiryQuote, InsufficientCredits, OPTION_TINTS, type OrderBilling, type PaidWithCredits, type PendingTopup, type PlacedWidget, type Point, PortalConflict, type PortalCredits, type PortalData, type PortalDocument, type PortalDocumentSummary, type PortalField, type PortalFile, type PortalRow, type PortalRowAuthor, type PortalRowPage, type PortalShop, type PortalShopConfig, type PortalTable, type Purchased, QUOTE_BALANCE_LABEL, QUOTE_DEPOSIT_LABEL, type QuoteScheduleLine, type QuoteTerms, type QuotedLine, type ResolvedWidget, type SeriesWidget, type ShopApplication, type ShopApplyResult, type ShopFormField, type ShopInclusion, type ShopMode, type ShopPricing, type ShopProduct, type ShopShelf, type ShopVariant, type StatView, type StatWidget, TIME_FORMATS, type TableResponses, type TableReviewVerdict, type TableWidget, type TextWidget, type ThreadMessage, type TimeFormat, type TopupStarted, type TransferDetails, type UseChat, type UseCredits, type UseShop, type UseThread, type Widget, type WidgetTransportConfig, type WidgetType, arrangedColumns, bandOfKind, bandOfType, buyRequestText, cellValue, createApiTransport, createHolaClient, createPortalCredits, createPortalData, createPortalShop, createWidgetTransport, creditsOfMoney, deliverableCellText, deliverableCellValues, deliverableStatus, deriveFields, emptyTableResponses, facetValues, footprintOf, footprintWith, formatDeliverableDate, groupDeliverableVersions, includesFor, inferSpec, isDeliverableChecked, mergeMessage, modeOf, money, normalizeDeliverableColType, normalizeDeliverableItem, optionTintIndex, orderBilling, parseArrangement, parseDashboardSpec, parseDeliverableItems, parseDeliverableTable, parseTableResponses, paymentAsked, paymentPayMethods, placeWidgets, priceFor, priceLabel, publishedVersionOf, quantityRange, quoteSchedule, renderModel, setResponse, setTableReview, shelfPriceLabel, shelfProblem, shortenUrl, splitLayout, textDeltaOf, thinkingDeltaOf, toolEventOf, totalFor, useArtifactUrl, useChat, useCredits, useHolaClient, useShop, useThread };
1687
+ export { type Agg, type ApiTransportConfig, type Band, COLUMN_TYPES, type ChartView, Chat, type ChatMessage, type ChosenPrice, type ColumnType, type CreateHolaClientOptions, type CreditEntry, type CreditHistory, type CreditPack, CreditRefused, type CreditTotals, type CreditWallet, type CustomerPayment, DATE_FORMATS, type DashboardLayout, type DashboardSpec, type DataSource, type DateFormat, type DeliverableArrangement, type DeliverableColType, type DeliverableColumn, type DeliverableItem, type DeliverableItemKind, type DeliverableReviewState, type DeliverableRow, type DeliverableTable, type DeliverableVersion, type DonutWidget, GRID_COLS, GRID_MAX_COLS, GRID_MAX_ROWS, type HolaArtifact, type HolaAuthor, type HolaClient, type HolaCompletion, type HolaEmployeeInfo, type HolaError, type HolaIdentity, type HolaMessage, HolaProvider, type HolaStreamHandlers, type HolaSubscribeHandlers, type HolaSubscribeOptions, type HolaToolEvent, type HolaTransport, type InquiryQuote, InsufficientCredits, OPTION_TINTS, type OrderBilling, type PaidWithCredits, type PendingTopup, type PlacedWidget, type Point, PortalConflict, type PortalCredits, type PortalData, type PortalDocument, type PortalDocumentSummary, type PortalField, type PortalFile, type PortalRow, type PortalRowAuthor, type PortalRowPage, type PortalShop, type PortalShopConfig, type PortalTable, type Purchased, QUOTE_BALANCE_LABEL, QUOTE_DEPOSIT_LABEL, type QuoteScheduleLine, type QuoteTerms, type QuotedLine, type ResolvedWidget, type SeriesWidget, type ShopApplication, type ShopApplyResult, type ShopFormField, type ShopInclusion, type ShopMode, type ShopPricing, type ShopProduct, type ShopShelf, type ShopVariant, type StatView, type StatWidget, TIME_FORMATS, type TableResponses, type TableReviewVerdict, type TableWidget, type TextWidget, type ThreadMessage, type TimeFormat, type TopupStarted, type TransferDetails, type UseChat, type UseCredits, type UseShop, type UseThread, type Widget, type WidgetTransportConfig, type WidgetType, arrangedColumns, bandOfKind, bandOfType, buyRequestText, cellValue, createApiTransport, createHolaClient, createPortalCredits, createPortalData, createPortalShop, createWidgetTransport, creditsOfMoney, deliverableCellText, deliverableCellValues, deliverableStatus, deriveFields, emptyTableResponses, facetValues, footprintOf, footprintWith, formatDeliverableDate, groupDeliverableVersions, includesFor, inferSpec, isDeliverableChecked, mergeMessage, modeOf, money, normalizeColumnType, normalizeDeliverableColType, normalizeDeliverableItem, optionTintIndex, orderBilling, parseArrangement, parseDashboardSpec, parseDeliverableItems, parseDeliverableTable, parseTableResponses, paymentAsked, paymentPayMethods, placeWidgets, priceFor, priceLabel, publishedVersionOf, quantityRange, quoteSchedule, renderModel, setResponse, setTableReview, shelfPriceLabel, shelfProblem, shortenUrl, splitLayout, textDeltaOf, thinkingDeltaOf, toolEventOf, totalFor, useArtifactUrl, useChat, useCredits, useHolaClient, useShop, useThread };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use client'
2
- var me=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},N=e=>{let t=me(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},q=e=>{let t=me(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},j=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 nt=/^ /,x=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"}},rt=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(nt,"")));return n.length>0?{event:t,data:n.join(`
4
- `)}:null},ot=(e,t,n)=>{let r;try{r=JSON.parse(e.data)}catch{return}if(e.event==="session"){let i=r.sessionId;i&&(n(i),t.onSession?.(i));return}if(e.event==="turn_event"){t.onEvent?.(r);let i=N(r);i&&t.onText?.(i);let l=q(r);l&&t.onThinking?.(l);let o=j(r);o&&t.onTool?.(o);return}if(e.event==="chat_completed"){let i=r;n(i.sessionId),t.onComplete?.(i);return}e.event==="chat_error"&&t.onError?.(x(r))},S=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()},ge=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()},fe=async(e,t,n,r)=>{let i=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body,signal:r});if(!(i.ok&&i.body)){t.onError?.({error:`stream_failed_${i.status}`});return}let l=i.body.getReader(),o=new TextDecoder,s="",a=()=>{let d=s.indexOf(`
2
+ var ge=["text","number","url","date","boolean","select","multi_select","file"],ot={checkbox:"boolean",link:"url"};function N(e){return typeof e!="string"?"text":ge.includes(e)?e:ot[e]??"text"}var fe=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},q=e=>{let t=fe(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},j=e=>{let t=fe(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},B=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 st=/^ /,x=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"}},it=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(st,"")));return n.length>0?{event:t,data:n.join(`
4
+ `)}:null},at=(e,t,n)=>{let r;try{r=JSON.parse(e.data)}catch{return}if(e.event==="session"){let i=r.sessionId;i&&(n(i),t.onSession?.(i));return}if(e.event==="turn_event"){t.onEvent?.(r);let i=q(r);i&&t.onText?.(i);let l=j(r);l&&t.onThinking?.(l);let o=B(r);o&&t.onTool?.(o);return}if(e.event==="chat_completed"){let i=r;n(i.sessionId),t.onComplete?.(i);return}e.event==="chat_error"&&t.onError?.(x(r))},T=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()},ye=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()},be=async(e,t,n,r)=>{let i=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body,signal:r});if(!(i.ok&&i.body)){t.onError?.({error:`stream_failed_${i.status}`});return}let l=i.body.getReader(),o=new TextDecoder,s="",a=()=>{let d=s.indexOf(`
5
5
 
6
- `);for(;d!==-1;){let m=s.slice(0,d);s=s.slice(d+2);let p=rt(m);p&&ot(p,t,n),d=s.indexOf(`
6
+ `);for(;d!==-1;){let m=s.slice(0,d);s=s.slice(d+2);let p=it(m);p&&at(p,t,n),d=s.indexOf(`
7
7
 
8
- `)}},u=async()=>{let d=await l.read();if(!d.done)return s+=o.decode(d.value,{stream:!0}),a(),u()};await u()};var st=/\/+$/,B="/api/v1/end-user",it=e=>{let t=e.baseUrl.replace(st,""),n=()=>typeof e.token=="function"?e.token():e.token,r=o=>e.project?`${o}project=${encodeURIComponent(e.project)}`:"",i=async()=>({"content-type":"application/json",authorization:`Bearer ${await n()}`}),l=async o=>{let s=await fetch(`${t}${B}/chat${r("?")}`,{method:"POST",headers:await i(),body:JSON.stringify({message:o})});if(!s.ok)throw new Error(`hola: message failed (${s.status})`);return{reply:(await s.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>S(`${t}${B}/chat/info${r("?")}`,await i()),sendMessage:l,streamMessage:async(o,s)=>{try{let a=await l(o);s.onText?.(a.reply),s.onComplete?.(a)}catch(a){s.onError?.(x(a))}},subscribe:(o,s)=>{let a=s?.since??"0",u=!1,d,m=s?.intervalMs??3e3,p=typeof document<"u",c=()=>p&&document.visibilityState==="hidden",g=!1,y=()=>{if(!u){if(c()){g=!0;return}d=setTimeout(b,m)}},b=async()=>{try{let w=await S(`${t}${B}/chat/thread?since=${encodeURIComponent(a)}${r("&")}`,await i());for(let k of w.messages)o.onMessage(k);a=w.cursor,o.onHealthy?.()}catch(w){o.onError?.(x(w))}y()},T=()=>{u||!g||c()||(g=!1,d&&clearTimeout(d),d=setTimeout(b,0))};p&&document.addEventListener("visibilitychange",T);let f=()=>{u=!0,d&&clearTimeout(d),p&&document.removeEventListener("visibilitychange",T)};return s?.signal?.addEventListener("abort",f),d=setTimeout(b,0),f}}};import{useEffect as at,useState as lt}from"react";var V=(e,t)=>{let[n,r]=lt("");return at(()=>{if(!e){r("");return}let i=Uint8Array.from(atob(e),o=>o.charCodeAt(0)),l=URL.createObjectURL(new Blob([i],{type:t}));return r(l),()=>URL.revokeObjectURL(l)},[e,t]),n};import{useEffect as mt,useRef as gt}from"react";import{createContext as ut,useContext as dt}from"react";import{jsx as ct}from"react/jsx-runtime";var ye=ut(null),pt=({client:e,children:t})=>ct(ye.Provider,{value:e,children:t}),G=()=>{let e=dt(ye);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};import{useCallback as be,useEffect as he,useRef as we,useState as O}from"react";var Q=e=>{let[t,n]=O([]),[r,i]=O(""),[l,o]=O(!1),[s,a]=O(null),u=we(0),d=we(null);he(()=>()=>d.current?.abort(),[]);let m=be(()=>{let c=u.current;return u.current+=1,c},[]);he(()=>{let c=!0;return e.getInfo().then(g=>{c&&g.greeting&&n([{id:m(),role:"assistant",text:g.greeting}])}).catch(()=>{}),()=>{c=!1}},[e,m]);let p=be(()=>{let c=r.trim();if(!c||l)return;i(""),a(null),o(!0);let g=m(),y=m();n(f=>[...f,{id:g,role:"user",text:c},{id:y,role:"assistant",text:"",streaming:!0}]);let b=f=>{n(w=>w.map(k=>k.id===y?f(k):k))},T=new AbortController;d.current=T,e.streamMessage(c,{onText:f=>b(w=>({...w,text:w.text+f})),onComplete:f=>{b(w=>({...w,text:f.reply||w.text,artifacts:f.artifacts,streaming:!1})),o(!1)},onError:f=>{b(w=>({...w,streaming:!1})),a(f.error),o(!1)}},T.signal).catch(f=>{b(w=>({...w,streaming:!1})),a(f instanceof Error?f.message:"stream_failed"),o(!1)}).finally(()=>{o(!1),b(f=>f.streaming?{...f,streaming:!1}:f)})},[r,l,e,m]);return{messages:t,input:r,setInput:i,send:p,sending:l,error:s}};import{jsx as C,jsxs as z}from"react/jsx-runtime";var v={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"}},ft=({artifact:e})=>{let t=V(e.dataBase64??"",e.mimeType),n=e.url??t;return n?e.mimeType.startsWith("image/")?C("a",{href:n,rel:"noopener noreferrer",target:"_blank",children:C("img",{alt:e.filename,src:n,style:v.image})}):C("a",{download:e.filename,href:n,style:v.link,children:e.filename}):null},yt=()=>{let e=G(),{messages:t,input:n,setInput:r,send:i,sending:l,error:o}=Q(e),s=gt(null);mt(()=>{let u=s.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let a=u=>{u.preventDefault(),i()};return z("div",{style:v.root,children:[C("div",{ref:s,style:v.log,children:t.map(u=>z("div",{style:u.role==="user"?v.user:v.assistant,children:[u.text||(u.streaming?"\u2026":""),u.artifacts&&u.artifacts.length>0?C("div",{style:v.artifacts,children:u.artifacts.map(d=>C(ft,{artifact:d},d.filename))}):null]},u.id))}),o?C("div",{style:v.error,children:o}):null,z("form",{onSubmit:a,style:v.form,children:[C("input",{"aria-label":"Message",onChange:u=>r(u.target.value),placeholder:"Type a message\u2026",style:v.input,value:n}),C("button",{disabled:l||n.trim().length===0,style:v.button,type:"submit",children:"Send"})]})]})};var bt=/\/+$/,J=e=>{let t=e.sessionId,n=e.baseUrl.replace(bt,""),r=o=>`${n}/endpoint/${encodeURIComponent(e.token)}${o}`,i={"content-type":"application/json"},l=(o,s)=>({url:r(o),headers:i,body:JSON.stringify({message:s,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>S(r("/config"),{}),sendMessage:async o=>{let s=await ge(l("/message",o));return t=s.sessionId,s},streamMessage:(o,s,a)=>fe(l("/message/stream",o),s,u=>{t=u},a),subscribe:(o,s)=>{let a=s?.since??"0",u=!1,d,m=s?.intervalMs??3e3,p=async()=>{let g=t;if(g)try{let y=await S(r(`/messages?session=${encodeURIComponent(g)}&since=${encodeURIComponent(a)}`),{});for(let b of y.messages)o.onMessage(b);a=y.cursor,o.onHealthy?.()}catch(y){o.onError?.(x(y))}u||(d=setTimeout(p,m))},c=()=>{u=!0,d&&clearTimeout(d)};return s?.signal?.addEventListener("abort",c),d=setTimeout(p,0),c}}};var ht=e=>"transport"in e?e.transport:J(e);var wt=/^https?:\/\//i,xt=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,St=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function vt(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(wt.test(e))return"url";if(xt.test(e))return"date"}return"text"}function xe(e){let t=[],n=new Map,r=[...e].sort((i,l)=>String(i.rowId??"").localeCompare(String(l.rowId??"")));for(let i of r)for(let[l,o]of Object.entries(i.data??{})){if(o==null)continue;let s=n.get(l);s||(s=new Map,n.set(l,s),t.push(l));let a=vt(o);s.set(a,(s.get(a)??0)+1)}return t.map(i=>{let l=n.get(i)??new Map,o="text",s=-1;for(let[a,u]of l)u>s&&(s=u,o=a);return{key:i,label:St(i),type:o}})}var Tt=e=>typeof e=="number"?e:Number(e)||0,Se=e=>/rate|position|rank|score|percent|avg/i.test(e),Pt=/posted|published|sent|completed|shipped|launched|_at/i,kt=new Set(["service","order","end_user_id"]);function ve(e,t){let n=e.filter(a=>!kt.has(a.key)),r=n.filter(a=>a.type==="number").slice(0,3),i=n.find(a=>a.key==="status")??n.find(a=>a.type==="select"),l=n.find(a=>a.type==="date"&&Pt.test(a.key))??n.find(a=>a.type==="date"),o=n.filter(a=>a.type==="number"&&!Se(a.key)).map(a=>({field:a,total:t.reduce((u,d)=>u+Tt(d.data[a.key]),0)})).sort((a,u)=>u.total-a.total).find(a=>a.total>0)?.field??null,s=[{type:"stat",label:"Items",agg:"count"}];for(let a of r){let u=Se(a.key);s.push({type:"stat",metric:a.key,agg:u?"avg":"sum",label:u?`Avg ${a.label.toLowerCase()}`:a.label})}return l&&s.push({type:"line",x:l.key,y:o?.key,agg:"sum",title:o?`${o.label} by day`:"Items by day"}),i&&s.push({type:"donut",groupBy:i.key,title:i.label}),s.push({type:"table",columns:n.map(a=>a.key)}),{version:1,widgets:s}}var Te=6,Pe=6,ke=4,Ce={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:2}},Ct=e=>Math.max(1,Math.min(6,Math.round(e))),Rt=e=>Math.max(1,Math.min(4,Math.round(e)));function H(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function Re(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function De(e){return Ce[e]}function K(e,t,n){let r=Ce[e];return{w:t===void 0?r.w:Ct(t),h:n===void 0?r.h:Rt(n)}}function X(e){let t=[],n=[],r=(o,s,a,u)=>{if(o<0||o+a>6)return!1;for(let d=0;d<u;d+=1){let m=n[s+d];if(m){for(let p=0;p<a;p+=1)if(m[o+p])return!1}}return!0},i=(o,s,a,u)=>{for(let d=0;d<u;d+=1){let m=n[s+d]??[];for(let p=0;p<a;p+=1)m[o+p]=!0;n[s+d]=m}},l=(o,s)=>{for(let a=0;;a+=1)for(let u=0;u+o<=6;u+=1)if(r(u,a,o,s))return{gx:u,gy:a}};for(let o of e){let s=K(H(o.kind),o.w,o.h),u=o.gx!==void 0&&o.gy!==void 0&&r(o.gx,o.gy,s.w,s.h)&&o.gx!==void 0&&o.gy!==void 0?{gx:o.gx,gy:o.gy}:l(s.w,s.h);i(u.gx,u.gy,s.w,s.h),t.push({widget:o,gx:u.gx,gy:u.gy,w:s.w,h:s.h})}return t}function Ie(e){let t=[],n=[];for(let r of e)H(r.kind)==="block"?n.push(r):t.push(r);return{tiles:X(t),blocks:n}}var Ae=new Set(["service","order","end_user_id"]),Y=e=>typeof e=="number"?e:Number(e)||0,Me=e=>e==null?"":String(e);function Z(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,i)=>r+i,0);return e==="avg"?Math.round(n/t.length*100)/100:n}function Dt(e,t,n,r){let i=new Map;for(let l of e){let o=new Date(Me(l.data[t]));if(Number.isNaN(o.getTime()))continue;let s=o.toISOString().slice(0,10),a=i.get(s)??[];a.push(n?Y(l.data[n]):1),i.set(s,a)}return[...i.entries()].sort((l,o)=>l[0]<o[0]?-1:1).map(([l,o])=>({label:new Date(`${l}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:n?Z(r,o):o.length}))}function It(e,t,n,r="sum"){let i=new Map;for(let l of e){let o=Me(l.data[t]).trim();if(!o)continue;let s=i.get(o)??[];s.push(n?Y(l.data[n]):1),i.set(o,s)}return[...i.entries()].map(([l,o])=>({label:l,value:n?Z(r,o):o.length})).sort((l,o)=>o.value-l.value)}function At(e,t,n,r){switch(e.type){case"stat":{let i=e.metric?t.get(e.metric):void 0;if(e.metric&&!i)return null;if(!i)return{kind:"stat",label:e.label??"Items",value:r.length};let l=r.map(o=>Y(o.data[i.key]));return{kind:"stat",label:e.label??i.label,value:Z(e.agg??"sum",l)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let i=Dt(r,e.x,e.y,e.agg??"sum");return i.length<2?null:{kind:"series",draw:e.type,title:e.title??"By day",points:i}}case"donut":{if(!t.has(e.groupBy))return null;let i=It(r,e.groupBy,e.metric,e.agg??"sum");return i.length===0?null:{kind:"donut",title:e.title??t.get(e.groupBy)?.label??"Breakdown",points:i}}case"table":{let i=e.columns?e.columns.map(l=>t.get(l)).filter(l=>l!==void 0&&!Ae.has(l.key)):n;return i.length===0?null:{kind:"table",title:e.title,columns:i,rows:r}}case"text":return{kind:"text",title:e.title,body:e.body};default:return null}}function Fe(e,t,n,r={}){let i=new Map,l=a=>({byKey:new Map(a.fields.map(u=>[u.key,u])),cols:a.fields.filter(u=>!Ae.has(u.key)),rows:a.rows}),o=l({fields:t,rows:n});for(let[a,u]of Object.entries(r))i.set(a,l(u));let s=[];for(let a of e.widgets){let u=a.type==="text"?void 0:a.source,d=u?i.get(u):o;if(!d)continue;let m=At(a,d.byKey,d.cols,d.rows);m&&s.push({...m,w:a.w,h:a.h,gx:a.gx,gy:a.gy})}return s}var Mt=new Set(["sum","avg","count","min","max","last"]),Ee=e=>typeof e=="string"&&Mt.has(e)?e:void 0,h=e=>typeof e=="string"&&e!==""?e:void 0,M=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,F=e=>typeof e=="number"&&e>=1?Math.min(4,Math.round(e)):void 0,P=e=>typeof e=="number"&&e>=0?Math.round(e):void 0;function Ft(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:Ee(t.agg),w:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(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:Ee(t.agg),w:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(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:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(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:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(t.gy)}}case"text":{let n=h(t.body);return n?{type:"text",title:h(t.title),body:n,w:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(t.gy)}:null}default:return null}}function Oe(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(Ft).filter(l=>l!==null);if(r.length===0)return null;let i=t.version;return{version:typeof i=="number"?i:1,title:h(t.title),widgets:r}}function ee(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",i=typeof t.v=="number"&&t.v>=1?Math.floor(t.v):void 0;return n?{kind:r,value:n,...i?{v:i}:{}}:null}return null}function te(e){let t=new Map;for(let n of e){let r=n.v??1,i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.entries()].sort(([n],[r])=>n-r).map(([n,r])=>({v:n,items:r}))}function He(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(ee).filter(i=>i!==null)}catch{}let n=String(e.file??"");return n?[{kind:"file",value:n}]:[]}function _e(e,t,n,r=""){let l=te(e).find(s=>s.v===t)?.items??[],o=l.filter(s=>s.kind==="file").map(s=>n.get(s.value)??"");return l.some(s=>s.kind==="table")&&o.push(r),o.length===0||o.some(s=>s==="")?"awaiting":o.some(s=>s==="revise")?"revise":"accepted"}function $e(e){return Number(e.published_version)||0}var re=["short","medium","long","iso","relative"],oe=["none","12h","24h"];function se(e){return e==="number"||e==="date"||e==="boolean"||e==="select"||e==="multi_select"||e==="file"||e==="url"?e:e==="link"?"url":e==="checkbox"?"boolean":"text"}function Le(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let n=t.columns.map((o,s)=>({key:typeof o.key=="string"&&o.key?o.key:typeof o.id=="string"&&o.id?o.id:`column_${s+1}`,label:typeof o.label=="string"?o.label:"",type:se(o.type),...(()=>{let a=Array.isArray(o.options)?[...new Set(o.options.map(u=>String(u).trim()).filter(u=>u!==""))]:[];return a.length>0?{options:a}:{}})(),...re.includes(o.dateFormat)?{dateFormat:o.dateFormat}:{},...oe.includes(o.timeFormat)?{timeFormat:o.timeFormat}:{},...o.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((o,s)=>({id:typeof o.id=="string"&&o.id?o.id:`row_${s}`,cells:o.cells&&typeof o.cells=="object"?o.cells:{}})),i=typeof t.name=="string"?t.name:void 0,l=ie(t.view);return{columns:n,rows:r,...i?{name:i}:{},...l?{view:l}:{}}}}catch{}return null}var D=e=>{if(!Array.isArray(e))return;let t=e.map(n=>String(n).trim()).filter(n=>n!=="");return t.length>0?t:void 0};function ie(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n={};if(t.widths&&typeof t.widths=="object"&&!Array.isArray(t.widths))for(let[l,o]of Object.entries(t.widths))typeof o=="number"&&Number.isFinite(o)&&o>0&&(n[l]=Math.round(o));let r=typeof t.frozen=="number"&&Number.isFinite(t.frozen)&&t.frozen>0?Math.floor(t.frozen):void 0,i={...D(t.hidden)?{hidden:D(t.hidden)}:{},...D(t.order)?{order:D(t.order)}:{},...D(t.wrap)?{wrap:D(t.wrap)}:{},...Object.keys(n).length>0?{widths:n}:{},...r?{frozen:r}:{}};return Object.keys(i).length>0?i:void 0}function Ue(e){let t=e.view;if(!t)return e.columns;let n=new Set(e.columns.map(s=>s.key)),r=new Set(t.hidden??[]),i=(t.order??[]).filter(s=>n.has(s)),l=e.columns.map(s=>s.key).filter(s=>!i.includes(s)),o=new Map(e.columns.map(s=>[s.key,s]));return[...i,...l].filter(s=>!r.has(s)).map(s=>o.get(s)).filter(s=>!!s)}var ae=6;function Ne(e){let t=e.trim().toLowerCase();if(t==="")return-1;let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return Math.abs(n)%ae}function qe(e){try{let t=new URL(e),n=t.pathname.split("/").filter(Boolean).pop()??"";return n===""?t.host:`${t.host}/\u2026/${n}`}catch{return e}}function le(e){return e==null?"":String(e)}function je(e){let t=le(e).trim();if(t==="")return[];try{let n=JSON.parse(t);if(Array.isArray(n))return n.map(r=>String(r).trim()).filter(r=>r!=="")}catch{}return t.split(",").map(n=>n.trim()).filter(n=>n!=="")}function Be(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function _(){return{cells:{},verdict:"",comment:""}}function Ve(e){if(typeof e!="string"||e.trim()==="")return _();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 _()}function Ge(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 Qe(e,t,n,r){return{...e,cells:{...e.cells,[t]:{...e.cells[t]??{},[n]:r}}}}function ze(e,t,n){return{...e,verdict:t,comment:n}}function Je(e,t="medium",n="none"){let r=new Date(/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00`:e);if(Number.isNaN(r.getTime()))return e;if(t==="iso"){let o=a=>String(a).padStart(2,"0"),s=`${r.getFullYear()}-${o(r.getMonth()+1)}-${o(r.getDate())}`;return n==="none"?s:`${s} ${o(r.getHours())}:${o(r.getMinutes())}`}if(t==="relative")return Ot(r);let i=t==="short"?{year:"numeric",month:"numeric",day:"numeric"}:t==="long"?{year:"numeric",month:"long",day:"numeric",weekday:"long"}:{year:"numeric",month:"short",day:"numeric"},l=n==="none"?{}:{hour:"numeric",minute:"2-digit",hour12:n==="12h"};return r.toLocaleString(void 0,{...i,...l})}var Et=6e4,We=36e5,ne=864e5;function Ot(e){let t=e.getTime()-Date.now(),n=Math.abs(t);if(n>30*ne)return e.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});let r=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});return n<We?r.format(Math.round(t/Et),"minute"):n<ne?r.format(Math.round(t/We),"hour"):r.format(Math.round(t/ne),"day")}var I=class extends Error{code;status;constructor(t,n,r){super(n),this.name="CreditRefused",this.code=t,this.status=r}},W=class extends I{credits;balance;short;constructor(t,n){super("insufficient_credits",t,402),this.name="InsufficientCredits",this.credits=n.credits,this.balance=n.balance,this.short=n.short}},Ht=/\/+$/,_t="/api/v1/end-user",de="Pre-payment",pe="After-payment";function $t(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,i=[];return n>0&&i.push({label:de,amount:n}),r>0&&i.push({label:pe,amount:r}),i}var ue=e=>e.status!=="paid"&&e.asked!==!1,Wt=(e,t)=>e.payMethods&&e.payMethods.length>0?[...e.payMethods]:[...t],Lt=(e,t)=>{let n=typeof t=="number"&&Number.isFinite(t)&&t>0?t:1;return!Number.isFinite(e)||e<=0?0:Math.ceil(e*n)},$=e=>{let t=e.label.trim().toLowerCase();return t===de.toLowerCase()?0:t===pe.toLowerCase()?2:1},Ut=(e,t,n)=>{let r=t.filter(p=>p.order===n),i=p=>p.reduce((c,g)=>c+g.amount,0),l=i(r),o=i(r.filter(p=>p.status==="paid")),s=e.value>0,a=[...r].sort((p,c)=>$(p)!==$(c)?$(p)-$(c):(p.dueDate||p.paidAt).localeCompare(c.dueDate||c.paidAt)),u=a.filter(ue),d=a.filter(p=>p.status!=="paid"&&!ue(p)),m=l>0?i(u):e.value-o;return{value:e.value,priced:s,billed:l,paid:o,due:Math.max(0,m),scheduled:i(d),lines:a,asked:u,upcoming:d,awaitingPayment:s&&o<=0}},Nt=e=>{let{credits:t,balance:n,short:r}=e;return typeof t!="number"||typeof n!="number"||typeof r!="number"||!(Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r))?null:{credits:t,balance:n,short:r}},qt=e=>{let t=e.baseUrl.replace(Ht,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async(i,l={method:"GET"})=>{try{let o=await fetch(`${t}${_t}${i}`,{method:l.method,headers:{"content-type":"application/json",authorization:`Bearer ${await n()}`},...l.body===void 0?{}:{body:JSON.stringify(l.body)}});if(!o.ok){let s=await o.json().catch(()=>({})),a=s.message??`${l.method} ${i} \u2192 ${String(o.status)}`,u=Nt(s);throw o.status===402&&s.error==="insufficient_credits"&&u?new W(a,u):new I(s.error??"request_failed",a,o.status)}return await o.json()}catch(o){throw o instanceof I?o:x(o)}};return{wallet:()=>r("/credits"),history:()=>r("/credits/history"),topup:i=>r("/credits/checkout",{method:"POST",body:{packId:i}}),checkout:i=>r("/shop/checkout",{method:"POST",body:i}),payments:()=>r("/payments"),paymentMethods:()=>r("/payment-methods"),markPaymentSent:(i,l)=>r(`/payments/${encodeURIComponent(i)}/sent`,{method:"POST",body:{reference:l??""}}),payWithCredits:i=>r(`/payments/${encodeURIComponent(i)}/pay-with-credits`,{method:"POST",body:{}}),inquiryQuote:i=>r(`/inquiries/${encodeURIComponent(i)}/quote`),acceptInquiry:(i,l)=>r(`/inquiries/${encodeURIComponent(i)}/accept`,{method:"POST",body:{version:l}}),enquire:(i,l,o)=>r("/shop/enquire",{method:"POST",body:{productId:i,answers:l,name:o??""}})}};var jt=/\/+$/,R="/api/v1/end-user",E=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function Bt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var Vt=e=>{let t=e.baseUrl.replace(jt,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await n()}`}),i=async(o,s)=>{try{let a=await fetch(`${t}${R}${o}`,{method:s.method,headers:await r(),...s.body===void 0?{}:{body:JSON.stringify(s.body)}});if(a.status===409){let u=await a.json().catch(()=>({}));throw new E(u.message??"Someone else saved this first.")}if(!a.ok){let u=await a.text().catch(()=>""),d=`${s.method} ${o} \u2192 ${String(a.status)}`;try{let m=JSON.parse(u);m.message&&(d=m.message)}catch{d=u?`${d}: ${u}`:d}throw x({error:d})}return await a.json()}catch(a){throw a instanceof E?a:x(a)}},l=o=>`/tables/${encodeURIComponent(o)}`;return{listTables:async()=>(await S(`${t}${R}/tables`,await r())).tables,listRows:async(o,s)=>await S(`${t}${R}${l(o)}/rows?limit=${String(s??100)}`,await r()),insertRow:async(o,s)=>{let{rowIds:a}=await i(`${l(o)}/rows`,{method:"POST",body:{rows:[s]}}),u=a[0];if(!u)throw x(new Error("The row was not created."));return u},patchRow:async(o,s,a)=>(await i(`${l(o)}/rows/${encodeURIComponent(s)}`,{method:"PATCH",body:a})).updated,deleteRow:async(o,s)=>(await i(`/${encodeURIComponent(o)}/${encodeURIComponent(s)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await S(`${t}${R}/tables/files/rows?limit=200`,await r())).rows.map(s=>({id:s.rowId,filename:String(s.data.filename??""),source:String(s.data.source??"client"),campaign:String(s.data.campaign??""),size:typeof s.data.size=="number"?s.data.size:0,createdAt:s.createdAt})),uploadFile:async(o,s)=>{let a=new Uint8Array(await o.arrayBuffer());return await i("/files",{method:"POST",body:{filename:o.name,mime:o.type||"application/octet-stream",data:Bt(a),...s===void 0?{}:{message:s}}})},fileLink:async o=>await S(`${t}${R}/files/${encodeURIComponent(o)}/url`,await r()),deleteFile:async o=>(await i(`/files/${encodeURIComponent(o)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await S(`${t}${R}/documents`,await r())).documents,readDocument:async o=>(await S(`${t}${R}/documents/${encodeURIComponent(o)}`,await r())).document,saveDocument:async(o,s)=>await i(`/documents/${encodeURIComponent(o)}`,{method:"PATCH",body:s})}};var Gt=/\/+$/,Qt="/api/v1/end-user",zt=e=>{let t=e.baseUrl.replace(Gt,""),n=async(r,i)=>{let l;try{l=await fetch(`${t}${Qt}${r}`,i===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i)})}catch(o){throw x(o)}if(l.status===429)throw x({error:"rate_limited",retryable:!0});if(!l.ok)throw x({error:`shop_request_failed_${String(l.status)}`});try{return await l.json()}catch(o){throw x(o)}};return{listProducts:async()=>{let r=await n(`/shop/products?publishable_key=${encodeURIComponent(e.publishableKey)}`);return{products:r.products.map(i=>({...i,currency:typeof i.currency=="string"?i.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 Jt=new Set(["buy","ask"]);function Kt(e){return Jt.has(e.mode)?e.mode:"ask"}var Xt={kind:"quoted"};function L(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 Ke(e,t){let n=/^[a-z]+$/i.test(t)&&!t.endsWith("s")?"s":"";return`${e.toLocaleString()} ${t}${n}`}function Xe(e,t){return e.kind==="quoted"?"Priced on enquiry":e.kind==="flat"?L(e.price,t):`${L(e.unitPrice,t)} per ${e.unitStep===1?e.unit:Ke(e.unitStep,e.unit)}`}function Yt(e){let t=e.currency,n=e.pricing;if(n.kind!=="variants")return Xe(n,t);let r=n.variants.map(i=>i.price).filter(i=>typeof i=="number");return r.length>0?`From ${L(Math.min(...r),t)}`:"Priced on enquiry"}function Zt(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}:Xt}function en(e,t){return e.kind==="flat"?e.price:e.kind==="per_unit"?e.unitPrice*Math.ceil(t/Math.max(e.unitStep,1)):null}function tn(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 nn(e,t){let n=e.variants?.find(r=>r.name===t);return n&&n.includes.length>0?n.includes:e.includes}function rn(e,t){let n=[];for(let r of e){let i=t(r).trim();i&&!n.includes(i)&&n.push(i)}return n}function on(e,t,n,r){let i=t?`${e.name} \u2014 ${t}`:e.name,l=n.kind==="per_unit"?`, ${Ke(r,n.unit)}`:"";return`I'd like to buy ${i}${l}. How do I go ahead?`}function sn(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}import{useCallback as Ye,useEffect as an,useState as ce}from"react";var ln=e=>{let[t,n]=ce(null),[r,i]=ce(!0),[l,o]=ce(null),s=Ye(async()=>{try{n(await e.wallet()),o(null)}catch{o("Couldn't read your balance just now.")}finally{i(!1)}},[e]),a=Ye(()=>{s().catch(()=>{})},[s]);return an(()=>(a(),window.addEventListener("focus",a),()=>{window.removeEventListener("focus",a)}),[a]),{wallet:t,loading:r,failure:l,refresh:a}};import{useCallback as un,useEffect as dn,useState as A}from"react";var pn=e=>e&&typeof e=="object"&&typeof e.error=="string"?e.error:e instanceof Error?e.message:"shop_unavailable",cn=e=>{let[t,n]=A([]),[r,i]=A([]),[l,o]=A(!1),[s,a]=A(!0),[u,d]=A(null),[m,p]=A(0);dn(()=>{let g=!0;return a(!0),e.listProducts().then(y=>{g&&(n(y.products),i(y.enquiryForm),o(y.truncated),d(null))}).catch(y=>{g&&d(pn(y))}).finally(()=>{g&&a(!1)}),()=>{g=!1}},[e,m]);let c=un(()=>p(g=>g+1),[]);return{products:t,enquiryForm:r,truncated:l,loading:s,error:u,reload:c}};import{useCallback as mn,useEffect as Ze,useRef as gn,useState as U}from"react";var et="greeting";function tt(e,t){if(e.some(l=>l.id===t.id))return e;let n=e.filter(l=>l.id!==et),r=l=>l.author==="client"==(t.author==="client");return[...n.filter(l=>!(l.pending&&r(l)&&l.text===t.text)),t]}var fn=(e,t)=>{let[n,r]=U([]),[i,l]=U(""),[o,s]=U(!1),[a,u]=U(null),d=gn(0),m=t?.pollMs??2e3;Ze(()=>{let c=!0;return e.getInfo().then(g=>{c&&g.greeting&&r(y=>y.length===0?[{id:et,cursor:"",author:"agent",text:g.greeting}]:y)}).catch(()=>{}),()=>{c=!1}},[e]),Ze(()=>e.subscribe?.({onMessage:c=>r(g=>tt(g,c)),onError:c=>u(c.error),onHealthy:()=>u(null)},{intervalMs:m}),[e,m]);let p=mn(()=>{let c=i.trim();if(!c||o)return;l(""),u(null),s(!0),d.current+=1;let g=`pending-${d.current}`,y={id:g,cursor:"",author:"client",text:c,pending:!0};r(b=>[...b,y]),e.sendMessage(c).then(b=>{s(!1),b.reply.trim()&&r(f=>f.some(k=>!k.pending&&k.author!=="client"&&k.text===b.reply)?f:(d.current+=1,[...f,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:b.reply,pending:!0}]))}).catch(b=>{u(b instanceof Error?b.message:"send_failed"),s(!1),r(T=>T.filter(f=>f.id!==g)),l(T=>T||c)})},[i,o,e]);return{messages:n,input:i,setInput:l,send:p,sending:o,error:a}};export{yt as Chat,I as CreditRefused,re as DATE_FORMATS,Te as GRID_COLS,Pe as GRID_MAX_COLS,ke as GRID_MAX_ROWS,pt as HolaProvider,W as InsufficientCredits,ae as OPTION_TINTS,E as PortalConflict,pe as QUOTE_BALANCE_LABEL,de as QUOTE_DEPOSIT_LABEL,oe as TIME_FORMATS,Ue as arrangedColumns,H as bandOfKind,Re as bandOfType,on as buyRequestText,Ge as cellValue,it as createApiTransport,ht as createHolaClient,qt as createPortalCredits,Vt as createPortalData,zt as createPortalShop,J as createWidgetTransport,Lt as creditsOfMoney,le as deliverableCellText,je as deliverableCellValues,_e as deliverableStatus,xe as deriveFields,_ as emptyTableResponses,rn as facetValues,De as footprintOf,K as footprintWith,Je as formatDeliverableDate,te as groupDeliverableVersions,nn as includesFor,ve as inferSpec,Be as isDeliverableChecked,tt as mergeMessage,Kt as modeOf,L as money,se as normalizeDeliverableColType,ee as normalizeDeliverableItem,Ne as optionTintIndex,Ut as orderBilling,ie as parseArrangement,Oe as parseDashboardSpec,He as parseDeliverableItems,Le as parseDeliverableTable,Ve as parseTableResponses,ue as paymentAsked,Wt as paymentPayMethods,X as placeWidgets,Zt as priceFor,Xe as priceLabel,$e as publishedVersionOf,tn as quantityRange,$t as quoteSchedule,Fe as renderModel,Qe as setResponse,ze as setTableReview,Yt as shelfPriceLabel,sn as shelfProblem,qe as shortenUrl,Ie as splitLayout,N as textDeltaOf,q as thinkingDeltaOf,j as toolEventOf,en as totalFor,V as useArtifactUrl,Q as useChat,ln as useCredits,G as useHolaClient,cn as useShop,fn as useThread};
8
+ `)}},u=async()=>{let d=await l.read();if(!d.done)return s+=o.decode(d.value,{stream:!0}),a(),u()};await u()};var lt=/\/+$/,V="/api/v1/end-user",ut=e=>{let t=e.baseUrl.replace(lt,""),n=()=>typeof e.token=="function"?e.token():e.token,r=o=>e.project?`${o}project=${encodeURIComponent(e.project)}`:"",i=async()=>({"content-type":"application/json",authorization:`Bearer ${await n()}`}),l=async o=>{let s=await fetch(`${t}${V}/chat${r("?")}`,{method:"POST",headers:await i(),body:JSON.stringify({message:o})});if(!s.ok)throw new Error(`hola: message failed (${s.status})`);return{reply:(await s.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>T(`${t}${V}/chat/info${r("?")}`,await i()),sendMessage:l,streamMessage:async(o,s)=>{try{let a=await l(o);s.onText?.(a.reply),s.onComplete?.(a)}catch(a){s.onError?.(x(a))}},subscribe:(o,s)=>{let a=s?.since??"0",u=!1,d,m=s?.intervalMs??3e3,p=typeof document<"u",c=()=>p&&document.visibilityState==="hidden",g=!1,y=()=>{if(!u){if(c()){g=!0;return}d=setTimeout(b,m)}},b=async()=>{try{let w=await T(`${t}${V}/chat/thread?since=${encodeURIComponent(a)}${r("&")}`,await i());for(let k of w.messages)o.onMessage(k);a=w.cursor,o.onHealthy?.()}catch(w){o.onError?.(x(w))}y()},v=()=>{u||!g||c()||(g=!1,d&&clearTimeout(d),d=setTimeout(b,0))};p&&document.addEventListener("visibilitychange",v);let f=()=>{u=!0,d&&clearTimeout(d),p&&document.removeEventListener("visibilitychange",v)};return s?.signal?.addEventListener("abort",f),d=setTimeout(b,0),f}}};import{useEffect as dt,useState as pt}from"react";var z=(e,t)=>{let[n,r]=pt("");return dt(()=>{if(!e){r("");return}let i=Uint8Array.from(atob(e),o=>o.charCodeAt(0)),l=URL.createObjectURL(new Blob([i],{type:t}));return r(l),()=>URL.revokeObjectURL(l)},[e,t]),n};import{useEffect as yt,useRef as bt}from"react";import{createContext as ct,useContext as mt}from"react";import{jsx as ft}from"react/jsx-runtime";var he=ct(null),gt=({client:e,children:t})=>ft(he.Provider,{value:e,children:t}),G=()=>{let e=mt(he);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};import{useCallback as we,useEffect as xe,useRef as Te,useState as O}from"react";var Q=e=>{let[t,n]=O([]),[r,i]=O(""),[l,o]=O(!1),[s,a]=O(null),u=Te(0),d=Te(null);xe(()=>()=>d.current?.abort(),[]);let m=we(()=>{let c=u.current;return u.current+=1,c},[]);xe(()=>{let c=!0;return e.getInfo().then(g=>{c&&g.greeting&&n([{id:m(),role:"assistant",text:g.greeting}])}).catch(()=>{}),()=>{c=!1}},[e,m]);let p=we(()=>{let c=r.trim();if(!c||l)return;i(""),a(null),o(!0);let g=m(),y=m();n(f=>[...f,{id:g,role:"user",text:c},{id:y,role:"assistant",text:"",streaming:!0}]);let b=f=>{n(w=>w.map(k=>k.id===y?f(k):k))},v=new AbortController;d.current=v,e.streamMessage(c,{onText:f=>b(w=>({...w,text:w.text+f})),onComplete:f=>{b(w=>({...w,text:f.reply||w.text,artifacts:f.artifacts,streaming:!1})),o(!1)},onError:f=>{b(w=>({...w,streaming:!1})),a(f.error),o(!1)}},v.signal).catch(f=>{b(w=>({...w,streaming:!1})),a(f instanceof Error?f.message:"stream_failed"),o(!1)}).finally(()=>{o(!1),b(f=>f.streaming?{...f,streaming:!1}:f)})},[r,l,e,m]);return{messages:t,input:r,setInput:i,send:p,sending:l,error:s}};import{jsx as C,jsxs as J}from"react/jsx-runtime";var S={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=z(e.dataBase64??"",e.mimeType),n=e.url??t;return n?e.mimeType.startsWith("image/")?C("a",{href:n,rel:"noopener noreferrer",target:"_blank",children:C("img",{alt:e.filename,src:n,style:S.image})}):C("a",{download:e.filename,href:n,style:S.link,children:e.filename}):null},wt=()=>{let e=G(),{messages:t,input:n,setInput:r,send:i,sending:l,error:o}=Q(e),s=bt(null);yt(()=>{let u=s.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let a=u=>{u.preventDefault(),i()};return J("div",{style:S.root,children:[C("div",{ref:s,style:S.log,children:t.map(u=>J("div",{style:u.role==="user"?S.user:S.assistant,children:[u.text||(u.streaming?"\u2026":""),u.artifacts&&u.artifacts.length>0?C("div",{style:S.artifacts,children:u.artifacts.map(d=>C(ht,{artifact:d},d.filename))}):null]},u.id))}),o?C("div",{style:S.error,children:o}):null,J("form",{onSubmit:a,style:S.form,children:[C("input",{"aria-label":"Message",onChange:u=>r(u.target.value),placeholder:"Type a message\u2026",style:S.input,value:n}),C("button",{disabled:l||n.trim().length===0,style:S.button,type:"submit",children:"Send"})]})]})};var xt=/\/+$/,K=e=>{let t=e.sessionId,n=e.baseUrl.replace(xt,""),r=o=>`${n}/endpoint/${encodeURIComponent(e.token)}${o}`,i={"content-type":"application/json"},l=(o,s)=>({url:r(o),headers:i,body:JSON.stringify({message:s,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>T(r("/config"),{}),sendMessage:async o=>{let s=await ye(l("/message",o));return t=s.sessionId,s},streamMessage:(o,s,a)=>be(l("/message/stream",o),s,u=>{t=u},a),subscribe:(o,s)=>{let a=s?.since??"0",u=!1,d,m=s?.intervalMs??3e3,p=async()=>{let g=t;if(g)try{let y=await T(r(`/messages?session=${encodeURIComponent(g)}&since=${encodeURIComponent(a)}`),{});for(let b of y.messages)o.onMessage(b);a=y.cursor,o.onHealthy?.()}catch(y){o.onError?.(x(y))}u||(d=setTimeout(p,m))},c=()=>{u=!0,d&&clearTimeout(d)};return s?.signal?.addEventListener("abort",c),d=setTimeout(p,0),c}}};var Tt=e=>"transport"in e?e.transport:K(e);var St=/^https?:\/\//i,vt=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,Pt=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function kt(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(St.test(e))return"url";if(vt.test(e))return"date"}return"text"}function Se(e){let t=[],n=new Map,r=[...e].sort((i,l)=>String(i.rowId??"").localeCompare(String(l.rowId??"")));for(let i of r)for(let[l,o]of Object.entries(i.data??{})){if(o==null)continue;let s=n.get(l);s||(s=new Map,n.set(l,s),t.push(l));let a=kt(o);s.set(a,(s.get(a)??0)+1)}return t.map(i=>{let l=n.get(i)??new Map,o="text",s=-1;for(let[a,u]of l)u>s&&(s=u,o=a);return{key:i,label:Pt(i),type:o}})}var Ct=e=>typeof e=="number"?e:Number(e)||0,ve=e=>/rate|position|rank|score|percent|avg/i.test(e),Rt=/posted|published|sent|completed|shipped|launched|_at/i,Dt=new Set(["service","order","end_user_id"]);function Pe(e,t){let n=e.filter(a=>!Dt.has(a.key)),r=n.filter(a=>a.type==="number").slice(0,3),i=n.find(a=>a.key==="status")??n.find(a=>a.type==="select"),l=n.find(a=>a.type==="date"&&Rt.test(a.key))??n.find(a=>a.type==="date"),o=n.filter(a=>a.type==="number"&&!ve(a.key)).map(a=>({field:a,total:t.reduce((u,d)=>u+Ct(d.data[a.key]),0)})).sort((a,u)=>u.total-a.total).find(a=>a.total>0)?.field??null,s=[{type:"stat",label:"Items",agg:"count"}];for(let a of r){let u=ve(a.key);s.push({type:"stat",metric:a.key,agg:u?"avg":"sum",label:u?`Avg ${a.label.toLowerCase()}`:a.label})}return l&&s.push({type:"line",x:l.key,y:o?.key,agg:"sum",title:o?`${o.label} by day`:"Items by day"}),i&&s.push({type:"donut",groupBy:i.key,title:i.label}),s.push({type:"table",columns:n.map(a=>a.key)}),{version:1,widgets:s}}var ke=6,Ce=6,Re=4,De={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:2}},It=e=>Math.max(1,Math.min(6,Math.round(e))),At=e=>Math.max(1,Math.min(4,Math.round(e)));function H(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function Ie(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function Ae(e){return De[e]}function X(e,t,n){let r=De[e];return{w:t===void 0?r.w:It(t),h:n===void 0?r.h:At(n)}}function Y(e){let t=[],n=[],r=(o,s,a,u)=>{if(o<0||o+a>6)return!1;for(let d=0;d<u;d+=1){let m=n[s+d];if(m){for(let p=0;p<a;p+=1)if(m[o+p])return!1}}return!0},i=(o,s,a,u)=>{for(let d=0;d<u;d+=1){let m=n[s+d]??[];for(let p=0;p<a;p+=1)m[o+p]=!0;n[s+d]=m}},l=(o,s)=>{for(let a=0;;a+=1)for(let u=0;u+o<=6;u+=1)if(r(u,a,o,s))return{gx:u,gy:a}};for(let o of e){let s=X(H(o.kind),o.w,o.h),u=o.gx!==void 0&&o.gy!==void 0&&r(o.gx,o.gy,s.w,s.h)&&o.gx!==void 0&&o.gy!==void 0?{gx:o.gx,gy:o.gy}:l(s.w,s.h);i(u.gx,u.gy,s.w,s.h),t.push({widget:o,gx:u.gx,gy:u.gy,w:s.w,h:s.h})}return t}function Me(e){let t=[],n=[];for(let r of e)H(r.kind)==="block"?n.push(r):t.push(r);return{tiles:Y(t),blocks:n}}var Fe=new Set(["service","order","end_user_id"]),Z=e=>typeof e=="number"?e:Number(e)||0,Ee=e=>e==null?"":String(e);function ee(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,i)=>r+i,0);return e==="avg"?Math.round(n/t.length*100)/100:n}function Mt(e,t,n,r){let i=new Map;for(let l of e){let o=new Date(Ee(l.data[t]));if(Number.isNaN(o.getTime()))continue;let s=o.toISOString().slice(0,10),a=i.get(s)??[];a.push(n?Z(l.data[n]):1),i.set(s,a)}return[...i.entries()].sort((l,o)=>l[0]<o[0]?-1:1).map(([l,o])=>({label:new Date(`${l}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:n?ee(r,o):o.length}))}function Ft(e,t,n,r="sum"){let i=new Map;for(let l of e){let o=Ee(l.data[t]).trim();if(!o)continue;let s=i.get(o)??[];s.push(n?Z(l.data[n]):1),i.set(o,s)}return[...i.entries()].map(([l,o])=>({label:l,value:n?ee(r,o):o.length})).sort((l,o)=>o.value-l.value)}function Et(e,t,n,r){switch(e.type){case"stat":{let i=e.metric?t.get(e.metric):void 0;if(e.metric&&!i)return null;if(!i)return{kind:"stat",label:e.label??"Items",value:r.length};let l=r.map(o=>Z(o.data[i.key]));return{kind:"stat",label:e.label??i.label,value:ee(e.agg??"sum",l)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let i=Mt(r,e.x,e.y,e.agg??"sum");return i.length<2?null:{kind:"series",draw:e.type,title:e.title??"By day",points:i}}case"donut":{if(!t.has(e.groupBy))return null;let i=Ft(r,e.groupBy,e.metric,e.agg??"sum");return i.length===0?null:{kind:"donut",title:e.title??t.get(e.groupBy)?.label??"Breakdown",points:i}}case"table":{let i=e.columns?e.columns.map(l=>t.get(l)).filter(l=>l!==void 0&&!Fe.has(l.key)):n;return i.length===0?null:{kind:"table",title:e.title,columns:i,rows:r}}case"text":return{kind:"text",title:e.title,body:e.body};default:return null}}function Oe(e,t,n,r={}){let i=new Map,l=a=>({byKey:new Map(a.fields.map(u=>[u.key,u])),cols:a.fields.filter(u=>!Fe.has(u.key)),rows:a.rows}),o=l({fields:t,rows:n});for(let[a,u]of Object.entries(r))i.set(a,l(u));let s=[];for(let a of e.widgets){let u=a.type==="text"?void 0:a.source,d=u?i.get(u):o;if(!d)continue;let m=Et(a,d.byKey,d.cols,d.rows);m&&s.push({...m,w:a.w,h:a.h,gx:a.gx,gy:a.gy})}return s}var Ot=new Set(["sum","avg","count","min","max","last"]),He=e=>typeof e=="string"&&Ot.has(e)?e:void 0,h=e=>typeof e=="string"&&e!==""?e:void 0,M=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,F=e=>typeof e=="number"&&e>=1?Math.min(4,Math.round(e)):void 0,P=e=>typeof e=="number"&&e>=0?Math.round(e):void 0;function Ht(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:He(t.agg),w:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(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:He(t.agg),w:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(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:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(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:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(t.gy)}}case"text":{let n=h(t.body);return n?{type:"text",title:h(t.title),body:n,w:M(t.w),h:F(t.h),gx:P(t.gx),gy:P(t.gy)}:null}default:return null}}function _e(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(Ht).filter(l=>l!==null);if(r.length===0)return null;let i=t.version;return{version:typeof i=="number"?i:1,title:h(t.title),widgets:r}}function te(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",i=typeof t.v=="number"&&t.v>=1?Math.floor(t.v):void 0;return n?{kind:r,value:n,...i?{v:i}:{}}:null}return null}function ne(e){let t=new Map;for(let n of e){let r=n.v??1,i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.entries()].sort(([n],[r])=>n-r).map(([n,r])=>({v:n,items:r}))}function $e(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(te).filter(i=>i!==null)}catch{}let n=String(e.file??"");return n?[{kind:"file",value:n}]:[]}function We(e,t,n,r=""){let l=ne(e).find(s=>s.v===t)?.items??[],o=l.filter(s=>s.kind==="file").map(s=>n.get(s.value)??"");return l.some(s=>s.kind==="table")&&o.push(r),o.length===0||o.some(s=>s==="")?"awaiting":o.some(s=>s==="revise")?"revise":"accepted"}function Le(e){return Number(e.published_version)||0}var oe=["short","medium","long","iso","relative"],se=["none","12h","24h"],ie=N;function Ne(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let n=t.columns.map((o,s)=>({key:typeof o.key=="string"&&o.key?o.key:typeof o.id=="string"&&o.id?o.id:`column_${s+1}`,label:typeof o.label=="string"?o.label:"",type:ie(o.type),...(()=>{let a=Array.isArray(o.options)?[...new Set(o.options.map(u=>String(u).trim()).filter(u=>u!==""))]:[];return a.length>0?{options:a}:{}})(),...oe.includes(o.dateFormat)?{dateFormat:o.dateFormat}:{},...se.includes(o.timeFormat)?{timeFormat:o.timeFormat}:{},...o.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((o,s)=>({id:typeof o.id=="string"&&o.id?o.id:`row_${s}`,cells:o.cells&&typeof o.cells=="object"?o.cells:{}})),i=typeof t.name=="string"?t.name:void 0,l=ae(t.view);return{columns:n,rows:r,...i?{name:i}:{},...l?{view:l}:{}}}}catch{}return null}var D=e=>{if(!Array.isArray(e))return;let t=e.map(n=>String(n).trim()).filter(n=>n!=="");return t.length>0?t:void 0};function ae(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n={};if(t.widths&&typeof t.widths=="object"&&!Array.isArray(t.widths))for(let[l,o]of Object.entries(t.widths))typeof o=="number"&&Number.isFinite(o)&&o>0&&(n[l]=Math.round(o));let r=typeof t.frozen=="number"&&Number.isFinite(t.frozen)&&t.frozen>0?Math.floor(t.frozen):void 0,i={...D(t.hidden)?{hidden:D(t.hidden)}:{},...D(t.order)?{order:D(t.order)}:{},...D(t.wrap)?{wrap:D(t.wrap)}:{},...Object.keys(n).length>0?{widths:n}:{},...r?{frozen:r}:{}};return Object.keys(i).length>0?i:void 0}function qe(e){let t=e.view;if(!t)return e.columns;let n=new Set(e.columns.map(s=>s.key)),r=new Set(t.hidden??[]),i=(t.order??[]).filter(s=>n.has(s)),l=e.columns.map(s=>s.key).filter(s=>!i.includes(s)),o=new Map(e.columns.map(s=>[s.key,s]));return[...i,...l].filter(s=>!r.has(s)).map(s=>o.get(s)).filter(s=>!!s)}var le=6;function je(e){let t=e.trim().toLowerCase();if(t==="")return-1;let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return Math.abs(n)%le}function Be(e){try{let t=new URL(e),n=t.pathname.split("/").filter(Boolean).pop()??"";return n===""?t.host:`${t.host}/\u2026/${n}`}catch{return e}}function ue(e){return e==null?"":String(e)}function Ve(e){let t=ue(e).trim();if(t==="")return[];try{let n=JSON.parse(t);if(Array.isArray(n))return n.map(r=>String(r).trim()).filter(r=>r!=="")}catch{}return t.split(",").map(n=>n.trim()).filter(n=>n!=="")}function ze(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function _(){return{cells:{},verdict:"",comment:""}}function Ge(e){if(typeof e!="string"||e.trim()==="")return _();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 _()}function Qe(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 Je(e,t,n,r){return{...e,cells:{...e.cells,[t]:{...e.cells[t]??{},[n]:r}}}}function Ke(e,t,n){return{...e,verdict:t,comment:n}}function Xe(e,t="medium",n="none"){let r=new Date(/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00`:e);if(Number.isNaN(r.getTime()))return e;if(t==="iso"){let o=a=>String(a).padStart(2,"0"),s=`${r.getFullYear()}-${o(r.getMonth()+1)}-${o(r.getDate())}`;return n==="none"?s:`${s} ${o(r.getHours())}:${o(r.getMinutes())}`}if(t==="relative")return $t(r);let i=t==="short"?{year:"numeric",month:"numeric",day:"numeric"}:t==="long"?{year:"numeric",month:"long",day:"numeric",weekday:"long"}:{year:"numeric",month:"short",day:"numeric"},l=n==="none"?{}:{hour:"numeric",minute:"2-digit",hour12:n==="12h"};return r.toLocaleString(void 0,{...i,...l})}var _t=6e4,Ue=36e5,re=864e5;function $t(e){let t=e.getTime()-Date.now(),n=Math.abs(t);if(n>30*re)return e.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});let r=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});return n<Ue?r.format(Math.round(t/_t),"minute"):n<re?r.format(Math.round(t/Ue),"hour"):r.format(Math.round(t/re),"day")}var I=class extends Error{code;status;constructor(t,n,r){super(n),this.name="CreditRefused",this.code=t,this.status=r}},W=class extends I{credits;balance;short;constructor(t,n){super("insufficient_credits",t,402),this.name="InsufficientCredits",this.credits=n.credits,this.balance=n.balance,this.short=n.short}},Wt=/\/+$/,Lt="/api/v1/end-user",pe="Pre-payment",ce="After-payment";function Ut(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,i=[];return n>0&&i.push({label:pe,amount:n}),r>0&&i.push({label:ce,amount:r}),i}var de=e=>e.status!=="paid"&&e.asked!==!1,Nt=(e,t)=>e.payMethods&&e.payMethods.length>0?[...e.payMethods]:[...t],qt=(e,t)=>{let n=typeof t=="number"&&Number.isFinite(t)&&t>0?t:1;return!Number.isFinite(e)||e<=0?0:Math.ceil(e*n)},$=e=>{let t=e.label.trim().toLowerCase();return t===pe.toLowerCase()?0:t===ce.toLowerCase()?2:1},jt=(e,t,n)=>{let r=t.filter(p=>p.order===n),i=p=>p.reduce((c,g)=>c+g.amount,0),l=i(r),o=i(r.filter(p=>p.status==="paid")),s=e.value>0,a=[...r].sort((p,c)=>$(p)!==$(c)?$(p)-$(c):(p.dueDate||p.paidAt).localeCompare(c.dueDate||c.paidAt)),u=a.filter(de),d=a.filter(p=>p.status!=="paid"&&!de(p)),m=l>0?i(u):e.value-o;return{value:e.value,priced:s,billed:l,paid:o,due:Math.max(0,m),scheduled:i(d),lines:a,asked:u,upcoming:d,awaitingPayment:s&&o<=0}},Bt=e=>{let{credits:t,balance:n,short:r}=e;return typeof t!="number"||typeof n!="number"||typeof r!="number"||!(Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r))?null:{credits:t,balance:n,short:r}},Vt=e=>{let t=e.baseUrl.replace(Wt,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async(i,l={method:"GET"})=>{try{let o=await fetch(`${t}${Lt}${i}`,{method:l.method,headers:{"content-type":"application/json",authorization:`Bearer ${await n()}`},...l.body===void 0?{}:{body:JSON.stringify(l.body)}});if(!o.ok){let s=await o.json().catch(()=>({})),a=s.message??`${l.method} ${i} \u2192 ${String(o.status)}`,u=Bt(s);throw o.status===402&&s.error==="insufficient_credits"&&u?new W(a,u):new I(s.error??"request_failed",a,o.status)}return await o.json()}catch(o){throw o instanceof I?o:x(o)}};return{wallet:()=>r("/credits"),history:()=>r("/credits/history"),topup:i=>r("/credits/checkout",{method:"POST",body:{packId:i}}),checkout:i=>r("/shop/checkout",{method:"POST",body:i}),payments:()=>r("/payments"),paymentMethods:()=>r("/payment-methods"),markPaymentSent:(i,l)=>r(`/payments/${encodeURIComponent(i)}/sent`,{method:"POST",body:{reference:l??""}}),payWithCredits:i=>r(`/payments/${encodeURIComponent(i)}/pay-with-credits`,{method:"POST",body:{}}),inquiryQuote:i=>r(`/inquiries/${encodeURIComponent(i)}/quote`),acceptInquiry:(i,l)=>r(`/inquiries/${encodeURIComponent(i)}/accept`,{method:"POST",body:{version:l}}),enquire:(i,l,o)=>r("/shop/enquire",{method:"POST",body:{productId:i,answers:l,name:o??""}})}};var zt=/\/+$/,R="/api/v1/end-user",E=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function Gt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var Qt=e=>{let t=e.baseUrl.replace(zt,""),n=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await n()}`}),i=async(o,s)=>{try{let a=await fetch(`${t}${R}${o}`,{method:s.method,headers:await r(),...s.body===void 0?{}:{body:JSON.stringify(s.body)}});if(a.status===409){let u=await a.json().catch(()=>({}));throw new E(u.message??"Someone else saved this first.")}if(!a.ok){let u=await a.text().catch(()=>""),d=`${s.method} ${o} \u2192 ${String(a.status)}`;try{let m=JSON.parse(u);m.message&&(d=m.message)}catch{d=u?`${d}: ${u}`:d}throw x({error:d})}return await a.json()}catch(a){throw a instanceof E?a:x(a)}},l=o=>`/tables/${encodeURIComponent(o)}`;return{listTables:async()=>(await T(`${t}${R}/tables`,await r())).tables,listRows:async(o,s)=>await T(`${t}${R}${l(o)}/rows?limit=${String(s??100)}`,await r()),insertRow:async(o,s)=>{let{rowIds:a}=await i(`${l(o)}/rows`,{method:"POST",body:{rows:[s]}}),u=a[0];if(!u)throw x(new Error("The row was not created."));return u},patchRow:async(o,s,a)=>(await i(`${l(o)}/rows/${encodeURIComponent(s)}`,{method:"PATCH",body:a})).updated,deleteRow:async(o,s)=>(await i(`/${encodeURIComponent(o)}/${encodeURIComponent(s)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await T(`${t}${R}/tables/files/rows?limit=200`,await r())).rows.map(s=>({id:s.rowId,filename:String(s.data.filename??""),source:String(s.data.source??"client"),campaign:String(s.data.campaign??""),size:typeof s.data.size=="number"?s.data.size:0,createdAt:s.createdAt})),uploadFile:async(o,s)=>{let a=new Uint8Array(await o.arrayBuffer());return await i("/files",{method:"POST",body:{filename:o.name,mime:o.type||"application/octet-stream",data:Gt(a),...s===void 0?{}:{message:s}}})},fileLink:async o=>await T(`${t}${R}/files/${encodeURIComponent(o)}/url`,await r()),deleteFile:async o=>(await i(`/files/${encodeURIComponent(o)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await T(`${t}${R}/documents`,await r())).documents,readDocument:async o=>(await T(`${t}${R}/documents/${encodeURIComponent(o)}`,await r())).document,saveDocument:async(o,s)=>await i(`/documents/${encodeURIComponent(o)}`,{method:"PATCH",body:s})}};var Jt=/\/+$/,Kt="/api/v1/end-user",Xt=e=>{let t=e.baseUrl.replace(Jt,""),n=async(r,i)=>{let l;try{l=await fetch(`${t}${Kt}${r}`,i===void 0?{}:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i)})}catch(o){throw x(o)}if(l.status===429)throw x({error:"rate_limited",retryable:!0});if(!l.ok)throw x({error:`shop_request_failed_${String(l.status)}`});try{return await l.json()}catch(o){throw x(o)}};return{listProducts:async()=>{let r=await n(`/shop/products?publishable_key=${encodeURIComponent(e.publishableKey)}`);return{products:r.products.map(i=>({...i,currency:typeof i.currency=="string"?i.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 Yt=new Set(["buy","ask"]);function Zt(e){return Yt.has(e.mode)?e.mode:"ask"}var en={kind:"quoted"};function L(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 Ye(e,t){let n=/^[a-z]+$/i.test(t)&&!t.endsWith("s")?"s":"";return`${e.toLocaleString()} ${t}${n}`}function Ze(e,t){return e.kind==="quoted"?"Priced on enquiry":e.kind==="flat"?L(e.price,t):`${L(e.unitPrice,t)} per ${e.unitStep===1?e.unit:Ye(e.unitStep,e.unit)}`}function tn(e){let t=e.currency,n=e.pricing;if(n.kind!=="variants")return Ze(n,t);let r=n.variants.map(i=>i.price).filter(i=>typeof i=="number");return r.length>0?`From ${L(Math.min(...r),t)}`:"Priced on enquiry"}function nn(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}:en}function rn(e,t){return e.kind==="flat"?e.price:e.kind==="per_unit"?e.unitPrice*Math.ceil(t/Math.max(e.unitStep,1)):null}function on(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 sn(e,t){let n=e.variants?.find(r=>r.name===t);return n&&n.includes.length>0?n.includes:e.includes}function an(e,t){let n=[];for(let r of e){let i=t(r).trim();i&&!n.includes(i)&&n.push(i)}return n}function ln(e,t,n,r){let i=t?`${e.name} \u2014 ${t}`:e.name,l=n.kind==="per_unit"?`, ${Ye(r,n.unit)}`:"";return`I'd like to buy ${i}${l}. How do I go ahead?`}function un(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}import{useCallback as et,useEffect as dn,useState as me}from"react";var pn=e=>{let[t,n]=me(null),[r,i]=me(!0),[l,o]=me(null),s=et(async()=>{try{n(await e.wallet()),o(null)}catch{o("Couldn't read your balance just now.")}finally{i(!1)}},[e]),a=et(()=>{s().catch(()=>{})},[s]);return dn(()=>(a(),window.addEventListener("focus",a),()=>{window.removeEventListener("focus",a)}),[a]),{wallet:t,loading:r,failure:l,refresh:a}};import{useCallback as cn,useEffect as mn,useState as A}from"react";var gn=e=>e&&typeof e=="object"&&typeof e.error=="string"?e.error:e instanceof Error?e.message:"shop_unavailable",fn=e=>{let[t,n]=A([]),[r,i]=A([]),[l,o]=A(!1),[s,a]=A(!0),[u,d]=A(null),[m,p]=A(0);mn(()=>{let g=!0;return a(!0),e.listProducts().then(y=>{g&&(n(y.products),i(y.enquiryForm),o(y.truncated),d(null))}).catch(y=>{g&&d(gn(y))}).finally(()=>{g&&a(!1)}),()=>{g=!1}},[e,m]);let c=cn(()=>p(g=>g+1),[]);return{products:t,enquiryForm:r,truncated:l,loading:s,error:u,reload:c}};import{useCallback as yn,useEffect as tt,useRef as bn,useState as U}from"react";var nt="greeting";function rt(e,t){if(e.some(l=>l.id===t.id))return e;let n=e.filter(l=>l.id!==nt),r=l=>l.author==="client"==(t.author==="client");return[...n.filter(l=>!(l.pending&&r(l)&&l.text===t.text)),t]}var hn=(e,t)=>{let[n,r]=U([]),[i,l]=U(""),[o,s]=U(!1),[a,u]=U(null),d=bn(0),m=t?.pollMs??2e3;tt(()=>{let c=!0;return e.getInfo().then(g=>{c&&g.greeting&&r(y=>y.length===0?[{id:nt,cursor:"",author:"agent",text:g.greeting}]:y)}).catch(()=>{}),()=>{c=!1}},[e]),tt(()=>e.subscribe?.({onMessage:c=>r(g=>rt(g,c)),onError:c=>u(c.error),onHealthy:()=>u(null)},{intervalMs:m}),[e,m]);let p=yn(()=>{let c=i.trim();if(!c||o)return;l(""),u(null),s(!0),d.current+=1;let g=`pending-${d.current}`,y={id:g,cursor:"",author:"client",text:c,pending:!0};r(b=>[...b,y]),e.sendMessage(c).then(b=>{s(!1),b.reply.trim()&&r(f=>f.some(k=>!k.pending&&k.author!=="client"&&k.text===b.reply)?f:(d.current+=1,[...f,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:b.reply,pending:!0}]))}).catch(b=>{u(b instanceof Error?b.message:"send_failed"),s(!1),r(v=>v.filter(f=>f.id!==g)),l(v=>v||c)})},[i,o,e]);return{messages:n,input:i,setInput:l,send:p,sending:o,error:a}};export{ge as COLUMN_TYPES,wt as Chat,I as CreditRefused,oe as DATE_FORMATS,ke as GRID_COLS,Ce as GRID_MAX_COLS,Re as GRID_MAX_ROWS,gt as HolaProvider,W as InsufficientCredits,le as OPTION_TINTS,E as PortalConflict,ce as QUOTE_BALANCE_LABEL,pe as QUOTE_DEPOSIT_LABEL,se as TIME_FORMATS,qe as arrangedColumns,H as bandOfKind,Ie as bandOfType,ln as buyRequestText,Qe as cellValue,ut as createApiTransport,Tt as createHolaClient,Vt as createPortalCredits,Qt as createPortalData,Xt as createPortalShop,K as createWidgetTransport,qt as creditsOfMoney,ue as deliverableCellText,Ve as deliverableCellValues,We as deliverableStatus,Se as deriveFields,_ as emptyTableResponses,an as facetValues,Ae as footprintOf,X as footprintWith,Xe as formatDeliverableDate,ne as groupDeliverableVersions,sn as includesFor,Pe as inferSpec,ze as isDeliverableChecked,rt as mergeMessage,Zt as modeOf,L as money,N as normalizeColumnType,ie as normalizeDeliverableColType,te as normalizeDeliverableItem,je as optionTintIndex,jt as orderBilling,ae as parseArrangement,_e as parseDashboardSpec,$e as parseDeliverableItems,Ne as parseDeliverableTable,Ge as parseTableResponses,de as paymentAsked,Nt as paymentPayMethods,Y as placeWidgets,nn as priceFor,Ze as priceLabel,Le as publishedVersionOf,on as quantityRange,Ut as quoteSchedule,Oe as renderModel,Je as setResponse,Ke as setTableReview,tn as shelfPriceLabel,un as shelfProblem,Be as shortenUrl,Me as splitLayout,q as textDeltaOf,j as thinkingDeltaOf,B as toolEventOf,rn as totalFor,z as useArtifactUrl,Q as useChat,pn as useCredits,G as useHolaClient,fn as useShop,hn as useThread};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holaboss/client",
3
- "version": "0.2.0-beta.35",
3
+ "version": "0.2.0-beta.36",
4
4
  "description": "Injectable client SDK for embedding a Holaboss AI employee (chat + configurable dashboards today; artifacts next) into your own web app.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",