@pickaxeproject/react 6.3.2 → 6.3.4

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.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tldts");const t="PXE-uid",r=(e,t=!1)=>{let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";t&&(r=r.replace(/[0-9]/g,""));let o="";for(let t=0;t<e;t++)o+=r.charAt(Math.floor(Math.random()*r.length));return o},o=e=>{try{const t=document.cookie.split("; ");for(const r of t){const[t,o]=r.split("=");if(t===e)return o}return null}catch(e){return console.error("[pxe] failed to get cookie",e),null}};exports.COOKIE_USER_ID=t,exports.deleteAuthToken=e=>{try{if("undefined"==typeof window)return;localStorage.removeItem(e)}catch(e){console.error("[pxe] failed to delete auth token",e)}},exports.deleteCookie=e=>{document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},exports.extractUrlsFromText=e=>{const t=e.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(t))},exports.formatBytes=(e,t=2)=>{if(!+e)return"0 Bytes";const r=t<0?0:t,o=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,o)).toFixed(r))} ${["Bytes","KB","MB","PB","EB"][o]}`},exports.generateId=(e,t="",r="")=>{let o="";for(let t=0;t<e;t++){o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return t+o+r},exports.getAuthToken=e=>{try{if("undefined"==typeof window)return null;let t=null;return t=new URLSearchParams(window.location.search).get("pxtoken"),t||(t=localStorage.getItem(`PXE-token-${e}`)),t||(t=o(`PXE-token-${e}`)),t||(t=o(`__Secure-PS-${e}.session-token`)),t?decodeURIComponent(t):null}catch(e){return null}},exports.getCookie=o,exports.initializeEmbedUserId=()=>{try{const n=o(t);if(!n){const o=r(28),n=new Date;n.setFullYear(n.getFullYear()+1);let s=window.location.hostname;const l=e.parse(s).domain;if(l)s=`.${l}`;else{const e=s.split(":")[0],t=e.split(".");s=e,t.length>=2&&(s=`.${t.slice(-2).join(".")}`)}return document.cookie=`${t}=${o};Path=/; Domain=${s}; Expires=${n.toUTCString()}`,o}return n}catch(e){return console.error("[pxe-embed] failed to initialized embed user id",e),r(28)}},exports.isInIframe=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(e){return!0}},exports.mergeRefs=function(...e){return t=>{for(const r of e)r&&("function"==typeof r?r(t):r.current=t)}},exports.randomStr=r,exports.safeJSONParse=e=>{try{return JSON.parse(e)}catch(e){return null}},exports.setAuthToken=(e,t)=>{try{if("undefined"==typeof window)return;localStorage.setItem(e,t)}catch(e){console.error("[pxe] failed to set auth token",e)}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tldts");const t="PXE-uid",r=(e,t=!1)=>{let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";t&&(r=r.replace(/[0-9]/g,""));let o="";for(let t=0;t<e;t++)o+=r.charAt(Math.floor(Math.random()*r.length));return o},o=e=>{try{const t=document.cookie.split("; ");for(const r of t){const[t,o]=r.split("=");if(t===e)return o}return null}catch(e){return console.error("[pxe] failed to get cookie",e),null}};exports.COOKIE_USER_ID=t,exports.buildUpgradeUrl=({baseUrl:e,redirectUrl:t,accessGroupId:r,currentUrl:o})=>{if(!e)return null;const n=null!=o?o:"undefined"!=typeof window?window.location.href:null;if(!n)return null;try{const o=new URL(e,n);if(r){const e=encodeURIComponent(r),t=o.pathname.replace(/\/+$/,"");t.endsWith(`/${e}`)||(o.pathname=`${t}/${e}`)}return t&&o.searchParams.set("redirectUrl",t),o.toString()}catch(e){return console.error("[pxe] failed to build upgrade url",e),null}},exports.deleteAuthToken=e=>{try{if("undefined"==typeof window)return;localStorage.removeItem(e)}catch(e){console.error("[pxe] failed to delete auth token",e)}},exports.deleteCookie=e=>{document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},exports.extractUrlsFromText=e=>{const t=e.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(t))},exports.formatBytes=(e,t=2)=>{if(!+e)return"0 Bytes";const r=t<0?0:t,o=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,o)).toFixed(r))} ${["Bytes","KB","MB","PB","EB"][o]}`},exports.generateId=(e,t="",r="")=>{let o="";for(let t=0;t<e;t++){o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return t+o+r},exports.getAuthToken=e=>{try{if("undefined"==typeof window)return null;let t=null;return t=new URLSearchParams(window.location.search).get("pxtoken"),t||(t=localStorage.getItem(`PXE-token-${e}`)),t||(t=o(`PXE-token-${e}`)),t||(t=o(`__Secure-PS-${e}.session-token`)),t?decodeURIComponent(t):null}catch(e){return null}},exports.getCookie=o,exports.initializeEmbedUserId=()=>{try{const n=o(t);if(!n){const o=r(28),n=new Date;n.setFullYear(n.getFullYear()+1);let l=window.location.hostname;const s=e.parse(l).domain;if(s)l=`.${s}`;else{const e=l.split(":")[0],t=e.split(".");l=e,t.length>=2&&(l=`.${t.slice(-2).join(".")}`)}return document.cookie=`${t}=${o};Path=/; Domain=${l}; Expires=${n.toUTCString()}`,o}return n}catch(e){return console.error("[pxe-embed] failed to initialized embed user id",e),r(28)}},exports.isInIframe=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(e){return!0}},exports.mergeRefs=function(...e){return t=>{for(const r of e)r&&("function"==typeof r?r(t):r.current=t)}},exports.randomStr=r,exports.safeJSONParse=e=>{try{return JSON.parse(e)}catch(e){return null}},exports.setAuthToken=(e,t)=>{try{if("undefined"==typeof window)return;localStorage.setItem(e,t)}catch(e){console.error("[pxe] failed to set auth token",e)}};
@@ -0,0 +1 @@
1
+ "use strict";function e(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}})),r.default=e,Object.freeze(r)}Object.defineProperty(exports,"__esModule",{value:!0});var r,t=e(require("react"));function n(){return n=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},n.apply(null,arguments)}var l=e=>t.createElement("svg",n({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 16 16"},e),r||(r=t.createElement("path",{fill:"currentColor",d:"m0 8 1.41-1.41L7 12.17V0h2v12.17l5.59-5.58L16 8l-8 8z"})));exports.default=l;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("./useScrollContext.js");exports.useScroll=({auto:t,debug:n})=>{const{scrollContainerRef:l,scrollTargetRef:o,isLocked:s,isScrollSession:c,isScrollIncreasing:u,setIsLocked:i,setIsScrollSession:d,setIsScrolling:a,setIsScrollIncreasing:f}=r.useScrollContext(),[g,v]=e.useState(0),S=e.useRef(!1),w=e.useMemo((()=>null!=t&&t&&c),[t,c]),h=e.useMemo((()=>l&&l.current?l.current:"undefined"==typeof window?null:window),[l]);e.useEffect((()=>{if(!h)return;const e=e=>{c&&s&&("mousedown"===e.type||"wheel"===e.type||"DOMMouseScroll"===e.type||"mousewheel"===e.type)&&i(!1)};return null==h||h.addEventListener("scroll",e),null==h||h.addEventListener("mousedown",e),null==h||h.addEventListener("wheel",e),null==h||h.addEventListener("DOMMouseScroll",e),null==h||h.addEventListener("mousewheel",e),()=>{null==h||h.removeEventListener("scroll",e),null==h||h.removeEventListener("mousedown",e),null==h||h.removeEventListener("wheel",e),null==h||h.removeEventListener("DOMMouseScroll",e),null==h||h.removeEventListener("mousewheel",e)}}),[h,c,s]),e.useEffect((()=>{S.current=!s}),[s]),e.useEffect((()=>{const e=setInterval((()=>{if(!l.current)return;const e=l.current.scrollHeight;if(e===g)return;const r=e>g;n&&console.log("[useScroll] isIncreasing:",r,e,g),f(r),v(e),r&&t&&m()}),100);return()=>clearInterval(e)}),[l,g,t]),e.useEffect((()=>{const e=setInterval((()=>{if(l.current)return;if(!o.current)return;const e=o.current.getBoundingClientRect().top+o.current.getBoundingClientRect().height+window.scrollY;if(e===g)return;const r=e>g;f(r),v(e),r&&w&&E()}),100);return()=>clearInterval(e)}),[o,g,w]);const m=()=>{try{if(a(!0),!l.current)return void(n&&console.log("[useScroll] scrollContainerRef not detected"));if(S.current)return;const e=l.current.scrollHeight;l.current.scrollTo({top:e,behavior:"smooth"}),n&&console.log("[useScroll] scrolled scrollContainerRef")}finally{a(!1)}},E=()=>{try{if(a(!0),!o.current)return void(n&&console.log("[useScroll] scrollTargetRef not detected"));if(S.current)return;const e=o.current.getBoundingClientRect().top+o.current.getBoundingClientRect().height+window.scrollY;window.scrollTo({top:e-500,behavior:"smooth"}),n&&console.log("[useScroll] scrolled scrollTargetRef")}finally{a(!1)}};return{scrollContainerRef:l,scrollTargetRef:o,isScrollIncreasing:u,scrollStartSession:()=>{d(!0),i(!0),S.current=!1},scrollEndSession:()=>{d(!1)},scrollToBottom:m,scrollToTarget:E}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("./useScrollContext.js");exports.useScroll=({auto:t,debug:n})=>{const{scrollContainerRef:o,scrollTargetRef:l,isLocked:s,isScrollSession:c,isScrollIncreasing:u,setIsLocked:i,setIsScrollSession:d,setIsScrolling:a,setIsScrollIncreasing:f}=r.useScrollContext(),[g,v]=e.useState(0),S=e.useRef(!1),h=e.useMemo((()=>null!=t&&t&&c),[t,c]),m=e.useMemo((()=>o&&o.current?o.current:"undefined"==typeof window?null:window),[o]);e.useEffect((()=>{if(!m)return;const e=e=>{!s||"mousedown"!==e.type&&"touchmove"!==e.type&&"wheel"!==e.type&&"DOMMouseScroll"!==e.type&&"mousewheel"!==e.type||i(!1)};return null==m||m.addEventListener("mousedown",e),null==m||m.addEventListener("touchmove",e),null==m||m.addEventListener("wheel",e),null==m||m.addEventListener("DOMMouseScroll",e),null==m||m.addEventListener("mousewheel",e),()=>{null==m||m.removeEventListener("mousedown",e),null==m||m.removeEventListener("touchmove",e),null==m||m.removeEventListener("wheel",e),null==m||m.removeEventListener("DOMMouseScroll",e),null==m||m.removeEventListener("mousewheel",e)}}),[m,s]),e.useEffect((()=>{S.current=!s}),[s]),e.useEffect((()=>{const e=setInterval((()=>{if(!o.current)return;const e=o.current.scrollHeight;if(e===g)return;const r=e>g;n&&console.log("[useScroll] isIncreasing:",r,e,g),f(r),v(e),r&&t&&w()}),100);return()=>clearInterval(e)}),[o,g,t]),e.useEffect((()=>{const e=setInterval((()=>{if(o.current)return;if(!l.current)return;const e=l.current.getBoundingClientRect().top+l.current.getBoundingClientRect().height+window.scrollY;if(e===g)return;const r=e>g;f(r),v(e),r&&h&&E()}),100);return()=>clearInterval(e)}),[l,g,h]);const w=()=>{try{if(a(!0),!o.current)return void(n&&console.log("[useScroll] scrollContainerRef not detected"));if(S.current)return;const e=o.current.scrollHeight;o.current.scrollTo({top:e,behavior:"smooth"}),n&&console.log("[useScroll] scrolled scrollContainerRef")}finally{a(!1)}},E=()=>{try{if(a(!0),!l.current)return void(n&&console.log("[useScroll] scrollTargetRef not detected"));if(S.current)return;const e=l.current.getBoundingClientRect().top+l.current.getBoundingClientRect().height+window.scrollY;window.scrollTo({top:e-500,behavior:"smooth"}),n&&console.log("[useScroll] scrolled scrollTargetRef")}finally{a(!1)}};return{scrollContainerRef:o,scrollTargetRef:l,isScrollIncreasing:u,scrollStartSession:()=>{d(!0),i(!0),S.current=!1},scrollEndSession:()=>{d(!1)},scrollToBottom:w,scrollToTarget:E}};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../hooks/pickaxe/useResponseContext.js"),o=require("../../../hooks/studio/useStyleInput.js"),r=require("../../../hooks/studio/useStyleFontSize.js"),a=require("../../../hooks/pickaxe/useConversation.js"),l=require("../../../hooks/pickaxe/useDimensionContext.js"),c=require("../Addons/Auth/hooks/useAuthContext.js"),d=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),f=require("../../../hooks/core/useHover.js"),g=require("../../../hooks/core/useMediaQuery.js"),h=require("../../../common/documents.js"),m=require("eventsource-parser"),v=require("../../Icons/attach-vertical.svg.js"),b=require("../../Icons/arrow-right.svg.js"),x=require("../../Icons/microphone.svg.js"),y=require("../../Icons/stop.svg.js"),j=require("../Addons/Document/List.js"),w=require("../../Core/Textarea.js"),O=require("../../Core/ErrorAlert.js"),S=require("../../../common/error.js"),k=require("../../../common/validation.js"),C=require("../../../common/cn.js"),N=require("../../../common/utils.js"),I=require("../../../hooks/studio/useStudio.js"),_=require("../../../hooks/pickaxe/useSpeech.js");const E=s.forwardRef((({resubmitPrompt:E,onFocus:T,onBlur:A,onInputHeightChange:P,initSmitheryAuthData:q},R)=>{var D,U,L;const{origin:M,pickaxeId:$,sessionId:F,sender:B,senderType:H,portalId:V,deploymentId:X,deploymentType:K,pickaxe:W,styles:J,colors:z,translations:G,locale:Q,forceMobile:Y,isNewChat:Z,isRtl:ee,isShowFeedbackMessage:te,accessGroup:se,setIsNewChat:ne,setIsShowIceBreaker:ie,setValidationStatus:oe,setValidationUpgradeGroups:re,setValidationUpgradeUrl:ae,onGenerateComplete:le}=n.usePickaxeContext(),{token:ce,isLoggedOut:de,isSent:ue,isPricingAuth:pe}=c.useAuthContext(),{messages:fe,isGenerating:ge,setMessages:he,setStatus:me,setLimitData:ve,setError:be}=i.useResponseContext(),{documents:xe,isUploading:ye,documentError:je,onFileUpload:we,setDocuments:Oe,setDocumentError:Se}=d.useDocument(),{studio:ke}=I.useStudio(),{scrollStartSession:Ce,scrollEndSession:Ne,scrollToBottom:Ie}=u.useScroll({auto:!0}),{artifacts:_e,currentPopupType:Ee,setArtifacts:Te,setCurrentArtifact:Ae}=p.useArtifactContext(),{height:Pe}=l.useDimensionContext(),qe=a.useConversation(),[Re,De]=s.useState(""),[Ue,Le]=s.useState(!1),[Me,$e]=s.useState(!1),[Fe,Be]=s.useState(null),[He,Ve]=s.useState(null),[Xe,Ke]=s.useState(!1),We=s.useRef(null),Je=s.useRef(""),ze=s.useRef(null),Ge=s.useRef(null),Qe=s.useRef(null),Ye=s.useRef(null),Ze=s.useRef(null),et=Math.max(.4*Pe,100),{speechTranscript:tt,isSpeechListening:st,isSpeechProcessing:nt,isSpeechSupported:it,onStartListening:ot,onStopListening:rt}=_.useSpeech(),[at]=g.useMediaQuery("(max-width: 480px)"),lt=f.useHover(),{isHover:ct}=lt,dt=e.__rest(lt,["isHover"]),ut=f.useHover(),{isHover:pt}=ut,ft=e.__rest(ut,["isHover"]),gt=f.useHover(),{isHover:ht}=gt,mt=e.__rest(gt,["isHover"]),vt=r.useStyleFontSize(),bt=o.useStyleInput(),xt="undefined"!=typeof window?window.location.hostname:"",yt="undefined"!=typeof window?window.location.href:"",jt="undefined"!=typeof window&&window.self!==window.top,wt=xt.includes("pickaxe.co")&&!yt.includes("https://studio.pickaxe.co/_embed")&&!jt,Ot=null===(D=null==W?void 0:W.documentuploadtype)||void 0===D?void 0:D.startsWith("enduserupload"),St=it&&(null==W?void 0:W.enablevoicetotext),kt="chat-input"===K&&Z&&!ue,Ct="chat-input"===K&&pe&&de&&ue,Nt=s.useCallback((e=>{const t=k.getValidationFailure(e);return!!t&&(be(""),ve(null),oe(t.status),re(t.upgradeGroups),ae(t.upgradeUrl),!0)}),[be,ve,oe,re,ae]),It=null!==(U=null==W?void 0:W.placeholdertext)&&void 0!==U?U:ee?"بماذا تريد أن تتحدث؟":(null==G?void 0:G["what-do-you-want-to-talk-about"])||"What do you want to talk about?",_t=Ue||Me,Et=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/get_user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign(Object.assign(Object.assign({studioId:null==W?void 0:W.studioid},B&&{sender:B}),ce&&{studioSessionToken:ce}),!ce&&!B&&{sender:N.initializeEmbedUserId()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),wt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(Be(t.studioUser),Ve(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}}))),[M,$,F,H,B,ce,V,X,wt]);s.useEffect((()=>{Et()}),[Et]);const Tt=(null==se?void 0:se.limit)||0,At=(null==Fe?void 0:Fe.currentUses)||0,Pt=(null==Fe?void 0:Fe.extraUses)||0,qt=!!(null==ke?void 0:ke.data.usage)&&ke.data.usage.isCredits,Rt=Tt>At?Tt-At+Pt:Pt,Dt=s.useMemo((()=>!!Fe&&(!Xe&&(!(Tt<=0)&&Rt<=.05*Tt))),[Fe,Xe,Rt,Tt]),Ut=s.useMemo((()=>{var e,t,s;return!!Z&&(!!W&&(!qe.isLoading&&(!((null!==(t=null===(e=qe.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=W.icebreakers)||void 0===s?void 0:s.length)&&(!te&&!kt)))))}),[W,Z,te,kt,qe.data,qe.isLoading]),Lt=s.useMemo((()=>{if(ge||ye)return!1;const e=xe.length>0&&xe.every((e=>"finished"===e.status));return!(!Re.trim()&&!e)&&xe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[ge,ye,Re,xe]);s.useImperativeHandle(R,(()=>({onSubmit:Mt}))),s.useEffect((()=>{ie(Ut)}),[Ut]),s.useEffect((()=>{var e;if(E){const t=Array.from(fe),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Mt(s,!0)}}),[E]),s.useEffect((()=>{if(!Ye.current||!P)return;const e=new ResizeObserver((e=>{for(const t of e)P(t.contentRect.height)}));return e.observe(Ye.current),()=>{e.disconnect()}}),[P]),s.useEffect((()=>{if(!st)return;const e=Je.current?`${Je.current} `:"";De(`${e}${tt}`)}),[tt,st]),s.useEffect((()=>{if(!Ge.current)return;(()=>{if(!Ge.current)return;let e=Ge.current.scrollHeight>52;Re.includes("\n")||xe.length?e=!0:Re.trim()||(e=!1),Le(e)})()}),[Re,xe]),s.useEffect((()=>{const e=Ge.current,t=Qe.current;if(!e||!t||Ue||Re.includes("\n"))return void $e(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,i=document.createElement("span");Object.assign(i.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),i.textContent=Re||It,document.body.appendChild(i);const o=i.offsetWidth;i.remove();const r=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;$e(o>l)}),[Re,Ue,It]);const Mt=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i;try{if(ge||ye)return;const o=xe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=o.map((e=>e.documentId)).filter(Boolean),a=o.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=t?t:Re;if(!c&&!l)return;be(""),Se(""),ve(null),De(""),ne(!1),me("fetching"),Ce(),Ie();const d=null!==(n=null===(e=null==W?void 0:W.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&r.length>0,u=[...s?Array.from(fe.slice(0,fe.length-1)):Array.from(fe),...s?[]:[{id:fe.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:fe.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];he(u),Ie(),d&&Oe([]);const p=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:M,pickaxeId:$,sessionId:F,senderType:H,value:c},d&&{documentIds:r}),B&&{sender:B}),ce&&{studioSessionToken:ce}),!ce&&!B&&{sender:N.initializeEmbedUserId()}),V&&{portalId:V}),X&&{deploymentId:X}),a.length>0&&{uploadedModelImages:a})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},wt&&{credentials:"include"})),f=yield p.json();if(!f.success){if(Nt(f))return;const e=new Error(f.error||f.message||(null==G?void 0:G["failed-to-start-generation"])||"Failed to start generation");throw f.limitData&&(e.limitData=f.limitData),e}const g=f.submissionId;me("streaming"),Ze.current=new AbortController;const h=u.length-1,v=[];let b=[...null!=_e?_e:[]],x=0,y=!1,j="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${g}?index=${x}`,{signal:null===(i=Ze.current)||void 0===i?void 0:i.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();ze.current=t;const s=new TextDecoder,n=m.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&x++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==G?void 0:G["something-went-wrong"])||"Something went wrong.";return Nt(t)||be(s),void(y=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&q){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw y=!0,q({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,q({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)j="",v.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)j+=n.delta,v[v.length-1].content=j;else if("text-end"===n.type)j="";else if("reasoning-start"===n.type)j="",v.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)j+=n.delta,v[v.length-1].content=j;else if("reasoning-end"===n.type)j="";else if(n.type.startsWith("data-")){const e=n;v.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}he([...u.slice(0,h),Object.assign(Object.assign({},u[u.length-1]),{id:fe.length+1,role:"assistant",parts:v})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Te([...b]),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Te(b),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Te(b),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");b=b.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Te(b)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Te(b.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==G?void 0:G["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Nt(t))return void(y=!0);be(s)}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:i}=yield t.read();if(i)break;n.feed(s.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==le||le(F)}catch(e){if(e.limitData)ve(e.limitData),be("");else{let t=S.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==G?void 0:G["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Nt(t)||be(t)}}finally{Ie(),me("idle"),Ne(),ze.current=null,yield Et()}}));return Ct?null:t.jsx("div",Object.assign({className:C.default("flex w-full flex-shrink-0 flex-col items-center",!kt&&"px-4 pb-8"),dir:ee?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:Ye,className:C.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===J.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},bt),{maxHeight:`${et}px`,overflowY:"auto"})},{children:[Dt&&t.jsxs("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:bt.backgroundColor?`${bt.backgroundColor}E6`:void 0,borderColor:z.text+"20",color:z.text,borderTopRightRadius:J.cornerRadius+"px",borderTopLeftRadius:J.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[Rt," ",qt?(null==G?void 0:G.credits)||"Credits":(null==G?void 0:G.uses)||"Uses"," ",(null==G?void 0:G.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:z.accent,color:z.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=`${He}${null==se?void 0:se.accessGroupId}`;N.isInIframe()?window.open(t):location.href=t}},{children:(null==G?void 0:G.upgrade)||"Upgrade"})),t.jsx("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>Ke(!0)},{children:t.jsx("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!ge&&xe.length>0&&t.jsx(j.default,{className:"p-4 pb-0",isDisabled:ge}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[st&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(L=z.accent)&&void 0!==L?L:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:z.text+"90"}},{children:(null==G?void 0:G.listening)||"Listening..."}))]})),t.jsx(w.default,Object.assign({ref:Ge,className:C.default(vt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Re.trim()&&!Re.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ee?"text-right":"text-left",_t&&"mb-12",st&&"text-transparent"),value:Re,placeholder:It,onChange:e=>{if(De(e),P){const t=(e.match(/\n/g)||[]).length+1;if(!e)return void P(0);if(t>=11)return;let s=0;t>1&&(s=50),P(24*(t-1)+s)}},onKeyDown:e=>{Y||at||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),ye||ge||Mt()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);e.length>0&&(t.preventDefault(),ne(!1),yield we(e))}))},T&&{onFocus:T},A&&{onBlur:A},{dir:ee?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:Qe,className:C.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",_t?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!_t&&bt.backgroundColor&&{backgroundColor:bt.backgroundColor}),{borderTopRightRadius:J.cornerRadius+"px",borderBottomRightRadius:J.cornerRadius+"px"})},{children:ge?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{Ze.current&&(Ze.current.abort(),Ze.current=null),ze.current&&(ze.current.cancel(),ze.current=null),me("idle")},style:{backgroundColor:z.accent,color:z.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):st?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:rt,style:{backgroundColor:z.accent,color:z.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Ot&&t.jsxs("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:pt?z.accent+"10":void 0,color:pt?z.accent:z.accent+"80"},disabled:ye||ge,onClick:()=>{var e;return null===(e=We.current)||void 0===e?void 0:e.click()}},ft,{children:[t.jsx("input",{id:"file-upload",ref:We,type:"file",accept:[...h.allowedFileMimeTypes,...h.allowedImageMimeTypes,...h.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){ne(!1),yield we(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(v.default,{className:"h-6 w-6 shrink-0"})]})),St&&t.jsx("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:st?z.accent:ht?z.accent+"10":void 0,color:st?z.accentText:ht?z.accent:z.accent+"80"},disabled:ye||ge||nt,onClick:()=>{st?rt():(Je.current=Re,ot(Q||"en-US"))}},mt,{children:t.jsx(x.default,{className:"h-5 w-5 shrink-0"})})),t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:ct||Lt?z.accent:z.accent+"10",color:ct||Lt?z.accentText:z.accent+"80"},disabled:!Lt,onClick:()=>Mt()},dt,{children:t.jsx(b.default,{className:C.default("h-6 w-6 shrink-0",ee&&"scale-x-[-1] transform")})}))]})}))]}))]})),je&&t.jsx(O.default,{error:je,className:"mt-3"})]}))}))}));E.displayName="Input",exports.default=E;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../hooks/pickaxe/useResponseContext.js"),o=require("../../../hooks/studio/useStyleInput.js"),r=require("../../../hooks/studio/useStyleFontSize.js"),a=require("../../../hooks/pickaxe/useConversation.js"),l=require("../../../hooks/pickaxe/useDimensionContext.js"),c=require("../Addons/Auth/hooks/useAuthContext.js"),d=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),f=require("../../../hooks/core/useHover.js"),g=require("../../../hooks/core/useMediaQuery.js"),h=require("../../../common/documents.js"),m=require("eventsource-parser"),v=require("../../Icons/attach-vertical.svg.js"),b=require("../../Icons/arrow-right.svg.js"),x=require("../../Icons/microphone.svg.js"),y=require("../../Icons/stop.svg.js"),j=require("../Addons/Document/List.js"),w=require("../../Core/Textarea.js"),O=require("../../Core/ErrorAlert.js"),S=require("../../../common/error.js"),k=require("../../../common/validation.js"),C=require("../../../common/cn.js"),N=require("../../../common/utils.js"),I=require("../../../hooks/studio/useStudio.js"),_=require("../../../hooks/pickaxe/useSpeech.js");const E=s.forwardRef((({resubmitPrompt:E,onFocus:T,onBlur:A,onInputHeightChange:P,initSmitheryAuthData:q},R)=>{var U,D,L;const{origin:M,pickaxeId:F,sessionId:$,sender:B,senderType:H,portalId:V,deploymentId:X,deploymentType:K,pickaxe:W,styles:J,colors:z,translations:G,locale:Q,forceMobile:Y,isNewChat:Z,isRtl:ee,isShowFeedbackMessage:te,accessGroup:se,setIsNewChat:ne,setIsShowIceBreaker:ie,setValidationStatus:oe,setValidationUpgradeGroups:re,setValidationUpgradeUrl:ae,onGenerateComplete:le}=n.usePickaxeContext(),{token:ce,isLoggedOut:de,isSent:ue,isPricingAuth:pe}=c.useAuthContext(),{messages:fe,isGenerating:ge,setMessages:he,setStatus:me,setLimitData:ve,setError:be}=i.useResponseContext(),{documents:xe,isUploading:ye,documentError:je,onFileUpload:we,setDocuments:Oe,setDocumentError:Se}=d.useDocument(),{studio:ke}=I.useStudio(),{scrollStartSession:Ce,scrollEndSession:Ne,scrollToBottom:Ie}=u.useScroll({auto:!0}),{artifacts:_e,currentPopupType:Ee,setArtifacts:Te,setCurrentArtifact:Ae}=p.useArtifactContext(),{height:Pe}=l.useDimensionContext(),qe=a.useConversation(),[Re,Ue]=s.useState(""),[De,Le]=s.useState(!1),[Me,Fe]=s.useState(!1),[$e,Be]=s.useState(null),[He,Ve]=s.useState(null),[Xe,Ke]=s.useState(!1),We=s.useRef(null),Je=s.useRef(""),ze=s.useRef(null),Ge=s.useRef(null),Qe=s.useRef(null),Ye=s.useRef(null),Ze=s.useRef(null),et=Math.max(.4*Pe,100),{speechTranscript:tt,isSpeechListening:st,isSpeechProcessing:nt,isSpeechSupported:it,onStartListening:ot,onStopListening:rt}=_.useSpeech(),[at]=g.useMediaQuery("(max-width: 480px)"),lt=f.useHover(),{isHover:ct}=lt,dt=e.__rest(lt,["isHover"]),ut=f.useHover(),{isHover:pt}=ut,ft=e.__rest(ut,["isHover"]),gt=f.useHover(),{isHover:ht}=gt,mt=e.__rest(gt,["isHover"]),vt=r.useStyleFontSize(),bt=o.useStyleInput(),xt="undefined"!=typeof window?window.location.hostname:"",yt="undefined"!=typeof window?window.location.href:"",jt="undefined"!=typeof window&&window.self!==window.top,wt=xt.includes("pickaxe.co")&&!yt.includes("https://studio.pickaxe.co/_embed")&&!jt,Ot=null===(U=null==W?void 0:W.documentuploadtype)||void 0===U?void 0:U.startsWith("enduserupload"),St=it&&(null==W?void 0:W.enablevoicetotext),kt="chat-input"===K&&Z&&!ue,Ct="chat-input"===K&&pe&&de&&ue,Nt=s.useCallback((e=>{const t=k.getValidationFailure(e);return!!t&&(be(""),ve(null),oe(t.status),re(t.upgradeGroups),ae(t.upgradeUrl),!0)}),[be,ve,oe,re,ae]),It=null!==(D=null==W?void 0:W.placeholdertext)&&void 0!==D?D:ee?"بماذا تريد أن تتحدث؟":(null==G?void 0:G["what-do-you-want-to-talk-about"])||"What do you want to talk about?",_t=De||Me,Et=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/get_user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign(Object.assign(Object.assign({studioId:null==W?void 0:W.studioid},B&&{sender:B}),ce&&{studioSessionToken:ce}),!ce&&!B&&{sender:N.initializeEmbedUserId()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),wt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(Be(t.studioUser),Ve(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}}))),[M,F,$,H,B,ce,V,X,wt]);s.useEffect((()=>{Et()}),[Et]);const Tt=(null==se?void 0:se.limit)||0,At=(null==$e?void 0:$e.currentUses)||0,Pt=(null==$e?void 0:$e.extraUses)||0,qt=!!(null==ke?void 0:ke.data.usage)&&ke.data.usage.isCredits,Rt=Tt>At?Tt-At+Pt:Pt,Ut=s.useMemo((()=>!!$e&&(!Xe&&(!(Tt<=0)&&Rt<=.05*Tt))),[$e,Xe,Rt,Tt]),Dt=s.useMemo((()=>{var e,t,s;return!!Z&&(!!W&&(!qe.isLoading&&(!((null!==(t=null===(e=qe.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=W.icebreakers)||void 0===s?void 0:s.length)&&(!te&&!kt)))))}),[W,Z,te,kt,qe.data,qe.isLoading]),Lt=s.useMemo((()=>{if(ge||ye)return!1;const e=xe.length>0&&xe.every((e=>"finished"===e.status));return!(!Re.trim()&&!e)&&xe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[ge,ye,Re,xe]);s.useImperativeHandle(R,(()=>({onSubmit:Mt}))),s.useEffect((()=>{ie(Dt)}),[Dt]),s.useEffect((()=>{var e;if(E){const t=Array.from(fe),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Mt(s,!0)}}),[E]),s.useEffect((()=>{if(!Ye.current||!P)return;const e=new ResizeObserver((e=>{for(const t of e)P(t.contentRect.height)}));return e.observe(Ye.current),()=>{e.disconnect()}}),[P]),s.useEffect((()=>{if(!st)return;const e=Je.current?`${Je.current} `:"";Ue(`${e}${tt}`)}),[tt,st]),s.useEffect((()=>{if(!Ge.current)return;(()=>{if(!Ge.current)return;let e=Ge.current.scrollHeight>52;Re.includes("\n")||xe.length?e=!0:Re.trim()||(e=!1),Le(e)})()}),[Re,xe]),s.useEffect((()=>{const e=Ge.current,t=Qe.current;if(!e||!t||De||Re.includes("\n"))return void Fe(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,i=document.createElement("span");Object.assign(i.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),i.textContent=Re||It,document.body.appendChild(i);const o=i.offsetWidth;i.remove();const r=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Fe(o>l)}),[Re,De,It]);const Mt=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i;try{if(ge||ye)return;const o=xe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=o.map((e=>e.documentId)).filter(Boolean),a=o.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=t?t:Re;if(!c&&!l)return;be(""),Se(""),ve(null),Ue(""),ne(!1),me("fetching"),Ce(),Ie();const d=null!==(n=null===(e=null==W?void 0:W.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&r.length>0,u=[...s?Array.from(fe.slice(0,fe.length-1)):Array.from(fe),...s?[]:[{id:fe.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:fe.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];he(u),Ie(),d&&Oe([]);const p=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:M,pickaxeId:F,sessionId:$,senderType:H,value:c},d&&{documentIds:r}),B&&{sender:B}),ce&&{studioSessionToken:ce}),!ce&&!B&&{sender:N.initializeEmbedUserId()}),V&&{portalId:V}),X&&{deploymentId:X}),a.length>0&&{uploadedModelImages:a})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},wt&&{credentials:"include"})),f=yield p.json();if(!f.success){if(Nt(f))return;const e=new Error(f.error||f.message||(null==G?void 0:G["failed-to-start-generation"])||"Failed to start generation");throw f.limitData&&(e.limitData=f.limitData),e}const g=f.submissionId;me("streaming"),Ze.current=new AbortController;const h=u.length-1,v=[];let b=[...null!=_e?_e:[]],x=0,y=!1,j="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${g}?index=${x}`,{signal:null===(i=Ze.current)||void 0===i?void 0:i.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();ze.current=t;const s=new TextDecoder,n=m.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&x++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==G?void 0:G["something-went-wrong"])||"Something went wrong.";return Nt(t)||be(s),void(y=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&q){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw y=!0,q({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,q({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)j="",v.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)j+=n.delta,v[v.length-1].content=j;else if("text-end"===n.type)j="";else if("reasoning-start"===n.type)j="",v.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)j+=n.delta,v[v.length-1].content=j;else if("reasoning-end"===n.type)j="";else if(n.type.startsWith("data-")){const e=n;v.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}he([...u.slice(0,h),Object.assign(Object.assign({},u[u.length-1]),{id:fe.length+1,role:"assistant",parts:v})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Te([...b]),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Te(b),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);b=b.filter((e=>!(e.id===t.id&&e.version===t.version))),b.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Te(b),Ee.startsWith("inline")||Ae({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");b=b.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Te(b)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Te(b.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==G?void 0:G["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Nt(t))return void(y=!0);be(s)}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:i}=yield t.read();if(i)break;n.feed(s.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==le||le($)}catch(e){if(e.limitData)ve(e.limitData),be("");else{let t=S.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==G?void 0:G["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Nt(t)||be(t)}}finally{Ie(),me("idle"),Ne(),ze.current=null,yield Et()}}));return Ct?null:t.jsx("div",Object.assign({className:C.default("flex w-full flex-shrink-0 flex-col items-center",!kt&&"px-4 pb-8"),dir:ee?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:Ye,className:C.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===J.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},bt),{maxHeight:`${et}px`,overflowY:"auto"})},{children:[Ut&&t.jsxs("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:bt.backgroundColor?`${bt.backgroundColor}E6`:void 0,borderColor:z.text+"20",color:z.text,borderTopRightRadius:J.cornerRadius+"px",borderTopLeftRadius:J.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[Rt," ",qt?(null==G?void 0:G.credits)||"Credits":(null==G?void 0:G.uses)||"Uses"," ",(null==G?void 0:G.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:z.accent,color:z.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=N.buildUpgradeUrl({baseUrl:He,accessGroupId:null==se?void 0:se.accessGroupId});t&&(N.isInIframe()?window.open(t):location.href=t)}},{children:(null==G?void 0:G.upgrade)||"Upgrade"})),t.jsx("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>Ke(!0)},{children:t.jsx("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!ge&&xe.length>0&&t.jsx(j.default,{className:"p-4 pb-0",isDisabled:ge}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[st&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(L=z.accent)&&void 0!==L?L:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:z.text+"90"}},{children:(null==G?void 0:G.listening)||"Listening..."}))]})),t.jsx(w.default,Object.assign({ref:Ge,className:C.default(vt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Re.trim()&&!Re.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ee?"text-right":"text-left",_t&&"mb-12",st&&"text-transparent"),value:Re,placeholder:It,onChange:e=>{Ue(e)},onKeyDown:e=>{Y||at||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),ye||ge||Mt()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);e.length>0&&(t.preventDefault(),ne(!1),yield we(e))}))},T&&{onFocus:T},A&&{onBlur:A},{dir:ee?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:Qe,className:C.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",_t?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!_t&&bt.backgroundColor&&{backgroundColor:bt.backgroundColor}),{borderTopRightRadius:J.cornerRadius+"px",borderBottomRightRadius:J.cornerRadius+"px"})},{children:ge?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{Ze.current&&(Ze.current.abort(),Ze.current=null),ze.current&&(ze.current.cancel(),ze.current=null),me("idle")},style:{backgroundColor:z.accent,color:z.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):st?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:rt,style:{backgroundColor:z.accent,color:z.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Ot&&t.jsxs("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:pt?z.accent+"10":void 0,color:pt?z.accent:z.accent+"80"},disabled:ye||ge,onClick:()=>{var e;return null===(e=We.current)||void 0===e?void 0:e.click()}},ft,{children:[t.jsx("input",{id:"file-upload",ref:We,type:"file",accept:[...h.allowedFileMimeTypes,...h.allowedImageMimeTypes,...h.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){ne(!1),yield we(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(v.default,{className:"h-6 w-6 shrink-0"})]})),St&&t.jsx("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:st?z.accent:ht?z.accent+"10":void 0,color:st?z.accentText:ht?z.accent:z.accent+"80"},disabled:ye||ge||nt,onClick:()=>{st?rt():(Je.current=Re,ot(Q||"en-US"))}},mt,{children:t.jsx(x.default,{className:"h-5 w-5 shrink-0"})})),t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:ct||Lt?z.accent:z.accent+"10",color:ct||Lt?z.accentText:z.accent+"80"},disabled:!Lt,onClick:()=>Mt()},dt,{children:t.jsx(b.default,{className:C.default("h-6 w-6 shrink-0",ee&&"scale-x-[-1] transform")})}))]})}))]}))]})),je&&t.jsx(O.default,{error:je,className:"mt-3"})]}))}))}));E.displayName="Input",exports.default=E;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),i=require("../../../hooks/pickaxe/usePickaxeContext.js"),o=require("../Addons/Auth/hooks/useAuthContext.js"),n=require("../../../hooks/pickaxe/useDimensionContext.js"),r=require("../Addons/Document/hooks/useDocument.js"),a=require("../../../hooks/studio/useStyleFontSize.js"),l=require("./History/index.js"),u=require("./Input.js"),d=require("../../Icons/attach-vertical.svg.js"),c=require("../../../common/cn.js"),f=require("../../../common/api/pickaxe.js"),h=require("uuid"),m=require("../../Core/StudioTip.js"),v=require("../../../hooks/pickaxe/useResponseContext.js"),p=require("../Addons/Navbar/NavPill.js"),x=require("../../Icons/history.svg.js");exports.default=()=>{const{deploymentType:j,isNewChat:g,setIsNewChat:b,sessionId:y,setSessionId:k,setLastSessionId:w,pickaxeId:D,sender:I,pickaxe:S,styles:_,isEmbed:q,translations:C}=i.usePickaxeContext(),{isSent:N}=o.useAuthContext(),{width:P,height:F,setDimension:A}=n.useDimensionContext(),{setDocuments:T,onFileUpload:E}=r.useDocument(),{isGenerating:O,messages:R}=v.useResponseContext(),z=a.useStyleFontSize(),[H,G]=s.useState(0),[L,B]=s.useState(!1),[M,U]=s.useState(!1),J=s.useRef(null),K=s.useRef(null),Q=s.useRef(0),[V,W]=s.useState(null),[X,Y]=s.useState(!1),Z=(null==C?void 0:C["new-chat"])||"New chat",$="chat-input"===j&&g&&!N;s.useEffect((()=>()=>{T([])}),[]);const ee=s.useCallback((()=>{if(!D||!I)return;const t=(s=0)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;try{const t=yield f.default.post("/get_pickaxe_conversation",{sessionId:y,userId:I});if(t.data&&t.data.success){const e=t.data.title;if(e&&"Conversation Title"!==e)return void se(e)}else console.error("Failed to load conversation:",null===(e=t.data)||void 0===e?void 0:e.error)}catch(e){console.error("Error fetching conversation:",e)}s<20&&setTimeout((()=>t(s+1)),3e3)}));t()}),[D,I,y]);s.useEffect((()=>{O||g||!y||ee()}),[O,g,y,ee]),s.useEffect((()=>{if(!J.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:s}=t.contentRect;A(parseInt(e.toFixed(0)),parseInt(s.toFixed(0)))}}));return e.observe(J.current),()=>{e.disconnect()}}),[J.current]);const[te,se]=s.useState(Z),ie=(null==S?void 0:S.formtitle)||"Pickaxe",oe=(null==S?void 0:S.coverphoto)||void 0,[ne,re]=s.useState(!1);s.useEffect((()=>{const e=!$&&!q&&_.portalTheme&&(R.filter((e=>"user"===e.role)).length>0||L||!g);re(null!=e&&e)}),[R,L,g]);return t.jsxs("div",Object.assign({ref:J,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),Q.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&U(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),Q.current-=1,0===Q.current&&U(!1)},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e.__awaiter(void 0,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),U(!1),Q.current=0;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(b(!1),yield E(e))}))},{children:[M&&t.jsxs("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[t.jsx("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:t.jsx(d.default,{className:"h-10 w-10"})})),t.jsx("h3",Object.assign({className:c.default(z.h3,"mt-6 font-semibold text-c-primary text-black")},{children:(null==C?void 0:C["drop-files-to-upload"])||"Drop files to upload"})),t.jsx("p",Object.assign({className:c.default(z.b2,"mt-2 opacity-60 text-black")},{children:(null==C?void 0:C["add-anything-to-the-conversation"])||"Add anything to the conversation"}))]})),$?t.jsx(u.default,{}):t.jsxs(t.Fragment,{children:[ne&&t.jsxs("div",Object.assign({className:c.default("direct-link"===j?"absolute top-4 left-4 md:top-6 md:left-6 z-40 flex items-center gap-2 animate-in fade-in slide-in-from-top-4 duration-500":"w-full max-w-3xl mt-6 px-4 md:px-0 flex justify-start z-30 mb-4 animate-in fade-in slide-in-from-top-4 duration-500 gap-2","dark"===_.portalTheme?"glass-dark ":"")},{children:[t.jsx(p.NavPill,{text:ie,icon:oe}),g||te===Z?t.jsx(p.NavPill,{text:te}):t.jsx(p.EditableNavPill,{text:te,sessionId:y,onRename:t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(y)try{yield f.default.post("/edit_conversation_name",{sessionId:y,name:t,userId:I}),se(t)}catch(e){console.error("Error renaming chat:",e),alert((null==C?void 0:C["failed-rename-chat"])||"Failed to rename chat.")}})),onDelete:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(y&&window.confirm((null==C?void 0:C["delete-confirm"])||"Are you sure you want to delete this conversation?"))try{yield f.default.post("/delete_pickaxe_conversation",{sessionId:y,userId:I}),b(!0),k(h.v4()),se(Z)}catch(e){console.error("Error deleting chat:",e),alert((null==C?void 0:C["failed-delete-chat"])||"Failed to delete chat.")}})),isDarkGlass:"dark"===_.portalTheme}),t.jsx(m.StudioTip,Object.assign({content:C["chat-history"]||"Chat History",align:"bottom",containerClassName:"inline-flex shrink-0"},{children:t.jsx(p.HistoryPill,{icon:t.jsx(x.default,{}),onClick:()=>{k(""),w(y)}})}))]})),t.jsx(l.default,{additionalScrollHeight:H,isForceHideInfo:F<=545||P<=350||L,isInputFocused:L,onSubmit:t=>e.__awaiter(void 0,void 0,void 0,(function*(){K.current&&K.current.onSubmit(t)})),smitheryAuthData:V,resubmitPrompt:()=>{W(null),Y(!0)}}),t.jsx(u.default,{ref:K,onFocus:()=>B(!0),onBlur:()=>B(!1),onInputHeightChange:G,initSmitheryAuthData:e=>W(e),resubmitPrompt:X})]})]}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),o=require("react"),s=require("../../../hooks/pickaxe/usePickaxeContext.js"),n=require("../Addons/Auth/hooks/useAuthContext.js"),i=require("../../../hooks/pickaxe/useDimensionContext.js"),r=require("../Addons/Document/hooks/useDocument.js"),a=require("../Addons/Scroll/hooks/useScrollContext.js"),l=require("../../../hooks/studio/useStyleFontSize.js"),c=require("./History/index.js"),u=require("./Input.js"),d=require("../../Icons/attach-vertical.svg.js"),f=require("../../Icons/arrow-down.svg.js"),h=require("../../../common/cn.js"),m=require("../../../common/api/pickaxe.js"),v=require("uuid"),p=require("../../Core/StudioTip.js"),x=require("../../../hooks/pickaxe/useResponseContext.js"),j=require("../Addons/Navbar/NavPill.js"),g=require("../../Icons/history.svg.js");exports.default=()=>{const{deploymentType:b,isNewChat:k,setIsNewChat:y,sessionId:w,setSessionId:S,setLastSessionId:C,pickaxeId:I,sender:q,pickaxe:D,styles:_,colors:N,isEmbed:T,translations:E}=s.usePickaxeContext(),{isSent:P}=n.useAuthContext(),{width:A,height:F,setDimension:H}=i.useDimensionContext(),{setDocuments:O,onFileUpload:R}=r.useDocument(),{scrollContainerRef:z,isLocked:L,setIsLocked:G}=a.useScrollContext(),{isGenerating:M,messages:B}=x.useResponseContext(),U=l.useStyleFontSize(),[$,J]=o.useState(0),[K,Q]=o.useState(!1),[V,W]=o.useState(!1),[X,Y]=o.useState(!1),[Z,ee]=o.useState(!0),te=o.useRef(null),oe=o.useRef(null),se=o.useRef(0),[ne,ie]=o.useState(null),[re,ae]=o.useState(!1),le=(null==E?void 0:E["new-chat"])||"New chat",ce="chat-input"===b&&k&&!P;o.useEffect((()=>()=>{O([])}),[]);const ue=o.useCallback((()=>{if(!I||!q)return;const t=(o=0)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;try{const t=yield m.default.post("/get_pickaxe_conversation",{sessionId:w,userId:q});if(t.data&&t.data.success){const e=t.data.title;if(e&&"Conversation Title"!==e)return void fe(e)}else console.error("Failed to load conversation:",null===(e=t.data)||void 0===e?void 0:e.error)}catch(e){console.error("Error fetching conversation:",e)}o<20&&setTimeout((()=>t(o+1)),3e3)}));t()}),[I,q,w]);o.useEffect((()=>{M||k||!w||ue()}),[M,k,w,ue]),o.useEffect((()=>{if(!te.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:o}=t.contentRect;H(parseInt(e.toFixed(0)),parseInt(o.toFixed(0)))}}));return e.observe(te.current),()=>{e.disconnect()}}),[H]);const[de,fe]=o.useState(le),he=(null==D?void 0:D.formtitle)||"Pickaxe",me=(null==D?void 0:D.coverphoto)||void 0,[ve,pe]=o.useState(!1);o.useEffect((()=>{const e=!ce&&!T&&_.portalTheme&&(B.filter((e=>"user"===e.role)).length>0||K||!k);pe(null!=e&&e)}),[ce,T,K,k,B,_.portalTheme]),o.useEffect((()=>{const e=z.current;if(!e)return;const t=()=>{const t=e.scrollHeight-e.scrollTop-e.clientHeight;Y(e.scrollHeight>e.clientHeight+8),ee(t<=24)};t(),e.addEventListener("scroll",t,{passive:!0});const o=new ResizeObserver((()=>{t()}));o.observe(e);const s=e.firstElementChild;return s instanceof HTMLElement&&o.observe(s),()=>{e.removeEventListener("scroll",t),o.disconnect()}}),[ce,z]);const xe=o.useCallback((()=>{z.current&&(G(!0),z.current.scrollTo({top:z.current.scrollHeight,behavior:"smooth"}))}),[z,G]);return t.jsxs("div",Object.assign({ref:te,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),se.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&W(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),se.current-=1,0===se.current&&W(!1)},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e.__awaiter(void 0,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),W(!1),se.current=0;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(y(!1),yield R(e))}))},{children:[V&&t.jsxs("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[t.jsx("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:t.jsx(d.default,{className:"h-10 w-10"})})),t.jsx("h3",Object.assign({className:h.default(U.h3,"mt-6 font-semibold text-c-primary text-black")},{children:(null==E?void 0:E["drop-files-to-upload"])||"Drop files to upload"})),t.jsx("p",Object.assign({className:h.default(U.b2,"mt-2 opacity-60 text-black")},{children:(null==E?void 0:E["add-anything-to-the-conversation"])||"Add anything to the conversation"}))]})),ce?t.jsx(u.default,{}):t.jsxs(t.Fragment,{children:[ve&&t.jsxs("div",Object.assign({className:h.default("direct-link"===b?"absolute top-4 left-4 md:top-6 md:left-6 z-40 flex items-center gap-2 animate-in fade-in slide-in-from-top-4 duration-500":"w-full max-w-3xl mt-6 px-4 md:px-0 flex justify-start z-30 mb-4 animate-in fade-in slide-in-from-top-4 duration-500 gap-2","dark"===_.portalTheme?"glass-dark ":"")},{children:[t.jsx(j.NavPill,{text:he,icon:me}),k||de===le?t.jsx(j.NavPill,{text:de}):t.jsx(j.EditableNavPill,{text:de,sessionId:w,onRename:t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(w)try{yield m.default.post("/edit_conversation_name",{sessionId:w,name:t,userId:q}),fe(t)}catch(e){console.error("Error renaming chat:",e),alert((null==E?void 0:E["failed-rename-chat"])||"Failed to rename chat.")}})),onDelete:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(w&&window.confirm((null==E?void 0:E["delete-confirm"])||"Are you sure you want to delete this conversation?"))try{yield m.default.post("/delete_pickaxe_conversation",{sessionId:w,userId:q}),y(!0),S(v.v4()),fe(le)}catch(e){console.error("Error deleting chat:",e),alert((null==E?void 0:E["failed-delete-chat"])||"Failed to delete chat.")}})),isDarkGlass:"dark"===_.portalTheme}),t.jsx(p.StudioTip,Object.assign({content:E["chat-history"]||"Chat History",align:"bottom",containerClassName:"inline-flex shrink-0"},{children:t.jsx(j.HistoryPill,{icon:t.jsx(g.default,{}),onClick:()=>{S(""),C(w)}})}))]})),t.jsx(c.default,{additionalScrollHeight:$,isForceHideInfo:F<=545||A<=350||K,isInputFocused:K,onSubmit:t=>e.__awaiter(void 0,void 0,void 0,(function*(){oe.current&&oe.current.onSubmit(t)})),smitheryAuthData:ne,resubmitPrompt:()=>{ie(null),ae(!0)}}),t.jsx("button",Object.assign({type:"button","aria-label":(null==E?void 0:E["scroll-to-bottom"])||"Scroll to bottom",className:h.default("absolute left-1/2 z-30 flex h-8 w-8 -translate-x-1/2 items-center justify-center rounded-full shadow-md outline-none transition-all duration-200 ease-in-out",!X||L||Z?"pointer-events-none translate-y-2 opacity-0":"opacity-100"),style:{bottom:`${$+65}px`,backgroundColor:N.accent,color:N.accentText},onClick:xe},{children:t.jsx(f.default,{className:"h-3 w-3 shrink-0"})})),t.jsx(u.default,{ref:oe,onFocus:()=>Q(!0),onBlur:()=>Q(!1),onInputHeightChange:J,initSmitheryAuthData:e=>ie(e),resubmitPrompt:re})]})]}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),s=require("react/jsx-runtime"),i=require("react"),t=require("../../../hooks/pickaxe/usePickaxeContext.js"),r=require("./PickaxeButton.js"),a=require("./PickaxeCommon.js"),n=require("./PickaxeCurrency.js"),o=require("./PickaxeAvatar.js"),l=require("../Addons/Auth/hooks/useAuthContext.js"),c=require("../../../common/api/pickaxe.js"),u=require("../../../common/utils.js"),d=require("../../../hooks/pickaxe/useResponseContext.js"),x=require("../../../hooks/studio/useStudio.js");exports.default=({data:m,children:p,upgradeUrl:f})=>{var j;const{limitData:v}=d.useResponseContext(),{studio:h}=x.useStudio(),{colors:b,sender:g,pickaxe:k,translations:y,setValidationStatus:I,setStripeAccountId:O,setClientSecret:_}=t.usePickaxeContext(),{token:N,setRedirectUrl:S}=l.useAuthContext(),q=i.useMemo((()=>{var e;return null!==(e=m.displayName)&&void 0!==e?e:m.name}),[m]),C=i.useMemo((()=>{var e;return null!==(e=m.displayDescription)&&void 0!==e?e:m.description}),[m]),w=!!(null==h?void 0:h.data.usage)&&h.data.usage.isCredits,A=i.useMemo((()=>{var e;const{price:s,priceInterval:i,currency:t}=m;if(!s)return{price:(null==y?void 0:y.free)||"Free",suffix:""};const r=a.intervalToSuffix(i,!0);return{price:`${(null!==(e=n.currencyOptions.find((e=>e.id===t)))&&void 0!==e?e:n.currencyOptions[0]).symbol}${s.toLocaleString()}`,suffix:r}}),[m]),U=i.useMemo((()=>{const{limit:e,limitInterval:s}=m;if(e===a.STUDIO_INFINITY_VALUE)return{limit:(null==y?void 0:y.unlimited)||"Unlimited",suffix:""};const i=a.intervalToSuffix(s,!0);return{limit:e.toLocaleString(),suffix:i}}),[m]);return s.jsxs("div",Object.assign({className:"relative flex min-h-[260px] w-[220px] shrink-0 snap-center flex-col justify-between rounded-xl border p-4 shadow-sm",style:{backgroundColor:b.secondary,color:b.secondaryText}},{children:[p,s.jsxs("div",Object.assign({className:"flex flex-col"},{children:[s.jsxs("div",Object.assign({className:"flex flex-col"},{children:[s.jsxs(o.Avatar,Object.assign({className:"h-8 w-8"},{children:[s.jsx(o.AvatarImage,{src:null!==(j=m.image)&&void 0!==j?j:"",alt:q}),s.jsx(o.AvatarFallback,{})]})),s.jsx("p",Object.assign({className:"mt-2 text-sm font-semibold line-clamp-1",title:q},{children:q})),Boolean(C)&&s.jsx("p",Object.assign({className:"mt-1 text-[10px] opacity-70 line-clamp-2 leading-tight"},{children:C})),s.jsxs("p",Object.assign({className:"mt-2 text-base font-semibold"},{children:[A.price,s.jsx("span",Object.assign({className:"text-xs font-normal opacity-70"},{children:A.suffix}))]}))]})),s.jsxs("div",Object.assign({className:"mt-3 flex flex-col border-t py-2",style:{borderTopColor:b.secondaryText}},{children:[s.jsx("span",Object.assign({className:"text-[10px] font-bold opacity-50"},{children:w?(null==y?void 0:y.credits_upper)||"CREDITS":(null==y?void 0:y.uses_upper)||"USES"})),s.jsxs("p",Object.assign({className:"text-base font-semibold"},{children:[U.limit,s.jsx("span",Object.assign({className:"text-xs font-normal opacity-70"},{children:U.suffix}))]}))]}))]})),s.jsx(r.default,Object.assign({variant:"primary",className:"w-full mt-2 min-h-[32px] text-xs",onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(N)e.__awaiter(void 0,void 0,void 0,(function*(){try{const e=yield c.default.post("/access_group_checkout",{data:{studioUserId:g||void 0,studioId:null==k?void 0:k.studioid,accessGroupId:m.accessGroupId,successUrl:document.URL,isEmbed:u.isInIframe(),studioSessionToken:N}}),{success:s,url:i,clientSecret:t,stripeAccountId:r,error:a}=e.data;s?u.isInIframe()?t&&r?(O(r),_(t),I("stripe_checkout")):i&&window.open(i,"_blank"):i&&(window.location.href=i):alert(a)}catch(e){alert(e)}}));else if(u.isInIframe()){const e=f||(null==v?void 0:v.limitLink);S(e||null),I("login_required")}else window.location.href=f||`${null==v?void 0:v.limitLink}?redirectUrl=${document.URL}`}))},{children:m.ctaButtonText}))]}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),s=require("react/jsx-runtime"),i=require("react"),t=require("../../../hooks/pickaxe/usePickaxeContext.js"),r=require("./PickaxeButton.js"),a=require("./PickaxeCommon.js"),n=require("./PickaxeCurrency.js"),o=require("./PickaxeAvatar.js"),l=require("../Addons/Auth/hooks/useAuthContext.js"),c=require("../../../common/api/pickaxe.js"),u=require("../../../common/utils.js"),d=require("../../../hooks/pickaxe/useResponseContext.js"),x=require("../../../hooks/studio/useStudio.js");exports.default=({data:m,children:p,upgradeUrl:f})=>{var j;const{limitData:v}=d.useResponseContext(),{studio:b}=x.useStudio(),{colors:h,sender:g,pickaxe:k,translations:y,setValidationStatus:I,setStripeAccountId:O,setClientSecret:_}=t.usePickaxeContext(),{token:N,setRedirectUrl:S}=l.useAuthContext(),q=i.useMemo((()=>{var e;return null!==(e=m.displayName)&&void 0!==e?e:m.name}),[m]),C=i.useMemo((()=>{var e;return null!==(e=m.displayDescription)&&void 0!==e?e:m.description}),[m]),U=!!(null==b?void 0:b.data.usage)&&b.data.usage.isCredits,w=i.useMemo((()=>{var e;const{price:s,priceInterval:i,currency:t}=m;if(!s)return{price:(null==y?void 0:y.free)||"Free",suffix:""};const r=a.intervalToSuffix(i,!0);return{price:`${(null!==(e=n.currencyOptions.find((e=>e.id===t)))&&void 0!==e?e:n.currencyOptions[0]).symbol}${s.toLocaleString()}`,suffix:r}}),[m]),A=i.useMemo((()=>{const{limit:e,limitInterval:s}=m;if(e===a.STUDIO_INFINITY_VALUE)return{limit:(null==y?void 0:y.unlimited)||"Unlimited",suffix:""};const i=a.intervalToSuffix(s,!0);return{limit:e.toLocaleString(),suffix:i}}),[m]);return s.jsxs("div",Object.assign({className:"relative flex min-h-[260px] w-[220px] shrink-0 snap-center flex-col justify-between rounded-xl border p-4 shadow-sm",style:{backgroundColor:h.secondary,color:h.secondaryText}},{children:[p,s.jsxs("div",Object.assign({className:"flex flex-col"},{children:[s.jsxs("div",Object.assign({className:"flex flex-col"},{children:[s.jsxs(o.Avatar,Object.assign({className:"h-8 w-8"},{children:[s.jsx(o.AvatarImage,{src:null!==(j=m.image)&&void 0!==j?j:"",alt:q}),s.jsx(o.AvatarFallback,{})]})),s.jsx("p",Object.assign({className:"mt-2 text-sm font-semibold line-clamp-1",title:q},{children:q})),Boolean(C)&&s.jsx("p",Object.assign({className:"mt-1 text-[10px] opacity-70 line-clamp-2 leading-tight"},{children:C})),s.jsxs("p",Object.assign({className:"mt-2 text-base font-semibold"},{children:[w.price,s.jsx("span",Object.assign({className:"text-xs font-normal opacity-70"},{children:w.suffix}))]}))]})),s.jsxs("div",Object.assign({className:"mt-3 flex flex-col border-t py-2",style:{borderTopColor:h.secondaryText}},{children:[s.jsx("span",Object.assign({className:"text-[10px] font-bold opacity-50"},{children:U?(null==y?void 0:y.credits_upper)||"CREDITS":(null==y?void 0:y.uses_upper)||"USES"})),s.jsxs("p",Object.assign({className:"text-base font-semibold"},{children:[A.limit,s.jsx("span",Object.assign({className:"text-xs font-normal opacity-70"},{children:A.suffix}))]}))]}))]})),s.jsx(r.default,Object.assign({variant:"primary",className:"w-full mt-2 min-h-[32px] text-xs",onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(N)e.__awaiter(void 0,void 0,void 0,(function*(){try{const e=yield c.default.post("/access_group_checkout",{data:{studioUserId:g||void 0,studioId:null==k?void 0:k.studioid,accessGroupId:m.accessGroupId,successUrl:document.URL,isEmbed:u.isInIframe(),studioSessionToken:N}}),{success:s,url:i,clientSecret:t,stripeAccountId:r,error:a}=e.data;s?u.isInIframe()?t&&r?(O(r),_(t),I("stripe_checkout")):i&&window.open(i,"_blank"):i&&(window.location.href=i):alert(a)}catch(e){alert(e)}}));else if(u.isInIframe()){const e=f||(null==v?void 0:v.limitLink);S(e||null),I("login_required")}else{const e=f||u.buildUpgradeUrl({baseUrl:null==v?void 0:v.limitLink,redirectUrl:document.URL});e&&(window.location.href=e)}}))},{children:m.ctaButtonText}))]}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),s=require("react/jsx-runtime"),t=require("react"),i=require("framer-motion"),o=require("../../../hooks/pickaxe/usePickaxeContext.js"),a=require("../../../hooks/pickaxe/useResponseContext.js"),r=require("../../../hooks/studio/useStyleFontSize.js"),l=require("../../../common/utils.js"),n=require("../../Icons/circle-exclamation.svg.js"),c=require("../../Core/SpringTransition.js"),d=require("../../Core/HtmlRenderer.js"),u=require("./PickaxeButton.js"),p=require("../../../common/cn.js"),x=require("../../../common/api/pickaxe.js"),m=require("../Addons/Auth/hooks/useAuthContext.js"),v=require("./AccessGroupCardPreview.js"),f=require("../../../hooks/studio/useStudio.js"),j=require("./PickaxeCurrency.js");const g=({price:e,uses:t,isCredits:i,isSelected:o,costPerRun:a,onClick:r,colors:l})=>{const n={backgroundColor:l.secondary,color:l.secondaryText,borderColor:o?l.secondaryText:"rgba(0,0,0,0.1)"},c=i&&a?Math.ceil(t/a):0;return i?s.jsxs("button",Object.assign({onClick:r,className:p.default("flex min-w-[200px] shrink-0 cursor-pointer flex-col rounded-[16px] px-6 py-5 text-left transition-all duration-200",o?"border-2 shadow-sm":"border opacity-80 hover:opacity-100"),style:n},{children:[s.jsxs("div",Object.assign({className:"mb-4 flex items-center gap-2"},{children:[s.jsx("span",Object.assign({className:"text-[24px] font-semibold tracking-tight"},{children:e})),s.jsxs("span",Object.assign({className:"text-[14px] font-light opacity-80"},{children:["/",t," credits"]}))]})),s.jsx("div",{className:"mb-4 h-[1px] w-full",style:{backgroundColor:l.secondaryText,opacity:.15}}),s.jsxs("span",Object.assign({className:"text-[14px] italic opacity-70"},{children:["~ ",void 0!==c&&c>0?c.toLocaleString():"..."," ","runs"]}))]})):s.jsxs("button",Object.assign({onClick:r,className:p.default("flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-[16px] px-5 py-3 transition-all duration-200",o?"border-2 shadow-sm":"border opacity-80 hover:opacity-100"),style:n},{children:[s.jsx("span",Object.assign({className:"text-[24px] font-semibold tracking-tight"},{children:e})),s.jsxs("span",Object.assign({className:"text-[14px] font-light opacity-80"},{children:["/",t," uses"]}))]}))};exports.default=({className:h,iconClassName:b,htmlClassName:y})=>{var w,k,C,N,O,_;const{colors:q,pickaxe:S,sender:I,translations:A,setValidationStatus:U,setClientSecret:P,setStripeAccountId:R}=o.usePickaxeContext(),{token:G,setRedirectUrl:L}=m.useAuthContext(),{limitData:T}=a.useResponseContext(),{studio:$}=f.useStudio(),B=r.useStyleFontSize(),[E,F]=t.useState(0),[M,z]=t.useState(null),D=!!(null==$?void 0:$.data.usage)&&$.data.usage.isCredits,H=null!==(k=null===(w=j.currencyOptions.find((e=>e.id===(null==$?void 0:$.data.currency))))||void 0===w?void 0:w.symbol)&&void 0!==k?k:j.currencyOptions[0].symbol;t.useEffect((()=>{var e;(null===(e=null==T?void 0:T.buyUses)||void 0===e?void 0:e.length)&&F(0)}),[T]);const V=null==T?void 0:T.customLink,J=null==T?void 0:T.limitCTA,K=Array.isArray(null==T?void 0:T.upgradeGroups)&&(null==T?void 0:T.upgradeGroups)&&(null==T?void 0:T.upgradeGroups.length)>0,Q=(D?null===(C=null==$?void 0:$.data.usage)||void 0===C?void 0:C.availableCredits:null===(N=null==$?void 0:$.data.usage)||void 0===N?void 0:N.availableUses)||(null==T?void 0:T.buyUses),W=Array.isArray(Q)&&Q.length>0,X=W&&Array.isArray(Q)&&Q[E];t.useEffect((()=>{let s=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if($&&(null===(e=$.data)||void 0===e?void 0:e.workspaceId))try{const e=yield x.default.get(`/cost_per_run?workspaceId=${$.data.workspaceId}`,{withCredentials:!1});if(s){const s=1e4*e.data.costPerRun||0;z(s)}}catch(e){console.error("Failed to fetch cost per run:",e),s&&z(0)}else z(0)})),()=>{s=!1}}),[$,null===(O=null==$?void 0:$.data)||void 0===O?void 0:O.workspaceId,z]);return T?s.jsx(i.AnimatePresence,{children:s.jsxs(c.default,Object.assign({className:p.default("flex flex-col gap-5 w-full",h)},{children:[s.jsxs("div",Object.assign({className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between rounded-lg p-3 bg-opacity-5",style:{backgroundColor:q.secondary}},{children:[s.jsxs("div",Object.assign({className:"flex gap-3 items-start"},{children:[s.jsx(n.default,{className:p.default("h-5 w-5 shrink-0 mt-0.5",b),style:{color:q.accent}}),s.jsx(d.default,{className:p.default(B.b2,"font-semibold leading-relaxed text-sm",y),style:{color:q.text},html:T.limitMessage||""})]})),V&&s.jsx(u.default,Object.assign({variant:"primary",className:"whitespace-nowrap min-h-[32px] w-full sm:w-auto text-sm",onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(l.isInIframe()){if(!G)return L(V||null),void U("login_required");window.open(V)}else window.location.href=`${V}?redirectUrl=${document.URL}`}))},{children:J}))]})),K&&s.jsxs("div",Object.assign({className:"flex flex-col gap-2"},{children:[s.jsx("h3",Object.assign({className:"text-xs font-bold opacity-70 uppercase px-1",style:{color:q.text}},{children:(null==A?void 0:A["available-plans"])||"Available Plans"})),s.jsx("div",Object.assign({className:"flex flex-row gap-3 overflow-x-auto pb-4 pt-1 snap-x scrollbar-thin"},{children:null===(_=T.upgradeGroups)||void 0===_?void 0:_.map(((e,t)=>s.jsx(v.default,{data:e},e.accessGroupId||t)))}))]})),W&&X&&s.jsxs("div",Object.assign({className:"flex flex-col gap-3"},{children:[s.jsxs("h3",Object.assign({className:"text-xs font-bold opacity-70 uppercase px-1",style:{color:q.text}},{children:[(null==A?void 0:A.buy)||"Buy"," ",D?(null==A?void 0:A.credits)||"Credits":(null==A?void 0:A.uses)||"Uses"]})),s.jsx("div",Object.assign({className:"flex flex-row gap-3 overflow-x-auto pb-2 pt-1 snap-x scrollbar-thin"},{children:null==Q?void 0:Q.map(((e,t)=>s.jsx(g,{price:e.price,uses:e.uses,isCredits:D,costPerRun:M||void 0,isSelected:t===E,onClick:()=>F(t),colors:q},t)))})),s.jsxs(u.default,Object.assign({variant:"primary",className:"w-full py-3 text-sm font-bold shadow-md",onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){var s,t;G?(s=X.uses,t=X.price,e.__awaiter(void 0,void 0,void 0,(function*(){try{const e=yield x.default.post("/get_extra_usage_payment_link",{data:{sender:I||void 0,studioSessionToken:G,studioId:null==S?void 0:S.studioid,cost:t,isEmbed:l.isInIframe(),extraUses:s,successUrl:document.URL}}),{success:i,url:o,clientSecret:a,stripeAccountId:r,error:n}=e.data;i?l.isInIframe()?a&&r?(R(r),P(a),U("stripe_checkout")):o&&window.open(o,"_blank"):o&&(window.location.href=o):alert(n)}catch(e){alert(e)}}))):l.isInIframe()?(L(V||null),U("login_required")):window.location.href=`${V}?redirectUrl=${document.URL}`}))},{children:[(null==A?void 0:A.buy)||"Buy"," ",X.uses.toLocaleString()," ",D?(null==A?void 0:A.credits)||"Credits":(null==A?void 0:A.uses)||"Uses"," ","for ",H,X.price]}))]}))]}))}):null};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),s=require("react/jsx-runtime"),t=require("react"),i=require("framer-motion"),r=require("../../../hooks/pickaxe/usePickaxeContext.js"),a=require("../../../hooks/pickaxe/useResponseContext.js"),o=require("../../../hooks/studio/useStyleFontSize.js"),l=require("../../../common/utils.js"),n=require("../../Icons/circle-exclamation.svg.js"),c=require("../../Core/SpringTransition.js"),d=require("../../Core/HtmlRenderer.js"),u=require("./PickaxeButton.js"),p=require("../../../common/cn.js"),x=require("../../../common/api/pickaxe.js"),m=require("../Addons/Auth/hooks/useAuthContext.js"),v=require("./AccessGroupCardPreview.js"),f=require("../../../hooks/studio/useStudio.js"),g=require("./PickaxeCurrency.js");const b=({price:e,uses:t,isCredits:i,isSelected:r,costPerRun:a,onClick:o,colors:l})=>{const n={backgroundColor:l.secondary,color:l.secondaryText,borderColor:r?l.secondaryText:"rgba(0,0,0,0.1)"},c=i&&a?Math.ceil(t/a):0;return i?s.jsxs("button",Object.assign({onClick:o,className:p.default("flex min-w-[200px] shrink-0 cursor-pointer flex-col rounded-[16px] px-6 py-5 text-left transition-all duration-200",r?"border-2 shadow-sm":"border opacity-80 hover:opacity-100"),style:n},{children:[s.jsxs("div",Object.assign({className:"mb-4 flex items-center gap-2"},{children:[s.jsx("span",Object.assign({className:"text-[24px] font-semibold tracking-tight"},{children:e})),s.jsxs("span",Object.assign({className:"text-[14px] font-light opacity-80"},{children:["/",t," credits"]}))]})),s.jsx("div",{className:"mb-4 h-[1px] w-full",style:{backgroundColor:l.secondaryText,opacity:.15}}),s.jsxs("span",Object.assign({className:"text-[14px] italic opacity-70"},{children:["~ ",void 0!==c&&c>0?c.toLocaleString():"..."," ","runs"]}))]})):s.jsxs("button",Object.assign({onClick:o,className:p.default("flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-[16px] px-5 py-3 transition-all duration-200",r?"border-2 shadow-sm":"border opacity-80 hover:opacity-100"),style:n},{children:[s.jsx("span",Object.assign({className:"text-[24px] font-semibold tracking-tight"},{children:e})),s.jsxs("span",Object.assign({className:"text-[14px] font-light opacity-80"},{children:["/",t," uses"]}))]}))};exports.default=({className:j,iconClassName:h,htmlClassName:y})=>{var w,k,C,N,O,_;const{colors:q,pickaxe:U,sender:S,translations:I,setValidationStatus:A,setClientSecret:P,setStripeAccountId:R}=r.usePickaxeContext(),{token:G,setRedirectUrl:L}=m.useAuthContext(),{limitData:T}=a.useResponseContext(),{studio:B}=f.useStudio(),E=o.useStyleFontSize(),[F,M]=t.useState(0),[z,D]=t.useState(null),H=!!(null==B?void 0:B.data.usage)&&B.data.usage.isCredits,V=null!==(k=null===(w=g.currencyOptions.find((e=>e.id===(null==B?void 0:B.data.currency))))||void 0===w?void 0:w.symbol)&&void 0!==k?k:g.currencyOptions[0].symbol;t.useEffect((()=>{var e;(null===(e=null==T?void 0:T.buyUses)||void 0===e?void 0:e.length)&&M(0)}),[T]);const $=null==T?void 0:T.customLink,J=null==T?void 0:T.limitCTA,K=Array.isArray(null==T?void 0:T.upgradeGroups)&&(null==T?void 0:T.upgradeGroups)&&(null==T?void 0:T.upgradeGroups.length)>0,Q=(H?null===(C=null==B?void 0:B.data.usage)||void 0===C?void 0:C.availableCredits:null===(N=null==B?void 0:B.data.usage)||void 0===N?void 0:N.availableUses)||(null==T?void 0:T.buyUses),W=Array.isArray(Q)&&Q.length>0,X=W&&Array.isArray(Q)&&Q[F];t.useEffect((()=>{let s=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(B&&(null===(e=B.data)||void 0===e?void 0:e.workspaceId))try{const e=yield x.default.get(`/cost_per_run?workspaceId=${B.data.workspaceId}`,{withCredentials:!1});if(s){const s=1e4*e.data.costPerRun||0;D(s)}}catch(e){console.error("Failed to fetch cost per run:",e),s&&D(0)}else D(0)})),()=>{s=!1}}),[B,null===(O=null==B?void 0:B.data)||void 0===O?void 0:O.workspaceId,D]);return T?s.jsx(i.AnimatePresence,{children:s.jsxs(c.default,Object.assign({className:p.default("flex flex-col gap-5 w-full",j)},{children:[s.jsxs("div",Object.assign({className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between rounded-lg p-3 bg-opacity-5",style:{backgroundColor:q.secondary}},{children:[s.jsxs("div",Object.assign({className:"flex gap-3 items-start"},{children:[s.jsx(n.default,{className:p.default("h-5 w-5 shrink-0 mt-0.5",h),style:{color:q.accent}}),s.jsx(d.default,{className:p.default(E.b2,"font-semibold leading-relaxed text-sm",y),style:{color:q.text},html:T.limitMessage||""})]})),$&&s.jsx(u.default,Object.assign({variant:"primary",className:"whitespace-nowrap min-h-[32px] w-full sm:w-auto text-sm",onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(l.isInIframe()){if(!G)return L($||null),void A("login_required");window.open($)}else{const e=l.buildUpgradeUrl({baseUrl:$,redirectUrl:document.URL});e&&(window.location.href=e)}}))},{children:J}))]})),K&&s.jsxs("div",Object.assign({className:"flex flex-col gap-2"},{children:[s.jsx("h3",Object.assign({className:"text-xs font-bold opacity-70 uppercase px-1",style:{color:q.text}},{children:(null==I?void 0:I["available-plans"])||"Available Plans"})),s.jsx("div",Object.assign({className:"flex flex-row gap-3 overflow-x-auto pb-4 pt-1 snap-x scrollbar-thin"},{children:null===(_=T.upgradeGroups)||void 0===_?void 0:_.map(((e,t)=>s.jsx(v.default,{data:e},e.accessGroupId||t)))}))]})),W&&X&&s.jsxs("div",Object.assign({className:"flex flex-col gap-3"},{children:[s.jsxs("h3",Object.assign({className:"text-xs font-bold opacity-70 uppercase px-1",style:{color:q.text}},{children:[(null==I?void 0:I.buy)||"Buy"," ",H?(null==I?void 0:I.credits)||"Credits":(null==I?void 0:I.uses)||"Uses"]})),s.jsx("div",Object.assign({className:"flex flex-row gap-3 overflow-x-auto pb-2 pt-1 snap-x scrollbar-thin"},{children:null==Q?void 0:Q.map(((e,t)=>s.jsx(b,{price:e.price,uses:e.uses,isCredits:H,costPerRun:z||void 0,isSelected:t===F,onClick:()=>M(t),colors:q},t)))})),s.jsxs(u.default,Object.assign({variant:"primary",className:"w-full py-3 text-sm font-bold shadow-md",onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){var s,t;if(G)s=X.uses,t=X.price,e.__awaiter(void 0,void 0,void 0,(function*(){try{const e=yield x.default.post("/get_extra_usage_payment_link",{data:{sender:S||void 0,studioSessionToken:G,studioId:null==U?void 0:U.studioid,cost:t,isEmbed:l.isInIframe(),extraUses:s,successUrl:document.URL}}),{success:i,url:r,clientSecret:a,stripeAccountId:o,error:n}=e.data;i?l.isInIframe()?a&&o?(R(o),P(a),A("stripe_checkout")):r&&window.open(r,"_blank"):r&&(window.location.href=r):alert(n)}catch(e){alert(e)}}));else if(l.isInIframe())L($||null),A("login_required");else{const e=l.buildUpgradeUrl({baseUrl:$,redirectUrl:document.URL});e&&(window.location.href=e)}}))},{children:[(null==I?void 0:I.buy)||"Buy"," ",X.uses.toLocaleString()," ",H?(null==I?void 0:I.credits)||"Credits":(null==I?void 0:I.uses)||"Uses"," ","for ",V,X.price]}))]}))]}))}):null};
@@ -3,6 +3,13 @@ export declare const COOKIE_USER_ID = "PXE-uid";
3
3
  export declare const generateId: (length: number, prefix?: string, suffix?: string) => string;
