@pickaxeproject/react 6.5.1 → 6.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/cjs/components/Pickaxe/Addons/Document/hooks/useDocument.js +1 -1
  2. package/dist/cjs/components/Pickaxe/Chat/Input.js +1 -1
  3. package/dist/cjs/components/Pickaxe/Chat/index.js +1 -1
  4. package/dist/cjs/components/Pickaxe/Form/Questions/Submit.js +1 -1
  5. package/dist/cjs/components/Pickaxe/Provider.js +1 -1
  6. package/dist/cjs/components/Pickaxe/common/AccessGroupCardPreview.js +1 -1
  7. package/dist/cjs/components/Pickaxe/common/PickaxeMarkdown/Renderer.js +1 -1
  8. package/dist/cjs/components/Pickaxe/common/PickaxeMarkdown/utils/custom-plugins.js +1 -1
  9. package/dist/cjs/node_modules/.pnpm/cose-base@1.0.3/node_modules/cose-base/cose-base.js +1 -1
  10. package/dist/cjs/node_modules/.pnpm/cose-base@2.2.0/node_modules/cose-base/cose-base.js +1 -1
  11. package/dist/cjs/node_modules/.pnpm/layout-base@1.0.2/node_modules/layout-base/layout-base.js +1 -1
  12. package/dist/cjs/node_modules/.pnpm/layout-base@2.0.1/node_modules/layout-base/layout-base.js +1 -1
  13. package/dist/cjs/src/components/Pickaxe/common/AccessGroupCardPreview.d.ts +15 -1
  14. package/dist/cjs/src/components/Pickaxe/common/PickaxeMarkdown/utils/custom-plugins.d.ts +7 -0
  15. package/dist/esm/components/Pickaxe/Addons/Document/hooks/useDocument.js +1 -1
  16. package/dist/esm/components/Pickaxe/Chat/Input.js +1 -1
  17. package/dist/esm/components/Pickaxe/Chat/index.js +1 -1
  18. package/dist/esm/components/Pickaxe/Form/Questions/Submit.js +1 -1
  19. package/dist/esm/components/Pickaxe/Provider.js +1 -1
  20. package/dist/esm/components/Pickaxe/common/AccessGroupCardPreview.js +1 -1
  21. package/dist/esm/components/Pickaxe/common/PickaxeMarkdown/Renderer.js +1 -1
  22. package/dist/esm/components/Pickaxe/common/PickaxeMarkdown/utils/custom-plugins.js +1 -1
  23. package/dist/esm/node_modules/.pnpm/cose-base@1.0.3/node_modules/cose-base/cose-base.js +1 -1
  24. package/dist/esm/node_modules/.pnpm/cose-base@2.2.0/node_modules/cose-base/cose-base.js +1 -1
  25. package/dist/esm/node_modules/.pnpm/layout-base@1.0.2/node_modules/layout-base/layout-base.js +1 -1
  26. package/dist/esm/node_modules/.pnpm/layout-base@2.0.1/node_modules/layout-base/layout-base.js +1 -1
  27. package/dist/esm/src/components/Pickaxe/common/AccessGroupCardPreview.d.ts +15 -1
  28. package/dist/esm/src/components/Pickaxe/common/PickaxeMarkdown/utils/custom-plugins.d.ts +7 -0
  29. package/package.json +1 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../../../_virtual/_tslib.js"),t=require("../../../../../hooks/pickaxe/usePickaxeContext.js"),s=require("../../Auth/hooks/useAuthContext.js"),i=require("../../../../../hooks/pickaxe/useSubmitDocument.js"),n=require("./useDocumentContext.js"),o=require("../../../../../common/documents.js"),r=require("uuid"),d=require("../../../../../common/error.js");exports.useDocument=({onQuestionChange:a}={})=>{const{contextId:u,pickaxeId:l,sessionId:c,sender:m,senderType:p,pickaxe:f,translations:w}=t.usePickaxeContext(),{token:b}=s.useAuthContext(),I=n.useDocumentContext(),v=i.useSubmitDocument(),h=e=>{const t=[...o.allowedFileMimeTypes,...o.allowedImageMimeTypes];if(e.some((e=>{var s;if(t.includes(e.type))return!1;if(""===e.type){const t=null===(s=e.name.split(".").pop())||void 0===s?void 0:s.toLowerCase();if(t&&o.additionalAllowedFileExtensions.includes(`.${t}`))return!1}return!0}))){const e=(null==w?void 0:w["invalid-upload-file-types"])||"You can only upload PDF, TXT, DOCX, CSV, XLSX, JSON, PPTX, MD, XML, PNG, JPEG, WEBP, or GIF files. Please try again.",t=new Error(e),s=d.default(t);return I.setDocumentError(s),!0}return!1};return Object.assign(Object.assign({},I),{onFileUpload:t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(I.setDocumentError(""),!t.length)return null;if(h(t))return null;I.setIsUploading(!0),I.setIsShowList(!0);const s=t.map((e=>({file:e,id:r.v4()})));s.forEach((({file:e,id:t})=>{I.addDocument({type:"document",id:t,size:e.size,name:e.name,status:"uploading"})}));const i=s.map((({file:t,id:s})=>e.__awaiter(void 0,void 0,void 0,(function*(){try{const{success:e,documentId:i,folder:n,error:r}=yield v.document(Object.assign(Object.assign(Object.assign({contextId:u,pickaxeId:l,sessionId:c,file:t},(null==f?void 0:f.workspaceid)&&{workspaceId:f.workspaceid}),"STUDIO_USER"===p&&{studioUserId:m}),b&&{studioSessionToken:b}));if(!e)throw new Error(r||(null==w?void 0:w["document-processing-failed"])||"Document processing failed");null==a||a({input:t.name,documentId:i});const d=i.startsWith("IMAGE-")||o.allowedImageMimeTypes.includes(t.type);return I.editDocument(Object.assign({id:s,type:d?"image":"document",name:t.name,size:t.size,status:"finished",documentId:i},d&&n&&{folder:n})),{name:t.name,documentId:i}}catch(e){const i=d.default(e);return I.editDocument({id:s,name:t.name,size:t.size,status:"failed",error:i}),{error:i}}}))));yield Promise.allSettled(i),I.setIsUploading(!1)})),onWebsiteUpload:t=>e.__awaiter(void 0,void 0,void 0,(function*(){I.setDocumentError("");let e=t.trim();if(!e)return null;e.startsWith("http://")&&(e=e.replace("http://","https://")),e.startsWith("https://")||(e=`https://${e}`);try{if(!e.includes("."))throw new Error((null==w?void 0:w["invalid-website-or-youtube-link"])||"Please paste a valid website URL or Youtube video link to add to the knowledge base.");I.setIsUploading(!0),I.setIsShowList(!0),I.setWebsiteLink(""),I.setDocuments([{type:"website",id:e,size:0,name:e,status:"uploading"}]);const t=yield v.website(Object.assign(Object.assign(Object.assign({pickaxeId:l,sessionId:c,website:e},(null==f?void 0:f.workspaceid)&&{workspaceId:f.workspaceid}),"STUDIO_USER"===p&&{studioUserId:m}),b&&{studioSessionToken:b})),{success:s,documentId:i}=t;if(!s)throw new Error((null==w?void 0:w["website-processing-failed"])||"Website processing failed, please try again.");I.setDocuments([{type:"website",id:e,size:0,name:e,status:"finished",documentId:i}]);return{type:"website",id:e,name:e,size:0,status:"finished",documentId:i}}catch(t){const s=d.default(t);if(s.includes((null==w?void 0:w["invalid-website-url"])||"Please paste a valid website URL"))return I.setDocumentError(s),null;I.editDocument({type:"website",id:e,size:0,name:e,status:"failed",error:s});return{type:"website",id:e,size:0,name:e,status:"failed",error:s}}finally{I.setIsUploading(!1)}}))})};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../../../_virtual/_tslib.js"),t=require("../../../../../hooks/pickaxe/usePickaxeContext.js"),s=require("../../Auth/hooks/useAuthContext.js"),i=require("../../../../../hooks/pickaxe/useSubmitDocument.js"),o=require("./useDocumentContext.js"),n=require("../../../../../common/documents.js"),r=require("uuid"),d=require("../../../../../common/error.js");exports.useDocument=({onQuestionChange:u}={})=>{var a,l;const{contextId:c,pickaxeId:p,sessionId:m,sender:f,senderType:w,pickaxe:v,translations:b}=t.usePickaxeContext(),{token:I}=s.useAuthContext(),h=o.useDocumentContext(),g=i.useSubmitDocument(),y=null!==(l=null===(a=null==v?void 0:v.documentuploadtype)||void 0===a?void 0:a.startsWith("enduserupload"))&&void 0!==l&&l,k=(null==b?void 0:b["file-upload-disabled"])||"File uploads are disabled for this Pickaxe.",D=e=>{const t=[...n.allowedFileMimeTypes,...n.allowedImageMimeTypes],s=e.some((e=>{var s;if(t.includes(e.type))return!1;if(""===e.type){const t=null===(s=e.name.split(".").pop())||void 0===s?void 0:s.toLowerCase();if(t&&n.additionalAllowedFileExtensions.includes(`.${t}`))return!1}return!0}));if(s){const e=(null==b?void 0:b["invalid-upload-file-types"])||"You can only upload PDF, TXT, DOCX, CSV, XLSX, JSON, PPTX, MD, XML, PNG, JPEG, WEBP, or GIF files. Please try again.",t=new Error(e),s=d.default(t);return h.setDocumentError(s),!0}return!1};return Object.assign(Object.assign({},h),{onFileUpload:t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(h.setDocumentError(""),!t.length)return null;if(!y)return h.setDocumentError(k),null;if(D(t))return null;h.setIsUploading(!0),h.setIsShowList(!0);const s=t.map((e=>({file:e,id:r.v4()})));s.forEach((({file:e,id:t})=>{h.addDocument({type:"document",id:t,size:e.size,name:e.name,status:"uploading"})}));const i=s.map((({file:t,id:s})=>e.__awaiter(void 0,void 0,void 0,(function*(){try{const{success:e,documentId:i,folder:o,error:r}=yield g.document(Object.assign(Object.assign(Object.assign({contextId:c,pickaxeId:p,sessionId:m,file:t},(null==v?void 0:v.workspaceid)&&{workspaceId:v.workspaceid}),"STUDIO_USER"===w&&{studioUserId:f}),I&&{studioSessionToken:I}));if(!e)throw new Error(r||(null==b?void 0:b["document-processing-failed"])||"Document processing failed");null==u||u({input:t.name,documentId:i});const d=i.startsWith("IMAGE-")||n.allowedImageMimeTypes.includes(t.type);return h.editDocument(Object.assign({id:s,type:d?"image":"document",name:t.name,size:t.size,status:"finished",documentId:i},d&&o&&{folder:o})),{name:t.name,documentId:i}}catch(e){const i=d.default(e);return h.editDocument({id:s,name:t.name,size:t.size,status:"failed",error:i}),{error:i}}}))));yield Promise.allSettled(i),h.setIsUploading(!1)})),onWebsiteUpload:t=>e.__awaiter(void 0,void 0,void 0,(function*(){h.setDocumentError("");let e=t.trim();if(!e)return null;if(!y)return h.setDocumentError(k),null;e.startsWith("http://")&&(e=e.replace("http://","https://")),e.startsWith("https://")||(e=`https://${e}`);try{if(!e.includes("."))throw new Error((null==b?void 0:b["invalid-website-or-youtube-link"])||"Please paste a valid website URL or Youtube video link to add to the knowledge base.");h.setIsUploading(!0),h.setIsShowList(!0),h.setWebsiteLink(""),h.setDocuments([{type:"website",id:e,size:0,name:e,status:"uploading"}]);const t=yield g.website(Object.assign(Object.assign(Object.assign({pickaxeId:p,sessionId:m,website:e},(null==v?void 0:v.workspaceid)&&{workspaceId:v.workspaceid}),"STUDIO_USER"===w&&{studioUserId:f}),I&&{studioSessionToken:I})),{success:s,documentId:i}=t;if(!s)throw new Error((null==b?void 0:b["website-processing-failed"])||"Website processing failed, please try again.");h.setDocuments([{type:"website",id:e,size:0,name:e,status:"finished",documentId:i}]);return{type:"website",id:e,name:e,size:0,status:"finished",documentId:i}}catch(t){const s=d.default(t);if(s.includes((null==b?void 0:b["invalid-website-url"])||"Please paste a valid website URL"))return h.setDocumentError(s),null;h.editDocument({type:"website",id:e,size:0,name:e,status:"failed",error:s});return{type:"website",id:e,size:0,name:e,status:"failed",error:s}}finally{h.setIsUploading(!1)}}))})};
