UNPKG

decocms

Version:

Deco CMS — Self-hostable MCP Gateway for managing AI connections and tools

12 lines (11 loc) • 12.7 kB
import{r as z,c as H,j as u,gL as Y,gM as ee,E as te,J as ne,a as oe,m as q,h as se}from"./index-DoEtSiIe.js";import{D as ie,E as re,C as ae}from"./types-rurFGFZy.js";const W=["default-src 'none'","script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'","style-src 'unsafe-inline'","img-src * data: blob:","media-src * data: blob:","font-src data:","connect-src 'none'","frame-src 'none'","worker-src blob:","form-action 'none'","base-uri 'none'"].join("; ");function le(o,e={}){const n=`<meta http-equiv="Content-Security-Policy" content="${de(e)}">`,s=/<head(\s[^>]*)?>|<HEAD(\s[^>]*)?>/i,i=o.match(s);if(i){const l=(i.index??0)+i[0].length;return o.slice(0,l)+` `+n+o.slice(l)}const r=/<html(\s[^>]*)?>|<HTML(\s[^>]*)?>/i,a=o.match(r);if(a){const l=(a.index??0)+a[0].length;return o.slice(0,l)+` <head> `+n+` </head>`+o.slice(l)}const c=/<!DOCTYPE[^>]*>/i,d=o.match(c);if(d){const l=(d.index??0)+d[0].length;return o.slice(0,l)+` <head> `+n+` </head>`+o.slice(l)}return`<head> `+n+` </head> `+o}const ce=/^https?:\/\/(\*\.)?[a-zA-Z0-9._-]+(:\d+)?\/?$/;function j(o){return!o||o.length===0?[]:o.filter(e=>ce.test(e))}function ue(o){return[...o,...o.map(e=>e.replace(/^http/,"ws"))]}function de(o){if(o.csp)return o.csp;const e=o.resourceCsp;if(!e)return W;const t=j(e.resourceDomains),n=j(e.connectDomains),s=j(e.frameDomains),i=j(e.baseUriDomains),r=t.length>0,a=n.length>0,c=s.length>0,d=i.length>0;if(!r&&!a&&!c&&!d)return W;const l=t.join(" ");return["default-src 'none'",r?`script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' ${l}`:"script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'",r?`style-src 'unsafe-inline' ${l}`:"style-src 'unsafe-inline'",r?`img-src * data: blob: ${l}`:"img-src * data: blob:",r?`media-src * data: blob: ${l}`:"media-src * data: blob:",r?`font-src data: ${l}`:"font-src data:",a?`connect-src ${ue(n).join(" ")}`:"connect-src 'none'",c?`frame-src ${s.join(" ")}`:"frame-src 'none'","worker-src blob:","form-action 'none'",d?`base-uri ${i.join(" ")}`:"base-uri 'none'"].join("; ")}const he=[["--background","--color-background-primary"],["--muted","--color-background-secondary"],["--accent","--color-background-tertiary"],["--destructive","--color-background-danger"],["--success","--color-background-success"],["--warning","--color-background-warning"],["--foreground","--color-text-primary"],["--muted-foreground","--color-text-secondary"],["--accent-foreground","--color-text-tertiary"],["--destructive-foreground","--color-text-danger"],["--success-foreground","--color-text-success"],["--warning-foreground","--color-text-warning"],["--border","--color-border-primary"],["--input","--color-border-secondary"],["--ring","--color-ring-primary"],["--font-sans","--font-sans"],["--font-mono","--font-mono"],["--font-weight-normal","--font-weight-normal"],["--font-weight-medium","--font-weight-medium"],["--font-weight-semibold","--font-weight-semibold"],["--font-weight-bold","--font-weight-bold"],["--radius","--border-radius-md"],["--default-border-width","--border-width-regular"],["--shadow-sm","--shadow-sm"],["--shadow-md","--shadow-md"],["--shadow-lg","--shadow-lg"]];function fe(){if(typeof document>"u")return{};const o=getComputedStyle(document.documentElement),e={};for(const[t,n]of he){const s=o.getPropertyValue(t).trim();s&&(e[n]=s)}return{variables:e}}const me={name:"Studio",version:"1.0.0"},ge={openLinks:{},serverTools:{},serverResources:{},logging:{},message:{},downloadFile:{},updateModelContext:{text:{}}},pe=15e3;function be(){return typeof navigator>"u"?"en":navigator.language??"en"}function we(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function ye(){return typeof navigator>"u"?"web":/Mobi|Android/i.test(navigator.userAgent)?"mobile":"web"}function Z(o,e,t,n,s,i){return{theme:ae(),styles:fe(),displayMode:o,availableDisplayModes:["inline","fullscreen"],locale:s??be(),timeZone:we(),platform:ye(),...e!=null&&{toolInfo:e},...t!=null&&{containerDimensions:{maxHeight:t}},...n!=null&&{orgId:n},...i!=null&&{user:i}}}const V=new Set;let G=!1;function xe(){if(G||typeof document>"u")return;G=!0;const o=()=>V.forEach(e=>e());new MutationObserver(o).observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",o)}function Te(o){return V.add(o),xe(),()=>V.delete(o)}class ve{bridge=null;timeout=null;disposed=!1;unsubTheme=null;snapshot;listeners=new Set;config;constructor(e){this.config=e,this.snapshot=Object.freeze({height:e.minHeight,isLoading:!0,error:null})}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));getSnapshot=()=>this.snapshot;updateConfig(e){const t=this.config;this.config=e,!(!this.bridge||this.disposed)&&((e.displayMode!==t.displayMode||e.locale!==t.locale||e.user!==t.user)&&this.pushHostContext(),e.toolInput!==t.toolInput&&e.toolInput!=null&&this.bridge.sendToolInput({arguments:e.toolInput}),e.toolResult!==t.toolResult&&e.toolResult!=null&&this.bridge.sendToolResult(e.toolResult))}pushHostContext(){if(!this.bridge||this.disposed)return;const{displayMode:e,maxHeight:t,toolInfo:n,orgId:s,locale:i,user:r}=this.config;this.bridge.setHostContext(Z(e,n,t,s,i,r))}set(e){const t=this.snapshot,n={...t,...e};if(!(n.height===t.height&&n.isLoading===t.isLoading&&n.error===t.error)){this.snapshot=Object.freeze(n);for(const s of this.listeners)s()}}teardown(){(this.bridge||this.timeout||this.unsubTheme)&&this.config.onTeardown?.(),this.disposed=!0,this.unsubTheme?.(),this.unsubTheme=null,this.bridge&&(this.bridge.teardownResource({}).catch(()=>{}),this.bridge.close(),this.bridge=null),this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}attach=e=>{if(this.teardown(),this.disposed=!1,this.set({height:this.config.minHeight,isLoading:!0,error:null}),!e)return;e.onerror=()=>{this.disposed||this.set({error:"Failed to load app",isLoading:!1})};let t=!1;e.onload=()=>{if(!this.disposed){if(!t){t=!0;return}this.set({height:this.config.minHeight,isLoading:!0,error:null}),this.connectBridge(e)}},this.connectBridge(e)};connectBridge(e){this.clearTimeout(),this.unsubTheme?.(),this.unsubTheme=null,this.bridge&&(this.bridge.close(),this.bridge=null);try{const{client:t,displayMode:n,maxHeight:s,toolInfo:i,orgId:r,locale:a,user:c}=this.config,d=Z(n,i,s,r,a,c),l=new ie(t,me,ge,{hostContext:d});this.bridge=l,this.registerHandlers(l),this.startInitTimeout(),this.registerInitHandler(l),this.connectTransport(l,e),this.unsubTheme=Te(()=>this.pushHostContext())}catch(t){this.clearTimeout(),console.error("Failed to create AppBridge:",t),this.set({error:t instanceof Error?t.message:"Unknown error",isLoading:!1})}}registerHandlers(e){e.onopenlink=async({url:t})=>{let n=null;try{n=new URL(t)}catch{}if(!n||!["http:","https:"].includes(n.protocol))throw new Error("Only http and https URLs are allowed");return window.open(t,"_blank","noopener,noreferrer"),{}},e.onmessage=async t=>(this.config.onMessage?.(t),{}),e.onupdatemodelcontext=async t=>(this.config.onUpdateModelContext?.(t),{}),e.onsizechange=({height:t})=>{if(!this.disposed&&t!=null){const{minHeight:n,maxHeight:s}=this.config;this.set({height:Math.max(n,Math.min(s,t))})}},e.onloggingmessage=({level:t,data:n})=>{console[t==="error"?"error":"debug"](`[MCP App ${this.config.toolInfo?.tool.name??"unknown"}]`,n)},e.onrequestdisplaymode=async({mode:t})=>({mode:this.config.onRequestDisplayMode?await this.config.onRequestDisplayMode(t):this.config.displayMode}),e.ondownloadfile=async({contents:t})=>{for(const n of t)if(n.type==="resource"){const s=n.resource,i="blob"in s?new Blob([Uint8Array.from(atob(s.blob),c=>c.charCodeAt(0))],{type:s.mimeType}):new Blob([s.text??""],{type:s.mimeType}),r=URL.createObjectURL(i),a=document.createElement("a");a.href=r,a.download=s.uri.split("/").pop()??"download",a.click(),URL.revokeObjectURL(r)}else n.type==="resource_link"&&window.open(n.uri,"_blank");return{}}}registerInitHandler(e){e.oninitialized=()=>{if(this.disposed)return;this.clearTimeout(),this.set({isLoading:!1});const{toolInput:t,toolResult:n}=this.config;t!=null&&e.sendToolInput({arguments:t}),n!=null&&e.sendToolResult(n)}}startInitTimeout(){this.timeout=setTimeout(()=>{this.disposed||this.set({error:"App took too long to load",isLoading:!1})},pe)}clearTimeout(){this.timeout&&(globalThis.clearTimeout(this.timeout),this.timeout=null)}connectTransport(e,t){if(!t.contentWindow){console.warn("iframe contentWindow not yet available");return}const n=new re(t.contentWindow,t.contentWindow);e.connect(n).catch(s=>{this.disposed||(this.clearTimeout(),console.error("AppBridge connect failed:",s),this.set({error:s instanceof Error?s.message:"Connection failed",isLoading:!1}))})}}function Me(o){const e=z.useRef(new ve(o));z.useEffect(()=>{e.current.updateConfig(o)},[o]);const{height:t,isLoading:n,error:s}=z.useSyncExternalStore(e.current.subscribe,e.current.getSnapshot);return{height:t,isLoading:n,error:s,iframeRef:e.current.attach}}const J=new Set;function Re(o){const e=o?.contents?.[0];return!e||!("text"in e)||!e.text?null:le(e.text,{resourceCsp:e._meta?.ui?.csp})}function K(o){const e=H.c(43),{html:t,uri:n,orgId:s,toolInfo:i,toolInput:r,toolResult:a,displayMode:c,minHeight:d,maxHeight:l,client:v,onMessage:D,onUpdateModelContext:P,onTeardown:k,onRequestDisplayMode:A,className:m}=o,h=c===void 0?"inline":c,E=d===void 0?150:d,U=l===void 0?600:l;n&&!J.has(n)&&(J.add(n),te("mcp_app_opened",{resource_uri:n,display_mode:h,tool_name:i?.tool?.name??null}));const[_]=ne(),{data:Q}=oe.useSession(),f=Q?.user;let M;e[0]!==f?(M=f?{id:f.id,name:f.name,email:f.email,avatarUrl:f.image??void 0}:void 0,e[0]=f,e[1]=M):M=e[1];const $=M;let R;e[2]!==v||e[3]!==h||e[4]!==U||e[5]!==E||e[6]!==D||e[7]!==A||e[8]!==k||e[9]!==P||e[10]!==s||e[11]!==_.language||e[12]!==i||e[13]!==r||e[14]!==a||e[15]!==$?(R={client:v,displayMode:h,minHeight:E,maxHeight:U,orgId:s,user:$,locale:_.language,toolInfo:i,toolInput:r,toolResult:a,onMessage:D,onUpdateModelContext:P,onTeardown:k,onRequestDisplayMode:A},e[2]=v,e[3]=h,e[4]=U,e[5]=E,e[6]=D,e[7]=A,e[8]=k,e[9]=P,e[10]=s,e[11]=_.language,e[12]=i,e[13]=r,e[14]=a,e[15]=$,e[16]=R):R=e[16];const{height:O,isLoading:C,error:I,iframeRef:N}=Me(R);if(!t)return null;if(I){let x;e[17]!==m?(x=q("flex items-center justify-center p-4 text-destructive bg-destructive/10 rounded-lg",m),e[17]=m,e[18]=x):x=e[18];let T;e[19]!==I?(T=u.jsx("span",{className:"text-sm",children:I}),e[19]=I,e[20]=T):T=e[20];let L;return e[21]!==x||e[22]!==T?(L=u.jsx("div",{className:x,children:T}),e[21]=x,e[22]=T,e[23]=L):L=e[23],L}const X=i?.tool.name;let g;e[24]!==m?(g=q("relative w-full overflow-hidden rounded-lg",m),e[24]=m,e[25]=g):g=e[25];let p;e[26]!==h||e[27]!==O?(p=h!=="fullscreen"?{height:`${O}px`}:void 0,e[26]=h,e[27]=O,e[28]=p):p=e[28];let b;e[29]!==C?(b=C&&u.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background z-10",children:u.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[u.jsx(se,{className:"size-4"}),u.jsx("span",{className:"text-sm",children:"Loading app..."})]})}),e[29]=C,e[30]=b):b=e[30];const B=C&&"invisible";let w;e[31]!==B?(w=q("w-full h-full border-0",B),e[31]=B,e[32]=w):w=e[32];const F=`MCP App: ${X??n}`;let y;e[33]!==t||e[34]!==N||e[35]!==w||e[36]!==F?(y=u.jsx("iframe",{ref:N,srcDoc:t,sandbox:"allow-scripts allow-forms allow-popups allow-downloads",className:w,title:F}),e[33]=t,e[34]=N,e[35]=w,e[36]=F,e[37]=y):y=e[37];let S;return e[38]!==y||e[39]!==g||e[40]!==p||e[41]!==b?(S=u.jsxs("div",{className:g,style:p,children:[b,y]}),e[38]=y,e[39]=g,e[40]=p,e[41]=b,e[42]=S):S=e[42],S}function Ce(o){const e=H.c(13);let t,n,s,i;e[0]!==o?({resourceURI:i,orgSlug:s,connectionId:t,...n}=o,e[0]=o,e[1]=t,e[2]=n,e[3]=s,e[4]=i):(t=e[1],n=e[2],s=e[3],i=e[4]);let r;e[5]!==t||e[6]!==s||e[7]!==i?(r={orgSlug:s,connectionId:t,uri:i,staleTime:3e4},e[5]=t,e[6]=s,e[7]=i,e[8]=r):r=e[8];const a=Y(r);let c;return e[9]!==n||e[10]!==a.data||e[11]!==i?(c=u.jsx(K,{html:a.data,uri:i,...n}),e[9]=n,e[10]=a.data,e[11]=i,e[12]=c):c=e[12],c}function Ie(o){const e=H.c(10);let t,n;e[0]!==o?({resourceURI:n,...t}=o,e[0]=o,e[1]=t,e[2]=n):(t=e[1],n=e[2]);let s;e[3]!==t.client||e[4]!==n?(s={client:t.client,uri:n,staleTime:3e4},e[3]=t.client,e[4]=n,e[5]=s):s=e[5];const{data:i}=ee(s),r=Re(i);let a;return e[6]!==t||e[7]!==r||e[8]!==n?(a=u.jsx(K,{html:r,uri:n,...t}),e[6]=t,e[7]=r,e[8]=n,e[9]=a):a=e[9],a}function je(o){const e=H.c(4);if(o.orgSlug&&o.connectionId){let n;return e[0]!==o?(n=u.jsx(Ce,{...o,orgSlug:o.orgSlug,connectionId:o.connectionId}),e[0]=o,e[1]=n):n=e[1],n}let t;return e[2]!==o?(t=u.jsx(Ie,{...o}),e[2]=o,e[3]=t):t=e[3],t}export{je as M};