4
4
  export declare const randomStr: (len: number, charOnly?: boolean) => string;
5
5
  export declare const extractUrlsFromText: (text: string) => string[];
6
+ type BuildUpgradeUrlOptions = {
7
+ baseUrl?: string | null;
8
+ redirectUrl?: string;
9
+ accessGroupId?: string;
10
+ currentUrl?: string;
11
+ };
12
+ export declare const buildUpgradeUrl: ({ baseUrl, redirectUrl, accessGroupId, currentUrl, }: BuildUpgradeUrlOptions) => string | null;
6
13
  export declare const formatBytes: (bytes: number, decimals?: number) => string;
7
14
  export declare const getCookie: (name: string) => string | null;
8
15
  export declare const deleteCookie: (name: string) => void;
@@ -13,3 +20,4 @@ export declare const deleteAuthToken: (name: string) => void;
13
20
  export declare function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): (node: T) => void;
14
21
  export declare const isInIframe: () => boolean;
15
22
  export declare const safeJSONParse: <T>(str: string) => T | null;
23
+ export {};
@@ -1 +1 @@
1
- import{parse as t}from"tldts";const e="PXE-uid",o=(t,e="",o="")=>{let r="";for(let e=0;e<t;e++){r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return e+r+o},r=(t,e=!1)=>{let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";e&&(o=o.replace(/[0-9]/g,""));let r="";for(let e=0;e<t;e++)r+=o.charAt(Math.floor(Math.random()*o.length));return r},n=t=>{const e=t.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(e))},l=(t,e=2)=>{if(!+t)return"0 Bytes";const o=e<0?0:e,r=Math.floor(Math.log(t)/Math.log(1024));return`${parseFloat((t/Math.pow(1024,r)).toFixed(o))} ${["Bytes","KB","MB","PB","EB"][r]}`},c=t=>{try{const e=document.cookie.split("; ");for(const o of e){const[e,r]=o.split("=");if(e===t)return r}return null}catch(t){return console.error("[pxe] failed to get cookie",t),null}},a=t=>{document.cookie=t+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},i=()=>{try{const o=c(e);if(!o){const o=r(28),n=new Date;n.setFullYear(n.getFullYear()+1);let l=window.location.hostname;const c=t(l).domain;if(c)l=`.${c}`;else{const t=l.split(":")[0],e=t.split(".");l=t,e.length>=2&&(l=`.${e.slice(-2).join(".")}`)}return document.cookie=`${e}=${o};Path=/; Domain=${l}; Expires=${n.toUTCString()}`,o}return o}catch(t){return console.error("[pxe-embed] failed to initialized embed user id",t),r(28)}},u=t=>{try{if("undefined"==typeof window)return null;let e=null;return e=new URLSearchParams(window.location.search).get("pxtoken"),e||(e=localStorage.getItem(`PXE-token-${t}`)),e||(e=c(`PXE-token-${t}`)),e||(e=c(`__Secure-PS-${t}.session-token`)),e?decodeURIComponent(e):null}catch(t){return null}},s=(t,e)=>{try{if("undefined"==typeof window)return;localStorage.setItem(t,e)}catch(t){console.error("[pxe] failed to set auth token",t)}},d=t=>{try{if("undefined"==typeof window)return;localStorage.removeItem(t)}catch(t){console.error("[pxe] failed to delete auth token",t)}};function f(...t){return e=>{for(const o of t)o&&("function"==typeof o?o(e):o.current=e)}}const h=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(t){return!0}},p=t=>{try{return JSON.parse(t)}catch(t){return null}};export{e as COOKIE_USER_ID,d as deleteAuthToken,a as deleteCookie,n as extractUrlsFromText,l as formatBytes,o as generateId,u as getAuthToken,c as getCookie,i as initializeEmbedUserId,h as isInIframe,f as mergeRefs,r as randomStr,p as safeJSONParse,s as setAuthToken};
1
+ import{parse as e}from"tldts";const t="PXE-uid",r=(e,t="",r="")=>{let n="";for(let t=0;t<e;t++){n+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return t+n+r},n=(e,t=!1)=>{let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";t&&(r=r.replace(/[0-9]/g,""));let n="";for(let t=0;t<e;t++)n+=r.charAt(Math.floor(Math.random()*r.length));return n},o=e=>{const t=e.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(t))},l=({baseUrl:e,redirectUrl:t,accessGroupId:r,currentUrl:n})=>{if(!e)return null;const o=null!=n?n:"undefined"!=typeof window?window.location.href:null;if(!o)return null;try{const n=new URL(e,o);if(r){const e=encodeURIComponent(r),t=n.pathname.replace(/\/+$/,"");t.endsWith(`/${e}`)||(n.pathname=`${t}/${e}`)}return t&&n.searchParams.set("redirectUrl",t),n.toString()}catch(e){return console.error("[pxe] failed to build upgrade url",e),null}},c=(e,t=2)=>{if(!+e)return"0 Bytes";const r=t<0?0:t,n=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,n)).toFixed(r))} ${["Bytes","KB","MB","PB","EB"][n]}`},a=e=>{try{const t=document.cookie.split("; ");for(const r of t){const[t,n]=r.split("=");if(t===e)return n}return null}catch(e){return console.error("[pxe] failed to get cookie",e),null}},i=e=>{document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},u=()=>{try{const r=a(t);if(!r){const r=n(28),o=new Date;o.setFullYear(o.getFullYear()+1);let l=window.location.hostname;const c=e(l).domain;if(c)l=`.${c}`;else{const e=l.split(":")[0],t=e.split(".");l=e,t.length>=2&&(l=`.${t.slice(-2).join(".")}`)}return document.cookie=`${t}=${r};Path=/; Domain=${l}; Expires=${o.toUTCString()}`,r}return r}catch(e){return console.error("[pxe-embed] failed to initialized embed user id",e),n(28)}},s=e=>{try{if("undefined"==typeof window)return null;let t=null;return t=new URLSearchParams(window.location.search).get("pxtoken"),t||(t=localStorage.getItem(`PXE-token-${e}`)),t||(t=a(`PXE-token-${e}`)),t||(t=a(`__Secure-PS-${e}.session-token`)),t?decodeURIComponent(t):null}catch(e){return null}},d=(e,t)=>{try{if("undefined"==typeof window)return;localStorage.setItem(e,t)}catch(e){console.error("[pxe] failed to set auth token",e)}},f=e=>{try{if("undefined"==typeof window)return;localStorage.removeItem(e)}catch(e){console.error("[pxe] failed to delete auth token",e)}};function h(...e){return t=>{for(const r of e)r&&("function"==typeof r?r(t):r.current=t)}}const p=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(e){return!0}},w=e=>{try{return JSON.parse(e)}catch(e){return null}};export{t as COOKIE_USER_ID,l as buildUpgradeUrl,f as deleteAuthToken,i as deleteCookie,o as extractUrlsFromText,c as formatBytes,r as generateId,s as getAuthToken,a as getCookie,u as initializeEmbedUserId,p as isInIframe,h as mergeRefs,n as randomStr,w as safeJSONParse,d as setAuthToken};
@@ -0,0 +1 @@
1
+ import*as r from"react";var e;function t(){return t=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},t.apply(null,arguments)}var n=n=>r.createElement("svg",t({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 16 16"},n),e||(e=r.createElement("path",{fill:"currentColor",d:"m0 8 1.41-1.41L7 12.17V0h2v12.17l5.59-5.58L16 8l-8 8z"})));export{n as default};
@@ -1 +1 @@
1
- import{useState as e,useRef as r,useMemo as n,useEffect as t}from"react";import{useScrollContext as l}from"./useScrollContext.js";const o=({auto:o,debug:s})=>{const{scrollContainerRef:c,scrollTargetRef:u,isLocked:i,isScrollSession:d,isScrollIncreasing:a,setIsLocked:g,setIsScrollSession:f,setIsScrolling:v,setIsScrollIncreasing:S}=l(),[w,m]=e(0),h=r(!1),p=n((()=>null!=o&&o&&d),[o,d]),I=n((()=>c&&c.current?c.current:"undefined"==typeof window?null:window),[c]);t((()=>{if(!I)return;const e=e=>{d&&i&&("mousedown"===e.type||"wheel"===e.type||"DOMMouseScroll"===e.type||"mousewheel"===e.type)&&g(!1)};return null==I||I.addEventListener("scroll",e),null==I||I.addEventListener("mousedown",e),null==I||I.addEventListener("wheel",e),null==I||I.addEventListener("DOMMouseScroll",e),null==I||I.addEventListener("mousewheel",e),()=>{null==I||I.removeEventListener("scroll",e),null==I||I.removeEventListener("mousedown",e),null==I||I.removeEventListener("wheel",e),null==I||I.removeEventListener("DOMMouseScroll",e),null==I||I.removeEventListener("mousewheel",e)}}),[I,d,i]),t((()=>{h.current=!i}),[i]),t((()=>{const e=setInterval((()=>{if(!c.current)return;const e=c.current.scrollHeight;if(e===w)return;const r=e>w;s&&console.log("[useScroll] isIncreasing:",r,e,w),S(r),m(e),r&&o&&L()}),100);return()=>clearInterval(e)}),[c,w,o]),t((()=>{const e=setInterval((()=>{if(c.current)return;if(!u.current)return;const e=u.current.getBoundingClientRect().top+u.current.getBoundingClientRect().height+window.scrollY;if(e===w)return;const r=e>w;S(r),m(e),r&&p&&R()}),100);return()=>clearInterval(e)}),[u,w,p]);const L=()=>{try{if(v(!0),!c.current)return void(s&&console.log("[useScroll] scrollContainerRef not detected"));if(h.current)return;const e=c.current.scrollHeight;c.current.scrollTo({top:e,behavior:"smooth"}),s&&console.log("[useScroll] scrolled scrollContainerRef")}finally{v(!1)}},R=()=>{try{if(v(!0),!u.current)return void(s&&console.log("[useScroll] scrollTargetRef not detected"));if(h.current)return;const e=u.current.getBoundingClientRect().top+u.current.getBoundingClientRect().height+window.scrollY;window.scrollTo({top:e-500,behavior:"smooth"}),s&&console.log("[useScroll] scrolled scrollTargetRef")}finally{v(!1)}};return{scrollContainerRef:c,scrollTargetRef:u,isScrollIncreasing:a,scrollStartSession:()=>{f(!0),g(!0),h.current=!1},scrollEndSession:()=>{f(!1)},scrollToBottom:L,scrollToTarget:R}};export{o as useScroll};
1
+ import{useState as e,useRef as r,useMemo as n,useEffect as t}from"react";import{useScrollContext as o}from"./useScrollContext.js";const l=({auto:l,debug:s})=>{const{scrollContainerRef:c,scrollTargetRef:u,isLocked:i,isScrollSession:d,isScrollIncreasing:a,setIsLocked:g,setIsScrollSession:v,setIsScrolling:f,setIsScrollIncreasing:m}=o(),[S,h]=e(0),w=r(!1),p=n((()=>null!=l&&l&&d),[l,d]),I=n((()=>c&&c.current?c.current:"undefined"==typeof window?null:window),[c]);t((()=>{if(!I)return;const e=e=>{!i||"mousedown"!==e.type&&"touchmove"!==e.type&&"wheel"!==e.type&&"DOMMouseScroll"!==e.type&&"mousewheel"!==e.type||g(!1)};return null==I||I.addEventListener("mousedown",e),null==I||I.addEventListener("touchmove",e),null==I||I.addEventListener("wheel",e),null==I||I.addEventListener("DOMMouseScroll",e),null==I||I.addEventListener("mousewheel",e),()=>{null==I||I.removeEventListener("mousedown",e),null==I||I.removeEventListener("touchmove",e),null==I||I.removeEventListener("wheel",e),null==I||I.removeEventListener("DOMMouseScroll",e),null==I||I.removeEventListener("mousewheel",e)}}),[I,i]),t((()=>{w.current=!i}),[i]),t((()=>{const e=setInterval((()=>{if(!c.current)return;const e=c.current.scrollHeight;if(e===S)return;const r=e>S;s&&console.log("[useScroll] isIncreasing:",r,e,S),m(r),h(e),r&&l&&L()}),100);return()=>clearInterval(e)}),[c,S,l]),t((()=>{const e=setInterval((()=>{if(c.current)return;if(!u.current)return;const e=u.current.getBoundingClientRect().top+u.current.getBoundingClientRect().height+window.scrollY;if(e===S)return;const r=e>S;m(r),h(e),r&&p&&R()}),100);return()=>clearInterval(e)}),[u,S,p]);const L=()=>{try{if(f(!0),!c.current)return void(s&&console.log("[useScroll] scrollContainerRef not detected"));if(w.current)return;const e=c.current.scrollHeight;c.current.scrollTo({top:e,behavior:"smooth"}),s&&console.log("[useScroll] scrolled scrollContainerRef")}finally{f(!1)}},R=()=>{try{if(f(!0),!u.current)return void(s&&console.log("[useScroll] scrollTargetRef not detected"));if(w.current)return;const e=u.current.getBoundingClientRect().top+u.current.getBoundingClientRect().height+window.scrollY;window.scrollTo({top:e-500,behavior:"smooth"}),s&&console.log("[useScroll] scrolled scrollTargetRef")}finally{f(!1)}};return{scrollContainerRef:c,scrollTargetRef:u,isScrollIncreasing:a,scrollStartSession:()=>{v(!0),g(!0),w.current=!1},scrollEndSession:()=>{v(!1)},scrollToBottom:L,scrollToTarget:R}};export{l as useScroll};
@@ -1 +1 @@
1
- import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as s,Fragment as o}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as c,useMemo as d,useImperativeHandle as u}from"react";import{usePickaxeContext as p}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as m}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as f}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as h}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as v}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as j}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as w}from"../../../hooks/core/useHover.js";import{useMediaQuery as O}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as k,allowedImageMimeTypes as N,additionalAllowedFileExtensions as S}from"../../../common/documents.js";import{createParser as C}from"eventsource-parser";import I from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import T from"../../Icons/stop.svg.js";import A from"../Addons/Document/List.js";import P from"../../Core/Textarea.js";import D from"../../Core/ErrorAlert.js";import R from"../../../common/error.js";import{getValidationFailure as L}from"../../../common/validation.js";import U from"../../../common/cn.js";import{isInIframe as $,initializeEmbedUserId as B}from"../../../common/utils.js";import{useStudio as V}from"../../../hooks/studio/useStudio.js";import{useSpeech as X}from"../../../hooks/pickaxe/useSpeech.js";const K=i((({resubmitPrompt:i,onFocus:K,onBlur:W,onInputHeightChange:F,initSmitheryAuthData:H},J)=>{var M,z,G;const{origin:q,pickaxeId:Q,sessionId:Y,sender:Z,senderType:ee,portalId:te,deploymentId:ne,deploymentType:se,pickaxe:oe,styles:ie,colors:re,translations:ae,locale:le,forceMobile:ce,isNewChat:de,isRtl:ue,isShowFeedbackMessage:pe,accessGroup:me,setIsNewChat:fe,setIsShowIceBreaker:ge,setValidationStatus:he,setValidationUpgradeGroups:ve,setValidationUpgradeUrl:be,onGenerateComplete:ye}=p(),{token:xe,isLoggedOut:je,isSent:we,isPricingAuth:Oe}=b(),{messages:ke,isGenerating:Ne,setMessages:Se,setStatus:Ce,setLimitData:Ie,setError:Ee}=m(),{documents:_e,isUploading:Te,documentError:Ae,onFileUpload:Pe,setDocuments:De,setDocumentError:Re}=y(),{studio:Le}=V(),{scrollStartSession:Ue,scrollEndSession:$e,scrollToBottom:Be}=x({auto:!0}),{artifacts:Ve,currentPopupType:Xe,setArtifacts:Ke,setCurrentArtifact:We}=j(),{height:Fe}=v(),He=h(),[Je,Me]=r(""),[ze,Ge]=r(!1),[qe,Qe]=r(!1),[Ye,Ze]=r(null),[et,tt]=r(null),[nt,st]=r(!1),ot=a(null),it=a(""),rt=a(null),at=a(null),lt=a(null),ct=a(null),dt=a(null),ut=Math.max(.4*Fe,100),{speechTranscript:pt,isSpeechListening:mt,isSpeechProcessing:ft,isSpeechSupported:gt,onStartListening:ht,onStopListening:vt}=X(),[bt]=O("(max-width: 480px)"),yt=w(),{isHover:xt}=yt,jt=e(yt,["isHover"]),wt=w(),{isHover:Ot}=wt,kt=e(wt,["isHover"]),Nt=w(),{isHover:St}=Nt,Ct=e(Nt,["isHover"]),It=g(),Et=f(),_t="undefined"!=typeof window?window.location.hostname:"",Tt="undefined"!=typeof window?window.location.href:"",At="undefined"!=typeof window&&window.self!==window.top,Pt=_t.includes("pickaxe.co")&&!Tt.includes("https://studio.pickaxe.co/_embed")&&!At,Dt=null===(M=null==oe?void 0:oe.documentuploadtype)||void 0===M?void 0:M.startsWith("enduserupload"),Rt=gt&&(null==oe?void 0:oe.enablevoicetotext),Lt="chat-input"===se&&de&&!we,Ut="chat-input"===se&&Oe&&je&&we,$t=l((e=>{const t=L(e);return!!t&&(Ee(""),Ie(null),he(t.status),ve(t.upgradeGroups),be(t.upgradeUrl),!0)}),[Ee,Ie,he,ve,be]),Bt=null!==(z=null==oe?void 0:oe.placeholdertext)&&void 0!==z?z:ue?"بماذا تريد أن تتحدث؟":(null==ae?void 0:ae["what-do-you-want-to-talk-about"])||"What do you want to talk about?",Vt=ze||qe,Xt=l((()=>t(void 0,void 0,void 0,(function*(){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/get_user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign(Object.assign(Object.assign({studioId:null==oe?void 0:oe.studioid},Z&&{sender:Z}),xe&&{studioSessionToken:xe}),!xe&&!Z&&{sender:B()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),Pt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(Ze(t.studioUser),tt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}}))),[q,Q,Y,ee,Z,xe,te,ne,Pt]);c((()=>{Xt()}),[Xt]);const Kt=(null==me?void 0:me.limit)||0,Wt=(null==Ye?void 0:Ye.currentUses)||0,Ft=(null==Ye?void 0:Ye.extraUses)||0,Ht=!!(null==Le?void 0:Le.data.usage)&&Le.data.usage.isCredits,Jt=Kt>Wt?Kt-Wt+Ft:Ft,Mt=d((()=>!!Ye&&(!nt&&(!(Kt<=0)&&Jt<=.05*Kt))),[Ye,nt,Jt,Kt]),zt=d((()=>{var e,t,n;return!!de&&(!!oe&&(!He.isLoading&&(!((null!==(t=null===(e=He.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=oe.icebreakers)||void 0===n?void 0:n.length)&&(!pe&&!Lt)))))}),[oe,de,pe,Lt,He.data,He.isLoading]),Gt=d((()=>{if(Ne||Te)return!1;const e=_e.length>0&&_e.every((e=>"finished"===e.status));return!(!Je.trim()&&!e)&&_e.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Ne,Te,Je,_e]);u(J,(()=>({onSubmit:qt}))),c((()=>{ge(zt)}),[zt]),c((()=>{var e;if(i){const t=Array.from(ke),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;qt(n,!0)}}),[i]),c((()=>{if(!ct.current||!F)return;const e=new ResizeObserver((e=>{for(const t of e)F(t.contentRect.height)}));return e.observe(ct.current),()=>{e.disconnect()}}),[F]),c((()=>{if(!mt)return;const e=it.current?`${it.current} `:"";Me(`${e}${pt}`)}),[pt,mt]),c((()=>{if(!at.current)return;(()=>{if(!at.current)return;let e=at.current.scrollHeight>52;Je.includes("\n")||_e.length?e=!0:Je.trim()||(e=!1),Ge(e)})()}),[Je,_e]),c((()=>{const e=at.current,t=lt.current;if(!e||!t||ze||Je.includes("\n"))return void Qe(!1);const n=window.getComputedStyle(e),s=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:s,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=Je||Bt,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Qe(i>l)}),[Je,ze,Bt]);const qt=(e,n=!1)=>t(void 0,void 0,void 0,(function*(){var t,s,o;try{if(Ne||Te)return;const i=_e.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=i.map((e=>e.documentId)).filter(Boolean),a=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=e?e:Je;if(!c&&!l)return;Ee(""),Re(""),Ie(null),Me(""),fe(!1),Ce("fetching"),Ue(),Be();const d=null!==(s=null===(t=null==oe?void 0:oe.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==s&&s&&r.length>0,u=[...n?Array.from(ke.slice(0,ke.length-1)):Array.from(ke),...n?[]:[{id:ke.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:ke.length+(n?0:2),role:"assistant",parts:[],documentIds:[]}];Se(u),Be(),d&&De([]);const p=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:q,pickaxeId:Q,sessionId:Y,senderType:ee,value:c},d&&{documentIds:r}),Z&&{sender:Z}),xe&&{studioSessionToken:xe}),!xe&&!Z&&{sender:B()}),te&&{portalId:te}),ne&&{deploymentId:ne}),a.length>0&&{uploadedModelImages:a})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},Pt&&{credentials:"include"})),m=yield p.json();if(!m.success){if($t(m))return;const e=new Error(m.error||m.message||(null==ae?void 0:ae["failed-to-start-generation"])||"Failed to start generation");throw m.limitData&&(e.limitData=m.limitData),e}const f=m.submissionId;Ce("streaming"),dt.current=new AbortController;const g=u.length-1,h=[];let v=[...null!=Ve?Ve:[]],b=0,y=!1,x="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${f}?index=${b}`,{signal:null===(o=dt.current)||void 0===o?void 0:o.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();rt.current=t;const n=new TextDecoder,s=C({onEvent:e=>{var t,n;if(e.event&&"ping"!==e.event&&b++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),n=t.error||t.message||(null==ae?void 0:ae["something-went-wrong"])||"Something went wrong.";return $t(t)||Ee(n),void(y=!0)}if("delta"===e.event){const s=JSON.parse(e.data);if("data-error"===s.type&&H){const e=s.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw y=!0,H({smitheryId:t[1],serverId:n[1],name:s[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,H({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===s.type)x="",h.push({type:"text",content:"",isVisible:null===(t=s.isVisible)||void 0===t||t});else if("text-delta"===s.type)x+=s.delta,h[h.length-1].content=x;else if("text-end"===s.type)x="";else if("reasoning-start"===s.type)x="",h.push({type:"reasoning",content:"",isVisible:null===(n=s.isVisible)||void 0===n||n});else if("reasoning-delta"===s.type)x+=s.delta,h[h.length-1].content=x;else if("reasoning-end"===s.type)x="";else if(s.type.startsWith("data-")){const e=s;h.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Se([...u.slice(0,g),Object.assign(Object.assign({},u[u.length-1]),{id:ke.length+1,role:"assistant",parts:h})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ke([...v]),Xe.startsWith("inline")||We({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Ke(v),Xe.startsWith("inline")||We({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ke(v),Xe.startsWith("inline")||We({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");v=v.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),Ke(v)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Ke(v.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data),n=t.error||t.message||(null==ae?void 0:ae["something-went-wrong-try-again"])||"Something went wrong, please try again.";if($t(t))return void(y=!0);Ee(n)}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:o}=yield t.read();if(o)break;s.feed(n.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==ye||ye(Y)}catch(e){if(e.limitData)Ie(e.limitData),Ee("");else{let t=R(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==ae?void 0:ae["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),$t(t)||Ee(t)}}finally{Be(),Ce("idle"),$e(),rt.current=null,yield Xt()}}));return Ut?null:n("div",Object.assign({className:U("flex w-full flex-shrink-0 flex-col items-center",!Lt&&"px-4 pb-8"),dir:ue?"rtl":"ltr"},{children:s("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[s("div",Object.assign({ref:ct,className:U("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===ie.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Et),{maxHeight:`${ut}px`,overflowY:"auto"})},{children:[Mt&&s("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:Et.backgroundColor?`${Et.backgroundColor}E6`:void 0,borderColor:re.text+"20",color:re.text,borderTopRightRadius:ie.cornerRadius+"px",borderTopLeftRadius:ie.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:s("span",{children:[Jt," ",Ht?(null==ae?void 0:ae.credits)||"Credits":(null==ae?void 0:ae.uses)||"Uses"," ",(null==ae?void 0:ae.remaining)||"remaining"]})})),s("div",Object.assign({className:"flex items-center gap-3"},{children:[n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:re.accent,color:re.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=`${et}${null==me?void 0:me.accessGroupId}`;$()?window.open(t):location.href=t}},{children:(null==ae?void 0:ae.upgrade)||"Upgrade"})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>st(!0)},{children:n("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Ne&&_e.length>0&&n(A,{className:"p-4 pb-0",isDisabled:Ne}),s("div",Object.assign({className:"relative flex w-full flex-col"},{children:[mt&&s("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(G=re.accent)&&void 0!==G?G:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:re.text+"90"}},{children:(null==ae?void 0:ae.listening)||"Listening..."}))]})),n(P,Object.assign({ref:at,className:U(It.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Je.trim()&&!Je.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ue?"text-right":"text-left",Vt&&"mb-12",mt&&"text-transparent"),value:Je,placeholder:Bt,onChange:e=>{if(Me(e),F){const t=(e.match(/\n/g)||[]).length+1;if(!e)return void F(0);if(t>=11)return;let n=0;t>1&&(n=50),F(24*(t-1)+n)}},onKeyDown:e=>{ce||bt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Te||Ne||qt()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);t.length>0&&(e.preventDefault(),fe(!1),yield Pe(t))}))},K&&{onFocus:K},W&&{onBlur:W},{dir:ue?"rtl":"ltr"})),n("div",Object.assign({ref:lt,className:U("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",Vt?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!Vt&&Et.backgroundColor&&{backgroundColor:Et.backgroundColor}),{borderTopRightRadius:ie.cornerRadius+"px",borderBottomRightRadius:ie.cornerRadius+"px"})},{children:Ne?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{dt.current&&(dt.current.abort(),dt.current=null),rt.current&&(rt.current.cancel(),rt.current=null),Ce("idle")},style:{backgroundColor:re.accent,color:re.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):mt?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:vt,style:{backgroundColor:re.accent,color:re.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):s(o,{children:[Dt&&s("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Ot?re.accent+"10":void 0,color:Ot?re.accent:re.accent+"80"},disabled:Te||Ne,onClick:()=>{var e;return null===(e=ot.current)||void 0===e?void 0:e.click()}},kt,{children:[n("input",{id:"file-upload",ref:ot,type:"file",accept:[...k,...N,...S].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){fe(!1),yield Pe(Array.from(e.target.files||[])),e.target.value=""}))}),n(I,{className:"h-6 w-6 shrink-0"})]})),Rt&&n("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:mt?re.accent:St?re.accent+"10":void 0,color:mt?re.accentText:St?re.accent:re.accent+"80"},disabled:Te||Ne||ft,onClick:()=>{mt?vt():(it.current=Je,ht(le||"en-US"))}},Ct,{children:n(_,{className:"h-5 w-5 shrink-0"})})),n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:xt||Gt?re.accent:re.accent+"10",color:xt||Gt?re.accentText:re.accent+"80"},disabled:!Gt,onClick:()=>qt()},jt,{children:n(E,{className:U("h-6 w-6 shrink-0",ue&&"scale-x-[-1] transform")})}))]})}))]}))]})),Ae&&n(D,{error:Ae,className:"mt-3"})]}))}))}));K.displayName="Input";export{K as default};
1
+ import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as s,jsxs as n,Fragment as o}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as c,useMemo as d,useImperativeHandle as u}from"react";import{usePickaxeContext as p}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as m}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as f}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as h}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as v}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as j}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as w}from"../../../hooks/core/useHover.js";import{useMediaQuery as O}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as k,allowedImageMimeTypes as N,additionalAllowedFileExtensions as S}from"../../../common/documents.js";import{createParser as C}from"eventsource-parser";import I from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import T from"../../Icons/stop.svg.js";import A from"../Addons/Document/List.js";import P from"../../Core/Textarea.js";import D from"../../Core/ErrorAlert.js";import R from"../../../common/error.js";import{getValidationFailure as U}from"../../../common/validation.js";import L from"../../../common/cn.js";import{buildUpgradeUrl as $,isInIframe as B,initializeEmbedUserId as V}from"../../../common/utils.js";import{useStudio as X}from"../../../hooks/studio/useStudio.js";import{useSpeech as K}from"../../../hooks/pickaxe/useSpeech.js";const W=i((({resubmitPrompt:i,onFocus:W,onBlur:F,onInputHeightChange:H,initSmitheryAuthData:J},M)=>{var z,G,q;const{origin:Q,pickaxeId:Y,sessionId:Z,sender:ee,senderType:te,portalId:se,deploymentId:ne,deploymentType:oe,pickaxe:ie,styles:re,colors:ae,translations:le,locale:ce,forceMobile:de,isNewChat:ue,isRtl:pe,isShowFeedbackMessage:me,accessGroup:fe,setIsNewChat:ge,setIsShowIceBreaker:he,setValidationStatus:ve,setValidationUpgradeGroups:be,setValidationUpgradeUrl:ye,onGenerateComplete:xe}=p(),{token:je,isLoggedOut:we,isSent:Oe,isPricingAuth:ke}=b(),{messages:Ne,isGenerating:Se,setMessages:Ce,setStatus:Ie,setLimitData:Ee,setError:_e}=m(),{documents:Te,isUploading:Ae,documentError:Pe,onFileUpload:De,setDocuments:Re,setDocumentError:Ue}=y(),{studio:Le}=X(),{scrollStartSession:$e,scrollEndSession:Be,scrollToBottom:Ve}=x({auto:!0}),{artifacts:Xe,currentPopupType:Ke,setArtifacts:We,setCurrentArtifact:Fe}=j(),{height:He}=v(),Je=h(),[Me,ze]=r(""),[Ge,qe]=r(!1),[Qe,Ye]=r(!1),[Ze,et]=r(null),[tt,st]=r(null),[nt,ot]=r(!1),it=a(null),rt=a(""),at=a(null),lt=a(null),ct=a(null),dt=a(null),ut=a(null),pt=Math.max(.4*He,100),{speechTranscript:mt,isSpeechListening:ft,isSpeechProcessing:gt,isSpeechSupported:ht,onStartListening:vt,onStopListening:bt}=K(),[yt]=O("(max-width: 480px)"),xt=w(),{isHover:jt}=xt,wt=e(xt,["isHover"]),Ot=w(),{isHover:kt}=Ot,Nt=e(Ot,["isHover"]),St=w(),{isHover:Ct}=St,It=e(St,["isHover"]),Et=g(),_t=f(),Tt="undefined"!=typeof window?window.location.hostname:"",At="undefined"!=typeof window?window.location.href:"",Pt="undefined"!=typeof window&&window.self!==window.top,Dt=Tt.includes("pickaxe.co")&&!At.includes("https://studio.pickaxe.co/_embed")&&!Pt,Rt=null===(z=null==ie?void 0:ie.documentuploadtype)||void 0===z?void 0:z.startsWith("enduserupload"),Ut=ht&&(null==ie?void 0:ie.enablevoicetotext),Lt="chat-input"===oe&&ue&&!Oe,$t="chat-input"===oe&&ke&&we&&Oe,Bt=l((e=>{const t=U(e);return!!t&&(_e(""),Ee(null),ve(t.status),be(t.upgradeGroups),ye(t.upgradeUrl),!0)}),[_e,Ee,ve,be,ye]),Vt=null!==(G=null==ie?void 0:ie.placeholdertext)&&void 0!==G?G:pe?"بماذا تريد أن تتحدث؟":(null==le?void 0:le["what-do-you-want-to-talk-about"])||"What do you want to talk about?",Xt=Ge||Qe,Kt=l((()=>t(void 0,void 0,void 0,(function*(){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/get_user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign(Object.assign(Object.assign({studioId:null==ie?void 0:ie.studioid},ee&&{sender:ee}),je&&{studioSessionToken:je}),!je&&!ee&&{sender:V()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),Dt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(et(t.studioUser),st(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}}))),[Q,Y,Z,te,ee,je,se,ne,Dt]);c((()=>{Kt()}),[Kt]);const Wt=(null==fe?void 0:fe.limit)||0,Ft=(null==Ze?void 0:Ze.currentUses)||0,Ht=(null==Ze?void 0:Ze.extraUses)||0,Jt=!!(null==Le?void 0:Le.data.usage)&&Le.data.usage.isCredits,Mt=Wt>Ft?Wt-Ft+Ht:Ht,zt=d((()=>!!Ze&&(!nt&&(!(Wt<=0)&&Mt<=.05*Wt))),[Ze,nt,Mt,Wt]),Gt=d((()=>{var e,t,s;return!!ue&&(!!ie&&(!Je.isLoading&&(!((null!==(t=null===(e=Je.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=ie.icebreakers)||void 0===s?void 0:s.length)&&(!me&&!Lt)))))}),[ie,ue,me,Lt,Je.data,Je.isLoading]),qt=d((()=>{if(Se||Ae)return!1;const e=Te.length>0&&Te.every((e=>"finished"===e.status));return!(!Me.trim()&&!e)&&Te.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Se,Ae,Me,Te]);u(M,(()=>({onSubmit:Qt}))),c((()=>{he(Gt)}),[Gt]),c((()=>{var e;if(i){const t=Array.from(Ne),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Qt(s,!0)}}),[i]),c((()=>{if(!dt.current||!H)return;const e=new ResizeObserver((e=>{for(const t of e)H(t.contentRect.height)}));return e.observe(dt.current),()=>{e.disconnect()}}),[H]),c((()=>{if(!ft)return;const e=rt.current?`${rt.current} `:"";ze(`${e}${mt}`)}),[mt,ft]),c((()=>{if(!lt.current)return;(()=>{if(!lt.current)return;let e=lt.current.scrollHeight>52;Me.includes("\n")||Te.length?e=!0:Me.trim()||(e=!1),qe(e)})()}),[Me,Te]),c((()=>{const e=lt.current,t=ct.current;if(!e||!t||Ge||Me.includes("\n"))return void Ye(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=Me||Vt,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;Ye(i>l)}),[Me,Ge,Vt]);const Qt=(e,s=!1)=>t(void 0,void 0,void 0,(function*(){var t,n,o;try{if(Se||Ae)return;const i=Te.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),r=i.map((e=>e.documentId)).filter(Boolean),a=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),l=r.length>0,c=null!=e?e:Me;if(!c&&!l)return;_e(""),Ue(""),Ee(null),ze(""),ge(!1),Ie("fetching"),$e(),Ve();const d=null!==(n=null===(t=null==ie?void 0:ie.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==n&&n&&r.length>0,u=[...s?Array.from(Ne.slice(0,Ne.length-1)):Array.from(Ne),...s?[]:[{id:Ne.length+1,role:"user",parts:[{type:"text",content:c,isVisible:!0}],documentIds:d?r:[]}],{id:Ne.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];Ce(u),Ve(),d&&Re([]);const p=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:Q,pickaxeId:Y,sessionId:Z,senderType:te,value:c},d&&{documentIds:r}),ee&&{sender:ee}),je&&{studioSessionToken:je}),!je&&!ee&&{sender:V()}),se&&{portalId:se}),ne&&{deploymentId:ne}),a.length>0&&{uploadedModelImages:a})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},Dt&&{credentials:"include"})),m=yield p.json();if(!m.success){if(Bt(m))return;const e=new Error(m.error||m.message||(null==le?void 0:le["failed-to-start-generation"])||"Failed to start generation");throw m.limitData&&(e.limitData=m.limitData),e}const f=m.submissionId;Ie("streaming"),ut.current=new AbortController;const g=u.length-1,h=[];let v=[...null!=Xe?Xe:[]],b=0,y=!1,x="";for(;!y;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${f}?index=${b}`,{signal:null===(o=ut.current)||void 0===o?void 0:o.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();at.current=t;const s=new TextDecoder,n=C({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&b++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==le?void 0:le["something-went-wrong"])||"Something went wrong.";return Bt(t)||_e(s),void(y=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&J){const e=n.data.error;if("string"==typeof e){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw y=!0,J({smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw y=!0,J({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)x="",h.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)x+=n.delta,h[h.length-1].content=x;else if("text-end"===n.type)x="";else if("reasoning-start"===n.type)x="",h.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)x+=n.delta,h[h.length-1].content=x;else if("reasoning-end"===n.type)x="";else if(n.type.startsWith("data-")){const e=n;h.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Ce([...u.slice(0,g),Object.assign(Object.assign({},u[u.length-1]),{id:Ne.length+1,role:"assistant",parts:h})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),We([...v]),Ke.startsWith("inline")||Fe({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),We(v),Ke.startsWith("inline")||Fe({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);v=v.filter((e=>!(e.id===t.id&&e.version===t.version))),v.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),We(v),Ke.startsWith("inline")||Fe({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");v=v.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),We(v)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);We(v.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==le?void 0:le["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Bt(t))return void(y=!0);_e(s)}else"stop"===e.event&&(y=!0)}else y=!0}});for(;;){const{value:e,done:o}=yield t.read();if(o)break;n.feed(s.decode(e))}y||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(y=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==xe||xe(Z)}catch(e){if(e.limitData)Ee(e.limitData),_e("");else{let t=R(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==le?void 0:le["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Bt(t)||_e(t)}}finally{Ve(),Ie("idle"),Be(),at.current=null,yield Kt()}}));return $t?null:s("div",Object.assign({className:L("flex w-full flex-shrink-0 flex-col items-center",!Lt&&"px-4 pb-8"),dir:pe?"rtl":"ltr"},{children:n("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[n("div",Object.assign({ref:dt,className:L("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===re.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},_t),{maxHeight:`${pt}px`,overflowY:"auto"})},{children:[zt&&n("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:_t.backgroundColor?`${_t.backgroundColor}E6`:void 0,borderColor:ae.text+"20",color:ae.text,borderTopRightRadius:re.cornerRadius+"px",borderTopLeftRadius:re.cornerRadius+"px"}},{children:[s("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:n("span",{children:[Mt," ",Jt?(null==le?void 0:le.credits)||"Credits":(null==le?void 0:le.uses)||"Uses"," ",(null==le?void 0:le.remaining)||"remaining"]})})),n("div",Object.assign({className:"flex items-center gap-3"},{children:[s("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:ae.accent,color:ae.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=$({baseUrl:tt,accessGroupId:null==fe?void 0:fe.accessGroupId});t&&(B()?window.open(t):location.href=t)}},{children:(null==le?void 0:le.upgrade)||"Upgrade"})),s("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>ot(!0)},{children:s("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:s("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Se&&Te.length>0&&s(A,{className:"p-4 pb-0",isDisabled:Se}),n("div",Object.assign({className:"relative flex w-full flex-col"},{children:[ft&&n("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[s("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(q=ae.accent)&&void 0!==q?q:"#ff0000"}}),s("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:ae.text+"90"}},{children:(null==le?void 0:le.listening)||"Listening..."}))]})),s(P,Object.assign({ref:lt,className:L(Et.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Me.trim()&&!Me.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",pe?"text-right":"text-left",Xt&&"mb-12",ft&&"text-transparent"),value:Me,placeholder:Vt,onChange:e=>{ze(e)},onKeyDown:e=>{de||yt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Ae||Se||Qt()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);t.length>0&&(e.preventDefault(),ge(!1),yield De(t))}))},W&&{onFocus:W},F&&{onBlur:F},{dir:pe?"rtl":"ltr"})),s("div",Object.assign({ref:ct,className:L("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",Xt?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!Xt&&_t.backgroundColor&&{backgroundColor:_t.backgroundColor}),{borderTopRightRadius:re.cornerRadius+"px",borderBottomRightRadius:re.cornerRadius+"px"})},{children:Se?s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{ut.current&&(ut.current.abort(),ut.current=null),at.current&&(at.current.cancel(),at.current=null),Ie("idle")},style:{backgroundColor:ae.accent,color:ae.accentText}},{children:s(T,{className:"h-4 w-4 shrink-0"})})):ft?s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:bt,style:{backgroundColor:ae.accent,color:ae.accentText}},{children:s(T,{className:"h-4 w-4 shrink-0"})})):n(o,{children:[Rt&&n("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:kt?ae.accent+"10":void 0,color:kt?ae.accent:ae.accent+"80"},disabled:Ae||Se,onClick:()=>{var e;return null===(e=it.current)||void 0===e?void 0:e.click()}},Nt,{children:[s("input",{id:"file-upload",ref:it,type:"file",accept:[...k,...N,...S].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){ge(!1),yield De(Array.from(e.target.files||[])),e.target.value=""}))}),s(I,{className:"h-6 w-6 shrink-0"})]})),Ut&&s("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:ft?ae.accent:Ct?ae.accent+"10":void 0,color:ft?ae.accentText:Ct?ae.accent:ae.accent+"80"},disabled:Ae||Se||gt,onClick:()=>{ft?bt():(rt.current=Me,vt(ce||"en-US"))}},It,{children:s(_,{className:"h-5 w-5 shrink-0"})})),s("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:jt||qt?ae.accent:ae.accent+"10",color:jt||qt?ae.accentText:ae.accent+"80"},disabled:!qt,onClick:()=>Qt()},wt,{children:s(E,{className:L("h-6 w-6 shrink-0",pe&&"scale-x-[-1] transform")})}))]})}))]}))]})),Pe&&s(D,{error:Pe,className:"mt-3"})]}))}))}));W.displayName="Input";export{W as default};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as t,jsx as o,Fragment as i}from"react/jsx-runtime";import{useState as n,useRef as r,useEffect as s,useCallback as a}from"react";import{usePickaxeContext as l}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as c}from"../Addons/Auth/hooks/useAuthContext.js";import{useDimensionContext as d}from"../../../hooks/pickaxe/useDimensionContext.js";import{useDocument as m}from"../Addons/Document/hooks/useDocument.js";import{useStyleFontSize as u}from"../../../hooks/studio/useStyleFontSize.js";import p from"./History/index.js";import f from"./Input.js";import h from"../../Icons/attach-vertical.svg.js";import v from"../../../common/cn.js";import g from"../../../common/api/pickaxe.js";import{v4 as x}from"uuid";import{StudioTip as b}from"../../Core/StudioTip.js";import{useResponseContext as k}from"../../../hooks/pickaxe/useResponseContext.js";import{NavPill as y,EditableNavPill as j,HistoryPill as I}from"../Addons/Navbar/NavPill.js";import w from"../../Icons/history.svg.js";const D=()=>{const{deploymentType:D,isNewChat:N,setIsNewChat:C,sessionId:A,setSessionId:F,setLastSessionId:S,pickaxeId:T,sender:O,pickaxe:P,styles:_,isEmbed:z,translations:E}=l(),{isSent:H}=c(),{width:R,height:G,setDimension:L}=d(),{setDocuments:B,onFileUpload:U}=m(),{isGenerating:q,messages:J}=k(),K=u(),[M,Q]=n(0),[V,W]=n(!1),[X,Y]=n(!1),Z=r(null),$=r(null),ee=r(0),[te,oe]=n(null),[ie,ne]=n(!1),re=(null==E?void 0:E["new-chat"])||"New chat",se="chat-input"===D&&N&&!H;s((()=>()=>{B([])}),[]);const ae=a((()=>{if(!T||!O)return;const t=(o=0)=>e(void 0,void 0,void 0,(function*(){var e;try{const t=yield g.post("/get_pickaxe_conversation",{sessionId:A,userId:O});if(t.data&&t.data.success){const e=t.data.title;if(e&&"Conversation Title"!==e)return void ce(e)}else console.error("Failed to load conversation:",null===(e=t.data)||void 0===e?void 0:e.error)}catch(e){console.error("Error fetching conversation:",e)}o<20&&setTimeout((()=>t(o+1)),3e3)}));t()}),[T,O,A]);s((()=>{q||N||!A||ae()}),[q,N,A,ae]),s((()=>{if(!Z.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:o}=t.contentRect;L(parseInt(e.toFixed(0)),parseInt(o.toFixed(0)))}}));return e.observe(Z.current),()=>{e.disconnect()}}),[Z.current]);const[le,ce]=n(re),de=(null==P?void 0:P.formtitle)||"Pickaxe",me=(null==P?void 0:P.coverphoto)||void 0,[ue,pe]=n(!1);s((()=>{const e=!se&&!z&&_.portalTheme&&(J.filter((e=>"user"===e.role)).length>0||V||!N);pe(null!=e&&e)}),[J,V,N]);return t("div",Object.assign({ref:Z,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),ee.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&Y(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),ee.current-=1,0===ee.current&&Y(!1)},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e(void 0,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),Y(!1),ee.current=0;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(C(!1),yield U(e))}))},{children:[X&&t("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[o("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:o(h,{className:"h-10 w-10"})})),o("h3",Object.assign({className:v(K.h3,"mt-6 font-semibold text-c-primary text-black")},{children:(null==E?void 0:E["drop-files-to-upload"])||"Drop files to upload"})),o("p",Object.assign({className:v(K.b2,"mt-2 opacity-60 text-black")},{children:(null==E?void 0:E["add-anything-to-the-conversation"])||"Add anything to the conversation"}))]})),se?o(f,{}):t(i,{children:[ue&&t("div",Object.assign({className:v("direct-link"===D?"absolute top-4 left-4 md:top-6 md:left-6 z-40 flex items-center gap-2 animate-in fade-in slide-in-from-top-4 duration-500":"w-full max-w-3xl mt-6 px-4 md:px-0 flex justify-start z-30 mb-4 animate-in fade-in slide-in-from-top-4 duration-500 gap-2","dark"===_.portalTheme?"glass-dark ":"")},{children:[o(y,{text:de,icon:me}),N||le===re?o(y,{text:le}):o(j,{text:le,sessionId:A,onRename:t=>e(void 0,void 0,void 0,(function*(){if(A)try{yield g.post("/edit_conversation_name",{sessionId:A,name:t,userId:O}),ce(t)}catch(e){console.error("Error renaming chat:",e),alert((null==E?void 0:E["failed-rename-chat"])||"Failed to rename chat.")}})),onDelete:()=>e(void 0,void 0,void 0,(function*(){if(A&&window.confirm((null==E?void 0:E["delete-confirm"])||"Are you sure you want to delete this conversation?"))try{yield g.post("/delete_pickaxe_conversation",{sessionId:A,userId:O}),C(!0),F(x()),ce(re)}catch(e){console.error("Error deleting chat:",e),alert((null==E?void 0:E["failed-delete-chat"])||"Failed to delete chat.")}})),isDarkGlass:"dark"===_.portalTheme}),o(b,Object.assign({content:E["chat-history"]||"Chat History",align:"bottom",containerClassName:"inline-flex shrink-0"},{children:o(I,{icon:o(w,{}),onClick:()=>{F(""),S(A)}})}))]})),o(p,{additionalScrollHeight:M,isForceHideInfo:G<=545||R<=350||V,isInputFocused:V,onSubmit:t=>e(void 0,void 0,void 0,(function*(){$.current&&$.current.onSubmit(t)})),smitheryAuthData:te,resubmitPrompt:()=>{oe(null),ne(!0)}}),o(f,{ref:$,onFocus:()=>W(!0),onBlur:()=>W(!1),onInputHeightChange:Q,initSmitheryAuthData:e=>oe(e),resubmitPrompt:ie})]})]}))};export{D as default};
1
+ import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as t,jsx as o,Fragment as n}from"react/jsx-runtime";import{useState as r,useRef as i,useEffect as s,useCallback as a}from"react";import{usePickaxeContext as l}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as c}from"../Addons/Auth/hooks/useAuthContext.js";import{useDimensionContext as d}from"../../../hooks/pickaxe/useDimensionContext.js";import{useDocument as m}from"../Addons/Document/hooks/useDocument.js";import{useScrollContext as u}from"../Addons/Scroll/hooks/useScrollContext.js";import{useStyleFontSize as p}from"../../../hooks/studio/useStyleFontSize.js";import f from"./History/index.js";import h from"./Input.js";import v from"../../Icons/attach-vertical.svg.js";import g from"../../Icons/arrow-down.svg.js";import b from"../../../common/cn.js";import x from"../../../common/api/pickaxe.js";import{v4 as k}from"uuid";import{StudioTip as y}from"../../Core/StudioTip.js";import{useResponseContext as j}from"../../../hooks/pickaxe/useResponseContext.js";import{NavPill as w,EditableNavPill as I,HistoryPill as D}from"../Addons/Navbar/NavPill.js";import C from"../../Icons/history.svg.js";const N=()=>{const{deploymentType:N,isNewChat:T,setIsNewChat:S,sessionId:A,setSessionId:H,setLastSessionId:O,pickaxeId:F,sender:E,pickaxe:P,styles:_,colors:z,isEmbed:L,translations:R}=l(),{isSent:G}=c(),{width:B,height:M,setDimension:U}=d(),{setDocuments:$,onFileUpload:q}=m(),{scrollContainerRef:J,isLocked:K,setIsLocked:Q}=u(),{isGenerating:V,messages:W}=j(),X=p(),[Y,Z]=r(0),[ee,te]=r(!1),[oe,ne]=r(!1),[re,ie]=r(!1),[se,ae]=r(!0),le=i(null),ce=i(null),de=i(0),[me,ue]=r(null),[pe,fe]=r(!1),he=(null==R?void 0:R["new-chat"])||"New chat",ve="chat-input"===N&&T&&!G;s((()=>()=>{$([])}),[]);const ge=a((()=>{if(!F||!E)return;const t=(o=0)=>e(void 0,void 0,void 0,(function*(){var e;try{const t=yield x.post("/get_pickaxe_conversation",{sessionId:A,userId:E});if(t.data&&t.data.success){const e=t.data.title;if(e&&"Conversation Title"!==e)return void xe(e)}else console.error("Failed to load conversation:",null===(e=t.data)||void 0===e?void 0:e.error)}catch(e){console.error("Error fetching conversation:",e)}o<20&&setTimeout((()=>t(o+1)),3e3)}));t()}),[F,E,A]);s((()=>{V||T||!A||ge()}),[V,T,A,ge]),s((()=>{if(!le.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:o}=t.contentRect;U(parseInt(e.toFixed(0)),parseInt(o.toFixed(0)))}}));return e.observe(le.current),()=>{e.disconnect()}}),[U]);const[be,xe]=r(he),ke=(null==P?void 0:P.formtitle)||"Pickaxe",ye=(null==P?void 0:P.coverphoto)||void 0,[je,we]=r(!1);s((()=>{const e=!ve&&!L&&_.portalTheme&&(W.filter((e=>"user"===e.role)).length>0||ee||!T);we(null!=e&&e)}),[ve,L,ee,T,W,_.portalTheme]),s((()=>{const e=J.current;if(!e)return;const t=()=>{const t=e.scrollHeight-e.scrollTop-e.clientHeight;ie(e.scrollHeight>e.clientHeight+8),ae(t<=24)};t(),e.addEventListener("scroll",t,{passive:!0});const o=new ResizeObserver((()=>{t()}));o.observe(e);const n=e.firstElementChild;return n instanceof HTMLElement&&o.observe(n),()=>{e.removeEventListener("scroll",t),o.disconnect()}}),[ve,J]);const Ie=a((()=>{J.current&&(Q(!0),J.current.scrollTo({top:J.current.scrollHeight,behavior:"smooth"}))}),[J,Q]);return t("div",Object.assign({ref:le,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),de.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&ne(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),de.current-=1,0===de.current&&ne(!1)},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e(void 0,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),ne(!1),de.current=0;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(S(!1),yield q(e))}))},{children:[oe&&t("div",Object.assign({className:"absolute inset-0 z-50 flex flex-col items-center justify-center rounded-lg bg-white/80 backdrop-blur-sm transition-all duration-300"},{children:[o("div",Object.assign({className:"flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-lg animate-bounce text-black"},{children:o(v,{className:"h-10 w-10"})})),o("h3",Object.assign({className:b(X.h3,"mt-6 font-semibold text-c-primary text-black")},{children:(null==R?void 0:R["drop-files-to-upload"])||"Drop files to upload"})),o("p",Object.assign({className:b(X.b2,"mt-2 opacity-60 text-black")},{children:(null==R?void 0:R["add-anything-to-the-conversation"])||"Add anything to the conversation"}))]})),ve?o(h,{}):t(n,{children:[je&&t("div",Object.assign({className:b("direct-link"===N?"absolute top-4 left-4 md:top-6 md:left-6 z-40 flex items-center gap-2 animate-in fade-in slide-in-from-top-4 duration-500":"w-full max-w-3xl mt-6 px-4 md:px-0 flex justify-start z-30 mb-4 animate-in fade-in slide-in-from-top-4 duration-500 gap-2","dark"===_.portalTheme?"glass-dark ":"")},{children:[o(w,{text:ke,icon:ye}),T||be===he?o(w,{text:be}):o(I,{text:be,sessionId:A,onRename:t=>e(void 0,void 0,void 0,(function*(){if(A)try{yield x.post("/edit_conversation_name",{sessionId:A,name:t,userId:E}),xe(t)}catch(e){console.error("Error renaming chat:",e),alert((null==R?void 0:R["failed-rename-chat"])||"Failed to rename chat.")}})),onDelete:()=>e(void 0,void 0,void 0,(function*(){if(A&&window.confirm((null==R?void 0:R["delete-confirm"])||"Are you sure you want to delete this conversation?"))try{yield x.post("/delete_pickaxe_conversation",{sessionId:A,userId:E}),S(!0),H(k()),xe(he)}catch(e){console.error("Error deleting chat:",e),alert((null==R?void 0:R["failed-delete-chat"])||"Failed to delete chat.")}})),isDarkGlass:"dark"===_.portalTheme}),o(y,Object.assign({content:R["chat-history"]||"Chat History",align:"bottom",containerClassName:"inline-flex shrink-0"},{children:o(D,{icon:o(C,{}),onClick:()=>{H(""),O(A)}})}))]})),o(f,{additionalScrollHeight:Y,isForceHideInfo:M<=545||B<=350||ee,isInputFocused:ee,onSubmit:t=>e(void 0,void 0,void 0,(function*(){ce.current&&ce.current.onSubmit(t)})),smitheryAuthData:me,resubmitPrompt:()=>{ue(null),fe(!0)}}),o("button",Object.assign({type:"button","aria-label":(null==R?void 0:R["scroll-to-bottom"])||"Scroll to bottom",className:b("absolute left-1/2 z-30 flex h-8 w-8 -translate-x-1/2 items-center justify-center rounded-full shadow-md outline-none transition-all duration-200 ease-in-out",!re||K||se?"pointer-events-none translate-y-2 opacity-0":"opacity-100"),style:{bottom:`${Y+65}px`,backgroundColor:z.accent,color:z.accentText},onClick:Ie},{children:o(g,{className:"h-3 w-3 shrink-0"})})),o(h,{ref:ce,onFocus:()=>te(!0),onBlur:()=>te(!1),onInputHeightChange:Z,initSmitheryAuthData:e=>ue(e),resubmitPrompt:pe})]})]}))};export{N as default};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as i,jsx as t}from"react/jsx-runtime";import{useMemo as s}from"react";import{usePickaxeContext as o}from"../../../hooks/pickaxe/usePickaxeContext.js";import r from"./PickaxeButton.js";import{STUDIO_INFINITY_VALUE as n,intervalToSuffix as l}from"./PickaxeCommon.js";import{currencyOptions as a}from"./PickaxeCurrency.js";import{Avatar as c,AvatarImage as d,AvatarFallback as m}from"./PickaxeAvatar.js";import{useAuthContext as u}from"../Addons/Auth/hooks/useAuthContext.js";import p from"../../../common/api/pickaxe.js";import{isInIframe as f}from"../../../common/utils.js";import{useResponseContext as x}from"../../../hooks/pickaxe/useResponseContext.js";import{useStudio as v}from"../../../hooks/studio/useStudio.js";const h=({data:h,children:b,upgradeUrl:j})=>{var g;const{limitData:k}=x(),{studio:y}=v(),{colors:N,sender:O,pickaxe:w,translations:C,setValidationStatus:S,setStripeAccountId:I,setClientSecret:U}=o(),{token:_,setRedirectUrl:A}=u(),L=s((()=>{var e;return null!==(e=h.displayName)&&void 0!==e?e:h.name}),[h]),T=s((()=>{var e;return null!==(e=h.displayDescription)&&void 0!==e?e:h.description}),[h]),P=!!(null==y?void 0:y.data.usage)&&y.data.usage.isCredits,R=s((()=>{var e;const{price:i,priceInterval:t,currency:s}=h;if(!i)return{price:(null==C?void 0:C.free)||"Free",suffix:""};const o=l(t,!0);return{price:`${(null!==(e=a.find((e=>e.id===s)))&&void 0!==e?e:a[0]).symbol}${i.toLocaleString()}`,suffix:o}}),[h]),$=s((()=>{const{limit:e,limitInterval:i}=h;if(e===n)return{limit:(null==C?void 0:C.unlimited)||"Unlimited",suffix:""};const t=l(i,!0);return{limit:e.toLocaleString(),suffix:t}}),[h]);return i("div",Object.assign({className:"relative flex min-h-[260px] w-[220px] shrink-0 snap-center flex-col justify-between rounded-xl border p-4 shadow-sm",style:{backgroundColor:N.secondary,color:N.secondaryText}},{children:[b,i("div",Object.assign({className:"flex flex-col"},{children:[i("div",Object.assign({className:"flex flex-col"},{children:[i(c,Object.assign({className:"h-8 w-8"},{children:[t(d,{src:null!==(g=h.image)&&void 0!==g?g:"",alt:L}),t(m,{})]})),t("p",Object.assign({className:"mt-2 text-sm font-semibold line-clamp-1",title:L},{children:L})),Boolean(T)&&t("p",Object.assign({className:"mt-1 text-[10px] opacity-70 line-clamp-2 leading-tight"},{children:T})),i("p",Object.assign({className:"mt-2 text-base font-semibold"},{children:[R.price,t("span",Object.assign({className:"text-xs font-normal opacity-70"},{children:R.suffix}))]}))]})),i("div",Object.assign({className:"mt-3 flex flex-col border-t py-2",style:{borderTopColor:N.secondaryText}},{children:[t("span",Object.assign({className:"text-[10px] font-bold opacity-50"},{children:P?(null==C?void 0:C.credits_upper)||"CREDITS":(null==C?void 0:C.uses_upper)||"USES"})),i("p",Object.assign({className:"text-base font-semibold"},{children:[$.limit,t("span",Object.assign({className:"text-xs font-normal opacity-70"},{children:$.suffix}))]}))]}))]})),t(r,Object.assign({variant:"primary",className:"w-full mt-2 min-h-[32px] text-xs",onClick:()=>e(void 0,void 0,void 0,(function*(){if(_)e(void 0,void 0,void 0,(function*(){try{const e=yield p.post("/access_group_checkout",{data:{studioUserId:O||void 0,studioId:null==w?void 0:w.studioid,accessGroupId:h.accessGroupId,successUrl:document.URL,isEmbed:f(),studioSessionToken:_}}),{success:i,url:t,clientSecret:s,stripeAccountId:o,error:r}=e.data;i?f()?s&&o?(I(o),U(s),S("stripe_checkout")):t&&window.open(t,"_blank"):t&&(window.location.href=t):alert(r)}catch(e){alert(e)}}));else if(f()){const e=j||(null==k?void 0:k.limitLink);A(e||null),S("login_required")}else window.location.href=j||`${null==k?void 0:k.limitLink}?redirectUrl=${document.URL}`}))},{children:h.ctaButtonText}))]}))};export{h as default};
1
+ import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as i,jsx as t}from"react/jsx-runtime";import{useMemo as s}from"react";import{usePickaxeContext as o}from"../../../hooks/pickaxe/usePickaxeContext.js";import r from"./PickaxeButton.js";import{STUDIO_INFINITY_VALUE as n,intervalToSuffix as l}from"./PickaxeCommon.js";import{currencyOptions as a}from"./PickaxeCurrency.js";import{Avatar as c,AvatarImage as d,AvatarFallback as m}from"./PickaxeAvatar.js";import{useAuthContext as u}from"../Addons/Auth/hooks/useAuthContext.js";import p from"../../../common/api/pickaxe.js";import{isInIframe as f,buildUpgradeUrl as x}from"../../../common/utils.js";import{useResponseContext as v}from"../../../hooks/pickaxe/useResponseContext.js";import{useStudio as h}from"../../../hooks/studio/useStudio.js";const b=({data:b,children:j,upgradeUrl:g})=>{var k;const{limitData:y}=v(),{studio:N}=h(),{colors:O,sender:w,pickaxe:C,translations:S,setValidationStatus:U,setStripeAccountId:I,setClientSecret:_}=o(),{token:A,setRedirectUrl:L}=u(),T=s((()=>{var e;return null!==(e=b.displayName)&&void 0!==e?e:b.name}),[b]),P=s((()=>{var e;return null!==(e=b.displayDescription)&&void 0!==e?e:b.description}),[b]),R=!!(null==N?void 0:N.data.usage)&&N.data.usage.isCredits,B=s((()=>{var e;const{price:i,priceInterval:t,currency:s}=b;if(!i)return{price:(null==S?void 0:S.free)||"Free",suffix:""};const o=l(t,!0);return{price:`${(null!==(e=a.find((e=>e.id===s)))&&void 0!==e?e:a[0]).symbol}${i.toLocaleString()}`,suffix:o}}),[b]),D=s((()=>{const{limit:e,limitInterval:i}=b;if(e===n)return{limit:(null==S?void 0:S.unlimited)||"Unlimited",suffix:""};const t=l(i,!0);return{limit:e.toLocaleString(),suffix:t}}),[b]);return i("div",Object.assign({className:"relative flex min-h-[260px] w-[220px] shrink-0 snap-center flex-col justify-between rounded-xl border p-4 shadow-sm",style:{backgroundColor:O.secondary,color:O.secondaryText}},{children:[j,i("div",Object.assign({className:"flex flex-col"},{children:[i("div",Object.assign({className:"flex flex-col"},{children:[i(c,Object.assign({className:"h-8 w-8"},{children:[t(d,{src:null!==(k=b.image)&&void 0!==k?k:"",alt:T}),t(m,{})]})),t("p",Object.assign({className:"mt-2 text-sm font-semibold line-clamp-1",title:T},{children:T})),Boolean(P)&&t("p",Object.assign({className:"mt-1 text-[10px] opacity-70 line-clamp-2 leading-tight"},{children:P})),i("p",Object.assign({className:"mt-2 text-base font-semibold"},{children:[B.price,t("span",Object.assign({className:"text-xs font-normal opacity-70"},{children:B.suffix}))]}))]})),i("div",Object.assign({className:"mt-3 flex flex-col border-t py-2",style:{borderTopColor:O.secondaryText}},{children:[t("span",Object.assign({className:"text-[10px] font-bold opacity-50"},{children:R?(null==S?void 0:S.credits_upper)||"CREDITS":(null==S?void 0:S.uses_upper)||"USES"})),i("p",Object.assign({className:"text-base font-semibold"},{children:[D.limit,t("span",Object.assign({className:"text-xs font-normal opacity-70"},{children:D.suffix}))]}))]}))]})),t(r,Object.assign({variant:"primary",className:"w-full mt-2 min-h-[32px] text-xs",onClick:()=>e(void 0,void 0,void 0,(function*(){if(A)e(void 0,void 0,void 0,(function*(){try{const e=yield p.post("/access_group_checkout",{data:{studioUserId:w||void 0,studioId:null==C?void 0:C.studioid,accessGroupId:b.accessGroupId,successUrl:document.URL,isEmbed:f(),studioSessionToken:A}}),{success:i,url:t,clientSecret:s,stripeAccountId:o,error:r}=e.data;i?f()?s&&o?(I(o),_(s),U("stripe_checkout")):t&&window.open(t,"_blank"):t&&(window.location.href=t):alert(r)}catch(e){alert(e)}}));else if(f()){const e=g||(null==y?void 0:y.limitLink);L(e||null),U("login_required")}else{const e=g||x({baseUrl:null==y?void 0:y.limitLink,redirectUrl:document.URL});e&&(window.location.href=e)}}))},{children:b.ctaButtonText}))]}))};export{b as default};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsx as o,jsxs as s}from"react/jsx-runtime";import{useState as i,useEffect as t}from"react";import{AnimatePresence as r}from"framer-motion";import{usePickaxeContext as l}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as a}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleFontSize as n}from"../../../hooks/studio/useStyleFontSize.js";import{isInIframe as c}from"../../../common/utils.js";import d from"../../Icons/circle-exclamation.svg.js";import u from"../../Core/SpringTransition.js";import p from"../../Core/HtmlRenderer.js";import m from"./PickaxeButton.js";import v from"../../../common/cn.js";import x from"../../../common/api/pickaxe.js";import{useAuthContext as f}from"../Addons/Auth/hooks/useAuthContext.js";import g from"./AccessGroupCardPreview.js";import{useStudio as h}from"../../../hooks/studio/useStudio.js";import{currencyOptions as b}from"./PickaxeCurrency.js";const y=({price:e,uses:i,isCredits:t,isSelected:r,costPerRun:l,onClick:a,colors:n})=>{const c={backgroundColor:n.secondary,color:n.secondaryText,borderColor:r?n.secondaryText:"rgba(0,0,0,0.1)"},d=t&&l?Math.ceil(i/l):0;return s("button",t?Object.assign({onClick:a,className:v("flex min-w-[200px] shrink-0 cursor-pointer flex-col rounded-[16px] px-6 py-5 text-left transition-all duration-200",r?"border-2 shadow-sm":"border opacity-80 hover:opacity-100"),style:c},{children:[s("div",Object.assign({className:"mb-4 flex items-center gap-2"},{children:[o("span",Object.assign({className:"text-[24px] font-semibold tracking-tight"},{children:e})),s("span",Object.assign({className:"text-[14px] font-light opacity-80"},{children:["/",i," credits"]}))]})),o("div",{className:"mb-4 h-[1px] w-full",style:{backgroundColor:n.secondaryText,opacity:.15}}),s("span",Object.assign({className:"text-[14px] italic opacity-70"},{children:["~ ",void 0!==d&&d>0?d.toLocaleString():"..."," ","runs"]}))]}):Object.assign({onClick:a,className:v("flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-[16px] px-5 py-3 transition-all duration-200",r?"border-2 shadow-sm":"border opacity-80 hover:opacity-100"),style:c},{children:[o("span",Object.assign({className:"text-[24px] font-semibold tracking-tight"},{children:e})),s("span",Object.assign({className:"text-[14px] font-light opacity-80"},{children:["/",i," uses"]}))]}))},j=({className:j,iconClassName:k,htmlClassName:w})=>{var C,N,O,A,S,U;const{colors:_,pickaxe:I,sender:R,translations:P,setValidationStatus:G,setClientSecret:L,setStripeAccountId:T}=l(),{token:$,setRedirectUrl:B}=f(),{limitData:q}=a(),{studio:F}=h(),M=n(),[z,D]=i(0),[E,H]=i(null),V=!!(null==F?void 0:F.data.usage)&&F.data.usage.isCredits,J=null!==(N=null===(C=b.find((e=>e.id===(null==F?void 0:F.data.currency))))||void 0===C?void 0:C.symbol)&&void 0!==N?N:b[0].symbol;t((()=>{var e;(null===(e=null==q?void 0:q.buyUses)||void 0===e?void 0:e.length)&&D(0)}),[q]);const K=null==q?void 0:q.customLink,Q=null==q?void 0:q.limitCTA,W=Array.isArray(null==q?void 0:q.upgradeGroups)&&(null==q?void 0:q.upgradeGroups)&&(null==q?void 0:q.upgradeGroups.length)>0,X=(V?null===(O=null==F?void 0:F.data.usage)||void 0===O?void 0:O.availableCredits:null===(A=null==F?void 0:F.data.usage)||void 0===A?void 0:A.availableUses)||(null==q?void 0:q.buyUses),Y=Array.isArray(X)&&X.length>0,Z=Y&&Array.isArray(X)&&X[z];t((()=>{let o=!0;return e(void 0,void 0,void 0,(function*(){var e;if(F&&(null===(e=F.data)||void 0===e?void 0:e.workspaceId))try{const e=yield x.get(`/cost_per_run?workspaceId=${F.data.workspaceId}`,{withCredentials:!1});if(o){const o=1e4*e.data.costPerRun||0;H(o)}}catch(e){console.error("Failed to fetch cost per run:",e),o&&H(0)}else H(0)})),()=>{o=!1}}),[F,null===(S=null==F?void 0:F.data)||void 0===S?void 0:S.workspaceId,H]);return q?o(r,{children:s(u,Object.assign({className:v("flex flex-col gap-5 w-full",j)},{children:[s("div",Object.assign({className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between rounded-lg p-3 bg-opacity-5",style:{backgroundColor:_.secondary}},{children:[s("div",Object.assign({className:"flex gap-3 items-start"},{children:[o(d,{className:v("h-5 w-5 shrink-0 mt-0.5",k),style:{color:_.accent}}),o(p,{className:v(M.b2,"font-semibold leading-relaxed text-sm",w),style:{color:_.text},html:q.limitMessage||""})]})),K&&o(m,Object.assign({variant:"primary",className:"whitespace-nowrap min-h-[32px] w-full sm:w-auto text-sm",onClick:()=>e(void 0,void 0,void 0,(function*(){if(c()){if(!$)return B(K||null),void G("login_required");window.open(K)}else window.location.href=`${K}?redirectUrl=${document.URL}`}))},{children:Q}))]})),W&&s("div",Object.assign({className:"flex flex-col gap-2"},{children:[o("h3",Object.assign({className:"text-xs font-bold opacity-70 uppercase px-1",style:{color:_.text}},{children:(null==P?void 0:P["available-plans"])||"Available Plans"})),o("div",Object.assign({className:"flex flex-row gap-3 overflow-x-auto pb-4 pt-1 snap-x scrollbar-thin"},{children:null===(U=q.upgradeGroups)||void 0===U?void 0:U.map(((e,s)=>o(g,{data:e},e.accessGroupId||s)))}))]})),Y&&Z&&s("div",Object.assign({className:"flex flex-col gap-3"},{children:[s("h3",Object.assign({className:"text-xs font-bold opacity-70 uppercase px-1",style:{color:_.text}},{children:[(null==P?void 0:P.buy)||"Buy"," ",V?(null==P?void 0:P.credits)||"Credits":(null==P?void 0:P.uses)||"Uses"]})),o("div",Object.assign({className:"flex flex-row gap-3 overflow-x-auto pb-2 pt-1 snap-x scrollbar-thin"},{children:null==X?void 0:X.map(((e,s)=>o(y,{price:e.price,uses:e.uses,isCredits:V,costPerRun:E||void 0,isSelected:s===z,onClick:()=>D(s),colors:_},s)))})),s(m,Object.assign({variant:"primary",className:"w-full py-3 text-sm font-bold shadow-md",onClick:()=>e(void 0,void 0,void 0,(function*(){var o,s;$?(o=Z.uses,s=Z.price,e(void 0,void 0,void 0,(function*(){try{const e=yield x.post("/get_extra_usage_payment_link",{data:{sender:R||void 0,studioSessionToken:$,studioId:null==I?void 0:I.studioid,cost:s,isEmbed:c(),extraUses:o,successUrl:document.URL}}),{success:i,url:t,clientSecret:r,stripeAccountId:l,error:a}=e.data;i?c()?r&&l?(T(l),L(r),G("stripe_checkout")):t&&window.open(t,"_blank"):t&&(window.location.href=t):alert(a)}catch(e){alert(e)}}))):c()?(B(K||null),G("login_required")):window.location.href=`${K}?redirectUrl=${document.URL}`}))},{children:[(null==P?void 0:P.buy)||"Buy"," ",Z.uses.toLocaleString()," ",V?(null==P?void 0:P.credits)||"Credits":(null==P?void 0:P.uses)||"Uses"," ","for ",J,Z.price]}))]}))]}))}):null};export{j as default};
1
+ import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsx as s,jsxs as o}from"react/jsx-runtime";import{useState as i,useEffect as t}from"react";import{AnimatePresence as r}from"framer-motion";import{usePickaxeContext as l}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as a}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleFontSize as n}from"../../../hooks/studio/useStyleFontSize.js";import{isInIframe as c,buildUpgradeUrl as d}from"../../../common/utils.js";import u from"../../Icons/circle-exclamation.svg.js";import p from"../../Core/SpringTransition.js";import m from"../../Core/HtmlRenderer.js";import v from"./PickaxeButton.js";import f from"../../../common/cn.js";import x from"../../../common/api/pickaxe.js";import{useAuthContext as g}from"../Addons/Auth/hooks/useAuthContext.js";import h from"./AccessGroupCardPreview.js";import{useStudio as b}from"../../../hooks/studio/useStudio.js";import{currencyOptions as y}from"./PickaxeCurrency.js";const j=({price:e,uses:i,isCredits:t,isSelected:r,costPerRun:l,onClick:a,colors:n})=>{const c={backgroundColor:n.secondary,color:n.secondaryText,borderColor:r?n.secondaryText:"rgba(0,0,0,0.1)"},d=t&&l?Math.ceil(i/l):0;return o("button",t?Object.assign({onClick:a,className:f("flex min-w-[200px] shrink-0 cursor-pointer flex-col rounded-[16px] px-6 py-5 text-left transition-all duration-200",r?"border-2 shadow-sm":"border opacity-80 hover:opacity-100"),style:c},{children:[o("div",Object.assign({className:"mb-4 flex items-center gap-2"},{children:[s("span",Object.assign({className:"text-[24px] font-semibold tracking-tight"},{children:e})),o("span",Object.assign({className:"text-[14px] font-light opacity-80"},{children:["/",i," credits"]}))]})),s("div",{className:"mb-4 h-[1px] w-full",style:{backgroundColor:n.secondaryText,opacity:.15}}),o("span",Object.assign({className:"text-[14px] italic opacity-70"},{children:["~ ",void 0!==d&&d>0?d.toLocaleString():"..."," ","runs"]}))]}):Object.assign({onClick:a,className:f("flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-[16px] px-5 py-3 transition-all duration-200",r?"border-2 shadow-sm":"border opacity-80 hover:opacity-100"),style:c},{children:[s("span",Object.assign({className:"text-[24px] font-semibold tracking-tight"},{children:e})),o("span",Object.assign({className:"text-[14px] font-light opacity-80"},{children:["/",i," uses"]}))]}))},k=({className:k,iconClassName:w,htmlClassName:C})=>{var N,O,U,A,S,_;const{colors:I,pickaxe:R,sender:P,translations:G,setValidationStatus:L,setClientSecret:T,setStripeAccountId:B}=l(),{token:q,setRedirectUrl:F}=g(),{limitData:M}=a(),{studio:z}=b(),D=n(),[E,H]=i(0),[V,$]=i(null),J=!!(null==z?void 0:z.data.usage)&&z.data.usage.isCredits,K=null!==(O=null===(N=y.find((e=>e.id===(null==z?void 0:z.data.currency))))||void 0===N?void 0:N.symbol)&&void 0!==O?O:y[0].symbol;t((()=>{var e;(null===(e=null==M?void 0:M.buyUses)||void 0===e?void 0:e.length)&&H(0)}),[M]);const Q=null==M?void 0:M.customLink,W=null==M?void 0:M.limitCTA,X=Array.isArray(null==M?void 0:M.upgradeGroups)&&(null==M?void 0:M.upgradeGroups)&&(null==M?void 0:M.upgradeGroups.length)>0,Y=(J?null===(U=null==z?void 0:z.data.usage)||void 0===U?void 0:U.availableCredits:null===(A=null==z?void 0:z.data.usage)||void 0===A?void 0:A.availableUses)||(null==M?void 0:M.buyUses),Z=Array.isArray(Y)&&Y.length>0,ee=Z&&Array.isArray(Y)&&Y[E];t((()=>{let s=!0;return e(void 0,void 0,void 0,(function*(){var e;if(z&&(null===(e=z.data)||void 0===e?void 0:e.workspaceId))try{const e=yield x.get(`/cost_per_run?workspaceId=${z.data.workspaceId}`,{withCredentials:!1});if(s){const s=1e4*e.data.costPerRun||0;$(s)}}catch(e){console.error("Failed to fetch cost per run:",e),s&&$(0)}else $(0)})),()=>{s=!1}}),[z,null===(S=null==z?void 0:z.data)||void 0===S?void 0:S.workspaceId,$]);return M?s(r,{children:o(p,Object.assign({className:f("flex flex-col gap-5 w-full",k)},{children:[o("div",Object.assign({className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between rounded-lg p-3 bg-opacity-5",style:{backgroundColor:I.secondary}},{children:[o("div",Object.assign({className:"flex gap-3 items-start"},{children:[s(u,{className:f("h-5 w-5 shrink-0 mt-0.5",w),style:{color:I.accent}}),s(m,{className:f(D.b2,"font-semibold leading-relaxed text-sm",C),style:{color:I.text},html:M.limitMessage||""})]})),Q&&s(v,Object.assign({variant:"primary",className:"whitespace-nowrap min-h-[32px] w-full sm:w-auto text-sm",onClick:()=>e(void 0,void 0,void 0,(function*(){if(c()){if(!q)return F(Q||null),void L("login_required");window.open(Q)}else{const e=d({baseUrl:Q,redirectUrl:document.URL});e&&(window.location.href=e)}}))},{children:W}))]})),X&&o("div",Object.assign({className:"flex flex-col gap-2"},{children:[s("h3",Object.assign({className:"text-xs font-bold opacity-70 uppercase px-1",style:{color:I.text}},{children:(null==G?void 0:G["available-plans"])||"Available Plans"})),s("div",Object.assign({className:"flex flex-row gap-3 overflow-x-auto pb-4 pt-1 snap-x scrollbar-thin"},{children:null===(_=M.upgradeGroups)||void 0===_?void 0:_.map(((e,o)=>s(h,{data:e},e.accessGroupId||o)))}))]})),Z&&ee&&o("div",Object.assign({className:"flex flex-col gap-3"},{children:[o("h3",Object.assign({className:"text-xs font-bold opacity-70 uppercase px-1",style:{color:I.text}},{children:[(null==G?void 0:G.buy)||"Buy"," ",J?(null==G?void 0:G.credits)||"Credits":(null==G?void 0:G.uses)||"Uses"]})),s("div",Object.assign({className:"flex flex-row gap-3 overflow-x-auto pb-2 pt-1 snap-x scrollbar-thin"},{children:null==Y?void 0:Y.map(((e,o)=>s(j,{price:e.price,uses:e.uses,isCredits:J,costPerRun:V||void 0,isSelected:o===E,onClick:()=>H(o),colors:I},o)))})),o(v,Object.assign({variant:"primary",className:"w-full py-3 text-sm font-bold shadow-md",onClick:()=>e(void 0,void 0,void 0,(function*(){var s,o;if(q)s=ee.uses,o=ee.price,e(void 0,void 0,void 0,(function*(){try{const e=yield x.post("/get_extra_usage_payment_link",{data:{sender:P||void 0,studioSessionToken:q,studioId:null==R?void 0:R.studioid,cost:o,isEmbed:c(),extraUses:s,successUrl:document.URL}}),{success:i,url:t,clientSecret:r,stripeAccountId:l,error:a}=e.data;i?c()?r&&l?(B(l),T(r),L("stripe_checkout")):t&&window.open(t,"_blank"):t&&(window.location.href=t):alert(a)}catch(e){alert(e)}}));else if(c())F(Q||null),L("login_required");else{const e=d({baseUrl:Q,redirectUrl:document.URL});e&&(window.location.href=e)}}))},{children:[(null==G?void 0:G.buy)||"Buy"," ",ee.uses.toLocaleString()," ",J?(null==G?void 0:G.credits)||"Credits":(null==G?void 0:G.uses)||"Uses"," ","for ",K,ee.price]}))]}))]}))}):null};export{k as default};
@@ -3,6 +3,13 @@ export declare const COOKIE_USER_ID = "PXE-uid";
3
3
  export declare const generateId: (length: number, prefix?: string, suffix?: string) => string;
4
4
  export declare const randomStr: (len: number, charOnly?: boolean) => string;
5
5
  export declare const extractUrlsFromText: (text: string) => string[];
6
+ type BuildUpgradeUrlOptions = {
7
+ baseUrl?: string | null;
8
+ redirectUrl?: string;
9
+ accessGroupId?: string;
10
+ currentUrl?: string;
11
+ };
12
+ export declare const buildUpgradeUrl: ({ baseUrl, redirectUrl, accessGroupId, currentUrl, }: BuildUpgradeUrlOptions) => string | null;
6
13
  export declare const formatBytes: (bytes: number, decimals?: number) => string;
7
14
  export declare const getCookie: (name: string) => string | null;
8
15
  export declare const deleteCookie: (name: string) => void;
@@ -13,3 +20,4 @@ export declare const deleteAuthToken: (name: string) => void;
13
20
  export declare function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): (node: T) => void;
14
21
  export declare const isInIframe: () => boolean;
15
22
  export declare const safeJSONParse: <T>(str: string) => T | null;
23
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pickaxeproject/react",
3
- "version": "6.3.2",
3
+ "version": "6.3.4",
4
4
  "description": "Client utility library for Pickaxe",
5
5
  "repository": {
6
6
  "type": "git",