@@ -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"),d=require("../Addons/Auth/hooks/useAuthContext.js"),c=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),m=require("../../../hooks/core/useHover.js"),f=require("../../../hooks/core/useMediaQuery.js"),g=require("../../../common/documents.js"),h=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"),I=require("../Addons/Document/List.js"),j=require("../../Core/Textarea.js"),w=require("../../Core/ErrorAlert.js"),O=require("../../../common/error.js"),N=require("../../../common/api/pickaxe.js"),S=require("../../../common/validation.js"),k=require("../../../common/cn.js"),_=require("../../../common/utils.js"),U=require("../../../common/pickaxeConfig.js"),C=require("../../../common/deploymentWebhooks.js"),E=require("../../../hooks/studio/useStudio.js"),T=require("../../../hooks/pickaxe/useSpeech.js"),A=require("../common/PickaxeCommon.js");const D=e=>"string"==typeof e&&e.trim().length>0,L=(e,t)=>{if(e&&"object"==typeof e)return e[t]},P=(e,t)=>{const s=L(e,t);return D(s)?s:null},q=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},R=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const o=Array.isArray(L(e,"uses"))?L(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>D(e)?{type:"deployment",id:e}:D(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:s});if(!r)return{scope:r,record:null};const a=null!==(i=null!==(n=o.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==n?n:o.find((e=>e.id===r.id)))&&void 0!==i?i:null;return{scope:r,record:a}},M=s.forwardRef((({resubmitPrompt:L,onFocus:M,onBlur:F,onInputHeightChange:V,initSmitheryAuthData:H},W)=>{var $,B,X,Y,K,z,J,G,Q;const{origin:Z,pickaxeId:ee,sessionId:te,sender:se,senderType:ne,portalId:ie,deploymentId:oe,deploymentType:re,pickaxe:ae,styles:le,colors:de,translations:ce,locale:ue,forceMobile:pe,isNewChat:me,isRtl:fe,isShowFeedbackMessage:ge,accessGroup:he,setIsNewChat:ve,setIsShowIceBreaker:be,setValidationStatus:xe,setValidationUpgradeGroups:ye,setValidationUpgradeUrl:Ie,onGenerateComplete:je}=n.usePickaxeContext(),{token:we,isLoggedOut:Oe,isSent:Ne,isPricingAuth:Se}=d.useAuthContext(),{messages:ke,isGenerating:_e,setMessages:Ue,setStatus:Ce,setLimitData:Ee,setError:Te}=i.useResponseContext(),{documents:Ae,isUploading:De,documentError:Le,onFileUpload:Pe,setDocuments:qe,setDocumentError:Re}=c.useDocument(),{studio:Me}=E.useStudio(),{scrollStartSession:Fe,scrollEndSession:Ve,scrollToBottom:He}=u.useScroll({auto:!0}),{artifacts:We,currentPopupType:$e,setArtifacts:Be,setCurrentArtifact:Xe}=p.useArtifactContext(),{height:Ye}=l.useDimensionContext(),Ke=a.useConversation(),[ze,Je]=s.useState(""),[Ge,Qe]=s.useState(!1),[Ze,et]=s.useState(!1),[tt,st]=s.useState(null),[nt,it]=s.useState(null),[ot,rt]=s.useState(!1),[at,lt]=s.useState(!1),[dt,ct]=s.useState(0),ut=s.useRef(null),pt=s.useRef(""),mt=s.useRef(null),ft=s.useRef(null),gt=s.useRef(null),ht=s.useRef(null),vt=s.useRef(null),bt=s.useRef(new Set),xt=s.useRef(null),yt=Math.max(.4*Ye,100),{speechTranscript:It,isSpeechListening:jt,isSpeechProcessing:wt,isSpeechSupported:Ot,onStartListening:Nt,onStopListening:St}=T.useSpeech(),[kt]=f.useMediaQuery("(max-width: 480px)"),_t=m.useHover(),{isHover:Ut}=_t,Ct=e.__rest(_t,["isHover"]),Et=m.useHover(),{isHover:Tt}=Et,At=e.__rest(Et,["isHover"]),Dt=m.useHover(),{isHover:Lt}=Dt,Pt=e.__rest(Dt,["isHover"]),qt=r.useStyleFontSize(),Rt=o.useStyleInput(),Mt="undefined"!=typeof window?window.location.hostname:"",Ft="undefined"!=typeof window?window.location.href:"",Vt="undefined"!=typeof window&&window.self!==window.top,Ht=Mt.includes("pickaxe.co")&&!Ft.includes("https://studio.pickaxe.co/_embed")&&!Vt,Wt=null===($=null==ae?void 0:ae.documentuploadtype)||void 0===$?void 0:$.startsWith("enduserupload"),$t=Ot&&(null==ae?void 0:ae.enablevoicetotext),Bt=D(oe),Xt="chat-input"===re&&me&&!Ne,Yt="chat-input"===re&&Se&&Oe&&Ne,Kt=s.useCallback((e=>{const t=S.getValidationFailure(e);return!!t&&(Te(""),Ee(null),xe(t.status),ye(t.upgradeGroups),Ie(t.upgradeUrl),!0)}),[Te,Ee,xe,ye,Ie]),zt=null!==(B=null==ae?void 0:ae.placeholdertext)&&void 0!==B?B:fe?"بماذا تريد أن تتحدث؟":(null==ce?void 0:ce["what-do-you-want-to-talk-about"])||"What do you want to talk about?",Jt=Ge||Ze,Gt=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){rt(!1);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==ae?void 0:ae.studioid},se&&{sender:se}),we&&{studioSessionToken:we}),!we&&!se&&{sender:_.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}})),Ht&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(st(t.studioUser),it(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{rt(!0)}}))),[Z,ee,te,ne,se,we,ie,oe,Ht]);s.useEffect((()=>{Gt()}),[Gt]);const Qt=Number(null!==(X=null==he?void 0:he.limit)&&void 0!==X?X:0),Zt="string"==typeof(null==he?void 0:he.limitInterval)?he.limitInterval:null,es=!!(null==Me?void 0:Me.data.usage)&&Me.data.usage.isCredits,ts=s.useMemo((()=>R({studioUser:tt,deploymentId:oe,portalId:ie})),[oe,ie,tt]);s.useEffect((()=>{Bt&&me&&te&&bt.current.add(te)}),[me,te,Bt]);const ss=s.useCallback((()=>{var e,t,s;return{studioId:null==ae?void 0:ae.studioid,userEmail:P(tt,"email"),userId:null!==(e=P(tt,"userId"))&&void 0!==e?e:P(tt,"userid"),sessionId:te,deploymentId:oe,deploymentType:re,portalId:ie,accessGroupId:null!==(t=null==he?void 0:he.accessGroupId)&&void 0!==t?t:null,pickaxeId:ee,sender:se,senderType:ne,origin:Z,metadata:null!==(s=U.getPickaxeConfigMetadata(oe))&&void 0!==s?s:null}}),[null==he?void 0:he.accessGroupId,oe,re,Z,null==ae?void 0:ae.studioid,ee,ie,se,ne,te,tt]),ns=s.useCallback((()=>!!(Bt&&ot&&te)&&(!!bt.current.has(te)&&(C.fireDeploymentSessionInitializedWebhook(ss()),bt.current.delete(te),!0))),[ss,ot,te,Bt]);s.useEffect((()=>{if(!ot||!te)return;ns();const e=xt.current;(null==e?void 0:e.sessionId)===te&&(C.fireDeploymentFirstMessageSubmittedWebhook(Object.assign(Object.assign(Object.assign({},e),ss()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),xt.current=null)}),[ns,ss,ot,te]);const is={currentUses:q(null==tt?void 0:tt.currentUses),extraUses:q(null==tt?void 0:tt.extraUses)},os=ts.scope?{currentUses:null!==(K=q(null===(Y=ts.record)||void 0===Y?void 0:Y.currentUses))&&void 0!==K?K:0,extraUses:null!==(J=q(null===(z=ts.record)||void 0===z?void 0:z.extraUses))&&void 0!==J?J:0}:{currentUses:0,extraUses:0},rs=Oe?os:is;s.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(es&&(null===(e=null==Me?void 0:Me.data)||void 0===e?void 0:e.workspaceId))try{const e=yield N.default.get(`/cost_per_run?workspaceId=${Me.data.workspaceId}`,{withCredentials:!1});t&&ct(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&ct(0)}else t&&ct(0)})),()=>{t=!1}}),[es,null===(G=null==Me?void 0:Me.data)||void 0===G?void 0:G.workspaceId]);const as=(({currentUses:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=e?e:0),o=Number(null!=t?t:0);return s===A.STUDIO_INFINITY_VALUE||o===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,o-i):Math.max(0,s-i)+o})({currentUses:rs.currentUses,extraUses:rs.extraUses,limit:Qt,limitInterval:Zt}),ls=as===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(as)),ds=(({extraUses:e,limit:t,limitInterval:s})=>{const n=Number(null!=e?e:0);return t===A.STUDIO_INFINITY_VALUE||n===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:"one_time"===s?Math.max(0,n):Math.max(0,t)+Math.max(0,n)})({extraUses:rs.extraUses,limit:Qt,limitInterval:Zt}),cs=ds===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.ceil(.05*ds),us=es?Math.ceil(5*dt):5,ps=cs===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.max(cs,us);console.log("Usage and Limits Debug:",{remaining:ls,notificationThreshold:ps,studioUser:tt});const ms=s.useMemo((()=>!!tt&&(!at&&(ls!==A.STUDIO_INFINITY_VALUE&&(!(ls<=0)&&ls<=ps)))),[at,ps,ls,tt]),fs=s.useMemo((()=>{var e,t,s;return!!me&&(!!ae&&(!Ke.isLoading&&(!((null!==(t=null===(e=Ke.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=ae.icebreakers)||void 0===s?void 0:s.length)&&(!ge&&!Xt)))))}),[ae,me,ge,Xt,Ke.data,Ke.isLoading]),gs=s.useMemo((()=>{if(_e||De)return!1;const e=Ae.length>0&&Ae.every((e=>"finished"===e.status));return!(!ze.trim()&&!e)&&Ae.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[_e,De,ze,Ae]);s.useImperativeHandle(W,(()=>({onSubmit:hs}))),s.useEffect((()=>{be(fs)}),[fs]),s.useEffect((()=>{var e;if(L){const t=Array.from(ke),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;hs(s,!0)}}),[L]),s.useEffect((()=>{if(!ht.current||!V)return;const e=new ResizeObserver((e=>{for(const t of e)V(t.contentRect.height)}));return e.observe(ht.current),()=>{e.disconnect()}}),[V]),s.useEffect((()=>{if(!jt)return;const e=pt.current?`${pt.current} `:"";Je(`${e}${It}`)}),[It,jt]),s.useEffect((()=>{if(!ft.current)return;(()=>{if(!ft.current)return;let e=ft.current.scrollHeight>52;ze.includes("\n")||Ae.length?e=!0:ze.trim()||(e=!1),Qe(e)})()}),[ze,Ae]),s.useEffect((()=>{const e=ft.current,t=gt.current;if(!e||!t||Ge||ze.includes("\n"))return void et(!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=ze||zt,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;et(o>l)}),[ze,Ge,zt]);const hs=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i;try{if(_e||De)return;const o=Ae.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,d=null!=t?t:ze;if(!d&&!l)return;Te(""),Re(""),Ee(null),Je(""),ve(!1),Ce("fetching"),Fe(),He();const c=null!==(n=null===(e=null==ae?void 0:ae.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&r.length>0,u=[...s?Array.from(ke.slice(0,ke.length-1)):Array.from(ke),...s?[]:[{id:ke.length+1,role:"user",parts:[{type:"text",content:d,isVisible:!0}],documentIds:c?r:[]}],{id:ke.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];Ue(u),He(),c&&qe([]);const p=U.getPickaxeConfigMetadata(oe),m=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(Object.assign({origin:Z,pickaxeId:ee,sessionId:te,senderType:ne,value:d},c&&{documentIds:r}),se&&{sender:se}),we&&{studioSessionToken:we}),!we&&!se&&{sender:_.initializeEmbedUserId()}),ie&&{portalId:ie}),oe&&{deploymentId:oe}),p&&{metadata:p}),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()})},Ht&&{credentials:"include"})),f=yield m.json();if(!f.success){if(Kt(f))return;const e=new Error(f.error||f.message||(null==ce?void 0:ce["failed-to-start-generation"])||"Failed to start generation");throw f.limitData&&(e.limitData=f.limitData),e}const g=f.submissionId;Bt&&me&&te&&bt.current.add(te);const v=Object.assign(Object.assign({},ss()),{message:d,documentIds:c?r:[],uploadedModelImages:a,hasUploadedDocuments:c,isHidden:s,metadata:null!=p?p:null});ot?(ns(),C.fireDeploymentFirstMessageSubmittedWebhook(v)):xt.current=v,Ce("streaming"),vt.current=new AbortController;const b=u.length-1,x=[];let y=[...null!=We?We:[]],I=0,j=!1,w="";for(;!j;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${g}?index=${I}`,{signal:null===(i=vt.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();mt.current=t;const s=new TextDecoder,n=h.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&I++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==ce?void 0:ce["something-went-wrong"])||"Something went wrong.";return Kt(t)||Te(s),void(j=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&H){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 j=!0,H({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 j=!0,H({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)w="",x.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)w+=n.delta,x[x.length-1].content=w;else if("text-end"===n.type)w="";else if("reasoning-start"===n.type)w="",x.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)w+=n.delta,x[x.length-1].content=w;else if("reasoning-end"===n.type)w="";else if(n.type.startsWith("data-")){const e=n;x.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Ue([...u.slice(0,b),Object.assign(Object.assign({},u[u.length-1]),{id:ke.length+1,role:"assistant",parts:x})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);y=y.filter((e=>!(e.id===t.id&&e.version===t.version))),y.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Be([...y]),$e.startsWith("inline")||Xe({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);y=y.filter((e=>!(e.id===t.id&&e.version===t.version))),y.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Be(y),$e.startsWith("inline")||Xe({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);y=y.filter((e=>!(e.id===t.id&&e.version===t.version))),y.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Be(y),$e.startsWith("inline")||Xe({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");y=y.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Be(y)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Be(y.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==ce?void 0:ce["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Kt(t))return void(j=!0);Te(s)}else"stop"===e.event&&(j=!0)}else j=!0}});for(;;){const{value:e,done:i}=yield t.read();if(i)break;n.feed(s.decode(e))}j||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||"AbortError"===e.name)return void(j=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==je||je(te)}catch(e){if(e.limitData)Ee(e.limitData),Te("");else{let t=O.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==ce?void 0:ce["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Kt(t)||Te(t)}}finally{He(),Ce("idle"),Ve(),mt.current=null,yield Gt()}}));return Yt?null:t.jsx("div",Object.assign({className:k.default("flex w-full flex-shrink-0 flex-col items-center",!Xt&&"px-4 pb-8"),dir:fe?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:ht,className:k.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===le.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Rt),{maxHeight:`${yt}px`,overflowY:"auto"})},{children:[ms&&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:Rt.backgroundColor?`${Rt.backgroundColor}E6`:void 0,borderColor:de.text+"20",color:de.text,borderTopRightRadius:le.cornerRadius+"px",borderTopLeftRadius:le.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[ls.toLocaleString()," ",es?(null==ce?void 0:ce.credits)||"Credits":(null==ce?void 0:ce.uses)||"Uses"," ",(null==ce?void 0:ce.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:de.accent,color:de.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=_.buildUpgradeUrl({baseUrl:nt,accessGroupId:null==he?void 0:he.accessGroupId});t&&(_.isInIframe()?window.open(t):location.href=t)}},{children:(null==ce?void 0:ce.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:()=>lt(!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"})}))}))]}))]})),!_e&&Ae.length>0&&t.jsx(I.default,{className:"p-4 pb-0",isDisabled:_e}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[jt&&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!==(Q=de.accent)&&void 0!==Q?Q:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:de.text+"90"}},{children:(null==ce?void 0:ce.listening)||"Listening..."}))]})),t.jsx(j.default,Object.assign({ref:ft,className:k.default(qt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!ze.trim()&&!ze.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",fe?"text-right":"text-left",Jt&&"mb-12",jt&&"text-transparent"),value:ze,placeholder:zt,onChange:e=>{Je(e)},onKeyDown:e=>{pe||kt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),De||_e||hs()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);e.length>0&&(t.preventDefault(),ve(!1),yield Pe(e))}))},M&&{onFocus:M},F&&{onBlur:F},{dir:fe?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:gt,className:k.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",Jt?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!Jt&&Rt.backgroundColor&&{backgroundColor:Rt.backgroundColor}),{borderTopRightRadius:le.cornerRadius+"px",borderBottomRightRadius:le.cornerRadius+"px"})},{children:_e?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:()=>{vt.current&&(vt.current.abort(),vt.current=null),mt.current&&(mt.current.cancel(),mt.current=null),Ce("idle")},style:{backgroundColor:de.accent,color:de.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):jt?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:St,style:{backgroundColor:de.accent,color:de.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Wt&&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:Tt?de.accent+"10":void 0,color:Tt?de.accent:de.accent+"80"},disabled:De||_e,onClick:()=>{var e;return null===(e=ut.current)||void 0===e?void 0:e.click()}},At,{children:[t.jsx("input",{id:"file-upload",ref:ut,type:"file",accept:[...g.allowedFileMimeTypes,...g.allowedImageMimeTypes,...g.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){ve(!1),yield Pe(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(v.default,{className:"h-6 w-6 shrink-0"})]})),$t&&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:jt?de.accent:Lt?de.accent+"10":void 0,color:jt?de.accentText:Lt?de.accent:de.accent+"80"},disabled:De||_e||wt,onClick:()=>{jt?St():(pt.current=ze,Nt(ue||"en-US"))}},Pt,{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:Ut||gs?de.accent:de.accent+"10",color:Ut||gs?de.accentText:de.accent+"80"},disabled:!gs,onClick:()=>hs()},Ct,{children:t.jsx(b.default,{className:k.default("h-6 w-6 shrink-0",fe&&"scale-x-[-1] transform")})}))]})}))]}))]})),Le&&t.jsx(w.default,{error:Le,className:"mt-3"})]}))}))}));M.displayName="Input",exports.default=M;
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"),r=require("../../../hooks/studio/useStyleInput.js"),o=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"),m=require("../../../hooks/core/useHover.js"),f=require("../../../hooks/core/useMediaQuery.js"),g=require("../../../common/documents.js"),h=require("eventsource-parser"),v=require("../../Icons/attach-vertical.svg.js"),b=require("../../Icons/arrow-right.svg.js"),I=require("../../Icons/microphone.svg.js"),y=require("../../Icons/stop.svg.js"),x=require("../Addons/Document/List.js"),j=require("../../Core/Textarea.js"),O=require("../../Core/ErrorAlert.js"),N=require("../../../common/error.js"),S=require("../../../common/api/pickaxe.js"),w=require("../../../common/validation.js"),_=require("../../../common/cn.js"),k=require("../../../common/utils.js"),E=require("../../../common/pickaxeConfig.js"),U=require("../../../common/deploymentWebhooks.js"),C=require("../../../hooks/studio/useStudio.js"),T=require("../../../hooks/pickaxe/useSpeech.js"),A=require("../common/PickaxeCommon.js");const D=e=>"string"==typeof e&&e.trim().length>0,P=e=>e.map((e=>Object.assign({},e))),L=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),R=(e,t)=>{if(e&&"object"==typeof e)return e[t]},q=(e,t)=>{const s=R(e,t);return D(s)?s:null},M=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},F=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const r=Array.isArray(R(e,"uses"))?R(e,"uses"):[],o=(({deploymentId:e,portalId:t})=>D(e)?{type:"deployment",id:e}:D(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:s});if(!o)return{scope:o,record:null};const a=null!==(i=null!==(n=r.find((e=>e.id===o.id&&e.type===o.type)))&&void 0!==n?n:r.find((e=>e.id===o.id)))&&void 0!==i?i:null;return{scope:o,record:a}},V=s.forwardRef((({resubmitPrompt:R,onFocus:V,onBlur:$,onInputHeightChange:B,initSmitheryAuthData:X},H)=>{var K,W,Y,J,z,G,Q,Z,ee,te;const{origin:se,pickaxeId:ne,sessionId:ie,sender:re,senderType:oe,portalId:ae,deploymentId:le,deploymentType:ce,pickaxe:de,styles:ue,colors:pe,translations:me,locale:fe,forceMobile:ge,isNewChat:he,isRtl:ve,isShowFeedbackMessage:be,accessGroup:Ie,setIsNewChat:ye,setIsShowIceBreaker:xe,setValidationStatus:je,setValidationUpgradeGroups:Oe,setValidationUpgradeUrl:Ne,onGenerateComplete:Se}=n.usePickaxeContext(),{token:we,isLoggedOut:_e,isSent:ke,isPricingAuth:Ee}=c.useAuthContext(),{messages:Ue,isGenerating:Ce,setMessages:Te,setStatus:Ae,setLimitData:De,setError:Pe}=i.useResponseContext(),{documents:Le,isUploading:Re,documentError:qe,onFileUpload:Me,setDocuments:Fe,setDocumentError:Ve}=d.useDocument(),{studio:$e}=C.useStudio(),{scrollStartSession:Be,scrollEndSession:Xe,scrollToBottom:He}=u.useScroll({auto:!0}),{artifacts:Ke,currentPopupType:We,setArtifacts:Ye,setCurrentArtifact:Je}=p.useArtifactContext(),{height:ze}=l.useDimensionContext(),Ge=a.useConversation(),[Qe,Ze]=s.useState(""),[et,tt]=s.useState(!1),[st,nt]=s.useState(!1),[it,rt]=s.useState(null),[ot,at]=s.useState(null),[lt,ct]=s.useState(!1),[dt,ut]=s.useState(!1),[pt,mt]=s.useState(0),ft=s.useRef(null),gt=s.useRef(""),ht=s.useRef(null),vt=s.useRef(null),bt=s.useRef(null),It=s.useRef([]),yt=s.useRef(null),xt=s.useRef(null),jt=s.useRef(null),Ot=s.useRef(null),Nt=s.useRef(new Set),St=s.useRef(null),wt=Math.max(.4*ze,100),{speechTranscript:_t,isSpeechListening:kt,isSpeechProcessing:Et,isSpeechSupported:Ut,onStartListening:Ct,onStopListening:Tt}=T.useSpeech(),[At]=f.useMediaQuery("(max-width: 480px)"),Dt=m.useHover(),{isHover:Pt}=Dt,Lt=e.__rest(Dt,["isHover"]),Rt=m.useHover(),{isHover:qt}=Rt,Mt=e.__rest(Rt,["isHover"]),Ft=m.useHover(),{isHover:Vt}=Ft,$t=e.__rest(Ft,["isHover"]),Bt=o.useStyleFontSize(),Xt=r.useStyleInput(),Ht="undefined"!=typeof window?window.location.hostname:"",Kt="undefined"!=typeof window?window.location.href:"",Wt="undefined"!=typeof window&&window.self!==window.top,Yt=Ht.includes("pickaxe.co")&&!Kt.includes("https://studio.pickaxe.co/_embed")&&!Wt,Jt=null!==(W=null===(K=null==de?void 0:de.documentuploadtype)||void 0===K?void 0:K.startsWith("enduserupload"))&&void 0!==W&&W,zt=Ut&&(null==de?void 0:de.enablevoicetotext),Gt=D(le),Qt="chat-input"===ce&&he&&!ke,Zt="chat-input"===ce&&Ee&&_e&&ke,es=s.useCallback((e=>{const t=w.getValidationFailure(e);return!!t&&(Pe(""),De(null),je(t.status),Oe(t.upgradeGroups),Ne(t.upgradeUrl),!0)}),[Pe,De,je,Oe,Ne]),ts=null!==(Y=null==de?void 0:de.placeholdertext)&&void 0!==Y?Y:ve?"بماذا تريد أن تتحدث؟":(null==me?void 0:me["what-do-you-want-to-talk-about"])||"What do you want to talk about?",ss=et||st,ns=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){ct(!1);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==de?void 0:de.studioid},re&&{sender:re}),we&&{studioSessionToken:we}),!we&&!re&&{sender:k.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}})),Yt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(rt(t.studioUser),at(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{ct(!0)}}))),[se,ne,ie,oe,re,we,ae,le,Yt]);s.useEffect((()=>{ns()}),[ns]);const is=Number(null!==(J=null==Ie?void 0:Ie.limit)&&void 0!==J?J:0),rs="string"==typeof(null==Ie?void 0:Ie.limitInterval)?Ie.limitInterval:null,os=!!(null==$e?void 0:$e.data.usage)&&$e.data.usage.isCredits,as=s.useMemo((()=>F({studioUser:it,deploymentId:le,portalId:ae})),[le,ae,it]);s.useEffect((()=>{Gt&&he&&ie&&Nt.current.add(ie)}),[he,ie,Gt]);const ls=s.useCallback((()=>{var e,t,s;return{studioId:null==de?void 0:de.studioid,userEmail:q(it,"email"),userId:null!==(e=q(it,"userId"))&&void 0!==e?e:q(it,"userid"),sessionId:ie,deploymentId:le,deploymentType:ce,portalId:ae,accessGroupId:null!==(t=null==Ie?void 0:Ie.accessGroupId)&&void 0!==t?t:null,pickaxeId:ne,sender:re,senderType:oe,origin:se,metadata:null!==(s=E.getPickaxeConfigMetadata(le))&&void 0!==s?s:null}}),[null==Ie?void 0:Ie.accessGroupId,le,ce,se,null==de?void 0:de.studioid,ne,ae,re,oe,ie,it]),cs=s.useCallback((()=>!!(Gt&&lt&&ie)&&(!!Nt.current.has(ie)&&(U.fireDeploymentSessionInitializedWebhook(ls()),Nt.current.delete(ie),!0))),[ls,lt,ie,Gt]);s.useEffect((()=>{if(!lt||!ie)return;cs();const e=St.current;(null==e?void 0:e.sessionId)===ie&&(U.fireDeploymentFirstMessageSubmittedWebhook(Object.assign(Object.assign(Object.assign({},e),ls()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),St.current=null)}),[cs,ls,lt,ie]);const ds={currentUses:M(null==it?void 0:it.currentUses),extraUses:M(null==it?void 0:it.extraUses)},us=as.scope?{currentUses:null!==(G=M(null===(z=as.record)||void 0===z?void 0:z.currentUses))&&void 0!==G?G:0,extraUses:null!==(Z=M(null===(Q=as.record)||void 0===Q?void 0:Q.extraUses))&&void 0!==Z?Z:0}:{currentUses:0,extraUses:0},ps=_e?us:ds;s.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(os&&(null===(e=null==$e?void 0:$e.data)||void 0===e?void 0:e.workspaceId))try{const e=yield S.default.get(`/cost_per_run?workspaceId=${$e.data.workspaceId}`,{withCredentials:!1});t&&mt(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&mt(0)}else t&&mt(0)})),()=>{t=!1}}),[os,null===(ee=null==$e?void 0:$e.data)||void 0===ee?void 0:ee.workspaceId]);const ms=(({currentUses:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=e?e:0),r=Number(null!=t?t:0);return s===A.STUDIO_INFINITY_VALUE||r===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,r-i):Math.max(0,s-i)+r})({currentUses:ps.currentUses,extraUses:ps.extraUses,limit:is,limitInterval:rs}),fs=ms===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(ms)),gs=(({extraUses:e,limit:t,limitInterval:s})=>{const n=Number(null!=e?e:0);return t===A.STUDIO_INFINITY_VALUE||n===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:"one_time"===s?Math.max(0,n):Math.max(0,t)+Math.max(0,n)})({extraUses:ps.extraUses,limit:is,limitInterval:rs}),hs=gs===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.ceil(.05*gs),vs=os?Math.ceil(5*pt):5,bs=hs===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.max(hs,vs);console.log("Usage and Limits Debug:",{remaining:fs,notificationThreshold:bs,studioUser:it});const Is=s.useMemo((()=>!!it&&(!dt&&(fs!==A.STUDIO_INFINITY_VALUE&&(!(fs<=0)&&fs<=bs)))),[dt,bs,fs,it]),ys=s.useMemo((()=>{var e,t,s;return!!he&&(!!de&&(!Ge.isLoading&&(!((null!==(t=null===(e=Ge.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=de.icebreakers)||void 0===s?void 0:s.length)&&(!be&&!Qt)))))}),[de,he,be,Qt,Ge.data,Ge.isLoading]),xs=s.useMemo((()=>{if(Ce||Re)return!1;const e=Jt&&Le.length>0&&Le.every((e=>"finished"===e.status));return!(!Qe.trim()&&!e)&&Le.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Jt,Ce,Re,Qe,Le]);s.useImperativeHandle(H,(()=>({onSubmit:js}))),s.useEffect((()=>{xe(ys)}),[ys]),s.useEffect((()=>{var e;if(R){const t=Array.from(Ue),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;js(s,!0)}}),[R]),s.useEffect((()=>{if(!jt.current||!B)return;const e=new ResizeObserver((e=>{for(const t of e)B(t.contentRect.height)}));return e.observe(jt.current),()=>{e.disconnect()}}),[B]),s.useEffect((()=>{if(!kt)return;const e=gt.current?`${gt.current} `:"";Ze(`${e}${_t}`)}),[_t,kt]),s.useEffect((()=>{if(!yt.current)return;(()=>{if(!yt.current)return;let e=yt.current.scrollHeight>52;Qe.includes("\n")||Le.length?e=!0:Qe.trim()||(e=!1),tt(e)})()}),[Qe,Le]),s.useEffect((()=>{const e=yt.current,t=xt.current;if(!e||!t||et||Qe.includes("\n"))return void nt(!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=Qe||ts,document.body.appendChild(i);const r=i.offsetWidth;i.remove();const o=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-o-a-t.offsetWidth;nt(r>l)}),[Qe,et,ts]);const js=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i,r;let o=null;try{if(Ce||Re)return;const a=Le.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),l=a.map((e=>e.documentId)).filter(Boolean),c=a.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),d=null!=t?t:Qe,u=null!==(n=null===(e=null==de?void 0:de.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&l.length>0;if(!d&&!u)return;Pe(""),Ve(""),De(null),Ze(""),ye(!1),Ae("fetching"),Be(),He();const p=[...s?Array.from(Ue.slice(0,Ue.length-1)):Array.from(Ue),...s?[]:[{id:Ue.length+1,role:"user",parts:[{type:"text",content:d,isVisible:!0}],documentIds:u?l:[]}],{id:Ue.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];Te(p),He(),u&&Fe([]);const m=E.getPickaxeConfigMetadata(le),f="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;o=f,vt.current=f,bt.current=null,It.current=[];const g=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(Object.assign({origin:se,pickaxeId:ne,sessionId:ie,submissionId:f,senderType:oe,value:d},u&&{documentIds:l}),re&&{sender:re}),we&&{studioSessionToken:we}),!we&&!re&&{sender:k.initializeEmbedUserId()}),ae&&{portalId:ae}),le&&{deploymentId:le}),m&&{metadata:m}),u&&c.length>0?{uploadedModelImages:c}:{})),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()})},Yt&&{credentials:"include"})),v=yield g.json();if(!v.success){if(es(v))return;const e=new Error(v.error||v.message||(null==me?void 0:me["failed-to-start-generation"])||"Failed to start generation");throw v.limitData&&(e.limitData=v.limitData),e}const b=null!==(i=v.submissionId)&&void 0!==i?i:f;o=b,vt.current=b;const I=()=>bt.current===b;if(I())return;Gt&&he&&ie&&Nt.current.add(ie);const y=Object.assign(Object.assign({},ls()),{message:d,documentIds:u?l:[],uploadedModelImages:u?c:[],hasUploadedDocuments:u,isHidden:s,metadata:null!=m?m:null});lt?(cs(),U.fireDeploymentFirstMessageSubmittedWebhook(y)):St.current=y,Ae("streaming"),Ot.current=new AbortController;const x=p.length-1,j=[];let O=[...null!=Ke?Ke:[]],N=0,S=!1,w="";for(;!S;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${b}?index=${N}`,{signal:null===(r=Ot.current)||void 0===r?void 0:r.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();ht.current=t;const s=new TextDecoder,n=h.createParser({onEvent:e=>{var t,s;if(I())S=!0;else if(e.event&&"ping"!==e.event&&N++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==me?void 0:me["something-went-wrong"])||"Something went wrong.";return es(t)||Pe(s),void(S=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&X){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 S=!0,X({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 S=!0,X({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)w="",j.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)w+=n.delta,j[j.length-1].content=w;else if("text-end"===n.type)w="";else if("reasoning-start"===n.type)w="",j.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)w+=n.delta,j[j.length-1].content=w;else if("reasoning-end"===n.type)w="";else if(n.type.startsWith("data-")){const e=n;j.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}It.current=P(j),Te([...p.slice(0,x),Object.assign(Object.assign({},p[p.length-1]),{id:Ue.length+1,role:"assistant",parts:j})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);O=O.filter((e=>!(e.id===t.id&&e.version===t.version))),O.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ye([...O]),We.startsWith("inline")||Je({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);O=O.filter((e=>!(e.id===t.id&&e.version===t.version))),O.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Ye(O),We.startsWith("inline")||Je({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);O=O.filter((e=>!(e.id===t.id&&e.version===t.version))),O.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ye(O),We.startsWith("inline")||Je({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");O=O.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Ye(O)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Ye(O.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==me?void 0:me["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(es(t))return void(S=!0);Pe(s)}else"stop"===e.event&&(S=!0)}else S=!0}});for(;;){if(I()){S=!0,t.cancel().catch((()=>{}));break}const{value:e,done:i}=yield t.read();if(I()){S=!0,t.cancel().catch((()=>{}));break}if(i)break;n.feed(s.decode(e))}S||I()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||L(e)||I())return void(S=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==Se||Se(ie)}catch(e){if(L(e))return;if(e.limitData)De(e.limitData),Pe("");else{let t=N.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==me?void 0:me["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),es(t)||Pe(t)}}finally{const e=!o||vt.current===o;He(),e&&(Ae("idle"),Xe(),ht.current=null),o&&e&&(vt.current=null,It.current=[]),yield ns()}}));return Zt?null:t.jsx("div",Object.assign({className:_.default("flex w-full flex-shrink-0 flex-col items-center",!Qt&&"px-4 pb-8"),dir:ve?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:jt,className:_.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===ue.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Xt),{maxHeight:`${wt}px`,overflowY:"auto"})},{children:[Is&&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:Xt.backgroundColor?`${Xt.backgroundColor}E6`:void 0,borderColor:pe.text+"20",color:pe.text,borderTopRightRadius:ue.cornerRadius+"px",borderTopLeftRadius:ue.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[fs.toLocaleString()," ",os?(null==me?void 0:me.credits)||"Credits":(null==me?void 0:me.uses)||"Uses"," ",(null==me?void 0:me.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:pe.accent,color:pe.accentText},onClick:e=>{e.preventDefault(),e.stopPropagation();const t=k.buildUpgradeUrl({baseUrl:ot,accessGroupId:null==Ie?void 0:Ie.accessGroupId});t&&(k.isInIframe()?window.open(t):location.href=t)}},{children:(null==me?void 0:me["pricing.upgrade"])||(null==me?void 0:me.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:()=>ut(!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"})}))}))]}))]})),!Ce&&Le.length>0&&t.jsx(x.default,{className:"p-4 pb-0",isDisabled:Ce}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[kt&&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!==(te=pe.accent)&&void 0!==te?te:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:pe.text+"90"}},{children:(null==me?void 0:me.listening)||"Listening..."}))]})),t.jsx(j.default,Object.assign({ref:yt,className:_.default(Bt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Qe.trim()&&!Qe.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ve?"text-right":"text-left",ss&&"mb-12",kt&&"text-transparent"),value:Qe,placeholder:ts,onChange:e=>{Ze(e)},onKeyDown:e=>{ge||At||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Re||Ce||js()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);if(e.length>0){if(!Jt)return;t.preventDefault(),ye(!1),yield Me(e)}}))},V&&{onFocus:V},$&&{onBlur:$},{dir:ve?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:xt,className:_.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",ss?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!ss&&Xt.backgroundColor&&{backgroundColor:Xt.backgroundColor}),{borderTopRightRadius:ue.cornerRadius+"px",borderBottomRightRadius:ue.cornerRadius+"px"})},{children:Ce?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:()=>{const t=vt.current;t&&(bt.current=t,(t=>{e.__awaiter(void 0,void 0,void 0,(function*(){if(!(t=null!=t?t:vt.current))return;const e=P(It.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/cancel/${t}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!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()}),body:JSON.stringify({outputMessageParts:e})},Yt&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(t)),Ot.current&&(Ot.current.abort(),Ot.current=null),ht.current&&(ht.current.cancel().catch((()=>{})),ht.current=null),Ae("idle")},style:{backgroundColor:pe.accent,color:pe.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):kt?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:Tt,style:{backgroundColor:pe.accent,color:pe.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Jt&&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:qt?pe.accent+"10":void 0,color:qt?pe.accent:pe.accent+"80"},disabled:Re||Ce,onClick:()=>{var e;return null===(e=ft.current)||void 0===e?void 0:e.click()}},Mt,{children:[t.jsx("input",{id:"file-upload",ref:ft,type:"file",accept:[...g.allowedFileMimeTypes,...g.allowedImageMimeTypes,...g.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){ye(!1),yield Me(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(v.default,{className:"h-6 w-6 shrink-0"})]})),zt&&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:kt?pe.accent:Vt?pe.accent+"10":void 0,color:kt?pe.accentText:Vt?pe.accent:pe.accent+"80"},disabled:Re||Ce||Et,onClick:()=>{kt?Tt():(gt.current=Qe,Ct(fe||"en-US"))}},$t,{children:t.jsx(I.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:Pt||xs?pe.accent:pe.accent+"10",color:Pt||xs?pe.accentText:pe.accent+"80"},disabled:!xs,onClick:()=>js()},Lt,{children:t.jsx(b.default,{className:_.default("h-6 w-6 shrink-0",ve&&"scale-x-[-1] transform")})}))]})}))]}))]})),qe&&t.jsx(O.default,{error:qe,className:"mt-3"})]}))}))}));V.displayName="Input",exports.default=V;
@@ -1 +1 @@
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"),i=require("../Addons/Auth/hooks/useAuthContext.js"),r=require("../../../hooks/pickaxe/useDimensionContext.js"),n=require("../Addons/Document/hooks/useDocument.js"),a=require("../Addons/Scroll/hooks/useScrollContext.js"),l=require("../../../hooks/studio/useStyleFontSize.js"),u=require("../../../hooks/core/useScrollToBottomVisibility.js"),c=require("./History/index.js"),d=require("./Input.js"),f=require("../../Icons/attach-vertical.svg.js"),h=require("../../../common/cn.js"),m=require("../../../common/api/pickaxe.js"),p=require("uuid"),v=require("../../Core/StudioTip.js"),x=require("../common/ScrollToBottomButton.js"),j=require("../../../hooks/pickaxe/useResponseContext.js"),g=require("../Addons/Navbar/NavPill.js"),b=require("../../Icons/history.svg.js");exports.default=()=>{const{deploymentType:k,isNewChat:y,setIsNewChat:S,sessionId:w,setSessionId:C,setLastSessionId:q,pickaxeId:I,sender:D,pickaxe:_,styles:N,isEmbed:P,translations:T}=s.usePickaxeContext(),{isSent:A}=i.useAuthContext(),{width:F,height:E,setDimension:O}=r.useDimensionContext(),{setDocuments:R,onFileUpload:H}=n.useDocument(),{scrollContainerRef:z,isLocked:B,setIsLocked:L}=a.useScrollContext(),{isGenerating:G,messages:V}=j.useResponseContext(),M=l.useStyleFontSize(),[U,J]=o.useState(0),[K,Q]=o.useState(!1),[W,X]=o.useState(!1),Y=o.useRef(null),Z=o.useRef(null),$=o.useRef(0),[ee,te]=o.useState(null),[oe,se]=o.useState(!1),ie=(null==T?void 0:T["new-chat"])||"New chat",re="chat-input"===k&&y&&!A,{hasScrollableContent:ne,isNearBottom:ae}=u.default(z);o.useEffect((()=>()=>{R([])}),[]);const le=o.useCallback((()=>{if(!I||!D)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:D});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()}),[I,D,w]);o.useEffect((()=>{G||y||!w||le()}),[G,y,w,le]),o.useEffect((()=>{if(!Y.current)return;const e=new ResizeObserver((e=>{for(const t of e){const{width:e,height:o}=t.contentRect;O(parseInt(e.toFixed(0)),parseInt(o.toFixed(0)))}}));return e.observe(Y.current),()=>{e.disconnect()}}),[O]);const[ue,ce]=o.useState(ie),de=(null==_?void 0:_.formtitle)||"Pickaxe",fe=(null==_?void 0:_.coverphoto)||void 0,[he,me]=o.useState(!1);o.useEffect((()=>{const e=!re&&!P&&N.portalTheme&&(V.filter((e=>"user"===e.role)).length>0||K||!y);me(null!=e&&e)}),[re,P,K,y,V,N.portalTheme]);const pe=o.useCallback((()=>{z.current&&(L(!0),z.current.scrollTo({top:z.current.scrollHeight,behavior:"smooth"}))}),[z,L]);return t.jsxs("div",Object.assign({ref:Y,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),$.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&X(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),$.current-=1,0===$.current&&X(!1)},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e.__awaiter(void 0,void 0,void 0,(function*(){t.preventDefault(),t.stopPropagation(),X(!1),$.current=0;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(S(!1),yield H(e))}))},{children:[W&&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(f.default,{className:"h-10 w-10"})})),t.jsx("h3",Object.assign({className:h.default(M.h3,"mt-6 font-semibold text-c-primary text-black")},{children:(null==T?void 0:T["drop-files-to-upload"])||"Drop files to upload"})),t.jsx("p",Object.assign({className:h.default(M.b2,"mt-2 opacity-60 text-black")},{children:(null==T?void 0:T["add-anything-to-the-conversation"])||"Add anything to the conversation"}))]})),re?t.jsx(d.default,{}):t.jsxs(t.Fragment,{children:[he&&t.jsxs("div",Object.assign({className:h.default("direct-link"===k?"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"===N.portalTheme?"glass-dark ":"")},{children:[t.jsx(g.NavPill,{text:de,icon:fe}),y||ue===ie?t.jsx(g.NavPill,{text:ue}):t.jsx(g.EditableNavPill,{text:ue,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:D}),ce(t)}catch(e){console.error("Error renaming chat:",e),alert((null==T?void 0:T["failed-rename-chat"])||"Failed to rename chat.")}})),onDelete:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(w&&window.confirm((null==T?void 0:T["delete-confirm"])||"Are you sure you want to delete this conversation?"))try{yield m.default.post("/delete_pickaxe_conversation",{sessionId:w,userId:D}),S(!0),C(p.v4()),ce(ie)}catch(e){console.error("Error deleting chat:",e),alert((null==T?void 0:T["failed-delete-chat"])||"Failed to delete chat.")}})),isDarkGlass:"dark"===N.portalTheme}),t.jsx(v.StudioTip,Object.assign({content:T["chat-history"]||"Chat History",align:"bottom",containerClassName:"inline-flex shrink-0"},{children:t.jsx(g.HistoryPill,{icon:t.jsx(b.default,{}),onClick:()=>{C(""),q(w)}})}))]})),t.jsx(c.default,{additionalScrollHeight:U,isForceHideInfo:E<=545||F<=350||K,isInputFocused:K,onSubmit:t=>e.__awaiter(void 0,void 0,void 0,(function*(){Z.current&&Z.current.onSubmit(t)})),smitheryAuthData:ee,resubmitPrompt:()=>{te(null),se(!0)}}),t.jsx(x.default,{isVisible:ne&&!B&&!ae,bottom:U+65,onClick:pe}),t.jsx(d.default,{ref:Z,onFocus:()=>Q(!0),onBlur:()=>Q(!1),onInputHeightChange:J,initSmitheryAuthData:e=>te(e),resubmitPrompt:oe})]})]}))};
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"),i=require("../Addons/Auth/hooks/useAuthContext.js"),r=require("../../../hooks/pickaxe/useDimensionContext.js"),n=require("../Addons/Document/hooks/useDocument.js"),a=require("../Addons/Scroll/hooks/useScrollContext.js"),l=require("../../../hooks/studio/useStyleFontSize.js"),u=require("../../../hooks/core/useScrollToBottomVisibility.js"),c=require("./History/index.js"),d=require("./Input.js"),f=require("../../Icons/attach-vertical.svg.js"),h=require("../../../common/cn.js"),m=require("../../../common/api/pickaxe.js"),v=require("uuid"),p=require("../../Core/StudioTip.js"),x=require("../common/ScrollToBottomButton.js"),j=require("../../../hooks/pickaxe/useResponseContext.js"),g=require("../Addons/Navbar/NavPill.js"),b=require("../../Icons/history.svg.js");exports.default=()=>{var k,y;const{deploymentType:S,isNewChat:w,setIsNewChat:C,sessionId:q,setSessionId:I,setLastSessionId:D,pickaxeId:_,sender:N,pickaxe:P,styles:T,isEmbed:A,translations:F}=s.usePickaxeContext(),{isSent:E}=i.useAuthContext(),{width:O,height:R,setDimension:H}=r.useDimensionContext(),{setDocuments:z,onFileUpload:B}=n.useDocument(),{scrollContainerRef:L,isLocked:G,setIsLocked:V}=a.useScrollContext(),{isGenerating:M,messages:U}=j.useResponseContext(),W=l.useStyleFontSize(),[J,K]=o.useState(0),[Q,X]=o.useState(!1),[Y,Z]=o.useState(!1),$=o.useRef(null),ee=o.useRef(null),te=o.useRef(0),[oe,se]=o.useState(null),[ie,re]=o.useState(!1),ne=(null==F?void 0:F["new-chat"])||"New chat",ae="chat-input"===S&&w&&!E,le=null!==(y=null===(k=null==P?void 0:P.documentuploadtype)||void 0===k?void 0:k.startsWith("enduserupload"))&&void 0!==y&&y,{hasScrollableContent:ue,isNearBottom:ce}=u.default(L);o.useEffect((()=>()=>{z([])}),[]);const de=o.useCallback((()=>{if(!_||!N)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:q,userId:N});if(t.data&&t.data.success){const e=t.data.title;if(e&&"Conversation Title"!==e)return void he(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()}),[_,N,q]);o.useEffect((()=>{M||w||!q||de()}),[M,w,q,de]),o.useEffect((()=>{if(!$.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($.current),()=>{e.disconnect()}}),[H]);const[fe,he]=o.useState(ne),me=(null==P?void 0:P.formtitle)||"Pickaxe",ve=(null==P?void 0:P.coverphoto)||void 0,[pe,xe]=o.useState(!1);o.useEffect((()=>{const e=!ae&&!A&&T.portalTheme&&(U.filter((e=>"user"===e.role)).length>0||Q||!w);xe(null!=e&&e)}),[ae,A,Q,w,U,T.portalTheme]);const je=o.useCallback((()=>{L.current&&(V(!0),L.current.scrollTo({top:L.current.scrollHeight,behavior:"smooth"}))}),[L,V]);return t.jsxs("div",Object.assign({ref:$,className:"relative flex h-full w-full flex-col items-center overflow-hidden",onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),le&&(te.current+=1,e.dataTransfer.items&&e.dataTransfer.items.length>0&&Z(!0))},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),le&&(te.current-=1,0===te.current&&Z(!1))},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDrop:t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(t.preventDefault(),t.stopPropagation(),Z(!1),te.current=0,!le)return;const e=Array.from(t.dataTransfer.files||[]);e.length>0&&(C(!1),yield B(e))}))},{children:[Y&&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(f.default,{className:"h-10 w-10"})})),t.jsx("h3",Object.assign({className:h.default(W.h3,"mt-6 font-semibold text-c-primary text-black")},{children:(null==F?void 0:F["drop-files-to-upload"])||"Drop files to upload"})),t.jsx("p",Object.assign({className:h.default(W.b2,"mt-2 opacity-60 text-black")},{children:(null==F?void 0:F["add-anything-to-the-conversation"])||"Add anything to the conversation"}))]})),ae?t.jsx(d.default,{}):t.jsxs(t.Fragment,{children:[pe&&t.jsxs("div",Object.assign({className:h.default("direct-link"===S?"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"===T.portalTheme?"glass-dark ":"")},{children:[t.jsx(g.NavPill,{text:me,icon:ve}),w||fe===ne?t.jsx(g.NavPill,{text:fe}):t.jsx(g.EditableNavPill,{text:fe,sessionId:q,onRename:t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(q)try{yield m.default.post("/edit_conversation_name",{sessionId:q,name:t,userId:N}),he(t)}catch(e){console.error("Error renaming chat:",e),alert((null==F?void 0:F["failed-rename-chat"])||"Failed to rename chat.")}})),onDelete:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(q&&window.confirm((null==F?void 0:F["delete-confirm"])||"Are you sure you want to delete this conversation?"))try{yield m.default.post("/delete_pickaxe_conversation",{sessionId:q,userId:N}),C(!0),I(v.v4()),he(ne)}catch(e){console.error("Error deleting chat:",e),alert((null==F?void 0:F["failed-delete-chat"])||"Failed to delete chat.")}})),isDarkGlass:"dark"===T.portalTheme}),t.jsx(p.StudioTip,Object.assign({content:F["chat-history"]||"Chat History",align:"bottom",containerClassName:"inline-flex shrink-0"},{children:t.jsx(g.HistoryPill,{icon:t.jsx(b.default,{}),onClick:()=>{I(""),D(q)}})}))]})),t.jsx(c.default,{additionalScrollHeight:J,isForceHideInfo:R<=545||O<=350||Q,isInputFocused:Q,onSubmit:t=>e.__awaiter(void 0,void 0,void 0,(function*(){ee.current&&ee.current.onSubmit(t)})),smitheryAuthData:oe,resubmitPrompt:()=>{se(null),re(!0)}}),t.jsx(x.default,{isVisible:ue&&!G&&!ce,bottom:J+65,onClick:je}),t.jsx(d.default,{ref:ee,onFocus:()=>X(!0),onBlur:()=>X(!1),onInputHeightChange:K,initSmitheryAuthData:e=>se(e),resubmitPrompt:ie})]})]}))};
@@ -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("../../Addons/Auth/hooks/useAuthContext.js"),o=require("../../../../hooks/pickaxe/useResponseContext.js"),r=require("../../Addons/Document/hooks/useDocument.js"),a=require("../../Addons/Scroll/hooks/useScroll.js"),l=require("../../Addons/Artifact/hooks/useArtifactContext.js"),d=require("../../../../common/utils.js"),u=require("@nem035/gpt-3-encoder"),c=require("eventsource-parser"),p=require("../../common/PickaxeBranding.js"),g=require("../../common/PickaxeButton.js"),m=require("../../../../common/error.js"),f=require("../../../../common/validation.js");exports.default=({questions:h,resetQuestions:v})=>{var b;const{origin:x,pickaxeId:j,sender:y,senderType:O,portalId:w,deploymentId:S,pickaxe:C,misc:I,translations:k,isRtl:q,setSessionId:_,setIsNewChat:P,setValidationStatus:A,setValidationUpgradeGroups:E,setValidationUpgradeUrl:N,onGenerateComplete:T}=n.usePickaxeContext(),{token:U}=i.useAuthContext(),{isGenerating:D,setResponse:L,setMessages:R,setStatus:J,setLimitData:V,setError:B,setIsSwitchedToChat:K}=o.useResponseContext(),{documents:W,websiteLink:X,isUploading:F,onWebsiteUpload:G,setDocuments:M,setDocumentError:$}=r.useDocument(),{scrollStartSession:z,scrollEndSession:Q,scrollToTarget:Y}=a.useScroll({auto:!(null==C?void 0:C.enablechatresponses)}),{artifacts:H,currentPopupType:Z,setArtifacts:ee,setCurrentArtifact:te}=l.useArtifactContext(),[se,ne]=s.useState(!1),ie=s.useRef(null),oe=e=>{const t=f.getValidationFailure(e);return!!t&&(B(""),V(null),A(t.status),E(t.upgradeGroups),N(t.upgradeUrl),!0)},re=s.useMemo((()=>h.some((e=>("Short Answer"===e.type||"Long Answer"===e.type||"long"===e.type||"short"===e.type||"Checkbox"===e.type||"Knowledge Upload"===e.type||e.id.includes("documentupload"))&&e.input.length>0))),[h]);return t.jsxs("div",Object.assign({className:"mt-4 flex flex-wrap justify-between gap-4 items-center",dir:q?"rtl":"ltr"},{children:[t.jsxs("div",Object.assign({className:"flex items-center flex-grow flex-wrap gap-2"},{children:[t.jsx(g.default,Object.assign({className:"px-5 min-h-[42px]",isDisabled:F||D||se,onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,t,s;try{if(D||F||se)return;B(""),$(""),V(null),L(null);const n=["Multiple Choice","Checkbox"];for(const e of h){if(u.encode(e.input).length>e.maxLength&&!n.includes(e.type))throw new Error((null==k?void 0:k["response-too-long"])||"One or more of your responses is too long!");if(e.isRequired&&!e.input.trim()&&"userinput:documentupload"!==e.id)throw new Error((null==k?void 0:k["required-fields-missing"])||"You must fill out all required fields.")}const i=W.filter((e=>"finished"===e.status)),o=W.map((e=>e.name)),r=null!==(t=null===(e=null==C?void 0:C.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==t&&t,a=h.some((e=>"userinput:documentupload"===e.id&&e.isRequired)),l=d.extractUrlsFromText(X).filter((e=>!o.includes(e)));if(l.length){const e=l[l.length-1];ne(!0);const t=yield G(e);t&&(i.push(t),yield new Promise((e=>setTimeout(e,5e3)))),ne(!1)}else if(a&&r&&!i.length)return void $((null==k?void 0:k["document-upload-required"])||"Please paste a valid website/video link or drag a file to add to the knowledge base.");const p=i.map((e=>e.documentId||"")).filter(Boolean),g=r&&p.length>0,m={};h.forEach((e=>{m[e.id]="Knowledge Upload"===e.type||e.id.includes("documentupload")?i.map((e=>e.name)).join(",")||"":e.input})),J("fetching"),z(),Y();const f=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},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()}),body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:x,pickaxeId:j,senderType:O,valueObj:m},g&&{documentIds:p}),y&&{sender:y}),U&&{studioSessionToken:U}),!U&&!y&&{sender:d.initializeEmbedUserId()}),w&&{portalId:w}),S&&{deploymentId:S}))}),v=yield f.json();if(!v.success){if(oe(v))return;const e=new Error(v.error||v.message||(null==k?void 0:k["failed-to-start-generation"])||"Failed to start generation");throw v.limitData&&(e.limitData=v.limitData),e}if(!v.submissionId||!v.sessionId)throw new Error((null==k?void 0:k["failed-to-start-generation"])||"Failed to start generation");const b=v.submissionId,I=v.sessionId,q={sessionId:I,documentIds:g?p:[],question:{inputs:h.map((e=>({id:e.id,question:e.main,answer:e.input}))),responseParts:[]},messageCount:0,sentAt:new Date};L(q),(null==C?void 0:C.enablechatresponses)&&(_(I),P(!1),K(!0),R([{id:0,role:"assistant",parts:[],documentIds:[]}])),g&&M([]),J("streaming"),ie.current=new AbortController;const A=[];let E=[...null!=H?H:[]],N=0,Q=!1,re="";for(;!Q;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${b}?index=${N}`,{signal:null===(s=ie.current)||void 0===s?void 0:s.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader(),n=new TextDecoder,i=c.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&N++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==k?void 0:k["something-went-wrong"])||"Something went wrong.";return oe(t)||B(s),void(Q=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("text-start"===n.type)re="",A.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)re+=n.delta,A[A.length-1].content=re;else if("text-end"===n.type)re="";else if("reasoning-start"===n.type)re="",A.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)re+=n.delta,A[A.length-1].content=re;else if("reasoning-end"===n.type)re="";else if(n.type.startsWith("data-")){const e=n;A.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}const i=Object.assign(Object.assign({},q),{question:Object.assign(Object.assign({},q.question),{responseParts:[...A]})});L(i),(null==C?void 0:C.enablechatresponses)&&R([{id:0,role:"assistant",parts:[...A],documentIds:[]}])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);E=E.filter((e=>!(e.id===t.id&&e.version===t.version))),E.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),ee([...E]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);E=E.filter((e=>!(e.id===t.id&&e.version===t.version))),E.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),ee([...E]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);E=E.filter((e=>!(e.id===t.id&&e.version===t.version))),E.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),ee([...E]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");E=E.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),ee([...E])}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);ee(E.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}}else Q=!0}});for(;;){const{value:e,done:s}=yield t.read();if(s)break;i.feed(n.decode(e))}Q||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("AbortError"===e.name)return void(Q=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==T||T(I)}catch(e){let t=m.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==k?void 0:k["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),oe(t)||B(t),Y()}finally{J("idle"),ne(!1),Q()}}))},{children:se?(null==k?void 0:k.processing)||"Processing...":F?(null==k?void 0:k.uploading)||"Uploading...":D?(null==k?void 0:k.loading)||"Loading...":null!==(b=null==C?void 0:C.submittext)&&void 0!==b?b:"Submit"})),re&&t.jsx(g.default,Object.assign({variant:"transparent-text",className:"min-h-[42px] px-5",isDisabled:F||D||se,onClick:v},{children:(null==k?void 0:k["clear-form"])||"Clear form"}))]})),!I.isWhiteLabel&&t.jsx(p.default,{containerClassName:"justify-end"})]}))};
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("../../Addons/Auth/hooks/useAuthContext.js"),o=require("../../../../hooks/pickaxe/useResponseContext.js"),r=require("../../Addons/Document/hooks/useDocument.js"),a=require("../../Addons/Scroll/hooks/useScroll.js"),l=require("../../Addons/Artifact/hooks/useArtifactContext.js"),d=require("../../../../common/utils.js"),u=require("@nem035/gpt-3-encoder"),c=require("eventsource-parser"),p=require("../../common/PickaxeBranding.js"),g=require("../../common/PickaxeButton.js"),m=require("../../../../common/error.js"),f=require("../../../../common/validation.js");exports.default=({questions:v,resetQuestions:h})=>{var b;const{origin:x,pickaxeId:j,sender:y,senderType:O,portalId:w,deploymentId:S,pickaxe:C,misc:I,translations:k,isRtl:q,setSessionId:_,setIsNewChat:P,setValidationStatus:A,setValidationUpgradeGroups:E,setValidationUpgradeUrl:N,onGenerateComplete:T}=n.usePickaxeContext(),{token:U}=i.useAuthContext(),{isGenerating:D,setResponse:L,setMessages:R,setStatus:J,setLimitData:V,setError:B,setIsSwitchedToChat:K}=o.useResponseContext(),{documents:W,websiteLink:X,isUploading:F,onWebsiteUpload:G,setDocuments:M,setDocumentError:$}=r.useDocument(),{scrollStartSession:z,scrollEndSession:Q,scrollToTarget:Y}=a.useScroll({auto:!(null==C?void 0:C.enablechatresponses)}),{artifacts:H,currentPopupType:Z,setArtifacts:ee,setCurrentArtifact:te}=l.useArtifactContext(),[se,ne]=s.useState(!1),ie=s.useRef(null),oe=e=>{const t=f.getValidationFailure(e);return!!t&&(B(""),V(null),A(t.status),E(t.upgradeGroups),N(t.upgradeUrl),!0)},re=s.useMemo((()=>v.some((e=>("Short Answer"===e.type||"Long Answer"===e.type||"long"===e.type||"short"===e.type||"Checkbox"===e.type||"Knowledge Upload"===e.type||e.id.includes("documentupload"))&&e.input.length>0))),[v]);return t.jsxs("div",Object.assign({className:"mt-4 flex flex-wrap justify-between gap-4 items-center",dir:q?"rtl":"ltr"},{children:[t.jsxs("div",Object.assign({className:"flex items-center flex-grow flex-wrap gap-2"},{children:[t.jsx(g.default,Object.assign({className:"px-5 min-h-[42px]",isDisabled:F||D||se,onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,t,s;try{if(D||F||se)return;B(""),$(""),V(null),L(null);const n=["Multiple Choice","Checkbox"];for(const e of v){if(u.encode(e.input).length>e.maxLength&&!n.includes(e.type))throw new Error((null==k?void 0:k["response-too-long"])||"One or more of your responses is too long!");if(e.isRequired&&!e.input.trim()&&"userinput:documentupload"!==e.id)throw new Error((null==k?void 0:k["required-fields-missing"])||"You must fill out all required fields.")}const i=W.filter((e=>"finished"===e.status)),o=W.map((e=>e.name)),r=null!==(t=null===(e=null==C?void 0:C.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==t&&t,a=v.some((e=>"userinput:documentupload"===e.id&&e.isRequired)),l=d.extractUrlsFromText(X).filter((e=>!o.includes(e)));if(l.length){const e=l[l.length-1];ne(!0);const t=yield G(e);t&&(i.push(t),yield new Promise((e=>setTimeout(e,5e3)))),ne(!1)}else if(a&&r&&!i.length)return void $((null==k?void 0:k["document-upload-required"])||"Please paste a valid website/video link or drag a file to add to the knowledge base.");const p=i.map((e=>e.documentId||"")).filter(Boolean),g=r&&p.length>0,m={};v.forEach((e=>{m[e.id]="Knowledge Upload"===e.type||e.id.includes("documentupload")?i.map((e=>e.name)).join(",")||"":e.input})),J("fetching"),z(),Y();const f=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/submit`,{method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},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()}),body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:x,pickaxeId:j,senderType:O,valueObj:m},g&&{documentIds:p}),y&&{sender:y}),U&&{studioSessionToken:U}),!U&&!y&&{sender:d.initializeEmbedUserId()}),w&&{portalId:w}),S&&{deploymentId:S}))}),h=yield f.json();if(!h.success){if(oe(h))return;const e=new Error(h.error||h.message||(null==k?void 0:k["failed-to-start-generation"])||"Failed to start generation");throw h.limitData&&(e.limitData=h.limitData),e}if(!h.submissionId||!h.sessionId)throw new Error((null==k?void 0:k["failed-to-start-generation"])||"Failed to start generation");const b=h.submissionId,I=h.sessionId,q={sessionId:I,documentIds:g?p:[],question:{inputs:v.map((e=>({id:e.id,question:e.main,answer:e.input}))),responseParts:[]},messageCount:0,sentAt:new Date};L(q),(null==C?void 0:C.enablechatresponses)&&(_(I),P(!1),K(!0),R([{id:0,role:"assistant",parts:[],documentIds:[]}])),g&&M([]),J("streaming"),ie.current=new AbortController;const A=[];let E=[...null!=H?H:[]],N=0,Q=!1,re="";for(;!Q;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${b}?index=${N}`,{signal:null===(s=ie.current)||void 0===s?void 0:s.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader(),n=new TextDecoder,i=c.createParser({onEvent:e=>{var t,s;if(e.event&&"ping"!==e.event&&N++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data),s=t.error||t.message||(null==k?void 0:k["something-went-wrong"])||"Something went wrong.";return oe(t)||B(s),void(Q=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("text-start"===n.type)re="",A.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)re+=n.delta,A[A.length-1].content=re;else if("text-end"===n.type)re="";else if("reasoning-start"===n.type)re="",A.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)re+=n.delta,A[A.length-1].content=re;else if("reasoning-end"===n.type)re="";else if(n.type.startsWith("data-")){const e=n;A.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}const i=Object.assign(Object.assign({},q),{question:Object.assign(Object.assign({},q.question),{responseParts:[...A]})});L(i),(null==C?void 0:C.enablechatresponses)&&R([{id:0,role:"assistant",parts:[...A],documentIds:[]}])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);E=E.filter((e=>!(e.id===t.id&&e.version===t.version))),E.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),ee([...E]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);E=E.filter((e=>!(e.id===t.id&&e.version===t.version))),E.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),ee([...E]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);E=E.filter((e=>!(e.id===t.id&&e.version===t.version))),E.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),ee([...E]),Z.startsWith("inline")||te({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");E=E.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),ee([...E])}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);ee(E.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}}else Q=!0}});for(;;){const{value:e,done:s}=yield t.read();if(s)break;i.feed(n.decode(e))}Q||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("AbortError"===e.name)return void(Q=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==T||T(I)}catch(e){let t=m.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==k?void 0:k["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),oe(t)||B(t),Y()}finally{J("idle"),ne(!1),Q()}}))},{children:se?(null==k?void 0:k.processing)||"Processing...":F?(null==k?void 0:k.uploading)||"Uploading...":D?(null==k?void 0:k.loading)||"Loading...":null!==(b=null==C?void 0:C.submittext)&&void 0!==b?b:"Submit"})),re&&t.jsx(g.default,Object.assign({variant:"transparent-text",className:"min-h-[42px] px-5",isDisabled:F||D||se,onClick:h},{children:(null==k?void 0:k["form.clear-form"])||(null==k?void 0:k["clear-form"])||"Clear form"}))]})),!I.isWhiteLabel&&t.jsx(p.default,{containerClassName:"justify-end"})]}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),i=require("react"),o=require("./Addons/Artifact/Provider.js"),a=require("./DimensionProvider.js"),s=require("./ResponseProvider.js"),n=require("./Addons/Document/Provider.js"),r=require("./Addons/Auth/Provider.js");function l(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var o=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,o.get?o:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}const d=i.createContext({});exports.PickaxeContext=d,exports.PickaxeProvider=({children:c,origin:u,sender:p,senderType:f,deploymentId:h,portalId:g,deploymentType:m,deploymentDimensions:y,deploymentMisc:b,styles:w,colors:v,limits:S={},misc:k={isWhiteLabel:!0,isProfileImage:!0,isChatImage:!0,isTitle:!0,isDescription:!0,isHistory:!0},translations:P,artifact:x={popupType:"auto"},responsiveBy:C="viewport",locale:F="en",opacity:I=1,forceMobile:j=!1,disableHtml:q=!1,disableJs:T=!1,disableCss:D=!1,loadFont:O=!0,isRtl:A=!1,isEmbed:U=!1,isDropShadow:E=!1,allowGuestUsage:R=!0,preventInitialSessionId:L=!1,onGenerateComplete:M,onSessionIdChange:G})=>{const[H,W]=i.useState(""),[_,B]=i.useState(""),[N,X]=i.useState(""),[V,Y]=i.useState(""),[z,J]=i.useState(p),[K,Q]=i.useState(null),[Z,$]=i.useState(f),[ee,te]=i.useState("loading"),[ie,oe]=i.useState([]),[ae,se]=i.useState(null),[ne,re]=i.useState(null),[le,de]=i.useState(null),[ce,ue]=i.useState(null),[pe,fe]=i.useState(!1),[he,ge]=i.useState(!0),[me,ye]=i.useState(!0),[be,we]=i.useState(!1);return i.useEffect((()=>{fe(!1)}),[null==w?void 0:w.font]),i.useEffect((()=>{e.__awaiter(void 0,void 0,void 0,(function*(){if("undefined"!=typeof window&&O&&!pe&&(null==w?void 0:w.font)&&"Real Head Pro"!==w.font)try{(yield Promise.resolve().then((function(){return l(require("webfontloader"))}))).default.load({google:{families:[w.font]},active:()=>{fe(!0)},inactive:()=>{console.error("[pxe] failed to load font {styles.font}"),fe(!0)}})}catch(e){console.error("[pxe] failed to load font:",e),fe(!0)}}))}),[O,pe,null==w?void 0:w.font]),i.useEffect((()=>{J(p)}),[p]),t.jsx(d.Provider,Object.assign({value:Object.assign({origin:u,contextId:H,pickaxeId:_,sessionId:N,lastSessionId:V,sender:z,senderType:Z,portalId:g,deploymentId:h,deploymentType:m,validationStatus:ee,validationUpgradeGroups:ie,validationUpgradeUrl:ae,deploymentDimensions:y,deploymentMisc:b,accessGroup:K,pickaxe:ce,styles:Object.assign({theme:"light",font:"Real Head Pro",fontSize:"md",formFieldStyle:"box",btnStyle:"filled",outlineThickness:1,cornerRadius:4},w),colors:Object.assign({primary:"#F6F8FA",text:"#000000",secondary:"#FFFFFF",secondaryText:"#000000",accent:"#228DD7",accentText:"#FFFFFF",error:"#EF4444"},v),misc:k,translations:Object.assign({"new-chat":"New chat","see-history":"See history","see-input":"See input","hide-input":"Hide input",processing:"Processing...",uploading:"Uploading...",loading:"Loading...","powered-by-pickaxe":"Powered by Pickaxe","form-doc-placeholder":"Paste a website/video link or drag a file",website:"Website",copy:"Copy","file-limit-reached":"You have reached the file limit.",save:"Save","save-as":"Save as","please-enter-email-to-continue":"Please enter your email to continue:","enter-email-to-continue":"Enter here your email to continue",submit:"Submit",sending:"Sending...","check-your-inbox":"Check your inbox","we-sent-your-an-activation-link":"We sent you an activation link. Please be sure to check your spam folder too.",resend:"Resend",resending:"Resending...","chat-history":"Chat History","exit-chat-history":"Exit Chat History","no-history":"No history yet.","log-out":"Log Out","clear-form":"Clear form",expand:"Expand","expand-artifact":"Expand artifact",collapse:"Collapse","collapse-artifact":"Collapse artifact",close:"Close","close-artifact":"Close artifact",download:"Download","copy-artifact-content":"Copy artifact content","download-artifact-content":"Download artifact content","delete-confirm":"Are you sure you want to delete this conversation?",other:"Other","select-options":"Select option(s)","select-an-option":"Select an option","type-your-answer":"Type your answer...",cancel:"Cancel","rename-chat":"Rename chat","delete-chat":"Delete chat","conversation-name":"Conversation name","not-available":"n/a","open-chat":"Open Chat",copied:"Copied!","copy-assistant-message":"Copy assistant message","failed-delete-conversation":"Failed to delete conversation.","failed-update-name":"Failed to update name.","failed-rename-chat":"Failed to rename chat.","failed-delete-chat":"Failed to delete chat.","drop-files-to-upload":"Drop files to upload","add-anything-to-the-conversation":"Add anything to the conversation","something-went-wrong-please-try-again":"Something went wrong. Please try again, or","contact-us":"contact us","for-help":"for help.",back:"Back","upgrade-required":"Upgrade Required","please-upgrade-to-continue-using-this-tool":"Please upgrade to continue using this tool.","access-locked":"Access Locked","this-tool-is-locked-contact-owner":"This tool is locked to use. Contact owner for more information.","access-denied":"Access Denied","login-is-required":"Login is required.","no-access-request-access":"It looks like you don't have access to these resources. Please request access to continue.","request-access":"Request Access",or:"or","sign-in-with-different-account":"Sign in with a different account","access-requested-successfully":"Successfully requested access!","open-tool":"Open Tool","fab-icon":"FAB Icon","iframe-artifact-fallback":"Iframe is not supported, please view this artifact in a browser that supports it.","html-preview":"HTML preview","image-link-is-broken":"[Image link is broken]","download-video":"Download Video","available-plans":"Available Plans",buy:"Buy",credits:"Credits",uses:"Uses",credits_upper:"CREDITS",uses_upper:"USES",free:"Free",unlimited:"Unlimited","authentication-required":"Authentication Required","smithery-auth-description-prefix":"The tool you are trying to use requires authentication with",dismiss:"Dismiss",connect:"Connect",connecting:"Connecting...","auth-failed":"Auth failed","failed-to-finalize-authentication":"Failed to finalize authentication.","must-be-logged-in-to-connect-smithery":"You must be logged in to connect Smithery MCPs.","feedback-dislike-input-placeholder":"Write here...","feedback-submit":"Submit","feedback-thanks":"Thanks for the feedback!","feedback-like-title":"What went right?","feedback-dislike-title":"What went wrong?","feedback-dislike-message":"Help us improve our answers","what-do-you-want-to-talk-about":"What do you want to talk about?","failed-to-start-generation":"Failed to start generation","response-too-long":"One or more of your responses is too long!","required-fields-missing":"You must fill out all required fields.","something-went-wrong":"Something went wrong.","something-went-wrong-try-again":"Something went wrong, please try again.","high-traffic-try-again-later":"Oops! We're experiencing high traffic at the moment. Please try again later.",listening:"Listening...",remaining:"remaining",upgrade:"Upgrade","email-address-cannot-be-empty":"Email address cannot be empty.","please-enter-valid-email-address":"Please enter a valid email address.","failed-to-send-sign-in-link":"Failed to send sign-in link.",tool:"Tool","document-processing-failed":"Document processing failed","invalid-upload-file-types":"You can only upload PDF, TXT, DOCX, CSV, XLSX, JSON, PPTX, MD, XML, PNG, JPEG, WEBP, or GIF files. Please try again.","invalid-website-or-youtube-link":"Please paste a valid website URL or Youtube video link to add to the knowledge base.","website-processing-failed":"Website processing failed, please try again.","invalid-website-url":"Please paste a valid website URL","document-upload-required":"Please paste a valid website/video link or drag a file to add to the knowledge base.",thinking:"Thinking...",thought:"Thought","thought-for":"Thought for",seconds:"seconds","untitled-artifact":"Untitled Artifact",created:"Created",updated:"Updated",rewrote:"Rewrote",artifact:"Artifact","iframe-not-supported-use-different-browser":"Iframe not supported, use a different browser."},P),artifact:x,responsiveBy:C,locale:F,opacity:I,forceMobile:j,loadFont:O,disableHtml:q,disableJs:T,disableCss:D,isFontLoaded:pe,isNewChat:he,isShowIceBreaker:me,isShowFeedbackMessage:be,isRtl:A,isEmbed:U,isDropShadow:E,allowGuestUsage:R,clientSecret:le,stripeAccountId:ne,preventInitialSessionId:L,setClientSecret:de,setStripeAccountId:re,setContextId:W,setValidationStatus:te,setValidationUpgradeGroups:oe,setValidationUpgradeUrl:se,setPickaxeId:B,setSessionId:e=>{X((t=>{const i="function"==typeof e?e(t):e;return null==G||G(i),i}))},setLastSessionId:Y,setSender:J,setSenderType:$,setAccessGroup:Q,setPickaxe:ue,setIsFontLoaded:fe,setIsNewChat:ge,setIsShowIceBreaker:ye,setIsShowFeedbackMessage:we},M&&{onGenerateComplete:M})},{children:t.jsx(r.default,{children:t.jsx(a.default,{children:t.jsx(s.default,Object.assign({limits:S},{children:t.jsx(n.default,{children:t.jsx(o.ArtifactProvider,Object.assign({},x,{children:c}))})}))})})}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),i=require("react"),o=require("./Addons/Artifact/Provider.js"),a=require("./DimensionProvider.js"),s=require("./ResponseProvider.js"),n=require("./Addons/Document/Provider.js"),r=require("./Addons/Auth/Provider.js");function l(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var o=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,o.get?o:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}const d=i.createContext({});exports.PickaxeContext=d,exports.PickaxeProvider=({children:c,origin:u,sender:p,senderType:f,deploymentId:h,portalId:g,deploymentType:m,deploymentDimensions:y,deploymentMisc:b,styles:w,colors:v,limits:S={},misc:k={isWhiteLabel:!0,isProfileImage:!0,isChatImage:!0,isTitle:!0,isDescription:!0,isHistory:!0},translations:P,artifact:x={popupType:"auto"},responsiveBy:C="viewport",locale:F="en",opacity:I=1,forceMobile:j=!1,disableHtml:q=!1,disableJs:T=!1,disableCss:D=!1,loadFont:O=!0,isRtl:A=!1,isEmbed:U=!1,isDropShadow:E=!1,allowGuestUsage:R=!0,preventInitialSessionId:L=!1,onGenerateComplete:M,onSessionIdChange:G})=>{const[H,W]=i.useState(""),[_,B]=i.useState(""),[N,X]=i.useState(""),[V,Y]=i.useState(""),[z,J]=i.useState(p),[K,Q]=i.useState(null),[Z,$]=i.useState(f),[ee,te]=i.useState("loading"),[ie,oe]=i.useState([]),[ae,se]=i.useState(null),[ne,re]=i.useState(null),[le,de]=i.useState(null),[ce,ue]=i.useState(null),[pe,fe]=i.useState(!1),[he,ge]=i.useState(!0),[me,ye]=i.useState(!0),[be,we]=i.useState(!1);return i.useEffect((()=>{fe(!1)}),[null==w?void 0:w.font]),i.useEffect((()=>{e.__awaiter(void 0,void 0,void 0,(function*(){if("undefined"!=typeof window&&O&&!pe&&(null==w?void 0:w.font)&&"Real Head Pro"!==w.font)try{(yield Promise.resolve().then((function(){return l(require("webfontloader"))}))).default.load({google:{families:[w.font]},active:()=>{fe(!0)},inactive:()=>{console.error("[pxe] failed to load font {styles.font}"),fe(!0)}})}catch(e){console.error("[pxe] failed to load font:",e),fe(!0)}}))}),[O,pe,null==w?void 0:w.font]),i.useEffect((()=>{J(p)}),[p]),t.jsx(d.Provider,Object.assign({value:Object.assign({origin:u,contextId:H,pickaxeId:_,sessionId:N,lastSessionId:V,sender:z,senderType:Z,portalId:g,deploymentId:h,deploymentType:m,validationStatus:ee,validationUpgradeGroups:ie,validationUpgradeUrl:ae,deploymentDimensions:y,deploymentMisc:b,accessGroup:K,pickaxe:ce,styles:Object.assign({theme:"light",font:"Real Head Pro",fontSize:"md",formFieldStyle:"box",btnStyle:"filled",outlineThickness:1,cornerRadius:4},w),colors:Object.assign({primary:"#F6F8FA",text:"#000000",secondary:"#FFFFFF",secondaryText:"#000000",accent:"#228DD7",accentText:"#FFFFFF",error:"#EF4444"},v),misc:k,translations:Object.assign({"new-chat":"New chat","see-history":"See history","see-input":"See input","hide-input":"Hide input",processing:"Processing...",uploading:"Uploading...",loading:"Loading...","powered-by-pickaxe":"Powered by Pickaxe","form-doc-placeholder":"Paste a website/video link or drag a file",website:"Website",copy:"Copy","file-limit-reached":"You have reached the file limit.",save:"Save","save-as":"Save as","please-enter-email-to-continue":"Please enter your email to continue:","enter-email-to-continue":"Enter here your email to continue",submit:"Submit",sending:"Sending...","check-your-inbox":"Check your inbox","we-sent-your-an-activation-link":"We sent you an activation link. Please be sure to check your spam folder too.",resend:"Resend",resending:"Resending...","chat-history":"Chat History","exit-chat-history":"Exit Chat History","no-history":"No history yet.","log-out":"Log Out","clear-form":"Clear form","form.clear-form":"Clear form",expand:"Expand","expand-artifact":"Expand artifact",collapse:"Collapse","collapse-artifact":"Collapse artifact",close:"Close","close-artifact":"Close artifact",download:"Download","copy-artifact-content":"Copy artifact content","download-artifact-content":"Download artifact content","delete-confirm":"Are you sure you want to delete this conversation?",other:"Other","select-options":"Select option(s)","select-an-option":"Select an option","type-your-answer":"Type your answer...",cancel:"Cancel","rename-chat":"Rename chat","delete-chat":"Delete chat","conversation-name":"Conversation name","not-available":"n/a","open-chat":"Open Chat",copied:"Copied!","copy-assistant-message":"Copy assistant message","failed-delete-conversation":"Failed to delete conversation.","failed-update-name":"Failed to update name.","failed-rename-chat":"Failed to rename chat.","failed-delete-chat":"Failed to delete chat.","drop-files-to-upload":"Drop files to upload","add-anything-to-the-conversation":"Add anything to the conversation","something-went-wrong-please-try-again":"Something went wrong. Please try again, or","contact-us":"contact us","for-help":"for help.",back:"Back","upgrade-required":"Upgrade Required","please-upgrade-to-continue-using-this-tool":"Please upgrade to continue using this tool.","access-locked":"Access Locked","this-tool-is-locked-contact-owner":"This tool is locked to use. Contact owner for more information.","access-denied":"Access Denied","login-is-required":"Login is required.","no-access-request-access":"It looks like you don't have access to these resources. Please request access to continue.","request-access":"Request Access",or:"or","sign-in-with-different-account":"Sign in with a different account","access-requested-successfully":"Successfully requested access!","open-tool":"Open Tool","fab-icon":"FAB Icon","iframe-artifact-fallback":"Iframe is not supported, please view this artifact in a browser that supports it.","html-preview":"HTML preview","image-link-is-broken":"[Image link is broken]","download-video":"Download Video","available-plans":"Available Plans",buy:"Buy",credits:"Credits",uses:"Uses",credits_upper:"CREDITS",uses_upper:"USES",free:"Free","pricing.free":"Free",unlimited:"Unlimited","pricing.unlimited":"Unlimited","authentication-required":"Authentication Required","smithery-auth-description-prefix":"The tool you are trying to use requires authentication with",dismiss:"Dismiss",connect:"Connect",connecting:"Connecting...","auth-failed":"Auth failed","failed-to-finalize-authentication":"Failed to finalize authentication.","must-be-logged-in-to-connect-smithery":"You must be logged in to connect Smithery MCPs.","feedback-dislike-input-placeholder":"Write here...","feedback-submit":"Submit","feedback-thanks":"Thanks for the feedback!","feedback-like-title":"What went right?","feedback-dislike-title":"What went wrong?","feedback-dislike-message":"Help us improve our answers","what-do-you-want-to-talk-about":"What do you want to talk about?","failed-to-start-generation":"Failed to start generation","response-too-long":"One or more of your responses is too long!","required-fields-missing":"You must fill out all required fields.","something-went-wrong":"Something went wrong.","something-went-wrong-try-again":"Something went wrong, please try again.","high-traffic-try-again-later":"Oops! We're experiencing high traffic at the moment. Please try again later.",listening:"Listening...",remaining:"remaining",upgrade:"Upgrade","pricing.upgrade":"Upgrade","email-address-cannot-be-empty":"Email address cannot be empty.","please-enter-valid-email-address":"Please enter a valid email address.","failed-to-send-sign-in-link":"Failed to send sign-in link.",tool:"Tool","document-processing-failed":"Document processing failed","invalid-upload-file-types":"You can only upload PDF, TXT, DOCX, CSV, XLSX, JSON, PPTX, MD, XML, PNG, JPEG, WEBP, or GIF files. Please try again.","invalid-website-or-youtube-link":"Please paste a valid website URL or Youtube video link to add to the knowledge base.","website-processing-failed":"Website processing failed, please try again.","invalid-website-url":"Please paste a valid website URL","document-upload-required":"Please paste a valid website/video link or drag a file to add to the knowledge base.",thinking:"Thinking...",thought:"Thought","thought-for":"Thought for",seconds:"seconds","untitled-artifact":"Untitled Artifact",created:"Created",updated:"Updated",rewrote:"Rewrote",artifact:"Artifact","iframe-not-supported-use-different-browser":"Iframe not supported, use a different browser."},P),artifact:x,responsiveBy:C,locale:F,opacity:I,forceMobile:j,loadFont:O,disableHtml:q,disableJs:T,disableCss:D,isFontLoaded:pe,isNewChat:he,isShowIceBreaker:me,isShowFeedbackMessage:be,isRtl:A,isEmbed:U,isDropShadow:E,allowGuestUsage:R,clientSecret:le,stripeAccountId:ne,preventInitialSessionId:L,setClientSecret:de,setStripeAccountId:re,setContextId:W,setValidationStatus:te,setValidationUpgradeGroups:oe,setValidationUpgradeUrl:se,setPickaxeId:B,setSessionId:e=>{X((t=>{const i="function"==typeof e?e(t):e;return null==G||G(i),i}))},setLastSessionId:Y,setSender:J,setSenderType:$,setAccessGroup:Q,setPickaxe:ue,setIsFontLoaded:fe,setIsNewChat:ge,setIsShowIceBreaker:ye,setIsShowFeedbackMessage:we},M&&{onGenerateComplete:M})},{children:t.jsx(r.default,{children:t.jsx(a.default,{children:t.jsx(s.default,Object.assign({limits:S},{children:t.jsx(n.default,{children:t.jsx(o.ArtifactProvider,Object.assign({},x,{children:c}))})}))})})}))};
@@ -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"),o=require("./PickaxeCurrency.js"),n=require("./PickaxeAvatar.js"),c=require("../Addons/Auth/hooks/useAuthContext.js"),l=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:I,setValidationStatus:y,setStripeAccountId:O,setClientSecret:_}=t.usePickaxeContext(),{token:N,setRedirectUrl:S}=c.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==I?void 0:I.free)||"Free",suffix:""};const r=a.intervalToSuffix(i,!0);return{price:`${(null!==(e=o.currencyOptions.find((e=>e.id===t)))&&void 0!==e?e:o.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==I?void 0:I.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(n.Avatar,Object.assign({className:"h-8 w-8"},{children:[s.jsx(n.AvatarImage,{src:null!==(j=m.image)&&void 0!==j?j:"",alt:q}),s.jsx(n.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==I?void 0:I.credits_upper)||"CREDITS":(null==I?void 0:I.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 l.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),y("stripe_checkout")):i&&window.open(i,"_blank"):i&&(window.location.href=i):alert(a)}catch(e){alert(e)}}));else{const e=u.buildUpgradeUrl(Object.assign({baseUrl:f||(null==v?void 0:v.limitLink),accessGroupId:m.accessGroupId},!u.isInIframe()&&{redirectUrl:document.URL}));u.isInIframe()?(S(e||null),y("login_required")):e&&(window.location.href=e)}}))},{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"),l=require("./PickaxeAvatar.js"),o=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:p,children:m,upgradeUrl:f})=>{const{limitData:j}=d.useResponseContext(),{studio:v}=x.useStudio(),{colors:b,sender:g,pickaxe:h,translations:k,setValidationStatus:I,setStripeAccountId:y,setClientSecret:O}=t.usePickaxeContext(),{token:_,setRedirectUrl:N}=o.useAuthContext(),C=i.useCallback(((e,s)=>{var i;return null!==(i=null==k?void 0:k[e])&&void 0!==i?i:s}),[k]),S=i.useMemo((()=>{var e,s;return null!==(s=null!==(e=p.displayName)&&void 0!==e?e:p.name)&&void 0!==s?s:""}),[p]),U=i.useMemo((()=>{var e,s;return null!==(s=null!==(e=p.displayDescription)&&void 0!==e?e:p.description)&&void 0!==s?s:""}),[p]),q=!!(null==v?void 0:v.data.usage)&&v.data.usage.isCredits,w=i.useMemo((()=>{var e;const{price:s,priceInterval:i,currency:t}=p;if(!s)return{price:C("pricing.free",C("free","Free")),suffix:""};const r=a.intervalToSuffix(null!=i?i:null,!0);return{price:`${(null!==(e=n.currencyOptions.find((e=>e.id===t)))&&void 0!==e?e:n.currencyOptions[0]).symbol}${s.toLocaleString()}`,suffix:r}}),[p,C]),A=i.useMemo((()=>{const{limit:e,limitInterval:s}=p;if(e===a.STUDIO_INFINITY_VALUE)return{limit:C("pricing.unlimited",C("unlimited","Unlimited")),suffix:""};const i=a.intervalToSuffix(null!=s?s:null,!0);return{limit:e.toLocaleString(),suffix:i}}),[p,C]);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:[m,s.jsxs("div",Object.assign({className:"flex flex-col"},{children:[s.jsxs("div",Object.assign({className:"flex flex-col"},{children:[p.image&&s.jsxs(l.Avatar,Object.assign({className:"h-8 w-8"},{children:[s.jsx(l.AvatarImage,{src:p.image,alt:S}),s.jsx(l.AvatarFallback,{})]})),s.jsx("p",Object.assign({className:"mt-2 text-sm font-semibold line-clamp-1",title:S},{children:S})),Boolean(U)&&s.jsx("p",Object.assign({className:"mt-1 text-[10px] opacity-70 line-clamp-2 leading-tight"},{children:U})),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:b.secondaryText}},{children:[s.jsx("span",Object.assign({className:"text-[10px] font-bold opacity-50"},{children:q?(null==k?void 0:k.credits_upper)||"CREDITS":(null==k?void 0:k.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(_)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==h?void 0:h.studioid,accessGroupId:p.accessGroupId,successUrl:document.URL,isEmbed:u.isInIframe(),studioSessionToken:_}}),{success:s,url:i,clientSecret:t,stripeAccountId:r,error:a}=e.data;s?u.isInIframe()?t&&r?(y(r),O(t),I("stripe_checkout")):i&&window.open(i,"_blank"):i&&(window.location.href=i):alert(a)}catch(e){alert(e)}}));else{const e=u.buildUpgradeUrl(Object.assign({baseUrl:f||(null==j?void 0:j.limitLink),accessGroupId:p.accessGroupId},!u.isInIframe()&&{redirectUrl:document.URL}));u.isInIframe()?(N(e||null),I("login_required")):e&&(window.location.href=e)}}))},{children:p.ctaButtonText||C("pricing.upgrade",C("upgrade","Upgrade"))}))]}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../../_virtual/_tslib.js"),r=require("react/jsx-runtime"),n=require("react"),t=require("./hooks/usePickaxeMarkdownContext.js"),i=require("./utils/custom-plugins.js"),s=require("react-markdown"),a=require("remark-gfm"),o=require("remark-math"),l=require("rehype-katex"),c=require("rehype-raw"),u=require("./Components/A/index.js"),d=require("./Components/A/FilePreview.js"),p=require("./Components/P/index.js"),f=require("./Components/Img/index.js"),h=require("./Components/Iframe/index.js"),m=require("./Components/Code/index.js"),x=require("./Components/Headings/index.js"),g=require("./Components/List/index.js"),j=require("./Components/Table/index.js"),b=require("./Components/Others/index.js"),q=require("./Components/Action/index.js"),C=require("./Components/Artifact/index.js"),k=require("./Components/Others/Think.js"),w=require("../../../../common/cn.js");function v(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var y=v(s),O=v(a),$=v(o),P=v(l),S=v(c);exports.PickaxeMarkdownRenderer=({className:s,style:a,children:o,value:l,maxLines:c,maxChars:v,multiLineBreaks:A,onExpandClick:H,filePreviewSeenRef:T})=>{const{colors:M,rtl:R,disableHtml:I,disableJs:_,disableCss:N}=t.usePickaxeMarkdownContext(),[E,L]=n.useState({width:0,height:0}),[B,F]=n.useState(null),z=n.useRef(null),J=n.useMemo((()=>{if(!l)return"";let e=l.trim();return e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/\u200B/g,""),e=e.replace(/\\\((.*?)\\\)/g,"$$$ $1 $$$"),e=e.replace(/\\\[(.*?)\\\]/g,"$$$ $1 $$$"),e=e.replace(/<\/think>/g,"\n</think>"),A&&(e=e.replace(/```[\s\S]*?```|(\n(?=\n))/g,((e,r)=>r?"\n\n<br/>\n":e))),e||""}),[l,A]);n.useEffect((()=>{if(v)return void F(J.length>v?J.slice(0,v)+'<span class="pxe-expand-btn">...</span>':null);if(!c)return void F(null);if(!z.current||!J||B)return;const e=z.current,r=parseInt(window.getComputedStyle(e).lineHeight,10),n=c*r;if(!(E.height>n))return;const t=Math.floor(E.width/8),i=Math.floor(t*c);F(J.slice(0,i)+'<span class="pxe-expand-btn">...</span>')}),[J,c,v,E,B]);const W=n.useRef(new Set);T||(W.current=new Set);const D=null!=T?T:W,U={h1:x.H1,h2:x.H2,h3:x.H3,h4:x.H4,h5:x.H5,p:p.P,a:e=>r.jsx(u.A,Object.assign({},e,{filePreviewSeenRef:D})),img:e=>{const n="string"==typeof e.src?e.src:"",t=d.getFilePreviewInfo(n);return t?d.shouldRenderFilePreview(t,D)?r.jsx(d.default,{fileInfo:t,displayName:"string"==typeof e.alt?e.alt:void 0}):r.jsx("a",Object.assign({href:t.url,target:"_blank",rel:"noopener noreferrer",style:{color:M.accent}},{children:e.alt||t.fileName})):r.jsx(f.Img,Object.assign({},e))},iframe:h.Iframe,code:m.Code,ol:g.Ol,ul:g.Ul,li:g.Li,table:j.Table,th:j.Th,tr:j.Tr,td:j.Td,hr:b.Hr,br:b.Br,blockquote:b.Blockquote,span:n=>{var{children:t}=n,i=e.__rest(n,["children"]);return"pxe-expand-btn"===i.className?r.jsx("span",Object.assign({},i,{style:Object.assign({display:"inline",fontWeight:500,color:M.accent,marginLeft:".25rem",userSelect:"none"},H&&{cursor:"pointer"})},H&&{onClick:H},{children:t})):r.jsx("span",Object.assign({},i,{children:t}))},"action-caption":q.ActionCaption,"action-finished":q.ActionFinished,"action-error":q.ActionError,artifact:C.Artifact,"artifact-error":C.ArtifactError,think:k.Think};n.useEffect((()=>{if(!z.current)return;const e=new ResizeObserver((e=>{for(const r of e){const{width:e,height:n}=r.contentRect;L({width:e,height:n})}}));return e.observe(z.current),()=>{e.disconnect()}}),[]);const G=B||J;return r.jsxs("div",Object.assign({className:"pxe-markdown",ref:z,style:Object.assign({position:"relative",overflowWrap:"break-word",display:"grid",gridTemplateColumns:"repeat(1, minmax(0, 1fr))",gap:".625rem",width:"100%"},a)},R&&{dir:"rtl"},{children:[r.jsx(y.default,Object.assign({className:w.default("pxe-prose",s),components:U,remarkPlugins:[O.default,[$.default,{singleDollarTextMath:!1}]],rehypePlugins:[i.rehypeCode,P.default,...I?[]:[S.default],[i.rehypeSanitize,{disableJs:_,disableCss:N}]]},{children:G})),o]}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../../_virtual/_tslib.js"),r=require("react/jsx-runtime"),n=require("react"),t=require("./hooks/usePickaxeMarkdownContext.js"),i=require("./utils/custom-plugins.js"),s=require("react-markdown"),a=require("remark-gfm"),o=require("remark-math"),l=require("rehype-katex"),c=require("rehype-raw"),u=require("./Components/A/index.js"),d=require("./Components/A/FilePreview.js"),p=require("./Components/P/index.js"),f=require("./Components/Img/index.js"),h=require("./Components/Iframe/index.js"),m=require("./Components/Code/index.js"),x=require("./Components/Headings/index.js"),g=require("./Components/List/index.js"),j=require("./Components/Table/index.js"),b=require("./Components/Others/index.js"),k=require("./Components/Action/index.js"),q=require("./Components/Artifact/index.js"),C=require("./Components/Others/Think.js"),w=require("../../../../common/cn.js");function v(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var y=v(s),O=v(a),$=v(o),P=v(l),S=v(c);exports.PickaxeMarkdownRenderer=({className:s,style:a,children:o,value:l,maxLines:c,maxChars:v,multiLineBreaks:A,onExpandClick:H,filePreviewSeenRef:T})=>{const{colors:M,rtl:R,disableHtml:I,disableJs:_,disableCss:N}=t.usePickaxeMarkdownContext(),[E,L]=n.useState({width:0,height:0}),[B,F]=n.useState(null),z=n.useRef(null),J=n.useMemo((()=>{if(!l)return"";let e=l.trim();return e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/\u200B/g,""),e=e.replace(/\\\((.*?)\\\)/g,"$$$ $1 $$$"),e=e.replace(/\\\[(.*?)\\\]/g,"$$$ $1 $$$"),e=e.replace(/<\/think>/g,"\n</think>"),A&&(e=e.replace(/```[\s\S]*?```|(\n(?=\n))/g,((e,r)=>r?"\n\n<br/>\n":e))),e||""}),[l,A]);n.useEffect((()=>{if(v)return void F(J.length>v?J.slice(0,v)+'<span class="pxe-expand-btn">...</span>':null);if(!c)return void F(null);if(!z.current||!J||B)return;const e=z.current,r=parseInt(window.getComputedStyle(e).lineHeight,10),n=c*r;if(!(E.height>n))return;const t=Math.floor(E.width/8),i=Math.floor(t*c);F(J.slice(0,i)+'<span class="pxe-expand-btn">...</span>')}),[J,c,v,E,B]);const W=n.useRef(new Set);T||(W.current=new Set);const D=null!=T?T:W,Q={h1:x.H1,h2:x.H2,h3:x.H3,h4:x.H4,h5:x.H5,p:p.P,a:e=>r.jsx(u.A,Object.assign({},e,{filePreviewSeenRef:D})),img:e=>{const n="string"==typeof e.src?e.src:"",t=d.getFilePreviewInfo(n);return t?d.shouldRenderFilePreview(t,D)?r.jsx(d.default,{fileInfo:t,displayName:"string"==typeof e.alt?e.alt:void 0}):r.jsx("a",Object.assign({href:t.url,target:"_blank",rel:"noopener noreferrer",style:{color:M.accent}},{children:e.alt||t.fileName})):r.jsx(f.Img,Object.assign({},e))},iframe:h.Iframe,code:m.Code,ol:g.Ol,ul:g.Ul,li:g.Li,table:j.Table,th:j.Th,tr:j.Tr,td:j.Td,hr:b.Hr,br:b.Br,blockquote:b.Blockquote,span:n=>{var{children:t}=n,i=e.__rest(n,["children"]);return"pxe-expand-btn"===i.className?r.jsx("span",Object.assign({},i,{style:Object.assign({display:"inline",fontWeight:500,color:M.accent,marginLeft:".25rem",userSelect:"none"},H&&{cursor:"pointer"})},H&&{onClick:H},{children:t})):r.jsx("span",Object.assign({},i,{children:t}))},"action-caption":k.ActionCaption,"action-finished":k.ActionFinished,"action-error":k.ActionError,artifact:q.Artifact,"artifact-error":q.ArtifactError,think:C.Think};n.useEffect((()=>{if(!z.current)return;const e=new ResizeObserver((e=>{for(const r of e){const{width:e,height:n}=r.contentRect;L({width:e,height:n})}}));return e.observe(z.current),()=>{e.disconnect()}}),[]);const U=B||J;return r.jsxs("div",Object.assign({className:"pxe-markdown",ref:z,style:Object.assign({position:"relative",overflowWrap:"break-word",display:"grid",gridTemplateColumns:"repeat(1, minmax(0, 1fr))",gap:".625rem",width:"100%"},a)},R&&{dir:"rtl"},{children:[r.jsx(y.default,Object.assign({className:w.default("pxe-prose",s),components:Q,remarkPlugins:[O.default,[$.default,{singleDollarTextMath:!1}],i.remarkSmartQuotes],rehypePlugins:[i.rehypeCode,P.default,...I?[]:[S.default],[i.rehypeSanitize,{disableJs:_,disableCss:N}]]},{children:U})),o]}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("unist-util-visit");exports.rehypeCode=()=>r=>{e.visit(r,"code",(e=>{var r;e.lang=null!==(r=e.lang)&&void 0!==r?r:"plaintext"}))},exports.rehypeSanitize=(r={})=>t=>{e.visit(t,"element",((t,i,o)=>{if(r.disableJs){if("script"===t.tagName&&o&&"number"==typeof i)return o.children.splice(i,1),[e.SKIP,i];if(t.properties){["onclick","onload","onerror","onmouseover","onmouseout","onfocus","onblur"].forEach((e=>{t.properties[e]&&delete t.properties[e]})),t.properties.href&&"string"==typeof t.properties.href&&t.properties.href.toLowerCase().startsWith("javascript:")&&delete t.properties.href}}if(r.disableCss&&"style"===t.tagName&&o&&"number"==typeof i)return o.children.splice(i,1),[e.SKIP,i]}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("unist-util-visit");const t=new Set(["blockquote","break","delete","footnoteDefinition","heading","html","list","listItem","paragraph","root","table","tableCell","tableRow","thematicBreak","yaml"]),r=new Set(["code","html","inlineCode","inlineMath","math","mdxFlowExpression","mdxJsxFlowElement","mdxJsxTextElement","mdxTextExpression"]),o=/[\s([{<]/,i=/[:;—–-]/,s=(e,l)=>{if(e.type&&r.has(e.type))return;if("text"===e.type&&"string"==typeof e.value)return void(e.value=((e,t)=>{let r="";for(let n=0;n<e.length;n+=1){const a=e[n];if('"'!==a)r+=a,t.previousChar=a;else{const a=(s=t.previousChar,l=e[n+1],!s||o.test(s)||l&&!/\s/.test(l)&&i.test(s)?"“":"”");r+=a,t.previousChar=a}}var s,l;return r})(e.value,l));if(!e.children)return;const n=e.type&&t.has(e.type)?{previousChar:""}:l;e.children.forEach((e=>{s(e,n)}))};exports.rehypeCode=()=>t=>{e.visit(t,"code",(e=>{var t;e.lang=null!==(t=e.lang)&&void 0!==t?t:"plaintext"}))},exports.rehypeSanitize=(t={})=>r=>{e.visit(r,"element",((r,o,i)=>{if(t.disableJs){if("script"===r.tagName&&i&&"number"==typeof o)return i.children.splice(o,1),[e.SKIP,o];if(r.properties){["onclick","onload","onerror","onmouseover","onmouseout","onfocus","onblur"].forEach((e=>{r.properties[e]&&delete r.properties[e]})),r.properties.href&&"string"==typeof r.properties.href&&r.properties.href.toLowerCase().startsWith("javascript:")&&delete r.properties.href}}if(t.disableCss&&"style"===r.tagName&&i&&"number"==typeof o)return i.children.splice(o,1),[e.SKIP,o]}))},exports.remarkSmartQuotes=()=>e=>{s(e,{previousChar:""})};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=require("../../../../../_virtual/_commonjsHelpers.js"),r=require("../../../../../_virtual/cose-base2.js"),i=require("../../../layout-base@1.0.2/node_modules/layout-base/layout-base.js");r.__module.exports,exports.__require=function(){return t||(t=1,o=r.__module,r.__module.exports,e.commonjsGlobal,n=function(t){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:i})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=7)}([function(e,r){e.exports=t},function(t,e,r){var i=r(0).FDLayoutConstants;function o(){}for(var n in i)o[n]=i[n];o.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,o.DEFAULT_RADIAL_SEPARATION=i.DEFAULT_EDGE_LENGTH,o.DEFAULT_COMPONENT_SEPERATION=60,o.TILE=!0,o.TILING_PADDING_VERTICAL=10,o.TILING_PADDING_HORIZONTAL=10,o.TREE_REDUCTION_ON_INCREMENTAL=!1,t.exports=o},function(t,e,r){var i=r(0).FDLayoutEdge;function o(t,e,r){i.call(this,t,e,r)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).LGraph;function o(t,e,r){i.call(this,t,e,r)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).LGraphManager;function o(t){i.call(this,t)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).FDLayoutNode,o=r(0).IMath;function n(t,e,r,o){i.call(this,t,e,r,o)}for(var a in n.prototype=Object.create(i.prototype),i)n[a]=i[a];n.prototype.move=function(){var t=this.graphManager.getLayout();this.displacementX=t.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY=t.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren,Math.abs(this.displacementX)>t.coolingFactor*t.maxNodeDisplacement&&(this.displacementX=t.coolingFactor*t.maxNodeDisplacement*o.sign(this.displacementX)),Math.abs(this.displacementY)>t.coolingFactor*t.maxNodeDisplacement&&(this.displacementY=t.coolingFactor*t.maxNodeDisplacement*o.sign(this.displacementY)),null==this.child||0==this.child.getNodes().length?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),t.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},n.prototype.propogateDisplacementToChildren=function(t,e){for(var r,i=this.getChild().getNodes(),o=0;o<i.length;o++)null==(r=i[o]).getChild()?(r.moveBy(t,e),r.displacementX+=t,r.displacementY+=e):r.propogateDisplacementToChildren(t,e)},n.prototype.setPred1=function(t){this.pred1=t},n.prototype.getPred1=function(){return pred1},n.prototype.getPred2=function(){return pred2},n.prototype.setNext=function(t){this.next=t},n.prototype.getNext=function(){return next},n.prototype.setProcessed=function(t){this.processed=t},n.prototype.isProcessed=function(){return processed},t.exports=n},function(t,e,r){var i=r(0).FDLayout,o=r(4),n=r(3),a=r(5),s=r(2),h=r(1),d=r(0).FDLayoutConstants,g=r(0).LayoutConstants,l=r(0).Point,p=r(0).PointD,c=r(0).Layout,u=r(0).Integer,f=r(0).IGeometry,v=r(0).LGraph,T=r(0).Transform;function E(){i.call(this),this.toBeTiled={}}for(var m in E.prototype=Object.create(i.prototype),i)E[m]=i[m];E.prototype.newGraphManager=function(){var t=new o(this);return this.graphManager=t,t},E.prototype.newGraph=function(t){return new n(null,this.graphManager,t)},E.prototype.newNode=function(t){return new a(this.graphManager,t)},E.prototype.newEdge=function(t){return new s(null,null,t)},E.prototype.initParameters=function(){i.prototype.initParameters.call(this,arguments),this.isSubLayout||(h.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=h.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=h.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.springConstant=d.DEFAULT_SPRING_STRENGTH,this.repulsionConstant=d.DEFAULT_REPULSION_STRENGTH,this.gravityConstant=d.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=d.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=d.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=d.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1,this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/d.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=d.CONVERGENCE_CHECK_PERIOD/this.maxIterations,this.coolingAdjuster=1)},E.prototype.layout=function(){return g.DEFAULT_CREATE_BENDS_AS_NEEDED&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},E.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),this.incremental)h.TREE_REDUCTION_ON_INCREMENTAL&&(this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation(),e=new Set(this.getAllNodes()),r=this.nodesWithGravity.filter((function(t){return e.has(t)})),this.graphManager.setAllNodesToApplyGravitation(r));else{var t=this.getFlatForest();if(t.length>0)this.positionNodesRadially(t);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),r=this.nodesWithGravity.filter((function(t){return e.has(t)}));this.graphManager.setAllNodesToApplyGravitation(r),this.positionNodesRandomly()}}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},E.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished){if(!(this.prunedNodesAll.length>0))return!0;this.isTreeGrowing=!0}if(this.totalIterations%d.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged()){if(!(this.prunedNodesAll.length>0))return!0;this.isTreeGrowing=!0}this.coolingCycle++,0==this.layoutQuality?this.coolingAdjuster=this.coolingCycle:1==this.layoutQuality&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),e=this.nodesWithGravity.filter((function(e){return t.has(e)}));this.graphManager.setAllNodesToApplyGravitation(e),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var r=!this.isTreeGrowing&&!this.isGrowthFinished,i=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(r,i),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},E.prototype.getPositionsData=function(){for(var t=this.graphManager.getAllNodes(),e={},r=0;r<t.length;r++){var i=t[r].rect,o=t[r].id;e[o]={id:o,x:i.getCenterX(),y:i.getCenterY(),w:i.width,h:i.height}}return e},E.prototype.runSpringEmbedder=function(){this.initialAnimationPeriod=25,this.animationPeriod=this.initialAnimationPeriod;var t=!1;if("during"===d.ANIMATE)this.emit("layoutstarted");else{for(;!t;)t=this.tick();this.graphManager.updateBounds()}},E.prototype.calculateNodesToApplyGravitationTo=function(){var t,e,r=[],i=this.graphManager.getGraphs(),o=i.length;for(e=0;e<o;e++)(t=i[e]).updateConnected(),t.isConnected||(r=r.concat(t.getNodes()));return r},E.prototype.createBendpoints=function(){var t=[];t=t.concat(this.graphManager.getAllEdges());var e,r=new Set;for(e=0;e<t.length;e++){var i=t[e];if(!r.has(i)){var o=i.getSource(),n=i.getTarget();if(o==n)i.getBendpoints().push(new p),i.getBendpoints().push(new p),this.createDummyNodesForBendpoints(i),r.add(i);else{var a=[];if(a=(a=a.concat(o.getEdgeListToNode(n))).concat(n.getEdgeListToNode(o)),!r.has(a[0])){var s;if(a.length>1)for(s=0;s<a.length;s++){var h=a[s];h.getBendpoints().push(new p),this.createDummyNodesForBendpoints(h)}a.forEach((function(t){r.add(t)}))}}}if(r.size==t.length)break}},E.prototype.positionNodesRadially=function(t){for(var e=new l(0,0),r=Math.ceil(Math.sqrt(t.length)),i=0,o=0,n=0,a=new p(0,0),s=0;s<t.length;s++){s%r==0&&(n=0,o=i,0!=s&&(o+=h.DEFAULT_COMPONENT_SEPERATION),i=0);var d=t[s],u=c.findCenterOfTree(d);e.x=n,e.y=o,(a=E.radialLayout(d,u,e)).y>i&&(i=Math.floor(a.y)),n=Math.floor(a.x+h.DEFAULT_COMPONENT_SEPERATION)}this.transform(new p(g.WORLD_CENTER_X-a.x/2,g.WORLD_CENTER_Y-a.y/2))},E.radialLayout=function(t,e,r){var i=Math.max(this.maxDiagonalInTree(t),h.DEFAULT_RADIAL_SEPARATION);E.branchRadialLayout(e,null,0,359,0,i);var o=v.calculateBounds(t),n=new T;n.setDeviceOrgX(o.getMinX()),n.setDeviceOrgY(o.getMinY()),n.setWorldOrgX(r.x),n.setWorldOrgY(r.y);for(var a=0;a<t.length;a++)t[a].transform(n);var s=new p(o.getMaxX(),o.getMaxY());return n.inverseTransformPoint(s)},E.branchRadialLayout=function(t,e,r,i,o,n){var a=(i-r+1)/2;a<0&&(a+=180);var s=(a+r)%360*f.TWO_PI/360,h=o*Math.cos(s),d=o*Math.sin(s);t.setCenter(h,d);var g=[],l=(g=g.concat(t.getEdges())).length;null!=e&&l--;for(var p,c=0,u=g.length,v=t.getEdgesBetween(e);v.length>1;){var T=v[0];v.splice(0,1);var m=g.indexOf(T);m>=0&&g.splice(m,1),u--,l--}p=null!=e?(g.indexOf(v[0])+1)%u:0;for(var y=Math.abs(i-r)/l,N=p;c!=l;N=++N%u){var w=g[N].getOtherEnd(t);if(w!=e){var A=(r+c*y)%360,C=(A+y)%360;E.branchRadialLayout(w,t,A,C,o+n,n),c++}}},E.maxDiagonalInTree=function(t){for(var e=u.MIN_VALUE,r=0;r<t.length;r++){var i=t[r].getDiagonal();i>e&&(e=i)}return e},E.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},E.prototype.groupZeroDegreeMembers=function(){var t=this,e={};this.memberGroups={},this.idToDummyNode={};for(var r=[],i=this.graphManager.getAllNodes(),o=0;o<i.length;o++){var n=(s=i[o]).getParent();0!==this.getNodeDegreeWithChildren(s)||null!=n.id&&this.getToBeTiled(n)||r.push(s)}for(o=0;o<r.length;o++){var s,h=(s=r[o]).getParent().id;void 0===e[h]&&(e[h]=[]),e[h]=e[h].concat(s)}Object.keys(e).forEach((function(r){if(e[r].length>1){var i="DummyCompound_"+r;t.memberGroups[i]=e[r];var o=e[r][0].getParent(),n=new a(t.graphManager);n.id=i,n.paddingLeft=o.paddingLeft||0,n.paddingRight=o.paddingRight||0,n.paddingBottom=o.paddingBottom||0,n.paddingTop=o.paddingTop||0,t.idToDummyNode[i]=n;var s=t.getGraphManager().add(t.newGraph(),n),h=o.getChild();h.add(n);for(var d=0;d<e[r].length;d++){var g=e[r][d];h.remove(g),s.add(g)}}}))},E.prototype.clearCompounds=function(){var t={},e={};this.performDFSOnCompounds();for(var r=0;r<this.compoundOrder.length;r++)e[this.compoundOrder[r].id]=this.compoundOrder[r],t[this.compoundOrder[r].id]=[].concat(this.compoundOrder[r].getChild().getNodes()),this.graphManager.remove(this.compoundOrder[r].getChild()),this.compoundOrder[r].child=null;this.graphManager.resetAllNodes(),this.tileCompoundMembers(t,e)},E.prototype.clearZeroDegreeMembers=function(){var t=this,e=this.tiledZeroDegreePack=[];Object.keys(this.memberGroups).forEach((function(r){var i=t.idToDummyNode[r];e[r]=t.tileNodes(t.memberGroups[r],i.paddingLeft+i.paddingRight),i.rect.width=e[r].width,i.rect.height=e[r].height}))},E.prototype.repopulateCompounds=function(){for(var t=this.compoundOrder.length-1;t>=0;t--){var e=this.compoundOrder[t],r=e.id,i=e.paddingLeft,o=e.paddingTop;this.adjustLocations(this.tiledMemberPack[r],e.rect.x,e.rect.y,i,o)}},E.prototype.repopulateZeroDegreeMembers=function(){var t=this,e=this.tiledZeroDegreePack;Object.keys(e).forEach((function(r){var i=t.idToDummyNode[r],o=i.paddingLeft,n=i.paddingTop;t.adjustLocations(e[r],i.rect.x,i.rect.y,o,n)}))},E.prototype.getToBeTiled=function(t){var e=t.id;if(null!=this.toBeTiled[e])return this.toBeTiled[e];var r=t.getChild();if(null==r)return this.toBeTiled[e]=!1,!1;for(var i=r.getNodes(),o=0;o<i.length;o++){var n=i[o];if(this.getNodeDegree(n)>0)return this.toBeTiled[e]=!1,!1;if(null!=n.getChild()){if(!this.getToBeTiled(n))return this.toBeTiled[e]=!1,!1}else this.toBeTiled[n.id]=!1}return this.toBeTiled[e]=!0,!0},E.prototype.getNodeDegree=function(t){t.id;for(var e=t.getEdges(),r=0,i=0;i<e.length;i++){var o=e[i];o.getSource().id!==o.getTarget().id&&(r+=1)}return r},E.prototype.getNodeDegreeWithChildren=function(t){var e=this.getNodeDegree(t);if(null==t.getChild())return e;for(var r=t.getChild().getNodes(),i=0;i<r.length;i++){var o=r[i];e+=this.getNodeDegreeWithChildren(o)}return e},E.prototype.performDFSOnCompounds=function(){this.compoundOrder=[],this.fillCompexOrderByDFS(this.graphManager.getRoot().getNodes())},E.prototype.fillCompexOrderByDFS=function(t){for(var e=0;e<t.length;e++){var r=t[e];null!=r.getChild()&&this.fillCompexOrderByDFS(r.getChild().getNodes()),this.getToBeTiled(r)&&this.compoundOrder.push(r)}},E.prototype.adjustLocations=function(t,e,r,i,o){r+=o;for(var n=e+=i,a=0;a<t.rows.length;a++){var s=t.rows[a];e=n;for(var h=0,d=0;d<s.length;d++){var g=s[d];g.rect.x=e,g.rect.y=r,e+=g.rect.width+t.horizontalPadding,g.rect.height>h&&(h=g.rect.height)}r+=h+t.verticalPadding}},E.prototype.tileCompoundMembers=function(t,e){var r=this;this.tiledMemberPack=[],Object.keys(t).forEach((function(i){var o=e[i];r.tiledMemberPack[i]=r.tileNodes(t[i],o.paddingLeft+o.paddingRight),o.rect.width=r.tiledMemberPack[i].width,o.rect.height=r.tiledMemberPack[i].height}))},E.prototype.tileNodes=function(t,e){var r={rows:[],rowWidth:[],rowHeight:[],width:0,height:e,verticalPadding:h.TILING_PADDING_VERTICAL,horizontalPadding:h.TILING_PADDING_HORIZONTAL};t.sort((function(t,e){return t.rect.width*t.rect.height>e.rect.width*e.rect.height?-1:t.rect.width*t.rect.height<e.rect.width*e.rect.height?1:0}));for(var i=0;i<t.length;i++){var o=t[i];0==r.rows.length?this.insertNodeToRow(r,o,0,e):this.canAddHorizontal(r,o.rect.width,o.rect.height)?this.insertNodeToRow(r,o,this.getShortestRowIndex(r),e):this.insertNodeToRow(r,o,r.rows.length,e),this.shiftToLastRow(r)}return r},E.prototype.insertNodeToRow=function(t,e,r,i){var o=i;r==t.rows.length&&(t.rows.push([]),t.rowWidth.push(o),t.rowHeight.push(0));var n=t.rowWidth[r]+e.rect.width;t.rows[r].length>0&&(n+=t.horizontalPadding),t.rowWidth[r]=n,t.width<n&&(t.width=n);var a=e.rect.height;r>0&&(a+=t.verticalPadding);var s=0;a>t.rowHeight[r]&&(s=t.rowHeight[r],t.rowHeight[r]=a,s=t.rowHeight[r]-s),t.height+=s,t.rows[r].push(e)},E.prototype.getShortestRowIndex=function(t){for(var e=-1,r=Number.MAX_VALUE,i=0;i<t.rows.length;i++)t.rowWidth[i]<r&&(e=i,r=t.rowWidth[i]);return e},E.prototype.getLongestRowIndex=function(t){for(var e=-1,r=Number.MIN_VALUE,i=0;i<t.rows.length;i++)t.rowWidth[i]>r&&(e=i,r=t.rowWidth[i]);return e},E.prototype.canAddHorizontal=function(t,e,r){var i=this.getShortestRowIndex(t);if(i<0)return!0;var o=t.rowWidth[i];if(o+t.horizontalPadding+e<=t.width)return!0;var n,a,s=0;return t.rowHeight[i]<r&&i>0&&(s=r+t.verticalPadding-t.rowHeight[i]),n=t.width-o>=e+t.horizontalPadding?(t.height+s)/(o+e+t.horizontalPadding):(t.height+s)/t.width,s=r+t.verticalPadding,(a=t.width<e?(t.height+s)/e:(t.height+s)/t.width)<1&&(a=1/a),n<1&&(n=1/n),n<a},E.prototype.shiftToLastRow=function(t){var e=this.getLongestRowIndex(t),r=t.rowWidth.length-1,i=t.rows[e],o=i[i.length-1],n=o.width+t.horizontalPadding;if(t.width-t.rowWidth[r]>n&&e!=r){i.splice(-1,1),t.rows[r].push(o),t.rowWidth[e]=t.rowWidth[e]-n,t.rowWidth[r]=t.rowWidth[r]+n,t.width=t.rowWidth[instance.getLongestRowIndex(t)];for(var a=Number.MIN_VALUE,s=0;s<i.length;s++)i[s].height>a&&(a=i[s].height);e>0&&(a+=t.verticalPadding);var h=t.rowHeight[e]+t.rowHeight[r];t.rowHeight[e]=a,t.rowHeight[r]<o.height+t.verticalPadding&&(t.rowHeight[r]=o.height+t.verticalPadding);var d=t.rowHeight[e]+t.rowHeight[r];t.height+=d-h,this.shiftToLastRow(t)}},E.prototype.tilingPreLayout=function(){h.TILE&&(this.groupZeroDegreeMembers(),this.clearCompounds(),this.clearZeroDegreeMembers())},E.prototype.tilingPostLayout=function(){h.TILE&&(this.repopulateZeroDegreeMembers(),this.repopulateCompounds())},E.prototype.reduceTrees=function(){for(var t,e=[],r=!0;r;){var i=this.graphManager.getAllNodes(),o=[];r=!1;for(var n=0;n<i.length;n++)1!=(t=i[n]).getEdges().length||t.getEdges()[0].isInterGraph||null!=t.getChild()||(o.push([t,t.getEdges()[0],t.getOwner()]),r=!0);if(1==r){for(var a=[],s=0;s<o.length;s++)1==o[s][0].getEdges().length&&(a.push(o[s]),o[s][0].getOwner().remove(o[s][0]));e.push(a),this.graphManager.resetAllNodes(),this.graphManager.resetAllEdges()}}this.prunedNodesAll=e},E.prototype.growTree=function(t){for(var e,r=t[t.length-1],i=0;i<r.length;i++)e=r[i],this.findPlaceforPrunedNode(e),e[2].add(e[0]),e[2].add(e[1],e[1].source,e[1].target);t.splice(t.length-1,1),this.graphManager.resetAllNodes(),this.graphManager.resetAllEdges()},E.prototype.findPlaceforPrunedNode=function(t){var e,r,i=t[0],o=(r=i==t[1].source?t[1].target:t[1].source).startX,n=r.finishX,a=r.startY,s=r.finishY,h=[0,0,0,0];if(a>0)for(var g=o;g<=n;g++)h[0]+=this.grid[g][a-1].length+this.grid[g][a].length-1;if(n<this.grid.length-1)for(g=a;g<=s;g++)h[1]+=this.grid[n+1][g].length+this.grid[n][g].length-1;if(s<this.grid[0].length-1)for(g=o;g<=n;g++)h[2]+=this.grid[g][s+1].length+this.grid[g][s].length-1;if(o>0)for(g=a;g<=s;g++)h[3]+=this.grid[o-1][g].length+this.grid[o][g].length-1;for(var l,p,c=u.MAX_VALUE,f=0;f<h.length;f++)h[f]<c?(c=h[f],l=1,p=f):h[f]==c&&l++;if(3==l&&0==c)0==h[0]&&0==h[1]&&0==h[2]?e=1:0==h[0]&&0==h[1]&&0==h[3]?e=0:0==h[0]&&0==h[2]&&0==h[3]?e=3:0==h[1]&&0==h[2]&&0==h[3]&&(e=2);else if(2==l&&0==c){var v=Math.floor(2*Math.random());e=0==h[0]&&0==h[1]?0==v?0:1:0==h[0]&&0==h[2]?0==v?0:2:0==h[0]&&0==h[3]?0==v?0:3:0==h[1]&&0==h[2]?0==v?1:2:0==h[1]&&0==h[3]?0==v?1:3:0==v?2:3}else e=4==l&&0==c?v=Math.floor(4*Math.random()):p;0==e?i.setCenter(r.getCenterX(),r.getCenterY()-r.getHeight()/2-d.DEFAULT_EDGE_LENGTH-i.getHeight()/2):1==e?i.setCenter(r.getCenterX()+r.getWidth()/2+d.DEFAULT_EDGE_LENGTH+i.getWidth()/2,r.getCenterY()):2==e?i.setCenter(r.getCenterX(),r.getCenterY()+r.getHeight()/2+d.DEFAULT_EDGE_LENGTH+i.getHeight()/2):i.setCenter(r.getCenterX()-r.getWidth()/2-d.DEFAULT_EDGE_LENGTH-i.getWidth()/2,r.getCenterY())},t.exports=E},function(t,e,r){var i={};i.layoutBase=r(0),i.CoSEConstants=r(1),i.CoSEEdge=r(2),i.CoSEGraph=r(3),i.CoSEGraphManager=r(4),i.CoSELayout=r(6),i.CoSENode=r(5),t.exports=i}])},o.exports=n(i.__require())),r.__module.exports;var o,n};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=require("../../../../../_virtual/_commonjsHelpers.js"),r=require("../../../../../_virtual/cose-base.js"),i=require("../../../layout-base@1.0.2/node_modules/layout-base/layout-base.js");r.__module.exports,exports.__require=function(){return t||(t=1,o=r.__module,r.__module.exports,e.commonjsGlobal,n=function(t){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:i})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=7)}([function(e,r){e.exports=t},function(t,e,r){var i=r(0).FDLayoutConstants;function o(){}for(var n in i)o[n]=i[n];o.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,o.DEFAULT_RADIAL_SEPARATION=i.DEFAULT_EDGE_LENGTH,o.DEFAULT_COMPONENT_SEPERATION=60,o.TILE=!0,o.TILING_PADDING_VERTICAL=10,o.TILING_PADDING_HORIZONTAL=10,o.TREE_REDUCTION_ON_INCREMENTAL=!1,t.exports=o},function(t,e,r){var i=r(0).FDLayoutEdge;function o(t,e,r){i.call(this,t,e,r)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).LGraph;function o(t,e,r){i.call(this,t,e,r)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).LGraphManager;function o(t){i.call(this,t)}for(var n in o.prototype=Object.create(i.prototype),i)o[n]=i[n];t.exports=o},function(t,e,r){var i=r(0).FDLayoutNode,o=r(0).IMath;function n(t,e,r,o){i.call(this,t,e,r,o)}for(var a in n.prototype=Object.create(i.prototype),i)n[a]=i[a];n.prototype.move=function(){var t=this.graphManager.getLayout();this.displacementX=t.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY=t.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren,Math.abs(this.displacementX)>t.coolingFactor*t.maxNodeDisplacement&&(this.displacementX=t.coolingFactor*t.maxNodeDisplacement*o.sign(this.displacementX)),Math.abs(this.displacementY)>t.coolingFactor*t.maxNodeDisplacement&&(this.displacementY=t.coolingFactor*t.maxNodeDisplacement*o.sign(this.displacementY)),null==this.child||0==this.child.getNodes().length?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),t.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},n.prototype.propogateDisplacementToChildren=function(t,e){for(var r,i=this.getChild().getNodes(),o=0;o<i.length;o++)null==(r=i[o]).getChild()?(r.moveBy(t,e),r.displacementX+=t,r.displacementY+=e):r.propogateDisplacementToChildren(t,e)},n.prototype.setPred1=function(t){this.pred1=t},n.prototype.getPred1=function(){return pred1},n.prototype.getPred2=function(){return pred2},n.prototype.setNext=function(t){this.next=t},n.prototype.getNext=function(){return next},n.prototype.setProcessed=function(t){this.processed=t},n.prototype.isProcessed=function(){return processed},t.exports=n},function(t,e,r){var i=r(0).FDLayout,o=r(4),n=r(3),a=r(5),s=r(2),h=r(1),d=r(0).FDLayoutConstants,g=r(0).LayoutConstants,l=r(0).Point,p=r(0).PointD,c=r(0).Layout,u=r(0).Integer,f=r(0).IGeometry,v=r(0).LGraph,T=r(0).Transform;function E(){i.call(this),this.toBeTiled={}}for(var m in E.prototype=Object.create(i.prototype),i)E[m]=i[m];E.prototype.newGraphManager=function(){var t=new o(this);return this.graphManager=t,t},E.prototype.newGraph=function(t){return new n(null,this.graphManager,t)},E.prototype.newNode=function(t){return new a(this.graphManager,t)},E.prototype.newEdge=function(t){return new s(null,null,t)},E.prototype.initParameters=function(){i.prototype.initParameters.call(this,arguments),this.isSubLayout||(h.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=h.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=h.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.springConstant=d.DEFAULT_SPRING_STRENGTH,this.repulsionConstant=d.DEFAULT_REPULSION_STRENGTH,this.gravityConstant=d.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=d.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=d.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=d.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1,this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/d.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=d.CONVERGENCE_CHECK_PERIOD/this.maxIterations,this.coolingAdjuster=1)},E.prototype.layout=function(){return g.DEFAULT_CREATE_BENDS_AS_NEEDED&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},E.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),this.incremental)h.TREE_REDUCTION_ON_INCREMENTAL&&(this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation(),e=new Set(this.getAllNodes()),r=this.nodesWithGravity.filter((function(t){return e.has(t)})),this.graphManager.setAllNodesToApplyGravitation(r));else{var t=this.getFlatForest();if(t.length>0)this.positionNodesRadially(t);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),r=this.nodesWithGravity.filter((function(t){return e.has(t)}));this.graphManager.setAllNodesToApplyGravitation(r),this.positionNodesRandomly()}}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},E.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished){if(!(this.prunedNodesAll.length>0))return!0;this.isTreeGrowing=!0}if(this.totalIterations%d.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged()){if(!(this.prunedNodesAll.length>0))return!0;this.isTreeGrowing=!0}this.coolingCycle++,0==this.layoutQuality?this.coolingAdjuster=this.coolingCycle:1==this.layoutQuality&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),e=this.nodesWithGravity.filter((function(e){return t.has(e)}));this.graphManager.setAllNodesToApplyGravitation(e),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var r=!this.isTreeGrowing&&!this.isGrowthFinished,i=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(r,i),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},E.prototype.getPositionsData=function(){for(var t=this.graphManager.getAllNodes(),e={},r=0;r<t.length;r++){var i=t[r].rect,o=t[r].id;e[o]={id:o,x:i.getCenterX(),y:i.getCenterY(),w:i.width,h:i.height}}return e},E.prototype.runSpringEmbedder=function(){this.initialAnimationPeriod=25,this.animationPeriod=this.initialAnimationPeriod;var t=!1;if("during"===d.ANIMATE)this.emit("layoutstarted");else{for(;!t;)t=this.tick();this.graphManager.updateBounds()}},E.prototype.calculateNodesToApplyGravitationTo=function(){var t,e,r=[],i=this.graphManager.getGraphs(),o=i.length;for(e=0;e<o;e++)(t=i[e]).updateConnected(),t.isConnected||(r=r.concat(t.getNodes()));return r},E.prototype.createBendpoints=function(){var t=[];t=t.concat(this.graphManager.getAllEdges());var e,r=new Set;for(e=0;e<t.length;e++){var i=t[e];if(!r.has(i)){var o=i.getSource(),n=i.getTarget();if(o==n)i.getBendpoints().push(new p),i.getBendpoints().push(new p),this.createDummyNodesForBendpoints(i),r.add(i);else{var a=[];if(a=(a=a.concat(o.getEdgeListToNode(n))).concat(n.getEdgeListToNode(o)),!r.has(a[0])){var s;if(a.length>1)for(s=0;s<a.length;s++){var h=a[s];h.getBendpoints().push(new p),this.createDummyNodesForBendpoints(h)}a.forEach((function(t){r.add(t)}))}}}if(r.size==t.length)break}},E.prototype.positionNodesRadially=function(t){for(var e=new l(0,0),r=Math.ceil(Math.sqrt(t.length)),i=0,o=0,n=0,a=new p(0,0),s=0;s<t.length;s++){s%r==0&&(n=0,o=i,0!=s&&(o+=h.DEFAULT_COMPONENT_SEPERATION),i=0);var d=t[s],u=c.findCenterOfTree(d);e.x=n,e.y=o,(a=E.radialLayout(d,u,e)).y>i&&(i=Math.floor(a.y)),n=Math.floor(a.x+h.DEFAULT_COMPONENT_SEPERATION)}this.transform(new p(g.WORLD_CENTER_X-a.x/2,g.WORLD_CENTER_Y-a.y/2))},E.radialLayout=function(t,e,r){var i=Math.max(this.maxDiagonalInTree(t),h.DEFAULT_RADIAL_SEPARATION);E.branchRadialLayout(e,null,0,359,0,i);var o=v.calculateBounds(t),n=new T;n.setDeviceOrgX(o.getMinX()),n.setDeviceOrgY(o.getMinY()),n.setWorldOrgX(r.x),n.setWorldOrgY(r.y);for(var a=0;a<t.length;a++)t[a].transform(n);var s=new p(o.getMaxX(),o.getMaxY());return n.inverseTransformPoint(s)},E.branchRadialLayout=function(t,e,r,i,o,n){var a=(i-r+1)/2;a<0&&(a+=180);var s=(a+r)%360*f.TWO_PI/360,h=o*Math.cos(s),d=o*Math.sin(s);t.setCenter(h,d);var g=[],l=(g=g.concat(t.getEdges())).length;null!=e&&l--;for(var p,c=0,u=g.length,v=t.getEdgesBetween(e);v.length>1;){var T=v[0];v.splice(0,1);var m=g.indexOf(T);m>=0&&g.splice(m,1),u--,l--}p=null!=e?(g.indexOf(v[0])+1)%u:0;for(var y=Math.abs(i-r)/l,N=p;c!=l;N=++N%u){var w=g[N].getOtherEnd(t);if(w!=e){var A=(r+c*y)%360,C=(A+y)%360;E.branchRadialLayout(w,t,A,C,o+n,n),c++}}},E.maxDiagonalInTree=function(t){for(var e=u.MIN_VALUE,r=0;r<t.length;r++){var i=t[r].getDiagonal();i>e&&(e=i)}return e},E.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},E.prototype.groupZeroDegreeMembers=function(){var t=this,e={};this.memberGroups={},this.idToDummyNode={};for(var r=[],i=this.graphManager.getAllNodes(),o=0;o<i.length;o++){var n=(s=i[o]).getParent();0!==this.getNodeDegreeWithChildren(s)||null!=n.id&&this.getToBeTiled(n)||r.push(s)}for(o=0;o<r.length;o++){var s,h=(s=r[o]).getParent().id;void 0===e[h]&&(e[h]=[]),e[h]=e[h].concat(s)}Object.keys(e).forEach((function(r){if(e[r].length>1){var i="DummyCompound_"+r;t.memberGroups[i]=e[r];var o=e[r][0].getParent(),n=new a(t.graphManager);n.id=i,n.paddingLeft=o.paddingLeft||0,n.paddingRight=o.paddingRight||0,n.paddingBottom=o.paddingBottom||0,n.paddingTop=o.paddingTop||0,t.idToDummyNode[i]=n;var s=t.getGraphManager().add(t.newGraph(),n),h=o.getChild();h.add(n);for(var d=0;d<e[r].length;d++){var g=e[r][d];h.remove(g),s.add(g)}}}))},E.prototype.clearCompounds=function(){var t={},e={};this.performDFSOnCompounds();for(var r=0;r<this.compoundOrder.length;r++)e[this.compoundOrder[r].id]=this.compoundOrder[r],t[this.compoundOrder[r].id]=[].concat(this.compoundOrder[r].getChild().getNodes()),this.graphManager.remove(this.compoundOrder[r].getChild()),this.compoundOrder[r].child=null;this.graphManager.resetAllNodes(),this.tileCompoundMembers(t,e)},E.prototype.clearZeroDegreeMembers=function(){var t=this,e=this.tiledZeroDegreePack=[];Object.keys(this.memberGroups).forEach((function(r){var i=t.idToDummyNode[r];e[r]=t.tileNodes(t.memberGroups[r],i.paddingLeft+i.paddingRight),i.rect.width=e[r].width,i.rect.height=e[r].height}))},E.prototype.repopulateCompounds=function(){for(var t=this.compoundOrder.length-1;t>=0;t--){var e=this.compoundOrder[t],r=e.id,i=e.paddingLeft,o=e.paddingTop;this.adjustLocations(this.tiledMemberPack[r],e.rect.x,e.rect.y,i,o)}},E.prototype.repopulateZeroDegreeMembers=function(){var t=this,e=this.tiledZeroDegreePack;Object.keys(e).forEach((function(r){var i=t.idToDummyNode[r],o=i.paddingLeft,n=i.paddingTop;t.adjustLocations(e[r],i.rect.x,i.rect.y,o,n)}))},E.prototype.getToBeTiled=function(t){var e=t.id;if(null!=this.toBeTiled[e])return this.toBeTiled[e];var r=t.getChild();if(null==r)return this.toBeTiled[e]=!1,!1;for(var i=r.getNodes(),o=0;o<i.length;o++){var n=i[o];if(this.getNodeDegree(n)>0)return this.toBeTiled[e]=!1,!1;if(null!=n.getChild()){if(!this.getToBeTiled(n))return this.toBeTiled[e]=!1,!1}else this.toBeTiled[n.id]=!1}return this.toBeTiled[e]=!0,!0},E.prototype.getNodeDegree=function(t){t.id;for(var e=t.getEdges(),r=0,i=0;i<e.length;i++){var o=e[i];o.getSource().id!==o.getTarget().id&&(r+=1)}return r},E.prototype.getNodeDegreeWithChildren=function(t){var e=this.getNodeDegree(t);if(null==t.getChild())return e;for(var r=t.getChild().getNodes(),i=0;i<r.length;i++){var o=r[i];e+=this.getNodeDegreeWithChildren(o)}return e},E.prototype.performDFSOnCompounds=function(){this.compoundOrder=[],this.fillCompexOrderByDFS(this.graphManager.getRoot().getNodes())},E.prototype.fillCompexOrderByDFS=function(t){for(var e=0;e<t.length;e++){var r=t[e];null!=r.getChild()&&this.fillCompexOrderByDFS(r.getChild().getNodes()),this.getToBeTiled(r)&&this.compoundOrder.push(r)}},E.prototype.adjustLocations=function(t,e,r,i,o){r+=o;for(var n=e+=i,a=0;a<t.rows.length;a++){var s=t.rows[a];e=n;for(var h=0,d=0;d<s.length;d++){var g=s[d];g.rect.x=e,g.rect.y=r,e+=g.rect.width+t.horizontalPadding,g.rect.height>h&&(h=g.rect.height)}r+=h+t.verticalPadding}},E.prototype.tileCompoundMembers=function(t,e){var r=this;this.tiledMemberPack=[],Object.keys(t).forEach((function(i){var o=e[i];r.tiledMemberPack[i]=r.tileNodes(t[i],o.paddingLeft+o.paddingRight),o.rect.width=r.tiledMemberPack[i].width,o.rect.height=r.tiledMemberPack[i].height}))},E.prototype.tileNodes=function(t,e){var r={rows:[],rowWidth:[],rowHeight:[],width:0,height:e,verticalPadding:h.TILING_PADDING_VERTICAL,horizontalPadding:h.TILING_PADDING_HORIZONTAL};t.sort((function(t,e){return t.rect.width*t.rect.height>e.rect.width*e.rect.height?-1:t.rect.width*t.rect.height<e.rect.width*e.rect.height?1:0}));for(var i=0;i<t.length;i++){var o=t[i];0==r.rows.length?this.insertNodeToRow(r,o,0,e):this.canAddHorizontal(r,o.rect.width,o.rect.height)?this.insertNodeToRow(r,o,this.getShortestRowIndex(r),e):this.insertNodeToRow(r,o,r.rows.length,e),this.shiftToLastRow(r)}return r},E.prototype.insertNodeToRow=function(t,e,r,i){var o=i;r==t.rows.length&&(t.rows.push([]),t.rowWidth.push(o),t.rowHeight.push(0));var n=t.rowWidth[r]+e.rect.width;t.rows[r].length>0&&(n+=t.horizontalPadding),t.rowWidth[r]=n,t.width<n&&(t.width=n);var a=e.rect.height;r>0&&(a+=t.verticalPadding);var s=0;a>t.rowHeight[r]&&(s=t.rowHeight[r],t.rowHeight[r]=a,s=t.rowHeight[r]-s),t.height+=s,t.rows[r].push(e)},E.prototype.getShortestRowIndex=function(t){for(var e=-1,r=Number.MAX_VALUE,i=0;i<t.rows.length;i++)t.rowWidth[i]<r&&(e=i,r=t.rowWidth[i]);return e},E.prototype.getLongestRowIndex=function(t){for(var e=-1,r=Number.MIN_VALUE,i=0;i<t.rows.length;i++)t.rowWidth[i]>r&&(e=i,r=t.rowWidth[i]);return e},E.prototype.canAddHorizontal=function(t,e,r){var i=this.getShortestRowIndex(t);if(i<0)return!0;var o=t.rowWidth[i];if(o+t.horizontalPadding+e<=t.width)return!0;var n,a,s=0;return t.rowHeight[i]<r&&i>0&&(s=r+t.verticalPadding-t.rowHeight[i]),n=t.width-o>=e+t.horizontalPadding?(t.height+s)/(o+e+t.horizontalPadding):(t.height+s)/t.width,s=r+t.verticalPadding,(a=t.width<e?(t.height+s)/e:(t.height+s)/t.width)<1&&(a=1/a),n<1&&(n=1/n),n<a},E.prototype.shiftToLastRow=function(t){var e=this.getLongestRowIndex(t),r=t.rowWidth.length-1,i=t.rows[e],o=i[i.length-1],n=o.width+t.horizontalPadding;if(t.width-t.rowWidth[r]>n&&e!=r){i.splice(-1,1),t.rows[r].push(o),t.rowWidth[e]=t.rowWidth[e]-n,t.rowWidth[r]=t.rowWidth[r]+n,t.width=t.rowWidth[instance.getLongestRowIndex(t)];for(var a=Number.MIN_VALUE,s=0;s<i.length;s++)i[s].height>a&&(a=i[s].height);e>0&&(a+=t.verticalPadding);var h=t.rowHeight[e]+t.rowHeight[r];t.rowHeight[e]=a,t.rowHeight[r]<o.height+t.verticalPadding&&(t.rowHeight[r]=o.height+t.verticalPadding);var d=t.rowHeight[e]+t.rowHeight[r];t.height+=d-h,this.shiftToLastRow(t)}},E.prototype.tilingPreLayout=function(){h.TILE&&(this.groupZeroDegreeMembers(),this.clearCompounds(),this.clearZeroDegreeMembers())},E.prototype.tilingPostLayout=function(){h.TILE&&(this.repopulateZeroDegreeMembers(),this.repopulateCompounds())},E.prototype.reduceTrees=function(){for(var t,e=[],r=!0;r;){var i=this.graphManager.getAllNodes(),o=[];r=!1;for(var n=0;n<i.length;n++)1!=(t=i[n]).getEdges().length||t.getEdges()[0].isInterGraph||null!=t.getChild()||(o.push([t,t.getEdges()[0],t.getOwner()]),r=!0);if(1==r){for(var a=[],s=0;s<o.length;s++)1==o[s][0].getEdges().length&&(a.push(o[s]),o[s][0].getOwner().remove(o[s][0]));e.push(a),this.graphManager.resetAllNodes(),this.graphManager.resetAllEdges()}}this.prunedNodesAll=e},E.prototype.growTree=function(t){for(var e,r=t[t.length-1],i=0;i<r.length;i++)e=r[i],this.findPlaceforPrunedNode(e),e[2].add(e[0]),e[2].add(e[1],e[1].source,e[1].target);t.splice(t.length-1,1),this.graphManager.resetAllNodes(),this.graphManager.resetAllEdges()},E.prototype.findPlaceforPrunedNode=function(t){var e,r,i=t[0],o=(r=i==t[1].source?t[1].target:t[1].source).startX,n=r.finishX,a=r.startY,s=r.finishY,h=[0,0,0,0];if(a>0)for(var g=o;g<=n;g++)h[0]+=this.grid[g][a-1].length+this.grid[g][a].length-1;if(n<this.grid.length-1)for(g=a;g<=s;g++)h[1]+=this.grid[n+1][g].length+this.grid[n][g].length-1;if(s<this.grid[0].length-1)for(g=o;g<=n;g++)h[2]+=this.grid[g][s+1].length+this.grid[g][s].length-1;if(o>0)for(g=a;g<=s;g++)h[3]+=this.grid[o-1][g].length+this.grid[o][g].length-1;for(var l,p,c=u.MAX_VALUE,f=0;f<h.length;f++)h[f]<c?(c=h[f],l=1,p=f):h[f]==c&&l++;if(3==l&&0==c)0==h[0]&&0==h[1]&&0==h[2]?e=1:0==h[0]&&0==h[1]&&0==h[3]?e=0:0==h[0]&&0==h[2]&&0==h[3]?e=3:0==h[1]&&0==h[2]&&0==h[3]&&(e=2);else if(2==l&&0==c){var v=Math.floor(2*Math.random());e=0==h[0]&&0==h[1]?0==v?0:1:0==h[0]&&0==h[2]?0==v?0:2:0==h[0]&&0==h[3]?0==v?0:3:0==h[1]&&0==h[2]?0==v?1:2:0==h[1]&&0==h[3]?0==v?1:3:0==v?2:3}else e=4==l&&0==c?v=Math.floor(4*Math.random()):p;0==e?i.setCenter(r.getCenterX(),r.getCenterY()-r.getHeight()/2-d.DEFAULT_EDGE_LENGTH-i.getHeight()/2):1==e?i.setCenter(r.getCenterX()+r.getWidth()/2+d.DEFAULT_EDGE_LENGTH+i.getWidth()/2,r.getCenterY()):2==e?i.setCenter(r.getCenterX(),r.getCenterY()+r.getHeight()/2+d.DEFAULT_EDGE_LENGTH+i.getHeight()/2):i.setCenter(r.getCenterX()-r.getWidth()/2-d.DEFAULT_EDGE_LENGTH-i.getWidth()/2,r.getCenterY())},t.exports=E},function(t,e,r){var i={};i.layoutBase=r(0),i.CoSEConstants=r(1),i.CoSEEdge=r(2),i.CoSEGraph=r(3),i.CoSEGraphManager=r(4),i.CoSELayout=r(6),i.CoSENode=r(5),t.exports=i}])},o.exports=n(i.__require())),r.__module.exports;var o,n};