import{j as e,r as t}from"./vendor-react-RSDKEZ60.js";import{aC as s,bR as n,a0 as a,h as r,eI as o,jB as i,uK as l,uL as c,w as d,x as u,Ra as h,Rb as m,ul as p,uM as f,uN as g,Rc as y,Rd as w,jb as C,m as b,jz as v,jJ as R,jy as x,Gu as k,un as q,y as S,q as P,Re as M}from"./c818056db-BBpc4u6S.js";import{u as _,M as E}from"./vendor-intl-BNW8a19h.js";import{o as j,a as L,s as I}from"./vendor-zod-D1-NLVm9.js";import{m as A,d as T,f as O}from"./vendor-ant-cds-CBh5POw1.js";import{A as F,m as N}from"./vendor-motion-Bnihp5FA.js";const D=({isOpen:t=!1,filename:r,onClose:o,onConfirm:i})=>{const l=_();return e.jsxs(s,{title:l.formatMessage({defaultMessage:"Download file",id:"k9qHCCLPA5"}),isOpen:t,onClose:o,children:[e.jsxs("p",{className:"break-words flex flex-col gap-1 pt-3 text-sm",children:[e.jsx(E,{defaultMessage:"Artifacts are created by other users and aren\u2019t verified by Anthropic. Only download files you trust.",id:"MDebIUeu03"}),e.jsx("pre",{className:"font-mono text-wrap text-sm p-2 my-2 rounded border border-border-400 bg-bg-000",children:r})]}),e.jsxs(n,{children:[e.jsx(a,{variant:"secondary",onClick:o,children:e.jsx(E,{defaultMessage:"Cancel",id:"47FYwba+bI"})}),e.jsx(a,{onClick:i,children:e.jsx(E,{defaultMessage:"Download file",id:"k9qHCCLPA5"})})]})]})},z=({isOpen:i=!1,onClose:l,onConfirm:c})=>{const d=_(),[u,h]=t.useState(!1),{activeOrganization:m}=r();return t.useEffect(()=>{i&&!m?.uuid&&l()},[i,m?.uuid,l]),e.jsxs(s,{title:d.formatMessage({defaultMessage:"Access shared data",id:"BgSBBhOmOQ"}),isOpen:i,onClose:l,children:[e.jsx("p",{className:"break-words flex flex-col gap-1 pt-3 text-sm",children:e.jsx(E,{defaultMessage:"This artifact wants to access shared data that other users of this artifact can see. You might see unverified content from others, and any data you save will be visible to them. Make sure you aren\u2019t sharing sensitive information.",id:"HmdzJSxTnq"})}),e.jsx("div",{className:"mt-4 mb-2",children:e.jsx(o,{label:e.jsx("span",{className:"text-sm text-text-100",children:e.jsx(E,{defaultMessage:"Remember my choice for this artifact",id:"Rb5Xk94v+l"})}),checked:u,onChange:h})}),e.jsxs(n,{children:[e.jsx(a,{variant:"secondary",onClick:()=>l(u),children:e.jsx(E,{defaultMessage:"Deny",id:"htvX+Z11l+"})}),e.jsx(a,{onClick:()=>c(u),children:e.jsx(E,{defaultMessage:"Allow",id:"y/bmsG8rnv"})})]})]})};function H(e){const t={"anthropic-artifact-id":e.uuid,"anthropic-artifact-entity-type":e.type};return e.conversation_uuid&&(t["anthropic-chat-conversation-uuid"]=e.conversation_uuid),e.file_path&&(t["anthropic-file-path"]=e.file_path),t}const U=j({name:I().optional(),url:I().optional(),type:I().optional()}),B=new Set(["accept","accept-language","content-type","content-length"]),W=new Set(["set-cookie","x-api-key","x-auth-token","authorization"]),$=["api.anthropic.com"];let G=!1;const K=[];async function Q(e,t){return G=!0,new Promise(s=>{t({requestedServers:e,onClose:()=>{s();const e=K.shift();e?setTimeout(()=>{Q(e.validRequestedServers,e.setArtifactMcpModal).then(()=>{e.resolve()})},100):G=!1}})})}const V={"api.anthropic.com":async(e,t)=>await fetch(`/api/organizations/${e}/proxy/v1/messages`,t)};async function J(e,t,s,n,a,r){const{url:o,method:l,headers:c,body:d,channelId:u}=e,h=new URL(o),m={};for(const[i,w]of Object.entries(c))B.has(i.toLowerCase())&&(m[i]=w);n&&Object.assign(m,H(n));let p=d;if(r&&a&&d&&$.some(e=>e===h.hostname)){const e=(new TextDecoder).decode(d),t=j({mcp_servers:L(U).optional()}).passthrough().parse(JSON.parse(e));if(t.mcp_servers&&Array.isArray(t.mcp_servers)){const e=t.mcp_servers.filter(e=>e.url);e.length>0&&(G?await new Promise(t=>{K.push({validRequestedServers:e,setArtifactMcpModal:r,resolve:t})}):await Q(e,r));const s=(new TextEncoder).encode(JSON.stringify(t));p=s.buffer instanceof ArrayBuffer?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):new ArrayBuffer(0)}}const f=new AbortController;let g;if(!(h.hostname in V))throw new Error(`Unable to proxy requests for ${h.hostname}.`);g=await V[h.hostname](s||"",{method:l,headers:m,body:p||void 0,signal:f.signal,redirect:"manual"});const y={};return g.headers.forEach((e,t)=>{W.has(t.toLowerCase())||(y[t]=e)}),async function(e,t,s){const n=e.body?.getReader();if(!n)return void(await s(i.ProxyFetchStream,{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.ProxyFetchStreamRequest",channelId:t,chunk:null,done:!0}));let a=0;const r=10485760;try{for(;;){const{done:e,value:o}=await n.read();if(e){await s(i.ProxyFetchStream,{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.ProxyFetchStreamRequest",channelId:t,chunk:null,done:!0});break}if(o){if(a+=o.byteLength,a>r)throw new Error(`Response body exceeds maximum size of ${r} bytes`);const e=0===o.byteOffset&&o.byteLength===o.buffer.byteLength?o.buffer:o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);let n;n=e instanceof ArrayBuffer?e:new Uint8Array(e).slice().buffer,await s(i.ProxyFetchStream,{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.ProxyFetchStreamRequest",channelId:t,chunk:n,done:!1},[n])}}}catch(o){await s(i.ProxyFetchStream,{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.ProxyFetchStreamRequest",channelId:t,chunk:null,done:!1,error:o instanceof Error?o.message:"Unknown error"})}finally{n.releaseLock()}}(g,u,t),{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.ProxyFetchResponse",status:g.status,statusText:g.statusText,headers:y}}const X=new Map,Y="__sandbox_handshake_request__";class Z{constructor({iframe:e,allowedOrigin:t,onRateLimited:s=null,onPermissionRequested:n,onCapabilityAction:a}){this.messageCount=0,this.lastResetTime=Date.now(),this.MAX_MESSAGES_PER_INTERVAL=30,this.RESET_INTERVAL=5e3,this.onRateLimited=null,this.messageChannel=null,this.handshakeCompleted=!1,this.messageQueue=[],this.isConsumerRunning=!1,this.requestLog=new Map,this.inFlightRequests=new Map,this.iframe=e,this.allowedOrigin=t,this.onRateLimited=s,this.onPermissionRequested=n,this.onCapabilityAction=a,this.boundHandleMessage=this.handleMessage.bind(this),this.boundSendRequest=this.sendRequest.bind(this),this.setupMessageListener(),this.setupMessageChannel(),this.iframe.contentWindow&&this.allowedOrigin&&this.sendHandshakeWithPort()}setupMessageChannel(){this.messageChannel=new MessageChannel,this.messageChannel.port1.onmessage=e=>{this.handlePortMessage(e)}}handlePortMessage(e){const t=Date.now();if(t-this.lastResetTime>this.RESET_INTERVAL&&(this.messageCount=0,this.lastResetTime=t),this.isPendingResponse(e.data)||this.messageCount++,this.messageCount>this.MAX_MESSAGES_PER_INTERVAL){const t=e.data;return"request"===t?.channel&&"string"==typeof t.requestId&&this.messageChannel?.port1.postMessage({channel:"response",status:429,requestId:t.requestId,payload:l("Message rate limit exceeded. Reload to continue.")}),this.messageChannel?.port1.close(),window.removeEventListener("message",this.boundHandleMessage),void(this.onRateLimited&&this.onRateLimited())}const s=c.safeParse(e.data);if(!s.success)return void d.warn(u.ARTIFACTS,"Received port message does not conform to basic message shape, ignoring");const n=s.data;"response"!==n.channel?(this.messageQueue.push(n),this.isConsumerRunning||this.consumeMessages()):this.handleResponse(n)}sendHandshakeWithPort(){this.messageChannel&&(this.handshakeCompleted&&(this.messageChannel.port1.close(),this.setupMessageChannel()),this.iframe.contentWindow?.postMessage({type:"__sandbox_handshake__"},this.allowedOrigin,[this.messageChannel.port2]),this.handshakeCompleted=!0)}setupMessageListener(){window.addEventListener("message",this.boundHandleMessage,!1)}handleMessage(e){if(e.origin!==this.allowedOrigin)return;if(e.source!==this.iframe.contentWindow)return;const t=Date.now();if(t-this.lastResetTime>this.RESET_INTERVAL&&(this.messageCount=0,this.lastResetTime=t),this.isPendingResponse(e.data)||this.messageCount++,this.messageCount>this.MAX_MESSAGES_PER_INTERVAL){const t=e.data;return"request"===t?.channel&&"string"==typeof t.requestId&&this.sendErrorResponse(t.requestId,429,"Message rate limit exceeded. Reload to continue."),this.messageChannel?.port1.close(),window.removeEventListener("message",this.boundHandleMessage),void(this.onRateLimited&&this.onRateLimited())}if(e.data&&"object"==typeof e.data&&e.data.type===Y)return void this.sendHandshakeWithPort();const s=c.safeParse(e.data);if(!s.success)return void d.warn(u.ARTIFACTS,"Received message does not conform to basic message shape, ignoring");const n=s.data;"response"!==n.channel?(this.messageQueue.push(n),this.isConsumerRunning||this.consumeMessages()):this.handleResponse(n)}handleResponse(e){const t=this.inFlightRequests.get(e.requestId)||X.get(e.requestId);if(void 0!==t)return this.inFlightRequests.delete(e.requestId),X.delete(e.requestId),void t(e)}isPendingResponse(e){const t=c.safeParse(e);if(!t.success||"response"!==t.data.channel)return!1;const s=t.data.requestId;return t.data.type!==Y&&(this.inFlightRequests.has(s)||X.has(s))}async consumeMessages(){for(this.isConsumerRunning=!0;this.messageQueue.length>0;){const e=this.messageQueue.shift();if(!e)continue;const t=h.safeParse(e.method);if(!t.success){this.sendErrorResponse(e.requestId,400,"Unknown method");continue}const s=t.data,n=m.safeParse(e);if(!n.success){this.sendErrorResponse(e.requestId,400,"Invalid payload content");continue}const a=n.data;if(this.requestLog.has(a.requestId)){this.sendErrorResponse(a.requestId,400,"Request ID already processed");continue}this.requestLog.set(a.requestId,{message:a,requestTimestamp:(new Date).getTime()});await this.onPermissionRequested(s).then(e=>"denied"!==e||(this.sendErrorResponse(a.requestId,403,"Permission denied"),!1)).catch(e=>(d.error(u.ARTIFACTS,`Error checking permission for method ${s}:`,e),this.sendErrorResponse(a.requestId,500,"Error checking permission"),!1))&&(this.onCapabilityAction(a,this.boundSendRequest).then(e=>{const t=p.parse({channel:"response",status:200,requestId:a.requestId,payload:e??f}),s=this.requestLog.get(a.requestId);s&&this.requestLog.set(a.requestId,{...s,response:t,responseTimestamp:(new Date).getTime()}),this.iframe.contentWindow?.postMessage(t,this.allowedOrigin)}).catch(e=>{d.error(u.ARTIFACTS,`Error processing action for method ${s}:`,e),this.sendErrorResponse(a.requestId,500,"Internal server error while processing action")}),await new Promise(e=>setTimeout(e,0)))}this.isConsumerRunning=!1}sendErrorResponse(e,t,s){const n=g.parse({channel:"response",status:t,requestId:e,payload:l(s)}),a=this.requestLog.get(e);a&&this.requestLog.set(e,{...a,response:n,responseTimestamp:(new Date).getTime()}),this.iframe.contentWindow?.postMessage(n,this.allowedOrigin)}restartListening(){window.removeEventListener("message",this.boundHandleMessage),this.messageChannel?.port1.close(),this.messageChannel=null,this.handshakeCompleted=!1,this.messageCount=0,this.lastResetTime=Date.now(),this.setupMessageListener(),this.setupMessageChannel(),this.iframe.contentWindow&&this.allowedOrigin&&this.sendHandshakeWithPort()}cleanup(){window.removeEventListener("message",this.boundHandleMessage),this.messageChannel?.port1.close(),this.messageChannel=null,this.handshakeCompleted=!1,this.messageQueue=[],this.isConsumerRunning=!1,this.inFlightRequests.clear()}async sendRequest(e,t,s){return new Promise((n,a)=>{const r=Date.now().toString(),o={channel:"request",method:e,requestId:r,payload:t},i=e=>{const t=p.safeParse(e);if(!t.success)return void a(new Error("Invalid response format"));const s=t.data;if(s.status>=400){const e=g.safeParse(s);return void(e.success?a(new Error(e.data.payload.error)):a(new Error(`Error response (${s.status})`)))}const r=y.safeParse(s);r.success?n(r.data.payload):a(new Error("Invalid response payload for the method"))};this.inFlightRequests.set(r,i),X.set(r,i),s&&s.length>0?this.iframe.contentWindow?.postMessage(o,this.allowedOrigin,s):this.iframe.contentWindow?.postMessage(o,this.allowedOrigin)})}getRequestLog(){return Array.from(this.requestLog.entries()).map(([e,t])=>({...t,requestId:e})).sort((e,t)=>t.requestTimestamp-e.requestTimestamp)}}function ee({iframeRef:e,allowedOrigin:s,onRateLimited:n=null,initialPermissions:a,onPermissionRequested:r,onCapabilityAction:o}){const[i,l]=t.useState(null),c=t.useRef(a),h=t.useRef(n),m=t.useRef(r),p=t.useRef(o);t.useEffect(()=>{h.current=n,m.current=r,p.current=o},[n,r,o]);const[f,g]=t.useState(0);t.useEffect(()=>{if(!e.current&&f<20){const e=setTimeout(()=>{g(e=>e+1)},500);return()=>clearTimeout(e)}if(!e.current)return void d.warn(u.ARTIFACTS,"Max retries reached while waiting for iframe");const t=new Z({iframe:e.current,allowedOrigin:s,onRateLimited:()=>h.current?.(),onPermissionRequested:async e=>{if(w.includes(e))return"accepted";if("accepted"===c.current[e])return"accepted";const t=await m.current(e);return c.current={...c.current,[e]:t},t},onCapabilityAction:(e,t)=>p.current(e,t)});return l(t),()=>{t.cleanup()}},[e,s,c,f]);const y=t.useCallback(async(e,t)=>{if(i)return i.sendRequest(e,t);throw new Error("Communicator not initialized")},[i]),C=t.useCallback(()=>{i?.restartListening()},[i]),b=t.useCallback((e,t)=>{c.current={...c.current,[e]:t}},[]);return{sendRequest:null===i?void 0:y,restartListening:C,permissions:c.current,updatePermission:b}}const te=t.createContext(null),se=te.Provider;const ne={[v.Text]:"text",[v.Markdown]:"markdown",[v.Html]:"html",[v.Code]:"code",[v.Svg]:"svg",[v.Mermaid]:"mermaid",[v.React]:"react",[q.Pdf]:"pdf",[q.Excel]:"xlsx",[q.ExcelLegacy]:"xls",[q.Word]:"docx",[q.WordLegacy]:"doc",[q.PowerPoint]:"pptx",[q.PowerPointLegacy]:"ppt",[q.Csv]:"csv",[q.Tsv]:"tsv",[q.Skill]:"skill",[q.Plugin]:"plugin"};function ae(e){if(!e||"undefined"==typeof window)return null;try{const t=window.localStorage.getItem(e);return"allow"===t||"deny"===t?t:null}catch{return null}}function re(e){return e.replace(/[\u0000-\u001F\u007F-\u009F\u061C\u200B-\u200F\u2028\u2029\u202A-\u202E\u2060-\u206F\uFEFF]/g,"").replace(/[/\\]/g,"_").slice(0,255).trim()||"download"}const oe=t.forwardRef(({content:s,className:n,type:o,title:l,onSandboxConfirmation:c,onDOMContentLoaded:d,capabilities:u,onReportError:h,onSetContent:m,onRefresh:p,externalLinkBehavior:g,onOpenExternalLinkRequest:y,onTrackInteraction:w,showLoginModal:q,lazy:S=!0,zoom:P=1,artifactContext:M,ArtifactMcpModal:j,isChatStreaming:L},I)=>{const O=_(),H=A(),U=T(40),{userContentRendererUrl:B}=C(),W=!0,$=b("artifact_mcp_modal_skip_if_covered_main"),G=b("ucr_route_handler_pdf_conversion"),[K,Q]=t.useState(!1),V=t.useRef(null),X=`${B}${M?.uuid&&"published_artifact"===M.type?"/artifact/"+M.uuid:""}`,Y="undefined"!=typeof window?window.location.hostname:"",Z=new URLSearchParams;Z.set("domain",Y),"undefined"!=typeof window&&Z.set("parentOrigin",window.location.origin),h&&Z.set("errorReportingMode","parent"),Z.set("formattedSpreadsheets","true"),G&&Z.set("routeHandlerPdf","true");const se=Z.toString()?`${X}?${Z.toString()}`:X;t.useEffect(()=>{const e=V.current;if(e){if(navigator.userAgent.toLowerCase().includes("firefox")){e.setAttribute("data-no-service-worker","true");const t=setTimeout(()=>{e.sandbox&&e.src&&(e.sandbox.value="allow-scripts allow-same-origin",e.setAttribute("referrerpolicy","no-referrer"))},0);return()=>clearTimeout(t)}}},[]);const[oe,ie]=t.useState(null),[le,ce]=t.useState(null),[de,ue]=t.useState(null),[he,me]=t.useState(null),[pe,fe]=t.useState([]),[ge,ye]=t.useState([]),{activeOrganization:we,account:Ce}=r(),be=M?`shared-storage-consent:${Ce?.uuid??"anon"}:${M.conversation_uuid??M.type}:${M.id??M.file_path??M.uuid}`:null,[ve,Re]=t.useState(()=>({key:be,choice:ae(be)}));ve.key!==be&&Re({key:be,choice:ae(be)});const xe=ve.choice,ke=t.useCallback((e,t=be)=>{if(t===be&&Re({key:be,choice:e}),t)try{window.localStorage.setItem(t,e)}catch{}},[be]);t.useEffect(()=>{ue(e=>e?(e.onCancel("shared-storage request cancelled: artifact changed"),null):e)},[be]);const qe=t.useCallback((e,t,s)=>L?new Promise((n,a)=>{const r={method:e,data:t,executeOperation:s,resolve:n,reject:a,artifactUuid:M?.uuid,consentKey:be};ye(e=>{const t=M?.uuid;if(t!==(e.length>0?e[e.length-1]?.artifactUuid:null)){for(const t of e)t.reject(new Error("storage request cancelled: artifact changed while queued"));return[r]}return[...e,r]})}):s(),[L,M?.uuid,be,ye]),Se=b("apps_use_turmeric"),Pe=b("artifact_tailwind_styles"),Me=t.useContext(te),[_e,Ee]=t.useState(0),je=e=>e>=100,Le=t.useCallback(async(e,t)=>{if(e.method===i.ReadyForContent)return Q(!0),c?.(),Promise.resolve();if(e.method===i.GetFile){if(!u||!u.getFile)return Promise.reject();return{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.GetFileResponse",value:await u.getFile(e.payload.key)}}if(e.method===i.SendConversationMessage)return u&&u.sendMessage?(await u.sendMessage({prompt:e.payload.message,attachments:[],files:[],syncSources:[]}),Promise.resolve()):Promise.reject();if(e.method===i.ClaudeCompletion){if(!u||!u.claudeComplete)return Promise.reject();Ee(e=>e+1);return{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.ClaudeCompletionResponse",completion:await u.claudeComplete(e.payload.prompt)}}if(e.method===i.StorageGet){if(!u?.storage?.get)return Promise.reject();const t=u.storage.get,s=async()=>{const s=await t(e.payload.key,e.payload.shared);return s?{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.StorageGetResponse",key:s.key,value:s.value,shared:s.shared}:null};return qe("get",e.payload,s)}if(e.method===i.StorageSet){if(!u?.storage?.set)return Promise.reject();const t=u.storage.set,s=async()=>{const s=await t(e.payload.key,e.payload.value,e.payload.shared);return s?{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.StorageSetResponse",key:s.key,value:s.value,shared:s.shared}:null},n=async()=>!0===e.payload.shared?"allow"===xe?s():"deny"===xe?Promise.reject():new Promise((e,t)=>{ue(n=>{if(n)return t(new Error("shared-storage request superseded by pending confirmation")),n;let a=!1;return{onConfirm:async()=>{if(!a){a=!0,ue(null);try{const t=await s();e(t)}catch(n){t(n)}}},onCancel:e=>{a||(a=!0,t(new Error(e??"shared-storage request dismissed")))},consentKey:be}})}):s();return qe("set",e.payload,n)}if(e.method===i.StorageDelete){if(!u?.storage?.delete)return Promise.reject();const t=u.storage.delete,s=async()=>{const s=await t(e.payload.key,e.payload.shared);return s?{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.StorageDeleteResponse",key:s.key,deleted:s.deleted,shared:s.shared}:null},n=async()=>!0===e.payload.shared?"allow"===xe?s():"deny"===xe?Promise.reject():new Promise((e,t)=>{ue(n=>{if(n)return t(new Error("shared-storage request superseded by pending confirmation")),n;let a=!1;return{onConfirm:async()=>{if(!a){a=!0,ue(null);try{const t=await s();e(t)}catch(n){t(n)}}},onCancel:e=>{a||(a=!0,t(new Error(e??"shared-storage request dismissed")))},consentKey:be}})}):s();return qe("delete",e.payload,n)}if(e.method===i.StorageList){if(!u?.storage?.list)return Promise.reject();const t=u.storage.list,s=async()=>{const s=await t(e.payload.prefix,e.payload.shared);return s?{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.StorageListResponse",keys:s.keys,prefix:s.prefix,shared:s.shared}:null};return qe("list",e.payload,s)}if(e.method===i.BroadcastContentSize);else{if(e.method===i.DOMContentLoaded)return d?.(),Promise.resolve();if(e.method===i.OpenExternal)return"ask"===g?(ie(t=>t||e.payload.href),Promise.resolve()):"bubble"===g&&y?(y({href:e.payload.href}),Promise.resolve()):Promise.reject();if(e.method===i.DownloadFile)return ce(t=>t||{...e.payload,filename:re(e.payload.filename)}),Promise.resolve();if(e.method===i.ReportError)return h?.(e.payload.error),Promise.resolve();if(e.method===i.TrackInteraction)return w?.(e.payload),Promise.resolve();if(e.method===i.ProxyFetch)return we?.uuid?L?new Promise((s,n)=>{const a={data:e.payload,sendRequest:t,resolve:s,reject:n,artifactUuid:M?.uuid};fe(e=>{const t=M?.uuid;return t!==(e.length>0?e[e.length-1]?.artifactUuid:null)?[a]:[...e,a]})}):J(e.payload,t,we?.uuid,M,W,me):(q?.(),Promise.reject())}return Promise.reject()},[c,d,u,Q,h,Ee,g,y,w,q,we?.uuid,M,W,L,xe,be,qe]),Ie=t.useCallback(async e=>e===i.ClaudeCompletion&&je(_e)?"denied":Promise.resolve("accepted"),[_e]),{sendRequest:Ae,updatePermission:Te}=ee({iframeRef:V,allowedOrigin:B,onCapabilityAction:Le,onPermissionRequested:Ie,initialPermissions:{}});t.useEffect(()=>{je(_e)&&Te(i.ClaudeCompletion,"denied")},[_e,Te]),t.useEffect(()=>{(async()=>{!L&&pe.length>0&&we?.uuid&&M?.uuid&&(await Promise.all(pe.map(async({data:e,sendRequest:t,resolve:s,reject:n})=>{try{s(await J(e,t,we.uuid,M,W,me))}catch(a){n(a)}})),fe([]))})()},[L,pe,we?.uuid,M,W]),t.useEffect(()=>{(async()=>{if(!L&&ge.length>0&&M?.uuid){const e=ge;ye(t=>t.filter(t=>!e.includes(t))),await Promise.all(e.map(async({executeOperation:e,resolve:t,reject:s,data:n,consentKey:a})=>{if(!0!==n.shared||a===be)try{t(await e())}catch(r){s(r)}else s(new Error("storage request cancelled: artifact changed while queued"))}))}})()},[L,ge,M,be]);const Oe=t.useCallback(()=>{Ee(0),Te(i.ClaudeCompletion,"accepted")},[Te]),Fe=t.useCallback(async()=>{const e=performance.now(),t=(t,s)=>{k("artifactsScreenshotCapture",t,{variant:o?ne[o]:void 0,...s&&{error_code:s},..."failure"===t&&{error_type:"client_error"}},void 0,Math.round(performance.now()-e))};if(!Ae)return void t("aborted","screenshot_no_communicator");const s=Symbol("timeout");let n;try{n=await Promise.race([Ae(i.GetScreenshot,f),new Promise(e=>setTimeout(()=>e(s),15e3))])}catch{return void t("failure","screenshot_send_error")}if(n===s)return void t("failure","screenshot_timeout");if(!n?.screenshot)return void t("aborted","screenshot_no_root_element");if(n.screenshot.length>10485760)throw t("failure","screenshot_too_large"),new Error(O.formatMessage({defaultMessage:"Screenshot too large",id:"ifBuzEbIz2"}));if(!/^data:image\/(png|jpeg|gif);base64,/.test(n.screenshot))throw t("failure","screenshot_invalid_format"),new Error(O.formatMessage({defaultMessage:"Invalid screenshot format",id:"KCmGxpLNuq"}));return t("success"),n.screenshot},[O,Ae,o]),Ne=t.useCallback(async()=>{const e=await(Ae?.(i.CopyHtmlContent,{"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.CopyHtmlContentRequest"}));return e?.reportHTMLContent},[Ae]),De=t.useCallback(async()=>{const e=await(Ae?.(i.GetDOMSnapshot,f));return e?.domSnapshot||void 0},[Ae]);t.useEffect(()=>{K&&s&&o&&(m?.(),Object.values(v).includes(o),Ae?.(i.SetContent,{content:s,type:o,tailwindStylesEnabled:Pe,...Me?{theme:Me}:{},"@type":"type.googleapis.com/anthropic.claude.usercontent.sandbox.SandboxContent"}))},[s,Ae,o,K,m,Pe,Me]),t.useImperativeHandle(I,()=>({refresh:()=>{p?.(),Q(!1);const e=V.current;if(e){const t=e.parentNode;t?(t.removeChild(e),e.removeAttribute("src"),e.sandbox.value="allow-scripts allow-same-origin",e.setAttribute("data-no-service-worker","true"),e.setAttribute("referrerpolicy","no-referrer"),e.src=se,t.appendChild(e)):e.src=se}},getScreenshot:Fe,copyHtmlContent:Ne,getDOMSnapshot:De}));const ze=l||O.formatMessage({defaultMessage:"Claude content",id:"/Ma3teJf9/"});return e.jsxs("div",{className:x("relative",n),children:[e.jsx("iframe",{ref:V,className:"h-full w-full",style:{zoom:P},sandbox:"allow-scripts allow-same-origin",title:ze,loading:S?"lazy":void 0,src:se,allow:"fullscreen; clipboard-write",referrerPolicy:"no-referrer"}),e.jsx(F,{children:!K&&e.jsx(N.div,{className:"bg-bg-000 absolute inset-0 z-10",initial:{opacity:1},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15,ease:"easeInOut"}})}),oe?e.jsx(R,{isOpen:Boolean(oe),url:oe,onClose:()=>ie(null),onConfirm:()=>{oe&&window.open(oe,"_blank","noopener,noreferrer"),ie(null)}}):null,le?e.jsx(D,{isOpen:Boolean(le),filename:le.filename,onClose:()=>ce(null),onConfirm:()=>{if(le){const e=new Blob([le.data],{type:le.mimeType}),t=URL.createObjectURL(e),s=document.createElement("a");s.href=t,s.download=le.filename,s.click(),URL.revokeObjectURL(t)}ce(null)}}):null,de?e.jsx(z,{isOpen:Boolean(de),onClose:e=>{e&&ke("deny",de.consentKey),ue(e=>e===de?(e.onCancel(),null):e)},onConfirm:async e=>{de&&(e&&ke("allow",de.consentKey),await de.onConfirm())}}):null,he&&j&&M?e.jsx(j,{isOpen:Boolean(he),requestedServers:he.requestedServers,onClose:()=>{he.onClose(),me(null)},artifactContext:M,skipIfCovered:$}):null,Se&&je(_e)&&e.jsx("div",{className:"fixed inset-0 bg-always-black/50 flex items-center justify-center z-modal",style:H?{zIndex:U}:void 0,children:e.jsxs("div",{className:"bg-bg-100 p-4 rounded shadow-lg",children:[e.jsx("p",{className:"text-fg-100 mb-4",children:e.jsx(E,{defaultMessage:"Many requests made. Acknowledge that you\u2019re still here to continue.",id:"kmh/1AmVcl"})}),e.jsx(a,{onClick:Oe,variant:"primary",children:e.jsx(E,{defaultMessage:"I\u2019m still here",id:"NwhjMfjigc"})})]})})]})});oe.displayName="RichSandbox";function ie(){return e.jsx(O,{variant:"neutral",size:"xxs",children:e.jsx(E,{defaultMessage:"Team plan",id:"idguOo+PzU"})})}function le(e,s=!0){const{track:n}=S(),a=P(),r=t.useRef(!1);t.useEffect(()=>{s&&!r.current&&(r.current=!0,n({event_key:"claudeai.team_share_upsell_nudge.shown",surface:e}))},[s,n,e]);return{handleUpgradeClick:t.useCallback(()=>{n({event_key:"claudeai.team_share_upsell_nudge.clicked",surface:e,trigger:"cta_button"}),a.push("/upgrade?initialPlanType=team")},[n,e,a]),handleOptionSelected:t.useCallback(t=>{n({event_key:"claudeai.team_share_upsell_nudge.option_selected",surface:e,option:t})},[n,e]),handleDismissed:t.useCallback(()=>{n({event_key:"claudeai.team_share_upsell_nudge.dismissed",surface:e})},[n,e])}}function ce(){return M()}function de(e){const t=M();return e&&t}export{se as A,oe as R,Z as S,ie as T,ce as a,ee as b,de as c,H as d,J as p,re as s,le as u};
