@popmelt.com/core 0.31.1 → 0.31.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/claude-plugin/.claude-plugin/plugin.json +1 -1
- package/codex-plugin/.codex-plugin/plugin.json +1 -1
- package/dist/{ParticipantRuntime-HU2P2PJ6.mjs → ParticipantRuntime-BGVZAWZH.mjs} +1 -1
- package/dist/{PopmeltTasteConnectedPane-ALR3RTSC.mjs → PopmeltTasteConnectedPane-7YIHIFPE.mjs} +1 -1
- package/dist/{PreviewRuntime-YAUBP6HA.mjs → PreviewRuntime-QDA4OF67.mjs} +1 -1
- package/dist/bridge-entry.mjs +1 -1
- package/dist/{browser-runtime-LTQBOXZW.mjs → browser-runtime-VSD5R2HG.mjs} +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/{chunk-EG6SRS7N.mjs → chunk-2TFOULRG.mjs} +1 -1
- package/dist/chunk-4V7SK3M6.mjs +0 -0
- package/dist/{chunk-CECQ4VMR.mjs → chunk-7VW2KD6D.mjs} +1 -1
- package/dist/chunk-EXDOFFFJ.mjs +2 -0
- package/dist/{chunk-OLLUQ45J.mjs → chunk-F6AMPRUB.mjs} +1 -1
- package/dist/{chunk-253MCKJJ.mjs → chunk-GNZ73T3H.mjs} +1 -1
- package/dist/{chunk-GQ6CPJG6.mjs → chunk-IPR652AZ.mjs} +1 -1
- package/dist/{chunk-RXRZTZPN.mjs → chunk-JU7D4I76.mjs} +1 -1
- package/dist/{chunk-JQHZFDY5.mjs → chunk-MTQ5IWIK.mjs} +1 -1
- package/dist/{chunk-IRFL32GJ.mjs → chunk-Q5QRV4KJ.mjs} +3 -3
- package/dist/{chunk-CXQWNKZ4.mjs → chunk-QENHLODE.mjs} +2 -17
- package/dist/{chunk-LSPIP2IX.mjs → chunk-QLN5IYRL.mjs} +1 -1
- package/dist/{chunk-4ZZTJRHL.mjs → chunk-QTGE5KAA.mjs} +1 -1
- package/dist/chunk-RCVAPQ7X.mjs +2 -0
- package/dist/{chunk-E3ZTB2VR.mjs → chunk-SQA3PHME.mjs} +1 -1
- package/dist/{chunk-WIQ3RY6R.mjs → chunk-UZUYF4D5.mjs} +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/codex-note-context-SGNCDBK4.mjs +2 -0
- package/dist/{codex-project-IE6ZJFGB.mjs → codex-project-PA5DEEPH.mjs} +1 -1
- package/dist/codex-session-registry-25DAA2KO.mjs +0 -0
- package/dist/{focus-inspection-GJKMI6OE.mjs → focus-inspection-WPHGCN6Y.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/peer-client-BEU2VKYY.mjs +2 -0
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-nuxt.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server.mjs +1 -1
- package/dist/{workspace-snapshot-LKQWBDNS.mjs → workspace-snapshot-O34KMJ2V.mjs} +1 -1
- package/package.json +32 -22
- package/dist/chunk-HGW2U6PD.mjs +0 -2
- package/dist/chunk-XOGBFVWI.mjs +0 -2
- package/dist/codex-note-context-NVDO3PVT.mjs +0 -2
- package/dist/peer-client-2THOHRGA.mjs +0 -2
- /package/dist/{chunk-V6VQACC2.mjs → chunk-J5HW2SCX.mjs} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{b as Qf,f as Wi,h as Zf,g as ys,a as uc,d as pc,c as fc}from"./chunk-RXRZTZPN.mjs";import{a as eh}from"./chunk-GQ6CPJG6.mjs";import{M as il,vb as vs,Ua as hc,f as th,e as mc,tb as bs,a as nh,xb as gc,yb as yc,wb as xs,c as rh,jb as oh,kb as ih,Ja as Bi,ja as ah,Db as lh,Eb as vc,ia as sh,Kb as dh,Gb as ch,Hb as uh,Ib as ph,_a as fh,ka as hh,Da as mh,za as bc,ab as gh,ba as yh,ca as ws,da as vh,ea as bh,$a as xh,Fa as wh,ha as Sh,ob as Ss,nb as Ih,mb as Is,Fb as kh,la as Th,Oa as xc,Ba as wc,Ma as Sc,Na as Eh,La as Ic,Ka as Ah,Ga as ks,N as Ch,Cb as Mh,p as kc,ya as Rh,b as Lh,ub as Tc,Ra as Ph,Qa as jh,Ta as zh,Pa as $h,Sa as Dh,Ca as Hh,D as Nh,E as Oh,l as Fh,ra as nn,ua as _h,xa as Wh,Ha as Bh,sa as Ec,na as Ji,T as Jh,ma as qh,R as Ac,Y as Uh,fb as gi,Mb as Yh,Jb as Xh,eb as Cc,gb as Mc,Ab as Kh,Bb as Vh,lb as Gh,hb as Qh,ib as Zh,Aa as em,Ea as Ts,Q as tm,C as Rc,F as Lc,L as Pc,K as jc,o as yi,G as zc,J as qi,P as nm,va as Es,qa as rm,pa as As,oa as Cs,O as om,ga as im,fa as am,Ia as lm,ta as $c,wa as Dc,q as sm,W as Hc,U as Nc,V as Oc,X as dm,Z as Fc,$ as _c,aa as cm,S as um,zb as Wc,m as Ui,A as Ms,r as vi,I as al,u as Bc,g as pm,_ as fm,t as ll,h as Jc,y as hm,j as $r,v as Rs,s as Ta,i as Ls,k as mm,z as gm,x as ym,H as Ps,w as qc,n as Uc,B as vm}from"./chunk-IRFL32GJ.mjs";import{b as Yc,d as bm,a as xm,e as wm,c as Sm}from"./chunk-J4WDYITA.mjs";import{h as Im,Ca as Xc,R as Yi,ma as km,N as Tm,H as Kc,A as ro,la as sl,ka as Em,P as Am,D as Vc,O as Cm,da as Tn,Y as js,aa as lr,fa as zs,$ as Ea,ha as Mm,S as dl,ua as Gc,_ as oo,za as Rm,Aa as Lm,Ba as Qc,ta as Zc,J as $s,v as eu,u as Aa,r as cl,w as Xi,Z as tu,Q as nu,I as Pm,K as jm,M as zm,f as $m,ba as Dm,ca as Hm,wa as Nm,va as ru,ya as Om,xa as Fm,sa as ou,z as iu,t as Ds,g as _m,ea as Hs,C as Wm,E as au,G as Bm,F as Jm,ga as lu,ia as su,B as qm,s as ul,L as Um,y as Ns,q as du,x as Ym}from"./chunk-253MCKJJ.mjs";import{b as cu}from"./chunk-4LHTPRFY.mjs";import{c as Xm,a as uu,b as Ca}from"./chunk-JQHZFDY5.mjs";import{i as pu,k as Km,m as Vm,h as fu,g as Gm,a as pl,e as Qm,b as Dr,d as Zm,f as it,c as eg}from"./chunk-OLLUQ45J.mjs";import{c as hn,a as Ho,i as mn,j as bi,d as tg,e as ng,b as hu,l as rg,m as og,k as ig}from"./chunk-XOGBFVWI.mjs";import{a as ag}from"./chunk-2P2NUZW7.mjs";import{d as Os,i as lg}from"./chunk-D32YV5O6.mjs";import{a as Fs,h as mu,d as sg,c as dg,g as _s,e as Ws,b as cg}from"./chunk-V44RIEET.mjs";import{b as Yt,f as gu,d as yu,e as Bs,i as ug,j as Ma,l as vu,m as bu,r as pg,p as fg,u as hg,t as mg,s as gg,k as yg,a as vg,c as bg}from"./chunk-CPOYMGYY.mjs";import{a as xu,b as xg}from"./chunk-EX63NVDN.mjs";import{d as wg,g as Sg,m as Ig,l as kg}from"./chunk-N2ZEZCHO.mjs";import{a as Tg}from"./chunk-J3UIBBU2.mjs";import{b as Eg}from"./chunk-6VXFTT5U.mjs";import{a as Ag}from"./chunk-LVEMYZOA.mjs";import{d as xn,o as Ra,n as Ki,a as wu,i as Su,v as Iu,u as ku,h as fl,k as Cg,f as Mg,c as Js,m as Tu,l as qs}from"./chunk-HGW2U6PD.mjs";import{lazy as hl,memo as Rg,useContext as Hr,useState as j,Suspense as ml,Fragment as Lg,useRef as W,useEffect as O,useLayoutEffect as It,useCallback as J,useMemo as Se,cloneElement as Pg,useSyncExternalStore as jg,useId as zg}from"react";import{jsx as f,jsxs as M,Fragment as ct}from"react/jsx-runtime";import{Fingerprint as io,Component as gl,Reply as Eu,Ban as yl,Terminal as $g,PenLine as Dg,ImageIcon as Hg,Plug as Ng,SquareMousePointer as Og,ChevronRight as Us,ThumbsUp as Fg,Clock as Ys,ChevronDown as Vi,Check as xi,ChevronLeft as _g,X as Xs,Send as Au,Lock as Wg,ArrowDown as Bg,OctagonAlert as Cu,MessageCircleQuestionMark as Jg,TriangleAlert as qg,Command as Mu,CornerDownLeft as Ks,EyeOff as Ug}from"lucide-react";import{createPortal as Ru}from"react-dom";function Lu(e,t){return e.store===void 0&&(e.store=t),e.store}function Yg(e,t){let n=e.listeners??(e.listeners=new Set);return n.add(t),()=>n.delete(t)}function Xg(e,t,n){let r=n(Lu(e,t));e.store=r;for(let o of e.listeners??[])o();return r}var nt=globalThis.__POPMELT_BRIDGE_CONNECTION__??(globalThis.__POPMELT_BRIDGE_CONNECTION__={}),vl=nt.sourceId??(typeof localStorage<"u"?localStorage.getItem("popmelt-source-id"):null)??(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).slice(2));nt.sourceId=vl;try{typeof localStorage<"u"&&localStorage.setItem("popmelt-source-id",vl)}catch{}function Vs(){return vl}var bl={isConnected:!1,status:"disconnected",jobResponses:{},jobThinking:{},activeJobIds:[],activeJobThreads:{},currentResponse:"",currentThinking:"",events:[],activeJobId:null,lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[],capabilitiesVersion:0};nt.store??(nt.store={...bl}),nt.listeners??(nt.listeners=new Set);var Nr=nt.activeEs??null,xl=nt.activeBridgeUrl??null,ao=null,Xn=nt.connectionGeneration??0,La=new Set,wi=new Map,No={},wl=new Set,Oo=new Map;function zn(e,t){if(!e)return!1;if(wl.has(e))return!0;if(La.has(e)){let r=wi.get(e);return r||(r=[],wi.set(e,r)),r.push({type:t.type??"",data:t}),!0}let n=No[e];return n!==void 0&&typeof t.seq=="number"&&t.seq<=n}async function Pu(e,t,n,r=new Map){let o=()=>n!==(nt.connectionGeneration??0);for(let l of t){if(o())return;Oo.set(l,r.get(l)??Oo.get(l)),La.add(l),wi.set(l,[])}let{mergeBackfillHistory:i,selectBackfillTerminalEvent:a}=await import("./bridge-recovery-3IQN3U6D.mjs");o()||await Promise.all(t.map(async l=>{try{let s=await vu(e,l,-1,{retryUnavailable:!0});if(o()||wl.has(l))return;let d=wi.get(l)??[];if(s){pt(u=>{let h={...u.jobResponses,[l]:s.accumulated.response},m={...u.jobThinking,[l]:s.accumulated.thinking},g=i(u.events,l,s.events);return{...u,jobResponses:h,jobThinking:m,currentResponse:l===u.activeJobId?s.accumulated.response:u.currentResponse,currentThinking:l===u.activeJobId?s.accumulated.thinking:u.currentThinking,events:g}}),No[l]=s.currentSeq;let c=[...s.events].reverse().find(u=>u.type==="job_started"||u.type==="job_parked");c?.type==="job_parked"&&Gi("job_parked",c,l);let p=a(s.events,s.jobActive,r.get(l));p&&Gi(p.type,p,l);for(let u of d)typeof u.data.seq=="number"&&u.data.seq<=s.currentSeq||Gi(u.type,u.data,l)}else{let c=!1;for(let u of d)Gi(u.type,u.data,l),(u.type==="done"||u.type==="error")&&(c=!0);let p=r.get(l);!c&&p&&Gi(p.type,p,l)}Oo.delete(l)}finally{o()||(La.delete(l),wi.delete(l))}}))}function Gi(e,t,n){if(e==="job_parked")pt(r=>{let o=r.activeJobIds.filter(i=>i!==n);return{...r,activeJobIds:o,activeJobId:o.at(-1)??null,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}});else if(e==="job_started")pt(r=>({...r,status:"streaming",activeJobId:n,activeJobIds:[...new Set([...r.activeJobIds,n])],activeJobThreads:typeof t.threadId=="string"?{...r.activeJobThreads,[n]:t.threadId}:r.activeJobThreads,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}));else if(e==="delta"){let r=t.text||"";pt(o=>({...o,jobResponses:{...o.jobResponses,[n]:(o.jobResponses[n]||"")+r},currentResponse:n===o.activeJobId?o.currentResponse+r:o.currentResponse,events:[...o.events,{type:"delta",data:t,timestamp:Date.now()}]}))}else if(e==="thinking"){let r=t.text||"";pt(o=>({...o,jobThinking:{...o.jobThinking,[n]:(o.jobThinking[n]||"")+r},currentThinking:n===o.activeJobId?o.currentThinking+r:o.currentThinking,events:[...o.events,{type:"thinking",data:t,timestamp:Date.now()}]}))}else if(e==="status")pt(r=>({...r,events:[...r.events,{type:"status",data:t,timestamp:Date.now()}]}));else if(e==="done")delete No[n],pt(r=>{let o=r.activeJobIds.filter(d=>d!==n),i={...r.jobResponses},a={...r.jobThinking},l=i[n];delete i[n],delete a[n];let s=n===r.activeJobId?o.length>0?o[o.length-1]:null:r.activeJobId;return{...r,activeJobIds:o,activeJobId:s,jobResponses:i,jobThinking:a,lastCompletedJobId:n,lastResponseText:t.responseText||l||r.currentResponse||null,lastThreadId:t.threadId??null,...n===r.activeJobId?{currentResponse:s&&i[s]||"",currentThinking:s&&a[s]||""}:{},events:[...r.events,{type:"done",data:t,timestamp:Date.now()}]}});else if(e==="error"){delete No[n];let r=t.message??"";pt(o=>{let i=o.activeJobIds.filter(l=>l!==n),a=i.length>0?o.status:"error";return{...o,status:a,activeJobIds:i,lastCompletedJobId:n,lastErrorByJob:r?{...o.lastErrorByJob,[n]:r}:o.lastErrorByJob,events:[...o.events,{type:"error",data:t,timestamp:Date.now()}]}})}else pt(e==="question"?r=>{let o=typeof t.threadId=="string"?t.threadId:"",i=typeof t.question=="string"?t.question:"",a=Array.isArray(t.annotationIds)?t.annotationIds.filter(s=>typeof s=="string"):void 0,l=r.pendingQuestions.some(s=>s.jobId===n);return{...r,pendingQuestions:i&&o&&!l?[...r.pendingQuestions,{jobId:n,threadId:o,question:i,annotationIds:a,timestamp:Date.now()}]:r.pendingQuestions,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}}:r=>({...r,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}))}var Kn=nt.discoveredBridgeUrl??null,$n=nt.discoveredBridgeProjectId??null,Fo=null,Qi=null;function ju(e,t=!1){let n=e??null;if(!(!t&&(nt.expectedProjectId??null)===n)){Nr&&(Nr.close(),Nr=null,nt.activeEs=null),ao&&(clearTimeout(ao),ao=null),xl=null,nt.activeBridgeUrl=null,Kn=null,$n=null,nt.discoveredBridgeUrl=null,nt.discoveredBridgeProjectId=null,Fo=null,Qi=null,La.clear(),wi.clear(),wl.clear(),Oo.clear();for(let r of Object.keys(No))delete No[r];nt.expectedProjectId=n,Xn=(nt.connectionGeneration??Xn)+1,nt.connectionGeneration=Xn,pt(()=>({...bl}))}}function Kg(){nt.listeners?.size||ju(null,!0)}async function zu(e,t){if(Kn&&(t?$n===t:!$n))return Kn;if(!t&&$n&&(Kn=null,$n=null,nt.discoveredBridgeUrl=Kn,nt.discoveredBridgeProjectId=$n),t&&$n&&$n!==t&&(Kn=null,$n=null,nt.discoveredBridgeUrl=Kn,nt.discoveredBridgeProjectId=$n),Fo&&Qi===(t??null))return Fo;let n=Xn;return Qi=t??null,Fo=yg(e,t).then(r=>n!==Xn?null:(Kn=r?.url??null,$n=r?.projectId??t??null,nt.discoveredBridgeUrl=Kn,nt.discoveredBridgeProjectId=$n,Fo=null,Qi=null,Kn)).catch(()=>(n!==Xn||(Fo=null,Qi=null),null)),Fo}function Vg(){return Kn}async function Gg(e,t){Kn=null,$n=null,nt.discoveredBridgeUrl=null,nt.discoveredBridgeProjectId=null,Fo=null,Qi=null;let n=Xn,r=await zu(e,t);return r&&n===Xn&&Gs(r),r}function Pa(){return Lu(nt,{...bl})}function Qg(e){return Yg(nt,e)}function pt(e){Xg(nt,{...bl},t=>{let n=e(t),r=new Set(n.activeJobIds),o=n.activeJobId&&r.has(n.activeJobId)?n.activeJobId:n.activeJobIds.at(-1)??null;return{...n,activeJobId:o,activeJobThreads:Object.keys(n.activeJobThreads).some(i=>!r.has(i))?Object.fromEntries(Object.entries(n.activeJobThreads).filter(([i])=>r.has(i))):n.activeJobThreads,status:n.status==="streaming"&&r.size===0?"idle":n.status}})}function Zg(){return typeof window<"u"?window.__POPMELT_PROJECT_ID__??null:null}function Gs(e){if(Nr&&Nr.readyState!==EventSource.CLOSED&&xl===e)return;Nr&&(Nr.close(),Nr=null,nt.activeEs=null),ao&&(clearTimeout(ao),ao=null),xl=e,nt.activeBridgeUrl=xl,Xn=(nt.connectionGeneration??Xn)+1;let t=Xn;nt.connectionGeneration=Xn;let n=new URLSearchParams({sourceId:vl}),r=Zg();r&&n.set("projectId",r);let o=vg(`${e}/events?${n.toString()}`);Nr=o,nt.activeEs=Nr;let i=!1,a=()=>t!==(nt.connectionGeneration??0),l=()=>i||a();La.clear(),wi.clear();let s=5e3,d=()=>{a()||ao||(ao=setTimeout(()=>{ao=null,!a()&&Ma(e).then(p=>{a()||(p&&(!r||p.projectId===r)?Gs(e):(s=Math.min(s*2,3e4),d()))})},s))},c=()=>{l()||(i=!0,o.close(),pt(p=>({...p,isConnected:!1,status:"disconnected"})),d())};o.addEventListener("connected",()=>{l()||Ma(e).then(async p=>{if(l())return;if(!p||r&&p.projectId!==r){c();return}let u=[...p?.activeJobs??(p?.activeJob?[p.activeJob]:[]),...p?.queuedJobs?.filter(z=>z.parked)??[]],h=p?.recentJobs??[],{planBridgeReconnectRecovery:m}=await import("./bridge-recovery-3IQN3U6D.mjs");if(l())return;let g=m(Pa().activeJobIds,u,h),{serverActiveIds:x,terminalJobs:S}=g,D=S.map(z=>z.id),H=new Map(Oo);for(let z of S)H.set(z.id,z.status==="error"?{type:"error",jobId:z.id,message:z.error??"The agent run failed.",threadId:z.threadId,annotationIds:z.annotationIds}:{type:"done",jobId:z.id,success:!0,threadId:z.threadId,annotationIds:z.annotationIds});pt(z=>{let Z={...z.lastErrorByJob};for(let N of S)N?.status==="error"&&N.error&&(Z[N.id]=N.error);let k=m(z.activeJobIds,u,h).reconciledActiveIds,G={};for(let N of u)N.threadId&&(G[N.id]=N.threadId);return{...z,isConnected:!0,status:k.length>0?"streaming":D.length>0||z.status==="disconnected"?"idle":z.status,activeJobId:k.length>0?k[k.length-1]:null,activeJobIds:k,activeJobThreads:G,lastErrorByJob:Z,workspaceGeneration:p?.workspaceGeneration}});let w=[...new Set([...x,...D,...Oo.keys()])];w.length>0&&Pu(e,w,t,H).catch(c)}).catch(c)}),o.addEventListener("job_parked",p=>{if(l())return;let u=JSON.parse(p.data);zn(u.jobId,u)||Gi("job_parked",u,u.jobId)}),o.addEventListener("thread_changed",p=>{if(l())return;let u=JSON.parse(p.data);pt(h=>({...h,events:[...h.events,{type:"thread_changed",data:u,timestamp:Date.now()}]}))}),o.addEventListener("job_started",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if(zn(h,u))return;let m=u.threadId;pt(g=>({...g,status:"streaming",activeJobId:h,activeJobIds:g.activeJobIds.includes(h)?g.activeJobIds:[...g.activeJobIds,h],activeJobThreads:m?{...g.activeJobThreads,[h]:m}:g.activeJobThreads,jobResponses:{...g.jobResponses,[h]:g.jobResponses[h]??""},jobThinking:{...g.jobThinking,[h]:g.jobThinking[h]??""},currentResponse:g.jobResponses[h]??"",currentThinking:g.jobThinking[h]??"",lastResponseText:null,lastThreadId:null,events:[...g.events,{type:"job_started",data:u,timestamp:Date.now()}]}))}),o.addEventListener("delta",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if(zn(h,u))return;let m=u.text||"";pt(g=>({...g,jobResponses:h?{...g.jobResponses,[h]:(g.jobResponses[h]||"")+m}:g.jobResponses,currentResponse:!h||h===g.activeJobId?g.currentResponse+m:g.currentResponse,events:[...g.events,{type:"delta",data:u,timestamp:Date.now()}]}))}),o.addEventListener("thinking",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if(zn(h,u))return;let m=u.text||"";pt(g=>({...g,jobThinking:h?{...g.jobThinking,[h]:(g.jobThinking[h]||"")+m}:g.jobThinking,currentThinking:!h||h===g.activeJobId?g.currentThinking+m:g.currentThinking,events:[...g.events,{type:"thinking",data:u,timestamp:Date.now()}]}))}),o.addEventListener("status",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,events:[...m.events,{type:"status",data:u,timestamp:Date.now()}]}))}),o.addEventListener("orientation",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,events:[...m.events,{type:"orientation",data:u,timestamp:Date.now()}]}))}),o.addEventListener("approval",p=>{if(l())return;let u=JSON.parse(p.data);zn(u.jobId,u)||pt(h=>({...h,events:[...h.events,{type:"approval",data:u,timestamp:Date.now()}]}))}),o.addEventListener("imprint_used",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,events:[...m.events,{type:"imprint_used",data:u,timestamp:Date.now()}]}))}),o.addEventListener("tool_use",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,events:[...m.events,{type:"tool_use",data:u,timestamp:Date.now()}]}))});for(let p of["image_generation","image_ready"])o.addEventListener(p,u=>{if(l())return;let h=JSON.parse(u.data),m=h.jobId;zn(m,h)||pt(g=>({...g,events:[...g.events,{type:p,data:h,timestamp:Date.now()}]}))});o.addEventListener("done",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||(h&&delete No[h],pt(m=>{let g=h?m.activeJobIds.filter(z=>z!==h):m.activeJobIds,x={...m.jobResponses},S={...m.jobThinking},D={...m.activeJobThreads},H=h?x[h]:void 0;h&&(delete x[h],delete S[h],delete D[h]);let w=h===m.activeJobId?g.length>0?g[g.length-1]:null:m.activeJobId;return{...m,activeJobIds:g,activeJobId:w,jobResponses:x,jobThinking:S,lastCompletedJobId:h??m.activeJobId,lastResponseText:u.responseText||H||m.currentResponse||null,lastThreadId:u.threadId??null,...h===m.activeJobId?{currentResponse:w&&x[w]||"",currentThinking:w&&S[w]||""}:{},events:[...m.events,{type:"done",data:u,timestamp:Date.now()}]}}))}),o.addEventListener("question",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,pendingQuestions:[...m.pendingQuestions,{jobId:u.jobId,threadId:u.threadId,question:u.question,annotationIds:u.annotationIds,timestamp:Date.now()}],events:[...m.events,{type:"question",data:u,timestamp:Date.now()}]}))}),o.addEventListener("capabilities_changed",()=>{l()||pt(p=>({...p,capabilitiesVersion:p.capabilitiesVersion+1}))}),o.addEventListener("workspace_cleared",p=>{if(l())return;let u=JSON.parse(p.data);typeof u.workspaceGeneration!="number"||!Number.isInteger(u.workspaceGeneration)||u.workspaceGeneration<0||pt(h=>{for(let m of[...h.activeJobIds,...Oo.keys()])wl.add(m);return Oo.clear(),{...h,workspaceGeneration:u.workspaceGeneration,status:"idle",activeJobId:null,activeJobIds:[],activeJobThreads:{},jobResponses:{},jobThinking:{},currentResponse:"",currentThinking:"",events:[],lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[]}})}),o.addEventListener("queue_drained",()=>{if(l())return;let p=[...Pa().activeJobIds];if(p.length===0){pt(u=>({...u,status:u.status==="error"?"error":"idle",incrementalResolutions:[]}));return}Pu(e,p,t).then(()=>{l()||pt(u=>({...u,status:u.activeJobIds.length>0?u.status:u.status==="error"?"error":"idle",incrementalResolutions:u.activeJobIds.length>0?u.incrementalResolutions:[]}))}).catch(c)}),o.addEventListener("error",p=>{if(!l()){if(o.readyState===EventSource.CLOSED)c();else if(p instanceof MessageEvent){let u=JSON.parse(p.data),h=u.jobId??null;if(zn(h??void 0,u))return;h&&delete No[h];let m=u.message??"";pt(g=>{let x=h?g.activeJobIds.filter(D=>D!==h):g.activeJobIds,S=x.length>0?g.status:"error";return{...g,status:S,activeJobIds:x,lastCompletedJobId:h??g.activeJobId,lastErrorByJob:h&&m?{...g.lastErrorByJob,[h]:m}:g.lastErrorByJob,events:[...g.events,{type:"error",data:u,timestamp:Date.now()}]}})}}}),o.onerror=()=>{l()||o.readyState===EventSource.CLOSED&&pt(p=>({...p,isConnected:!1,status:"disconnected"}))}}function ey(e="http://localhost:1111",t=!0,n){let r=jg(Qg,Pa,Pa);O(()=>{if(ju(n),!t)return;let a=!1;return zu(e,n).then(l=>{!l||a||Ma(l).then(s=>{!a&&s&&(!n||s.projectId===n)&&Gs(l)})}),()=>{a=!0}},[e,t,n]);let o=J(()=>{pt(()=>({...Pa(),events:[],currentResponse:"",currentThinking:"",jobResponses:{},jobThinking:{},lastResponseText:null,lastThreadId:null,lastErrorByJob:{},incrementalResolutions:[]}))},[]),i=J(a=>{pt(l=>({...l,pendingQuestions:l.pendingQuestions.filter(s=>s.threadId!==a)}))},[]);return{...r,clearEvents:o,dismissQuestion:i}}function $u(e,t,n,r,o){let i=`devtools-model-id:${r}`,[a,l]=j(()=>typeof window>"u"?"":localStorage.getItem(i)??""),s=o?.(a)??!1,d=s?-1:e.findIndex(u=>u.id===a),c=d>=0?d:0,p=J(u=>{l(u),localStorage.setItem(i,u)},[i]);return O(()=>{n&&a&&(s||t&&d<0&&e.some(u=>u.id))&&p("")},[n,t,a,d,e,p,s]),{index:c,select:p}}function ty(e,t,n){let r=e.flatMap(({requestedAt:a,resolvedAt:l})=>Number.isFinite(a)&&Number.isFinite(l)?[[Math.max(t,a),Math.min(n,l)]]:[]).sort((a,l)=>a[0]-l[0]),o=t,i=0;for(let[a,l]of r)i+=Math.max(0,l-Math.max(o,a)),o=Math.max(o,l);return i}function Du(e){let t=new Map,n=new Set;for(let r of e)if(r.type==="approval"){let o=r.data.approval;t.set(o.id,o)}else(r.type==="done"||r.type==="error")&&n.add(String(r.data.jobId));return new Set([...t.values()].filter(r=>r.status==="pending"&&!n.has(r.jobId)).map(r=>r.jobId))}function Hu(e){let t=new MutationObserver(n=>{let r=n.filter(o=>document.body.contains(o.target)||o.target===document.documentElement&&[...o.addedNodes,...o.removedNodes].some(i=>i instanceof Element&&i.tagName==="BODY"));r.length&&e(r)});return t.observe(document.documentElement,{childList:!0,subtree:!0}),t}function ny(e,t,n,r=8*1024*1024){let o=d=>JSON.stringify({id:e,clientId:t,result:d}),i=d=>new TextEncoder().encode(d).length<=r,a=o(n);if(i(a))return a;let l=Array.isArray(n.images)?n.images:[],s=[l.filter(d=>d.kind==="annotated-viewport"),l.filter(d=>d.kind!=="annotated-viewport"),[]];for(let d of s){let c=o({...n,images:d,visualEvidence:{status:"partial",reason:"response_size_limit",omitted:l.filter(p=>!d.includes(p)).map(p=>p.kind)}});if(i(c))return c}return o({status:"context_too_large",targetKey:n.targetKey,images:[],warning:"Context exceeds the response limit even without images."})}function ry(e,t,n){let r=W(n);r.current=n;let[o,i]=j([]),a=h=>i(h?[h]:[]),l=W(null),s=W(null),d=W(null),c=J(()=>d.current?.(),[]),p=J(h=>{l.current=h,s.current?.(h)},[]),u=W(null);return O(()=>{if(!e)return;u.current?.url!==t&&(u.current={url:t,clientId:crypto.randomUUID(),sequence:0,sending:!1});let h=u.current,m={clientId:h.clientId,sequence:0,page:location.origin+location.pathname,title:document.title,active:!0,windowFocused:document.hasFocus(),lastInteractionAt:0,blurredAt:0,hover:null,pinned:null,history:[]},g=null,x=new WeakMap,S=new Map,D,H=!1,w,z=0,Z=()=>{let F=location.origin+location.pathname;m.page!==F&&(m.page=F,m.title=document.title,m.hover=null,m.pinned=null,m.history=[],m.recent=null,m.selected=null,S.clear(),g=null,m.lastInteractionAt=0),m.sequence=++h.sequence,h.pendingBody=JSON.stringify(m),!h.sending&&(h.sending=!0,(async()=>{for(;h.pendingBody;){let R=h.pendingBody;h.pendingBody=void 0;try{await Yt(`${t}/focus`,{method:"POST",headers:{"Content-Type":"application/json"},body:R,signal:AbortSignal.timeout(3e3)})}catch{}}h.sending=!1})())},k=(F,R)=>{x.has(F)||x.set(F,crypto.randomUUID());let $=mn(F),P=xn(F),A=getComputedStyle(F),ne={...R?{subject:R}:{},key:x.get(F),capturedAt:Date.now(),selector:$.selector,tagName:$.tagName,text:$.textContent?.slice(0,200),component:$.reactComponent,source:$.reactSource,rect:{x:P.x,y:P.y,width:P.width,height:P.height},styles:Object.fromEntries(["color","background-color","font-size","font-family","display","padding","border-radius"].map(re=>[re,A.getPropertyValue(re)]))};if(S.set(ne.key,{element:F,target:ne}),S.size>32){let re=[...S.keys()].find(ee=>ee!==m.pinned?.key);re&&S.delete(re)}return ne},G=F=>{let R=F?.element??null,$=F?.selection==="selected",P=m.selected??m.hover;R===g&&!!m.selected===$&&P?.subject?.key===F?.subject?.key||(g=R,clearTimeout(D),D=setTimeout(()=>{if(H)return;let A=R?.isConnected&&!Ra(R,"input, textarea, select, [contenteditable], [data-popmelt-private], [data-popmelt-canvas-block], [data-devtools]")?k(R,F?.subject):null;m.selected=$?A:null,m.hover=$?null:A,$&&(m.recent=null),m.hover&&(m.history=[...m.history,m.hover].slice(-8)),m.windowFocused&&(m.recent=null),Z()},R&&!$?120:0))};s.current=G,d.current=()=>{H||document.visibilityState!=="visible"||(m.lastInteractionAt=Date.now(),m.windowFocused=document.hasFocus(),!w&&(w=setTimeout(()=>{w=void 0,z=Date.now(),Z()},Math.max(0,250-(Date.now()-z)))))},G(l.current);let N=()=>{m.windowFocused=document.hasFocus(),m.blurredAt=m.windowFocused?0:Date.now(),m.recent=m.windowFocused?null:m.hover,Z()},Y=()=>{m.active=document.visibilityState==="visible",m.active?G(l.current):(clearTimeout(D),m.hover=null,m.history=[],m.recent=null,m.selected=null,S.clear(),g=null,m.lastInteractionAt=0),Z()};document.addEventListener("visibilitychange",Y),window.addEventListener("focus",N),window.addEventListener("blur",N);let q=setInterval(Z,1e4),ie=!1,I,Q=new Set,L=setInterval(async()=>{if(!(H||ie||document.visibilityState!=="visible")){ie=!0;try{let F=await Yt(`${t}/focus/requests?clientId=${m.clientId}`,{signal:AbortSignal.timeout(3e3)});if(!F.ok)return;let R=await F.json();for(let $ of R){if(Q.has($.id)||H||$.expiresAt<Date.now())continue;Q.add($.id),Q.size>64&&Q.delete(Q.values().next().value);let P=S.get($.targetKey),A={status:"target_unavailable"};if($.tasteProposal){let{tasteProposalSession:ne}=await import("./taste-proposal-session-XU4N7RUV.mjs");if(H||$.expiresAt<Date.now())continue;let re=document.activeElement;for(;re?.shadowRoot?.activeElement;)re=re.shadowRoot.activeElement;A=re?.matches("input, textarea, select, [contenteditable]")&&Ra(re,"[data-taste-editor]")&&$.tasteProposal.action!=="inspect"?{status:"busy",reason:"The human is editing a proposal field. Retry after editing ends."}:ne.command($.tasteProposal)}else if($.workspace){let{collectWorkspaceSnapshot:ne,workspaceAttentionTarget:re}=await import("./workspace-snapshot-LKQWBDNS.mjs");if(H||$.expiresAt<Date.now())continue;A=ne(r.current.state,$.workspace);let ee=$.workspace.entryId?[$.workspace.entryId]:"entries"in A?A.entries.map(U=>U.id):[],oe=[...new Set(ee.map(U=>re(r.current.state,U,r.current.registry)).filter(U=>!!U))];i(oe);for(let U of oe)U instanceof HTMLElement&&U.hasAttribute("data-popmelt-thread-header")&&Ag(U,U);if(oe.length&&(clearTimeout(I),I=setTimeout(()=>a(null),Math.max(0,$.expiresAt-Date.now())),await new Promise(U=>requestAnimationFrame(()=>setTimeout(U,0))),H))break;A.attention=$.workspace.entryId?oe.length?"shown":re(r.current.state,$.workspace.entryId,r.current.registry,!0)?"target_offscreen":"target_missing_hidden_or_ambiguous":{shown:oe.length,requested:ee.length}}else if(P?.element.isConnected&&m.page===location.origin+location.pathname&&!Ra(P.element,"[data-popmelt-private], input, textarea, select, [contenteditable]"))try{let ne=$.attentionOnly?null:(await import("./focus-inspection-GJKMI6OE.mjs")).inspectFocusElement;if(H||$.expiresAt<Date.now()||!P.element.isConnected||m.page!==location.origin+location.pathname)continue;if(a(P.element),clearTimeout(I),I=setTimeout(()=>a(null),Math.max(0,$.expiresAt-Date.now())),await new Promise(re=>requestAnimationFrame(()=>setTimeout(re,0))),H)break;A=ne?await ne(P.element,P.target,$.screenshot,r.current):{status:"ok",attention:"shown"}}catch{A={status:"capture_failed"}}if(H||document.visibilityState!=="visible")break;(await Yt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:ny($.id,m.clientId,A),signal:AbortSignal.timeout(3e3)})).ok||await Yt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:$.id,clientId:m.clientId,result:{status:"response_rejected"}}),signal:AbortSignal.timeout(3e3)}),clearTimeout(I),a(null)}}catch{}finally{clearTimeout(I),H||a(null),ie=!1}}},1e3);return Y(),()=>{H=!0,clearTimeout(D),clearTimeout(w),clearInterval(q),clearInterval(L),clearTimeout(I),a(null),document.removeEventListener("visibilitychange",Y),window.removeEventListener("focus",N),window.removeEventListener("blur",N),s.current=null,d.current=null,S.clear(),m.hover=null,m.selected=null,m.history=[],m.active=!1,Z()}},[e,t]),{onCanvasFocusChange:p,onCanvasActivity:c,inspectingElement:e?o[0]??null:null,inspectingElements:e?o:[]}}function oy(e,t,n,r){let[o,i]=j(null),[a,l]=j(null),s=W(0),d=W(Promise.resolve(!0)),c=J(()=>{s.current=Date.now()},[]),p=J(h=>{s.current=Date.now(),i(h)},[]),u=J(h=>l(m=>JSON.stringify(m)===JSON.stringify(h)?m:h),[]);return O(()=>{if(!e||!r)return;let h=o?.element;if(h&&Ra(h,"[data-private], [data-sensitive]"))return;let m=a?.targets??(h?[{selector:o?.subject?uu(o.subject):Ho(h),...o?.subject?{subject:o.subject}:{}}]:[]);if(!m.length)return;let g={pathname:window.location.pathname,ownerId:t,color:n,targets:m,activity:"looking",...a?{threadId:a.threadId}:{}},x=!1,S=null,D=!1,H=(N,Y,q)=>{let ie=d.current.then(()=>N!=="finish"&&(x||S!==Y)?!1:e(N,Y,q));return d.current=ie.catch(()=>!1),ie},w=()=>{let N=S;S=null,N&&H("finish",N).catch(()=>{})},z=async()=>{if(x||D)return;if(!(document.visibilityState!=="hidden"&&document.hasFocus()&&g.pathname===window.location.pathname&&(a||h?.isConnected&&(o?.selection==="selected"||Date.now()-s.current<5e3)))){w();return}D=!0;let N=S?"renew":"start",Y=S??crypto.randomUUID();S=Y;try{!await H(N,Y,g)&&S===Y&&(S=null),x&&w()}catch{S===Y&&(S=null)}finally{D=!1}},Z=setTimeout(z,120),k=setInterval(z,1e3),G=()=>w();return window.addEventListener("blur",G),window.addEventListener("focus",z),document.addEventListener("visibilitychange",z),()=>{x=!0,clearTimeout(Z),clearInterval(k),w(),window.removeEventListener("blur",G),window.removeEventListener("focus",z),document.removeEventListener("visibilitychange",z)}},[e,r,t,n,o,a]),{onFocus:p,onActivity:c,onThread:u}}var Sl="data-popmelt-preview-target",Nu="script,iframe,object,embed,link,meta,base,style,template";function iy({root:e,targets:t,revision:n,width:r,height:o,cleanClone:i}){let a=e.cloneNode(!0),l=[e,...e.querySelectorAll("*")],s=[a,...a.querySelectorAll("*")],d=new Set,c=new Map;for(let[u,h]of t){if(!u||!l.includes(h))throw new Error("Target is outside the preview root");if(c.has(h))throw new Error("Target has multiple identities");c.set(h,u)}l.forEach((u,h)=>{let m=s[h];(u.shadowRoot||u.matches("canvas,video"))&&d.add("Shadow DOM, canvas and video state are not mirrored");for(let x of[...m.attributes])(/^on/i.test(x.name)||["src","srcset","href","xlink:href","action","formaction","autofocus","contenteditable",Sl].includes(x.name))&&m.removeAttribute(x.name);u instanceof HTMLInputElement&&(u.type==="password"||u.type==="file"?m.removeAttribute("value"):m.setAttribute("value",u.value),m.toggleAttribute("checked",u.checked)),u instanceof HTMLTextAreaElement&&(m.textContent=u.value),u instanceof HTMLOptionElement&&m.toggleAttribute("selected",u.selected);let g=c.get(u);g&&m.setAttribute(Sl,g),i?.(u,m)});for(let u of a.querySelectorAll(Nu))u.remove();for(let u of a.querySelectorAll("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"))u.remove();if(a.matches(Nu))throw new Error("Unsupported preview root");let p="";for(let u of e.ownerDocument.styleSheets)if(!(u.ownerNode instanceof Element&&u.ownerNode.closest("[data-devtools], [data-popmelt-top-layer-host]")))try{p+=[...u.cssRules].map(h=>h.cssText).join(`
|
|
2
|
+
import{b as Qf,f as Wi,h as Zf,g as ys,a as uc,d as pc,c as fc}from"./chunk-JU7D4I76.mjs";import{a as eh}from"./chunk-IPR652AZ.mjs";import{M as il,vb as vs,Ua as hc,f as th,e as mc,tb as bs,a as nh,xb as gc,yb as yc,wb as xs,c as rh,jb as oh,kb as ih,Ja as Bi,ja as ah,Db as lh,Eb as vc,ia as sh,Kb as dh,Gb as ch,Hb as uh,Ib as ph,_a as fh,ka as hh,Da as mh,za as bc,ab as gh,ba as yh,ca as ws,da as vh,ea as bh,$a as xh,Fa as wh,ha as Sh,ob as Ss,nb as Ih,mb as Is,Fb as kh,la as Th,Oa as xc,Ba as wc,Ma as Sc,Na as Eh,La as Ic,Ka as Ah,Ga as ks,N as Ch,Cb as Mh,p as kc,ya as Rh,b as Lh,ub as Tc,Ra as Ph,Qa as jh,Ta as zh,Pa as $h,Sa as Dh,Ca as Hh,D as Nh,E as Oh,l as Fh,ra as nn,ua as _h,xa as Wh,Ha as Bh,sa as Ec,na as Ji,T as Jh,ma as qh,R as Ac,Y as Uh,fb as gi,Mb as Yh,Jb as Xh,eb as Cc,gb as Mc,Ab as Kh,Bb as Vh,lb as Gh,hb as Qh,ib as Zh,Aa as em,Ea as Ts,Q as tm,C as Rc,F as Lc,L as Pc,K as jc,o as yi,G as zc,J as qi,P as nm,va as Es,qa as rm,pa as As,oa as Cs,O as om,ga as im,fa as am,Ia as lm,ta as $c,wa as Dc,q as sm,W as Hc,U as Nc,V as Oc,X as dm,Z as Fc,$ as _c,aa as cm,S as um,zb as Wc,m as Ui,A as Ms,r as vi,I as al,u as Bc,g as pm,_ as fm,t as ll,h as Jc,y as hm,j as $r,v as Rs,s as Ta,i as Ls,k as mm,z as gm,x as ym,H as Ps,w as qc,n as Uc,B as vm}from"./chunk-Q5QRV4KJ.mjs";import{b as Yc,d as bm,a as xm,e as wm,c as Sm}from"./chunk-J4WDYITA.mjs";import{h as Im,Ca as Xc,R as Yi,ma as km,N as Tm,H as Kc,A as ro,la as sl,ka as Em,P as Am,D as Vc,O as Cm,da as Tn,Y as js,aa as lr,fa as zs,$ as Ea,ha as Mm,S as dl,ua as Gc,_ as oo,za as Rm,Aa as Lm,Ba as Qc,ta as Zc,J as $s,v as eu,u as Aa,r as cl,w as Xi,Z as tu,Q as nu,I as Pm,K as jm,M as zm,f as $m,ba as Dm,ca as Hm,wa as Nm,va as ru,ya as Om,xa as Fm,sa as ou,z as iu,t as Ds,g as _m,ea as Hs,C as Wm,E as au,G as Bm,F as Jm,ga as lu,ia as su,B as qm,s as ul,L as Um,y as Ns,q as du,x as Ym}from"./chunk-GNZ73T3H.mjs";import{b as cu}from"./chunk-4LHTPRFY.mjs";import{c as Xm,a as uu,b as Ca}from"./chunk-MTQ5IWIK.mjs";import{i as pu,k as Km,m as Vm,h as fu,g as Gm,a as pl,e as Qm,b as Dr,d as Zm,f as it,c as eg}from"./chunk-F6AMPRUB.mjs";import{c as hn,a as Ho,i as mn,j as bi,d as tg,e as ng,b as hu,l as rg,m as og,k as ig}from"./chunk-EXDOFFFJ.mjs";import{a as ag}from"./chunk-2P2NUZW7.mjs";import{d as Os,i as lg}from"./chunk-D32YV5O6.mjs";import{a as Fs,h as mu,d as sg,c as dg,g as _s,e as Ws,b as cg}from"./chunk-V44RIEET.mjs";import{b as Yt,f as gu,d as yu,e as Bs,i as ug,j as Ma,l as vu,m as bu,r as pg,p as fg,u as hg,t as mg,s as gg,k as yg,a as vg,c as bg}from"./chunk-CPOYMGYY.mjs";import{a as xu,b as xg}from"./chunk-EX63NVDN.mjs";import{d as wg,g as Sg,m as Ig,l as kg}from"./chunk-N2ZEZCHO.mjs";import{a as Tg}from"./chunk-J3UIBBU2.mjs";import{b as Eg}from"./chunk-6VXFTT5U.mjs";import{a as Ag}from"./chunk-LVEMYZOA.mjs";import{d as xn,o as Ra,n as Ki,a as wu,i as Su,v as Iu,u as ku,h as fl,k as Cg,f as Mg,c as Js,m as Tu,l as qs}from"./chunk-RCVAPQ7X.mjs";import{lazy as hl,memo as Rg,useContext as Hr,useState as j,Suspense as ml,Fragment as Lg,useRef as W,useEffect as O,useLayoutEffect as It,useCallback as J,useMemo as Se,cloneElement as Pg,useSyncExternalStore as jg,useId as zg}from"react";import{jsx as f,jsxs as M,Fragment as ct}from"react/jsx-runtime";import{Fingerprint as io,Component as gl,Reply as Eu,Ban as yl,Terminal as $g,PenLine as Dg,ImageIcon as Hg,Plug as Ng,SquareMousePointer as Og,ChevronRight as Us,ThumbsUp as Fg,Clock as Ys,ChevronDown as Vi,Check as xi,ChevronLeft as _g,X as Xs,Send as Au,Lock as Wg,ArrowDown as Bg,OctagonAlert as Cu,MessageCircleQuestionMark as Jg,TriangleAlert as qg,Command as Mu,CornerDownLeft as Ks,EyeOff as Ug}from"lucide-react";import{createPortal as Ru}from"react-dom";function Lu(e,t){return e.store===void 0&&(e.store=t),e.store}function Yg(e,t){let n=e.listeners??(e.listeners=new Set);return n.add(t),()=>n.delete(t)}function Xg(e,t,n){let r=n(Lu(e,t));e.store=r;for(let o of e.listeners??[])o();return r}var nt=globalThis.__POPMELT_BRIDGE_CONNECTION__??(globalThis.__POPMELT_BRIDGE_CONNECTION__={}),vl=nt.sourceId??(typeof localStorage<"u"?localStorage.getItem("popmelt-source-id"):null)??(typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Math.random().toString(36).slice(2));nt.sourceId=vl;try{typeof localStorage<"u"&&localStorage.setItem("popmelt-source-id",vl)}catch{}function Vs(){return vl}var bl={isConnected:!1,status:"disconnected",jobResponses:{},jobThinking:{},activeJobIds:[],activeJobThreads:{},currentResponse:"",currentThinking:"",events:[],activeJobId:null,lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[],capabilitiesVersion:0};nt.store??(nt.store={...bl}),nt.listeners??(nt.listeners=new Set);var Nr=nt.activeEs??null,xl=nt.activeBridgeUrl??null,ao=null,Xn=nt.connectionGeneration??0,La=new Set,wi=new Map,No={},wl=new Set,Oo=new Map;function zn(e,t){if(!e)return!1;if(wl.has(e))return!0;if(La.has(e)){let r=wi.get(e);return r||(r=[],wi.set(e,r)),r.push({type:t.type??"",data:t}),!0}let n=No[e];return n!==void 0&&typeof t.seq=="number"&&t.seq<=n}async function Pu(e,t,n,r=new Map){let o=()=>n!==(nt.connectionGeneration??0);for(let l of t){if(o())return;Oo.set(l,r.get(l)??Oo.get(l)),La.add(l),wi.set(l,[])}let{mergeBackfillHistory:i,selectBackfillTerminalEvent:a}=await import("./bridge-recovery-3IQN3U6D.mjs");o()||await Promise.all(t.map(async l=>{try{let s=await vu(e,l,-1,{retryUnavailable:!0});if(o()||wl.has(l))return;let d=wi.get(l)??[];if(s){pt(u=>{let h={...u.jobResponses,[l]:s.accumulated.response},m={...u.jobThinking,[l]:s.accumulated.thinking},g=i(u.events,l,s.events);return{...u,jobResponses:h,jobThinking:m,currentResponse:l===u.activeJobId?s.accumulated.response:u.currentResponse,currentThinking:l===u.activeJobId?s.accumulated.thinking:u.currentThinking,events:g}}),No[l]=s.currentSeq;let c=[...s.events].reverse().find(u=>u.type==="job_started"||u.type==="job_parked");c?.type==="job_parked"&&Gi("job_parked",c,l);let p=a(s.events,s.jobActive,r.get(l));p&&Gi(p.type,p,l);for(let u of d)typeof u.data.seq=="number"&&u.data.seq<=s.currentSeq||Gi(u.type,u.data,l)}else{let c=!1;for(let u of d)Gi(u.type,u.data,l),(u.type==="done"||u.type==="error")&&(c=!0);let p=r.get(l);!c&&p&&Gi(p.type,p,l)}Oo.delete(l)}finally{o()||(La.delete(l),wi.delete(l))}}))}function Gi(e,t,n){if(e==="job_parked")pt(r=>{let o=r.activeJobIds.filter(i=>i!==n);return{...r,activeJobIds:o,activeJobId:o.at(-1)??null,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}});else if(e==="job_started")pt(r=>({...r,status:"streaming",activeJobId:n,activeJobIds:[...new Set([...r.activeJobIds,n])],activeJobThreads:typeof t.threadId=="string"?{...r.activeJobThreads,[n]:t.threadId}:r.activeJobThreads,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}));else if(e==="delta"){let r=t.text||"";pt(o=>({...o,jobResponses:{...o.jobResponses,[n]:(o.jobResponses[n]||"")+r},currentResponse:n===o.activeJobId?o.currentResponse+r:o.currentResponse,events:[...o.events,{type:"delta",data:t,timestamp:Date.now()}]}))}else if(e==="thinking"){let r=t.text||"";pt(o=>({...o,jobThinking:{...o.jobThinking,[n]:(o.jobThinking[n]||"")+r},currentThinking:n===o.activeJobId?o.currentThinking+r:o.currentThinking,events:[...o.events,{type:"thinking",data:t,timestamp:Date.now()}]}))}else if(e==="status")pt(r=>({...r,events:[...r.events,{type:"status",data:t,timestamp:Date.now()}]}));else if(e==="done")delete No[n],pt(r=>{let o=r.activeJobIds.filter(d=>d!==n),i={...r.jobResponses},a={...r.jobThinking},l=i[n];delete i[n],delete a[n];let s=n===r.activeJobId?o.length>0?o[o.length-1]:null:r.activeJobId;return{...r,activeJobIds:o,activeJobId:s,jobResponses:i,jobThinking:a,lastCompletedJobId:n,lastResponseText:t.responseText||l||r.currentResponse||null,lastThreadId:t.threadId??null,...n===r.activeJobId?{currentResponse:s&&i[s]||"",currentThinking:s&&a[s]||""}:{},events:[...r.events,{type:"done",data:t,timestamp:Date.now()}]}});else if(e==="error"){delete No[n];let r=t.message??"";pt(o=>{let i=o.activeJobIds.filter(l=>l!==n),a=i.length>0?o.status:"error";return{...o,status:a,activeJobIds:i,lastCompletedJobId:n,lastErrorByJob:r?{...o.lastErrorByJob,[n]:r}:o.lastErrorByJob,events:[...o.events,{type:"error",data:t,timestamp:Date.now()}]}})}else pt(e==="question"?r=>{let o=typeof t.threadId=="string"?t.threadId:"",i=typeof t.question=="string"?t.question:"",a=Array.isArray(t.annotationIds)?t.annotationIds.filter(s=>typeof s=="string"):void 0,l=r.pendingQuestions.some(s=>s.jobId===n);return{...r,pendingQuestions:i&&o&&!l?[...r.pendingQuestions,{jobId:n,threadId:o,question:i,annotationIds:a,timestamp:Date.now()}]:r.pendingQuestions,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}}:r=>({...r,events:[...r.events,{type:e,data:t,timestamp:Date.now()}]}))}var Kn=nt.discoveredBridgeUrl??null,$n=nt.discoveredBridgeProjectId??null,Fo=null,Qi=null;function ju(e,t=!1){let n=e??null;if(!(!t&&(nt.expectedProjectId??null)===n)){Nr&&(Nr.close(),Nr=null,nt.activeEs=null),ao&&(clearTimeout(ao),ao=null),xl=null,nt.activeBridgeUrl=null,Kn=null,$n=null,nt.discoveredBridgeUrl=null,nt.discoveredBridgeProjectId=null,Fo=null,Qi=null,La.clear(),wi.clear(),wl.clear(),Oo.clear();for(let r of Object.keys(No))delete No[r];nt.expectedProjectId=n,Xn=(nt.connectionGeneration??Xn)+1,nt.connectionGeneration=Xn,pt(()=>({...bl}))}}function Kg(){nt.listeners?.size||ju(null,!0)}async function zu(e,t){if(Kn&&(t?$n===t:!$n))return Kn;if(!t&&$n&&(Kn=null,$n=null,nt.discoveredBridgeUrl=Kn,nt.discoveredBridgeProjectId=$n),t&&$n&&$n!==t&&(Kn=null,$n=null,nt.discoveredBridgeUrl=Kn,nt.discoveredBridgeProjectId=$n),Fo&&Qi===(t??null))return Fo;let n=Xn;return Qi=t??null,Fo=yg(e,t).then(r=>n!==Xn?null:(Kn=r?.url??null,$n=r?.projectId??t??null,nt.discoveredBridgeUrl=Kn,nt.discoveredBridgeProjectId=$n,Fo=null,Qi=null,Kn)).catch(()=>(n!==Xn||(Fo=null,Qi=null),null)),Fo}function Vg(){return Kn}async function Gg(e,t){Kn=null,$n=null,nt.discoveredBridgeUrl=null,nt.discoveredBridgeProjectId=null,Fo=null,Qi=null;let n=Xn,r=await zu(e,t);return r&&n===Xn&&Gs(r),r}function Pa(){return Lu(nt,{...bl})}function Qg(e){return Yg(nt,e)}function pt(e){Xg(nt,{...bl},t=>{let n=e(t),r=new Set(n.activeJobIds),o=n.activeJobId&&r.has(n.activeJobId)?n.activeJobId:n.activeJobIds.at(-1)??null;return{...n,activeJobId:o,activeJobThreads:Object.keys(n.activeJobThreads).some(i=>!r.has(i))?Object.fromEntries(Object.entries(n.activeJobThreads).filter(([i])=>r.has(i))):n.activeJobThreads,status:n.status==="streaming"&&r.size===0?"idle":n.status}})}function Zg(){return typeof window<"u"?window.__POPMELT_PROJECT_ID__??null:null}function Gs(e){if(Nr&&Nr.readyState!==EventSource.CLOSED&&xl===e)return;Nr&&(Nr.close(),Nr=null,nt.activeEs=null),ao&&(clearTimeout(ao),ao=null),xl=e,nt.activeBridgeUrl=xl,Xn=(nt.connectionGeneration??Xn)+1;let t=Xn;nt.connectionGeneration=Xn;let n=new URLSearchParams({sourceId:vl}),r=Zg();r&&n.set("projectId",r);let o=vg(`${e}/events?${n.toString()}`);Nr=o,nt.activeEs=Nr;let i=!1,a=()=>t!==(nt.connectionGeneration??0),l=()=>i||a();La.clear(),wi.clear();let s=5e3,d=()=>{a()||ao||(ao=setTimeout(()=>{ao=null,!a()&&Ma(e).then(p=>{a()||(p&&(!r||p.projectId===r)?Gs(e):(s=Math.min(s*2,3e4),d()))})},s))},c=()=>{l()||(i=!0,o.close(),pt(p=>({...p,isConnected:!1,status:"disconnected"})),d())};o.addEventListener("connected",()=>{l()||Ma(e).then(async p=>{if(l())return;if(!p||r&&p.projectId!==r){c();return}let u=[...p?.activeJobs??(p?.activeJob?[p.activeJob]:[]),...p?.queuedJobs?.filter(z=>z.parked)??[]],h=p?.recentJobs??[],{planBridgeReconnectRecovery:m}=await import("./bridge-recovery-3IQN3U6D.mjs");if(l())return;let g=m(Pa().activeJobIds,u,h),{serverActiveIds:x,terminalJobs:S}=g,D=S.map(z=>z.id),H=new Map(Oo);for(let z of S)H.set(z.id,z.status==="error"?{type:"error",jobId:z.id,message:z.error??"The agent run failed.",threadId:z.threadId,annotationIds:z.annotationIds}:{type:"done",jobId:z.id,success:!0,threadId:z.threadId,annotationIds:z.annotationIds});pt(z=>{let Z={...z.lastErrorByJob};for(let N of S)N?.status==="error"&&N.error&&(Z[N.id]=N.error);let k=m(z.activeJobIds,u,h).reconciledActiveIds,G={};for(let N of u)N.threadId&&(G[N.id]=N.threadId);return{...z,isConnected:!0,status:k.length>0?"streaming":D.length>0||z.status==="disconnected"?"idle":z.status,activeJobId:k.length>0?k[k.length-1]:null,activeJobIds:k,activeJobThreads:G,lastErrorByJob:Z,workspaceGeneration:p?.workspaceGeneration}});let w=[...new Set([...x,...D,...Oo.keys()])];w.length>0&&Pu(e,w,t,H).catch(c)}).catch(c)}),o.addEventListener("job_parked",p=>{if(l())return;let u=JSON.parse(p.data);zn(u.jobId,u)||Gi("job_parked",u,u.jobId)}),o.addEventListener("thread_changed",p=>{if(l())return;let u=JSON.parse(p.data);pt(h=>({...h,events:[...h.events,{type:"thread_changed",data:u,timestamp:Date.now()}]}))}),o.addEventListener("job_started",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if(zn(h,u))return;let m=u.threadId;pt(g=>({...g,status:"streaming",activeJobId:h,activeJobIds:g.activeJobIds.includes(h)?g.activeJobIds:[...g.activeJobIds,h],activeJobThreads:m?{...g.activeJobThreads,[h]:m}:g.activeJobThreads,jobResponses:{...g.jobResponses,[h]:g.jobResponses[h]??""},jobThinking:{...g.jobThinking,[h]:g.jobThinking[h]??""},currentResponse:g.jobResponses[h]??"",currentThinking:g.jobThinking[h]??"",lastResponseText:null,lastThreadId:null,events:[...g.events,{type:"job_started",data:u,timestamp:Date.now()}]}))}),o.addEventListener("delta",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if(zn(h,u))return;let m=u.text||"";pt(g=>({...g,jobResponses:h?{...g.jobResponses,[h]:(g.jobResponses[h]||"")+m}:g.jobResponses,currentResponse:!h||h===g.activeJobId?g.currentResponse+m:g.currentResponse,events:[...g.events,{type:"delta",data:u,timestamp:Date.now()}]}))}),o.addEventListener("thinking",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;if(zn(h,u))return;let m=u.text||"";pt(g=>({...g,jobThinking:h?{...g.jobThinking,[h]:(g.jobThinking[h]||"")+m}:g.jobThinking,currentThinking:!h||h===g.activeJobId?g.currentThinking+m:g.currentThinking,events:[...g.events,{type:"thinking",data:u,timestamp:Date.now()}]}))}),o.addEventListener("status",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,events:[...m.events,{type:"status",data:u,timestamp:Date.now()}]}))}),o.addEventListener("orientation",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,events:[...m.events,{type:"orientation",data:u,timestamp:Date.now()}]}))}),o.addEventListener("approval",p=>{if(l())return;let u=JSON.parse(p.data);zn(u.jobId,u)||pt(h=>({...h,events:[...h.events,{type:"approval",data:u,timestamp:Date.now()}]}))}),o.addEventListener("imprint_used",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,events:[...m.events,{type:"imprint_used",data:u,timestamp:Date.now()}]}))}),o.addEventListener("tool_use",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,events:[...m.events,{type:"tool_use",data:u,timestamp:Date.now()}]}))});for(let p of["image_generation","image_ready"])o.addEventListener(p,u=>{if(l())return;let h=JSON.parse(u.data),m=h.jobId;zn(m,h)||pt(g=>({...g,events:[...g.events,{type:p,data:h,timestamp:Date.now()}]}))});o.addEventListener("done",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||(h&&delete No[h],pt(m=>{let g=h?m.activeJobIds.filter(z=>z!==h):m.activeJobIds,x={...m.jobResponses},S={...m.jobThinking},D={...m.activeJobThreads},H=h?x[h]:void 0;h&&(delete x[h],delete S[h],delete D[h]);let w=h===m.activeJobId?g.length>0?g[g.length-1]:null:m.activeJobId;return{...m,activeJobIds:g,activeJobId:w,jobResponses:x,jobThinking:S,lastCompletedJobId:h??m.activeJobId,lastResponseText:u.responseText||H||m.currentResponse||null,lastThreadId:u.threadId??null,...h===m.activeJobId?{currentResponse:w&&x[w]||"",currentThinking:w&&S[w]||""}:{},events:[...m.events,{type:"done",data:u,timestamp:Date.now()}]}}))}),o.addEventListener("question",p=>{if(l())return;let u=JSON.parse(p.data),h=u.jobId;zn(h,u)||pt(m=>({...m,pendingQuestions:[...m.pendingQuestions,{jobId:u.jobId,threadId:u.threadId,question:u.question,annotationIds:u.annotationIds,timestamp:Date.now()}],events:[...m.events,{type:"question",data:u,timestamp:Date.now()}]}))}),o.addEventListener("capabilities_changed",()=>{l()||pt(p=>({...p,capabilitiesVersion:p.capabilitiesVersion+1}))}),o.addEventListener("workspace_cleared",p=>{if(l())return;let u=JSON.parse(p.data);typeof u.workspaceGeneration!="number"||!Number.isInteger(u.workspaceGeneration)||u.workspaceGeneration<0||pt(h=>{for(let m of[...h.activeJobIds,...Oo.keys()])wl.add(m);return Oo.clear(),{...h,workspaceGeneration:u.workspaceGeneration,status:"idle",activeJobId:null,activeJobIds:[],activeJobThreads:{},jobResponses:{},jobThinking:{},currentResponse:"",currentThinking:"",events:[],lastCompletedJobId:null,lastResponseText:null,lastThreadId:null,lastErrorByJob:{},pendingQuestions:[],incrementalResolutions:[]}})}),o.addEventListener("queue_drained",()=>{if(l())return;let p=[...Pa().activeJobIds];if(p.length===0){pt(u=>({...u,status:u.status==="error"?"error":"idle",incrementalResolutions:[]}));return}Pu(e,p,t).then(()=>{l()||pt(u=>({...u,status:u.activeJobIds.length>0?u.status:u.status==="error"?"error":"idle",incrementalResolutions:u.activeJobIds.length>0?u.incrementalResolutions:[]}))}).catch(c)}),o.addEventListener("error",p=>{if(!l()){if(o.readyState===EventSource.CLOSED)c();else if(p instanceof MessageEvent){let u=JSON.parse(p.data),h=u.jobId??null;if(zn(h??void 0,u))return;h&&delete No[h];let m=u.message??"";pt(g=>{let x=h?g.activeJobIds.filter(D=>D!==h):g.activeJobIds,S=x.length>0?g.status:"error";return{...g,status:S,activeJobIds:x,lastCompletedJobId:h??g.activeJobId,lastErrorByJob:h&&m?{...g.lastErrorByJob,[h]:m}:g.lastErrorByJob,events:[...g.events,{type:"error",data:u,timestamp:Date.now()}]}})}}}),o.onerror=()=>{l()||o.readyState===EventSource.CLOSED&&pt(p=>({...p,isConnected:!1,status:"disconnected"}))}}function ey(e="http://localhost:1111",t=!0,n){let r=jg(Qg,Pa,Pa);O(()=>{if(ju(n),!t)return;let a=!1;return zu(e,n).then(l=>{!l||a||Ma(l).then(s=>{!a&&s&&(!n||s.projectId===n)&&Gs(l)})}),()=>{a=!0}},[e,t,n]);let o=J(()=>{pt(()=>({...Pa(),events:[],currentResponse:"",currentThinking:"",jobResponses:{},jobThinking:{},lastResponseText:null,lastThreadId:null,lastErrorByJob:{},incrementalResolutions:[]}))},[]),i=J(a=>{pt(l=>({...l,pendingQuestions:l.pendingQuestions.filter(s=>s.threadId!==a)}))},[]);return{...r,clearEvents:o,dismissQuestion:i}}function $u(e,t,n,r,o){let i=`devtools-model-id:${r}`,[a,l]=j(()=>typeof window>"u"?"":localStorage.getItem(i)??""),s=o?.(a)??!1,d=s?-1:e.findIndex(u=>u.id===a),c=d>=0?d:0,p=J(u=>{l(u),localStorage.setItem(i,u)},[i]);return O(()=>{n&&a&&(s||t&&d<0&&e.some(u=>u.id))&&p("")},[n,t,a,d,e,p,s]),{index:c,select:p}}function ty(e,t,n){let r=e.flatMap(({requestedAt:a,resolvedAt:l})=>Number.isFinite(a)&&Number.isFinite(l)?[[Math.max(t,a),Math.min(n,l)]]:[]).sort((a,l)=>a[0]-l[0]),o=t,i=0;for(let[a,l]of r)i+=Math.max(0,l-Math.max(o,a)),o=Math.max(o,l);return i}function Du(e){let t=new Map,n=new Set;for(let r of e)if(r.type==="approval"){let o=r.data.approval;t.set(o.id,o)}else(r.type==="done"||r.type==="error")&&n.add(String(r.data.jobId));return new Set([...t.values()].filter(r=>r.status==="pending"&&!n.has(r.jobId)).map(r=>r.jobId))}function Hu(e){let t=new MutationObserver(n=>{let r=n.filter(o=>document.body.contains(o.target)||o.target===document.documentElement&&[...o.addedNodes,...o.removedNodes].some(i=>i instanceof Element&&i.tagName==="BODY"));r.length&&e(r)});return t.observe(document.documentElement,{childList:!0,subtree:!0}),t}function ny(e,t,n,r=8*1024*1024){let o=d=>JSON.stringify({id:e,clientId:t,result:d}),i=d=>new TextEncoder().encode(d).length<=r,a=o(n);if(i(a))return a;let l=Array.isArray(n.images)?n.images:[],s=[l.filter(d=>d.kind==="annotated-viewport"),l.filter(d=>d.kind!=="annotated-viewport"),[]];for(let d of s){let c=o({...n,images:d,visualEvidence:{status:"partial",reason:"response_size_limit",omitted:l.filter(p=>!d.includes(p)).map(p=>p.kind)}});if(i(c))return c}return o({status:"context_too_large",targetKey:n.targetKey,images:[],warning:"Context exceeds the response limit even without images."})}function ry(e,t,n){let r=W(n);r.current=n;let[o,i]=j([]),a=h=>i(h?[h]:[]),l=W(null),s=W(null),d=W(null),c=J(()=>d.current?.(),[]),p=J(h=>{l.current=h,s.current?.(h)},[]),u=W(null);return O(()=>{if(!e)return;u.current?.url!==t&&(u.current={url:t,clientId:crypto.randomUUID(),sequence:0,sending:!1});let h=u.current,m={clientId:h.clientId,sequence:0,page:location.origin+location.pathname,title:document.title,active:!0,windowFocused:document.hasFocus(),lastInteractionAt:0,blurredAt:0,hover:null,pinned:null,history:[]},g=null,x=new WeakMap,S=new Map,D,H=!1,w,z=0,Z=()=>{let F=location.origin+location.pathname;m.page!==F&&(m.page=F,m.title=document.title,m.hover=null,m.pinned=null,m.history=[],m.recent=null,m.selected=null,S.clear(),g=null,m.lastInteractionAt=0),m.sequence=++h.sequence,h.pendingBody=JSON.stringify(m),!h.sending&&(h.sending=!0,(async()=>{for(;h.pendingBody;){let R=h.pendingBody;h.pendingBody=void 0;try{await Yt(`${t}/focus`,{method:"POST",headers:{"Content-Type":"application/json"},body:R,signal:AbortSignal.timeout(3e3)})}catch{}}h.sending=!1})())},k=(F,R)=>{x.has(F)||x.set(F,crypto.randomUUID());let $=mn(F),P=xn(F),A=getComputedStyle(F),ne={...R?{subject:R}:{},key:x.get(F),capturedAt:Date.now(),selector:$.selector,tagName:$.tagName,text:$.textContent?.slice(0,200),component:$.reactComponent,source:$.reactSource,rect:{x:P.x,y:P.y,width:P.width,height:P.height},styles:Object.fromEntries(["color","background-color","font-size","font-family","display","padding","border-radius"].map(re=>[re,A.getPropertyValue(re)]))};if(S.set(ne.key,{element:F,target:ne}),S.size>32){let re=[...S.keys()].find(ee=>ee!==m.pinned?.key);re&&S.delete(re)}return ne},G=F=>{let R=F?.element??null,$=F?.selection==="selected",P=m.selected??m.hover;R===g&&!!m.selected===$&&P?.subject?.key===F?.subject?.key||(g=R,clearTimeout(D),D=setTimeout(()=>{if(H)return;let A=R?.isConnected&&!Ra(R,"input, textarea, select, [contenteditable], [data-popmelt-private], [data-popmelt-canvas-block], [data-devtools]")?k(R,F?.subject):null;m.selected=$?A:null,m.hover=$?null:A,$&&(m.recent=null),m.hover&&(m.history=[...m.history,m.hover].slice(-8)),m.windowFocused&&(m.recent=null),Z()},R&&!$?120:0))};s.current=G,d.current=()=>{H||document.visibilityState!=="visible"||(m.lastInteractionAt=Date.now(),m.windowFocused=document.hasFocus(),!w&&(w=setTimeout(()=>{w=void 0,z=Date.now(),Z()},Math.max(0,250-(Date.now()-z)))))},G(l.current);let N=()=>{m.windowFocused=document.hasFocus(),m.blurredAt=m.windowFocused?0:Date.now(),m.recent=m.windowFocused?null:m.hover,Z()},Y=()=>{m.active=document.visibilityState==="visible",m.active?G(l.current):(clearTimeout(D),m.hover=null,m.history=[],m.recent=null,m.selected=null,S.clear(),g=null,m.lastInteractionAt=0),Z()};document.addEventListener("visibilitychange",Y),window.addEventListener("focus",N),window.addEventListener("blur",N);let q=setInterval(Z,1e4),ie=!1,I,Q=new Set,L=setInterval(async()=>{if(!(H||ie||document.visibilityState!=="visible")){ie=!0;try{let F=await Yt(`${t}/focus/requests?clientId=${m.clientId}`,{signal:AbortSignal.timeout(3e3)});if(!F.ok)return;let R=await F.json();for(let $ of R){if(Q.has($.id)||H||$.expiresAt<Date.now())continue;Q.add($.id),Q.size>64&&Q.delete(Q.values().next().value);let P=S.get($.targetKey),A={status:"target_unavailable"};if($.tasteProposal){let{tasteProposalSession:ne}=await import("./taste-proposal-session-XU4N7RUV.mjs");if(H||$.expiresAt<Date.now())continue;let re=document.activeElement;for(;re?.shadowRoot?.activeElement;)re=re.shadowRoot.activeElement;A=re?.matches("input, textarea, select, [contenteditable]")&&Ra(re,"[data-taste-editor]")&&$.tasteProposal.action!=="inspect"?{status:"busy",reason:"The human is editing a proposal field. Retry after editing ends."}:ne.command($.tasteProposal)}else if($.workspace){let{collectWorkspaceSnapshot:ne,workspaceAttentionTarget:re}=await import("./workspace-snapshot-O34KMJ2V.mjs");if(H||$.expiresAt<Date.now())continue;A=ne(r.current.state,$.workspace);let ee=$.workspace.entryId?[$.workspace.entryId]:"entries"in A?A.entries.map(U=>U.id):[],oe=[...new Set(ee.map(U=>re(r.current.state,U,r.current.registry)).filter(U=>!!U))];i(oe);for(let U of oe)U instanceof HTMLElement&&U.hasAttribute("data-popmelt-thread-header")&&Ag(U,U);if(oe.length&&(clearTimeout(I),I=setTimeout(()=>a(null),Math.max(0,$.expiresAt-Date.now())),await new Promise(U=>requestAnimationFrame(()=>setTimeout(U,0))),H))break;A.attention=$.workspace.entryId?oe.length?"shown":re(r.current.state,$.workspace.entryId,r.current.registry,!0)?"target_offscreen":"target_missing_hidden_or_ambiguous":{shown:oe.length,requested:ee.length}}else if(P?.element.isConnected&&m.page===location.origin+location.pathname&&!Ra(P.element,"[data-popmelt-private], input, textarea, select, [contenteditable]"))try{let ne=$.attentionOnly?null:(await import("./focus-inspection-WPHGCN6Y.mjs")).inspectFocusElement;if(H||$.expiresAt<Date.now()||!P.element.isConnected||m.page!==location.origin+location.pathname)continue;if(a(P.element),clearTimeout(I),I=setTimeout(()=>a(null),Math.max(0,$.expiresAt-Date.now())),await new Promise(re=>requestAnimationFrame(()=>setTimeout(re,0))),H)break;A=ne?await ne(P.element,P.target,$.screenshot,r.current):{status:"ok",attention:"shown"}}catch{A={status:"capture_failed"}}if(H||document.visibilityState!=="visible")break;(await Yt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:ny($.id,m.clientId,A),signal:AbortSignal.timeout(3e3)})).ok||await Yt(`${t}/focus/response`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:$.id,clientId:m.clientId,result:{status:"response_rejected"}}),signal:AbortSignal.timeout(3e3)}),clearTimeout(I),a(null)}}catch{}finally{clearTimeout(I),H||a(null),ie=!1}}},1e3);return Y(),()=>{H=!0,clearTimeout(D),clearTimeout(w),clearInterval(q),clearInterval(L),clearTimeout(I),a(null),document.removeEventListener("visibilitychange",Y),window.removeEventListener("focus",N),window.removeEventListener("blur",N),s.current=null,d.current=null,S.clear(),m.hover=null,m.selected=null,m.history=[],m.active=!1,Z()}},[e,t]),{onCanvasFocusChange:p,onCanvasActivity:c,inspectingElement:e?o[0]??null:null,inspectingElements:e?o:[]}}function oy(e,t,n,r){let[o,i]=j(null),[a,l]=j(null),s=W(0),d=W(Promise.resolve(!0)),c=J(()=>{s.current=Date.now()},[]),p=J(h=>{s.current=Date.now(),i(h)},[]),u=J(h=>l(m=>JSON.stringify(m)===JSON.stringify(h)?m:h),[]);return O(()=>{if(!e||!r)return;let h=o?.element;if(h&&Ra(h,"[data-private], [data-sensitive]"))return;let m=a?.targets??(h?[{selector:o?.subject?uu(o.subject):Ho(h),...o?.subject?{subject:o.subject}:{}}]:[]);if(!m.length)return;let g={pathname:window.location.pathname,ownerId:t,color:n,targets:m,activity:"looking",...a?{threadId:a.threadId}:{}},x=!1,S=null,D=!1,H=(N,Y,q)=>{let ie=d.current.then(()=>N!=="finish"&&(x||S!==Y)?!1:e(N,Y,q));return d.current=ie.catch(()=>!1),ie},w=()=>{let N=S;S=null,N&&H("finish",N).catch(()=>{})},z=async()=>{if(x||D)return;if(!(document.visibilityState!=="hidden"&&document.hasFocus()&&g.pathname===window.location.pathname&&(a||h?.isConnected&&(o?.selection==="selected"||Date.now()-s.current<5e3)))){w();return}D=!0;let N=S?"renew":"start",Y=S??crypto.randomUUID();S=Y;try{!await H(N,Y,g)&&S===Y&&(S=null),x&&w()}catch{S===Y&&(S=null)}finally{D=!1}},Z=setTimeout(z,120),k=setInterval(z,1e3),G=()=>w();return window.addEventListener("blur",G),window.addEventListener("focus",z),document.addEventListener("visibilitychange",z),()=>{x=!0,clearTimeout(Z),clearInterval(k),w(),window.removeEventListener("blur",G),window.removeEventListener("focus",z),document.removeEventListener("visibilitychange",z)}},[e,r,t,n,o,a]),{onFocus:p,onActivity:c,onThread:u}}var Sl="data-popmelt-preview-target",Nu="script,iframe,object,embed,link,meta,base,style,template";function iy({root:e,targets:t,revision:n,width:r,height:o,cleanClone:i}){let a=e.cloneNode(!0),l=[e,...e.querySelectorAll("*")],s=[a,...a.querySelectorAll("*")],d=new Set,c=new Map;for(let[u,h]of t){if(!u||!l.includes(h))throw new Error("Target is outside the preview root");if(c.has(h))throw new Error("Target has multiple identities");c.set(h,u)}l.forEach((u,h)=>{let m=s[h];(u.shadowRoot||u.matches("canvas,video"))&&d.add("Shadow DOM, canvas and video state are not mirrored");for(let x of[...m.attributes])(/^on/i.test(x.name)||["src","srcset","href","xlink:href","action","formaction","autofocus","contenteditable",Sl].includes(x.name))&&m.removeAttribute(x.name);u instanceof HTMLInputElement&&(u.type==="password"||u.type==="file"?m.removeAttribute("value"):m.setAttribute("value",u.value),m.toggleAttribute("checked",u.checked)),u instanceof HTMLTextAreaElement&&(m.textContent=u.value),u instanceof HTMLOptionElement&&m.toggleAttribute("selected",u.selected);let g=c.get(u);g&&m.setAttribute(Sl,g),i?.(u,m)});for(let u of a.querySelectorAll(Nu))u.remove();for(let u of a.querySelectorAll("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"))u.remove();if(a.matches(Nu))throw new Error("Unsupported preview root");let p="";for(let u of e.ownerDocument.styleSheets)if(!(u.ownerNode instanceof Element&&u.ownerNode.closest("[data-devtools], [data-popmelt-top-layer-host]")))try{p+=[...u.cssRules].map(h=>h.cssText).join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}catch{d.add("An inaccessible stylesheet was omitted")}return d.add("Static snapshot: no scripts, external assets, event handlers or application runtime"),{revision:n,html:e.tagName==="BODY"?a.innerHTML:a.outerHTML,...e.tagName==="BODY"?{bodyAttributes:Object.fromEntries([...a.attributes].map(u=>[u.name,u.value]))}:{},css:p,width:r,height:o,warnings:[...d]}}function Ou(e,t){let n=[...e.querySelectorAll(`[${Sl}]`)].filter(r=>r.getAttribute(Sl)===t);return n.length===1?n[0]:null}var ay=class{constructor(e){this.generation=0,this.cancelPending=null,this.current=null,this.disposed=!1,this.frame=e.ownerDocument.createElement("iframe"),this.frame.setAttribute("sandbox","allow-same-origin"),this.frame.title="Peer plane preview",this.frame.style.cssText="border:0;display:block;pointer-events:none;",this.frame.tabIndex=-1,e.append(this.frame)}async render(e,t,n){if(this.disposed)throw new Error("Preview surface was disposed");this.cancelPending?.();let r=++this.generation;this.current=null,this.frame.width=String(e.width),this.frame.height=String(e.height);let o=this.frame.ownerDocument.implementation.createHTMLDocument("Peer preview"),i=o.createElement("meta");i.httpEquiv="Content-Security-Policy",i.content="default-src 'none'; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'; script-src 'none'",o.head.prepend(i);let a=o.createElement("style");a.textContent=e.css.replace(/<\/style/gi,"<\\/style"),o.head.append(a),o.body.innerHTML=e.html;for(let[s,d]of Object.entries(e.bodyAttributes??{}))o.body.setAttribute(s,d);let l=o.createElement("style");return l.textContent="*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}",o.head.append(l),o.documentElement.dataset.previewGeneration=String(r),new Promise(s=>{let d=h=>{clearTimeout(u),this.frame.removeEventListener("load",p),this.cancelPending===c&&(this.cancelPending=null),s(h)},c=()=>d(!1),p=()=>{if(r!==this.generation||this.frame.contentDocument?.documentElement.dataset.previewGeneration!==String(r))return;let h=this.frame.contentDocument;n?.(h);for(let m of t.artifacts)m.kind==="style"&&Ou(h,m.targetKey)?.style.setProperty(m.property,m.value,"important");this.current={baseline:e,plane:{...t}},d(!0)},u=setTimeout(c,5e3);this.cancelPending=c,this.frame.addEventListener("load",p),queueMicrotask(()=>{!this.disposed&&r===this.generation&&(this.frame.srcdoc="<!doctype html>"+o.documentElement.outerHTML)})})}inspect(e,t){let n=this.current,r=this.frame.contentDocument;if(!n||!r)return null;let o=Ou(r,e);if(!o)return null;let i=this.frame.contentWindow.getComputedStyle(o),a=o.getBoundingClientRect();return{planeId:n.plane.id,planeRevision:n.plane.revision,sourceRevision:n.baseline.revision,targetKey:e,styles:Object.fromEntries(t.map(l=>[l,i.getPropertyValue(l)])),rect:{x:a.x,y:a.y,width:a.width,height:a.height}}}dispose(){this.disposed=!0,++this.generation,this.cancelPending?.(),this.current=null,this.frame.remove()}};function ly(e,t){return{id:e,ownerId:t,revision:0,artifacts:[],undo:[],redo:[],attention:null}}function Qs(e){return ll(e).flatMap(t=>t==="color"?[...Jc]:[t])}function sy(e,t){if(e===void 0)return{families:Ui.map(n=>({family:n,label:Ms(n)}))};if(!Ui.includes(e))throw new Error("Unknown omnidial family");if(!t)return{family:e,subproperties:Qs(e)};if(!Qs(e).includes(t))throw new Error("Unknown omnidial subproperty");return{family:e,subproperty:t,...e==="transform"&&t==="translate"?{composedToken:"translate-x-<xStep>-y-<yStep>",axisSteps:vi(e,t)}:{},tokens:vi(e,t).map(n=>({token:al(e,n,t),value:qi(e,n,t)}))}}function dy(e,t){if(t!==void 0&&!Ui.includes(t))throw new Error("Unknown omnidial family");let n=/^translate-x-(-?\d+)-y-(-?\d+)$/.exec(e);if(n&&(!t||t==="transform")){let o=vi("transform","translate"),i=o.find(l=>String(l)===n[1]),a=o.find(l=>String(l)===n[2]);if(i!==void 0&&a!==void 0)return{family:"transform",subproperty:"translate",step:i,axisSteps:{x:i,y:a}}}let r=[];for(let o of t?[t]:Ui)for(let i of Qs(o))for(let a of vi(o,i))al(o,a,i)===e&&r.push({family:o,subproperty:i,step:a});if(r.length>1)throw new Error("Ambiguous omnidial token; include its family (for example stack or grid)");if(!r.length)throw new Error("Unknown omnidial token; discover available tokens or use an explicit custom property/value");return r[0]}function Fu(e,t,n,r){let o=e.ownerDocument.defaultView.getComputedStyle(e),i=Rc(t,r),a=qi(t,n,r),l=Pc(t),s=jc(t,r,n),d=t==="border"&&!yi(t,r)&&typeof n=="number"&&n>0?zc(r):null,c={family:t,subproperty:Bc(t,r),step:n},p=[{property:i,original:o.getPropertyValue(i).trim()||"0px",modified:a,token:al(t,n,r),sticker:c}];l&&p.unshift({property:"display",original:o.getPropertyValue("display").trim()||"block",modified:l,token:l,sticker:c});for(let u of s)p.push({property:u.property,original:o.getPropertyValue(u.property).trim(),modified:u.value,token:u.token,sticker:c});if(d){let u=o.getPropertyValue(d).trim();(!u||u==="none")&&p.push({property:d,original:u||"none",modified:"solid",token:al(t,n,r),sticker:c})}return{alreadyApplied:Lc(t,n,r,u=>o.getPropertyValue(u)),changes:p}}function _u(e,t,n){let r=e.ownerDocument.defaultView.getComputedStyle(e),o="translate",i=`${Number(t)*4}px ${Number(n)*4}px`,a={family:"transform",subproperty:"translate",step:t,axisSteps:{x:t,y:n}};return{alreadyApplied:r.getPropertyValue(o).trim()===i,changes:[{property:o,original:r.getPropertyValue(o).trim()||"none",modified:i,token:`translate-x-${t}-y-${n}`,sticker:a}]}}function cy(e,t){for(let n of t.changes)it(e,n.property,n.modified)}var uy=new Set(["text","transform","opacity"]),py=new Set(["padding","margin","border","radius","color"]);function fy(e){return e instanceof SVGSVGElement&&!(e.parentElement instanceof SVGElement)}function hy(e){return e!=="text-align"}function Il(e,t,n){return Dr(e)?e instanceof HTMLElement?!0:t==="text"&&!hy(n)?!1:uy.has(t)||fy(e)&&py.has(t):!1}function ja(e){return[...new Set([...e?.annotations.flatMap(t=>t.linkedSelector?[t.linkedSelector]:[])??[],...e?.styleModifications.map(t=>t.selector)??[],...e?.textModifications.map(t=>t.selector)??[]])]}function my(e,t){return Object.keys(t).filter(n=>e[n]!==void 0&&e[n]!==t[n])}function Wu(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(t).every(n=>e[n]===t[n])}function Zs(e,t,n,r){let o={...e};for(let i of r){if(n[i]===void 0){delete o[i];continue}o[i]=t[i]??e[i]??n[i]}return o}function gy(e){let t=e.ownerDocument.defaultView.getComputedStyle(e),n=Array.from(t).filter(i=>!i.startsWith("--")).map(i=>`${i}:${t.getPropertyValue(i)}`).join(";"),r=e.outerHTML+n,o=2166136261;for(let i=0;i<r.length;i++)o=Math.imul(o^r.charCodeAt(i),16777619);return`target-v2:${(o>>>0).toString(16)}`}var sr=()=>location.origin+location.pathname;function kl(e){let t=document.querySelectorAll(e),n=t[0];if(t.length!==1||!(n instanceof HTMLElement||n instanceof SVGElement)||n.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-canvas-block]"))throw new Error("Target must resolve to exactly one app element");if(n.matches("input,textarea,select,[contenteditable],script,style")||n.closest("[data-private], [data-sensitive]"))throw new Error("Private/editable controls are outside the peer preview");return n}var Bu=class{constructor(){this.sources={},this.changed=[],this.container=document.createElement("div"),this.container.dataset.popmeltPeerSurface="",this.container.setAttribute("aria-hidden","true"),this.container.style.cssText="position:fixed;left:-100000px;top:0;pointer-events:none;",document.body.append(this.container),this.surface=new ay(this.container)}async render(e,t,n,r=!1){if(t.domModifications.length||t.spacingTokenChanges.length)throw new Error("Independent previews do not yet support staged structure or spacing-token edits; your draft is preserved");let o=e.state??pl,i=new Set([...n?[n]:[],...ja(o)]),a=new Map;for(let c of i)a.set(c,kl(c));let l=new Map;for(let c of t.textModifications){let p=document.querySelector(c.selector);p&&l.set(p,[...l.get(p)??[],c])}let s=iy({root:document.body,targets:a,revision:sr(),width:innerWidth,height:innerHeight,cleanClone:(c,p)=>{if(!r){eg(c,p);for(let u of l.get(c)??[]){let h=p;for(let m of u.textNodePath)h=h?.childNodes[m];h?.nodeType===Node.TEXT_NODE&&(h.nodeValue=u.original)}}}}),d=ly(e.identity.id,e.identity.id);if(d.revision=e.revision,r||(d.artifacts=o.styleModifications.flatMap(c=>c.changes.map(p=>({kind:"style",id:c.selector+p.property,targetKey:c.selector,property:p.property,value:p.modified})))),!await this.surface.render(s,d,c=>{this.sources=Object.fromEntries([...i].map(p=>[p,gy(c.querySelector(`[data-popmelt-preview-target="${CSS.escape(p)}"]`))])),this.changed=my(e.basis??{},this.sources)}))throw new Error("Preview superseded or unavailable");return this.surface.frame.contentWindow?.scrollTo(scrollX,scrollY),s.warnings}async execute(e,t){let{action:n}=e,r=structuredClone(e.peer);if(n.type==="prepare-send"){if(!ja(r.state).length)throw new Error("There are no peer changes to send");if(await this.render(r,t),!e.observedSources||Object.keys(this.sources).some(s=>e.observedSources[s]!==this.sources[s]))throw new Error("Source changed since the last preview. Take another look, then send again.");return this.changed.length&&r.revision++,r.basis={...this.sources},delete r.pendingRevision,{peer:r,sources:this.sources}}if(n.type==="check-source"){let s={...r,state:{...structuredClone(pl),annotations:Object.keys(n.sources).map((d,c)=>({id:`source-${c}`,type:"text",text:"",points:[],strokeWidth:1,color:r.color,timestamp:0,linkedSelector:d}))}};if(await this.render(s,t),!Wu(n.sources,this.sources))throw new Error("Source changed since Send. Preview the current source and send again.");return{peer:r,evidence:{status:"source-current"}}}if(n.type==="tokens")return{peer:r,evidence:sy(n.family,n.subproperty)};let o=r.state??{...structuredClone(pl),isAnnotating:!0,activeColor:r.color},i=o,a,l=s=>{i=_m(i,s)};if(n.type==="send")throw new Error("Send requires the implementation bridge");if(n.type==="rebase")await this.render(r,t),r.basis={...this.sources},r.revision++,delete r.pendingRevision,a={status:"rebased",note:"Draft preserved against current source; Send requires a new approval if in Suggest."};else if(n.type==="undo"||n.type==="redo"){l({type:n.type==="undo"?"UNDO":"REDO"}),await this.render({...r,state:i},t);let s=[...new Set([...ja(o),...ja(i)])].filter(d=>{let c=p=>JSON.stringify([p.annotations.filter(u=>u.linkedSelector===d),p.styleModifications.filter(u=>u.selector===d)]);return c(o)!==c(i)});r.basis=Zs(r.basis??{},e.observedSources??{},this.sources,s)}else if(n.type==="attention"&&!n.selector)r.attention=null;else if(n.type==="clear"){let s=n.kind!=="style"&&o.annotations.some(c=>c.linkedSelector===n.selector),d=n.kind!=="comment"&&o.styleModifications.some(c=>c.selector===n.selector);if(!s&&!d)return{peer:r,evidence:{status:"nothing-to-clear"}};i={...o,annotations:n.kind==="style"?o.annotations:o.annotations.filter(c=>c.linkedSelector!==n.selector),styleModifications:n.kind==="comment"?o.styleModifications:o.styleModifications.filter(c=>c.selector!==n.selector),undoStack:[...o.undoStack,{annotations:o.annotations,styleModifications:o.styleModifications,textModifications:o.textModifications,domModifications:o.domModifications,spacingTokenChanges:o.spacingTokenChanges,spacingTokenMods:o.spacingTokenMods}],redoStack:[]},await this.render({...r,state:i},t),r.basis=Zs(r.basis??{},e.observedSources??{},this.sources,[n.selector])}else if("selector"in n&&n.selector){let s=kl(n.selector),d=mn(s),c=n.selector;if(n.type==="inspect"){let p=await this.render(r,t,c,n.plane==="host");a={...this.surface.inspect(c,n.properties??[]),element:d,warnings:p,view:n.plane??"own",url:sr(),changedSourceTargets:n.plane==="host"?void 0:this.changed}}else if(n.type==="style")if("token"in n){let p=dy(n.token,n.family);if(!Il(s,p.family,p.subproperty))throw new Error("This omnidial token does not support the target");await this.render(r,t,c);let u=this.surface.frame.contentDocument?.querySelector(c);if(!u)throw new Error("Could not inspect original style");let h=p.axisSteps?_u(u,p.axisSteps.x,p.axisSteps.y):Fu(u,p.family,p.step,p.subproperty);h.alreadyApplied||l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:h.changes}}),a={token:n.token,selection:p,alreadyApplied:h.alreadyApplied}}else{if(!CSS.supports(n.property,n.value))throw new Error("Unsupported CSS property/value");await this.render(r,t,c);let p=this.surface.inspect(c,[n.property])?.styles[n.property];if(p===void 0)throw new Error("Could not inspect original style");l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:[{property:n.property,original:p,modified:n.value}]}})}else if(n.type==="comment"){await this.render(r,t,c);let p=s.getBoundingClientRect();l({type:"ADD_TEXT",payload:{id:`peer-note-${e.id}`,point:{x:p.x+scrollX,y:p.y+scrollY-26},text:n.text,linkedSelector:c,elements:[{...d,selector:c}]}})}r.attention=null,(n.type==="comment"||n.type==="style")&&(r.basis=Zs(r.basis??{},e.observedSources??{},this.sources,[c]))}if(i!==o){if(i.annotations.length+i.styleModifications.length>100)throw new Error("Peer draft is full; submit or undo before adding more");i={...i,undoStack:i.undoStack.slice(-50),redoStack:i.redoStack.slice(-50)},r.state=i,r.revision++,r.url=sr(),delete r.pendingRevision}return{peer:r,evidence:a,...["inspect","style","comment","clear","undo","redo","rebase"].includes(n.type)&&!(n.type==="inspect"&&n.plane==="host")?{sources:this.sources}:{}}}dispose(){this.surface.dispose(),this.container.remove()}};async function yy(e,t,n){let r=!0,o,i=new Set,a=async c=>{let p=new AbortController;i.add(p);let u=setTimeout(()=>p.abort(),1500);try{return await e(c,p.signal)}catch{return!1}finally{clearTimeout(u),i.delete(p)}},l=()=>{r=!1,clearTimeout(o);for(let c of i)c.abort()},s=()=>{l(),a("finish")},d=async()=>{if(!r)return;let c=await a("renew");r&&c&&(o=setTimeout(()=>{d()},1e3))};n.addEventListener("abort",s,{once:!0});try{if(n.aborted)throw new Error("Canvas disconnected before action");let c=await a("start");if(n.aborted)throw new Error("Canvas disconnected before action");return r&&c&&(o=setTimeout(()=>{d()},1e3)),await t()}finally{l(),n.removeEventListener("abort",s),await a("finish")}}function vy(e){let t=`popmelt-peer-seen:${e}`,[n,r]=j({key:"",revisions:{}});return O(()=>{let o={};try{let i=JSON.parse(localStorage.getItem(t)??"{}");i&&typeof i=="object"&&!Array.isArray(i)&&(o=Object.fromEntries(Object.entries(i).filter(([,a])=>Number.isSafeInteger(a)&&a>=0)))}catch{}r({key:t,revisions:o})},[t]),{markSeen:J((o,i)=>{r(a=>{if(a.key!==t||(a.revisions[o]??0)>=i)return a;let l={key:t,revisions:{...a.revisions,[o]:i}};try{localStorage.setItem(t,JSON.stringify(l.revisions))}catch{}return l})},[t]),isUnseen:(o,i)=>n.key===t&&i>(n.revisions[o]??0)}}function by(e,t){let n,r=l=>(l instanceof Element?l:l.parentElement)?.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"),o=()=>{n===void 0&&(n=setTimeout(()=>{n=void 0,t()},400))},i=new MutationObserver(l=>{document.hidden||!e.length||l.some(s=>{if(r(s.target)||s.type==="childList"&&[...s.addedNodes,...s.removedNodes].every(c=>r(c)))return!1;let d=s.target instanceof Element?s.target:s.target.parentElement;return d?.closest("style,head")?!0:e.some(c=>{let p=document.querySelector(c);return!p||p.contains(s.target)||d?.contains(p)})})&&o()});i.observe(document.documentElement,{subtree:!0,attributes:!0,childList:!0,characterData:!0}),window.addEventListener("resize",o);let a=()=>{document.hidden||o()};return document.addEventListener("visibilitychange",a),()=>{i.disconnect(),clearTimeout(n),window.removeEventListener("resize",o),document.removeEventListener("visibilitychange",a)}}function Ju(e){if(!e)return 0;let t=em(e.annotations);return bc({annotations:e.annotations.filter(n=>!n.captured&&!t.has(n)),styleModifications:e.styleModifications.filter(n=>!n.captured),textModifications:e.textModifications.filter(n=>!n.captured)}).count}function xy(e,t,n,r,o){let[i,a]=j([]),[l,s]=j([]),d=Ph(l,e&&r.isAnnotating),c=jh(e&&r.isAnnotating),{viewedId:p,isPeeking:u}=c,[h,m]=j(),[g,x]=j(),[S,D]=j([]),H=W(null),{markSeen:w,isUnseen:z}=vy(n),Z=Se(()=>new Map(i.map(U=>[U.identity.id,Ju(U.state)])),[i]),{annotations:k,styleModifications:G,textModifications:N}=r,Y=Se(()=>Ju({annotations:k,styleModifications:G,textModifications:N}),[k,G,N]),[q,ie]=j(null),I=W(null),Q=W({human:r,settings:o});Q.current={human:r,settings:o};let L=W({clientId:crypto.randomUUID()}),F=W(async()=>{throw new Error("Canvas is disconnected")}),R=e?i.find(U=>U.identity.id===p):void 0,$=i.find(U=>U.identity.id===c.selectedId)?.state,P=Se(()=>zh($),[$]);O(()=>{if(!e||!n)return;L.current.token||(L.current={clientId:crypto.randomUUID()});let U=!1,fe,ge=-1,K=-1,Te=new AbortController,Me="",Ee=!1,Ge=new Bu,X=new Map,Oe=je=>{U||typeof je.presenceVersion!="number"||je.presenceVersion<=K||!Array.isArray(je.presence)||(K=je.presenceVersion,s(je.presence))},ve=async(je,$e={},ce=AbortSignal.any([Te.signal,AbortSignal.timeout(5e4)]))=>{let rt=L.current.token,at=await Yt(`${t}/peers/${je}`,{method:"POST",headers:{"Content-Type":"application/json","X-Popmelt-Project-Id":n},body:JSON.stringify({...L.current,...$e}),signal:ce}),Be=await at.json();if(je!=="host"&&rt!==L.current.token)throw new Error("Canvas session changed during request");if(!at.ok||Be.error)throw new Error(Be.error??`Peer request failed (${at.status})`);return Be};F.current=ve;async function Fe(je){if(je.url&&je.url!==sr())throw new Error("Canvas navigated before the operation could run");if(je.action.type!=="send"){let kt=pm(je.action);return kt?(kl(kt.selector),yy(async(lt,Ke)=>{let jt=await ve("activity",{id:je.id,phase:lt},Ke);return Oe(jt),jt.accepted===!0},()=>Ge.execute(je,Q.current.human),Te.signal)):Ge.execute(je,Q.current.human)}if(!je.grant)throw new Error("No host-approved Send grant");let $e=structuredClone(je.peer);if($e.url!==sr())throw new Error("Return to the proposal\u2019s page before sending");let ce=$e.state;if(!ce||!ce.annotations.length&&!ce.styleModifications.length)throw new Error("There are no peer changes to send");await Ge.render($e,Q.current.human);let rt={...Ge.sources};if(!je.observedSources||Object.keys(rt).some(kt=>je.observedSources[kt]!==rt[kt]))throw new Error("Source changed since the last preview. Take another look, then send again.");let at=Ge.surface.frame.contentDocument;if(!at)throw new Error("Peer preview is unavailable");let[Be]=await Wi(at.body,null,[],{viewportOnly:!0});if(!Be)throw new Error("Could not capture the peer preview");if(await Ge.render($e,Q.current.human),!Wu(rt,Ge.sources))throw new Error("Source changed while preparing Send. Take another look, then send again.");await ve("source",{grant:je.grant,sources:rt});let Ie=pc(ce.annotations,ce.styleModifications,void 0,void 0,ce.textModifications),{provider:_e,model:_t,agentSettings:wt}=Q.current.settings,Pt=await bu(Be,JSON.stringify(Ie),t,$e.color,_e,_t,void 0,void 0,wt,void 0,void 0,void 0,je.grant);return $e.state={...structuredClone(pl),isAnnotating:!0,activeColor:$e.color},$e.revision++,$e.basis={},delete $e.pendingRevision,$e.lastJob={jobId:Pt.jobId,threadId:Pt.threadId},{peer:$e,evidence:{status:"submitted",...Pt}}}async function qe(){try{if(!L.current.token||Me!==sr()){let $e=await ve("host",{url:sr()});if(U)return;L.current.token=String($e.token),Me=sr()}let je=await ve("poll",{version:ge,presenceVersion:K});if(U)return;Oe(je),je.peers&&(a(je.peers),Ee=je.peers.length>0,ge=Number(je.version));for(let $e of je.requests){let ce=X.get($e.id);if(!ce){try{ce=await Fe($e)}catch(rt){ce={error:rt instanceof Error?rt.message:String(rt)}}X.set($e.id,ce),X.size>100&&X.delete(X.keys().next().value)}await ve("response",{id:$e.id,result:ce})}}catch(je){!U&&je instanceof Error&&je.message.includes("Host capability")&&(L.current.token=void 0,ge=-1,K=-1,U||s([]))}finally{U||(fe=setTimeout(()=>{qe()},document.hidden||!Ee?2e3:600))}}return qe(),()=>{U=!0,Te.abort(),clearTimeout(fe),Ge.dispose(),a([]),s([]),F.current=async()=>{throw new Error("Canvas is disconnected")}}},[e,t,n]),O(()=>{if(x(void 0),D([]),H.current=null,!R||!r.isAnnotating||!I.current){ie(null);return}let U=new Bu;I.current.append(U.container),ie(null),U.container.removeAttribute("aria-hidden"),U.container.style.cssText="position:absolute;inset:0;pointer-events:none;";let fe=!1;R.url&&R.url!==sr()&&x("This draft belongs to another page. Return to it to preview.");let ge=!1,K=!1,Te=()=>{if(!fe){if(ge){K=!0;return}ge=!0,U.render(R,Q.current.human).then(()=>{fe||(x(void 0),D(U.changed),H.current={id:R.identity.id,revision:R.revision,values:{...U.sources}},ie(U.surface.frame),w(R.identity.id,R.revision))}).catch(X=>{fe||(H.current=null,ie(null),x(X.message))}).finally(()=>{ge=!1,K&&(K=!1,Te())})}},Me=!R.url||R.url===sr();Me&&Te();let Ee=Me?by(ja(R.state),Te):()=>{},Ge=()=>U.surface.frame.contentWindow?.scrollTo(scrollX,scrollY);return window.addEventListener("scroll",Ge,{passive:!0}),()=>{fe=!0,Ee(),window.removeEventListener("scroll",Ge),U.dispose()}},[R,r.isAnnotating,w]);let A=async U=>{try{return await U(),m(void 0),!0}catch(fe){return m(fe instanceof Error?fe.message:String(fe)),!1}},ne=e&&i.length?{peers:[{identity:{id:"host",name:"You",kind:"human",relationship:"host"},permission:"direct",color:r.activeColor,stagedCount:Y},...i.map(U=>({...U,stagedCount:Z.get(U.identity.id)??0,unseenActivity:z(U.identity.id,U.revision)}))],viewedPeerId:p,selectedPeerId:c.selectedId,onPeek:c.peek,onPeekEnd:c.leave,onPreview:U=>{c.select(U),m(void 0)},onPermissionChange:(U,fe)=>A(()=>F.current("permission",{peerId:U,permission:fe}))}:null,re=R?.pendingRevision!==void 0?()=>A(()=>{let U=H.current;if(!U||U.id!==p||U.revision!==R.revision)throw new Error("Wait for this draft\u2019s preview before sending.");return F.current("approve",{peerId:p,revision:R.pendingRevision,sources:U.values})}):void 0,ee=!!(R&&r.isAnnotating),oe=e&&(h??(ee?g:void 0));return O(()=>{if(!ee)return;let U=fe=>{fe.composedPath().some(ge=>ge instanceof Element&&ge.hasAttribute("data-devtools"))||(fe.metaKey||fe.ctrlKey)&&fe.key==="Enter"||(fe.key.length===1||["Backspace","Delete","Enter"].includes(fe.key))&&(fe.preventDefault(),fe.stopPropagation())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[ee]),{toolbar:ne,selectedId:c.selectedId,threadAnnotationNumbers:P,activePreview:ee,isPeeking:u,viewed:R,approve:re,overlay:M(ct,{children:[ee&&f("div",{ref:I,"data-devtools":"peer-preview","data-peer-revision":R?.revision,"data-pending-revision":R?.pendingRevision,"data-popmelt-peer-surface":!0,style:{position:"fixed",inset:0,zIndex:1e4,background:"#111",pointerEvents:"auto"}}),d.map(({presence:U,engaged:fe})=>{if(u)return null;let ge=i.find(Te=>Te.identity.id===U.peerId);if(!ge||U.clientId!==L.current.clientId||U.url!==sr()||ee&&ge.identity.id!==p)return null;let K=null;try{K=ee?q?.contentDocument?.querySelector(U.selector)??null:kl(U.selector)}catch{}return f(Xc,{element:K,engaged:fe,label:`${ge.identity.name} is looking at this element`},`${ge.identity.id}:${U.operationId}`)}),!u&&ee&&R&&q?.contentDocument&&f($h,{peer:R,targetDocument:q.contentDocument,onApprove:re?()=>{re()}:void 0}),ee&&R&&p===c.selectedId&&f("div",{"data-devtools":"peer-plane-border","data-plane-owner":R.identity.id,"aria-hidden":"true",style:{position:"fixed",inset:0,border:`2px solid ${R.color}`,boxSizing:"border-box",pointerEvents:"none",zIndex:10002}}),ee&&R&&p===c.selectedId&&f(Dh,{name:R.identity.name,isOwnPlane:R.identity.id==="host",color:R.color,changed:S.length>0}),oe&&f("div",{"data-devtools":"peer-error",role:"status",style:{position:"fixed",bottom:100,right:24,maxWidth:360,padding:12,background:"#222",color:"#ddd",borderRadius:12,fontFamily:Fs,fontSize:12,lineHeight:1.4,zIndex:10002},children:oe})]})}}function wy(e,t,n,r,o,i,a){let[l,s]=j(),d=W({navigation:e,selectedId:t});O(()=>{if(!e||!n||l?.navigation===e)return;let c=e.read(),p=o.current,u=!1;if(!c.threadId||c.selectedId!==t){s({navigation:e});return}return i(c.threadId).then(h=>{if(!u){if(p===o.current&&e.read()===c)if(h>=200&&h<300)a(c.threadId);else if(h===403||h===404||h===410)e.rememberThread(t,null);else{s({navigation:e,unresolvedRevision:p});return}s({navigation:e})}}).catch(()=>{u||s({navigation:e,unresolvedRevision:p})}),()=>{u=!0}},[e,t,n,l,o,i,a]),O(()=>{let c=d.current.navigation!==e||d.current.selectedId!==t;d.current={navigation:e,selectedId:t},!(!e||l?.navigation!==e||c)&&(l.unresolvedRevision===o.current&&!r||e.rememberThread(t,r))},[e,t,r,l,o])}var Sy=hl(()=>import("./ParticipantRuntime-HU2P2PJ6.mjs")),Iy=hl(()=>import("./PreviewRuntime-YAUBP6HA.mjs"));function ky({children:e,projectId:t,adapters:n,multiplayer:r=!1}){let[o,i]=j(!1);if(O(()=>{i(!0)},[]),!o)return null;let a=window.__POPMELT_PARTICIPANTS__;if(!r)return xu()?null:a?f("p",{role:"status","data-devtools":"participant-disabled",children:"Multiplayer is disabled. Enable the multiplayer option in your Popmelt integration to use this participant page."}):e;if(a)try{xg(a,t)}catch(l){return f("p",{role:"alert","data-devtools":"participant-error",children:l.message})}return xu()?a?f(ml,{fallback:null,children:f(Iy,{config:a,adapters:n})}):null:a?f(ml,{fallback:null,children:f(Sy,{config:a,children:Pg(e,{bridgeUrl:a.url,projectId:a.projectId})},a.projectId)}):e}function Ty(e,t,n,r){let o=W(e);o.current=e;let[i,a]=j([]),l=W(null),[s,d]=j(null),[c,p]=j(null),u=i.filter(x=>x.scope===e),h=x=>a(S=>S.filter(D=>D.id!==x)),m=(x,S)=>{let D=Symbol(x);p(null);let H=t(x).then(()=>!0,()=>(o.current===e&&(S(),p({scope:e,message:"Could not dismiss thread. Please try again."})),h(D),!1));a(w=>[...w.filter(z=>z.scope===e),{id:D,threadId:x,rollback:S,saved:H,scope:e,undoHead:r}])},g=async()=>{let x=u.at(-1);if(!(!x||l.current===e)){l.current=e,d(e),p(null);try{if(!await x.saved||o.current!==e||(await n(x.threadId),o.current!==e))return;x.rollback(),h(x.id)}catch{o.current===e&&p({scope:e,message:"Could not restore thread. Try Undo again."})}finally{l.current===e&&(l.current=null,d(null))}}};return{dismiss:m,undo:g,tryUndo:()=>{let x=u.at(-1);return!x||x.undoHead!==r?!1:(g(),!0)},busy:s===e,count:u.length,error:c?.scope===e?c.message:null}}function Ey({enabled:e,active:t,configuration:n=!0,adapters:r}){let[o,i]=j(!1),[a,l]=j(null),s=Se(()=>wg(),[]),{recognition:d,selector:c,root:p,observe:u,store:h,imageHasher:m,onError:g}=typeof n=="object"?n:{},x=r.some(w=>w.surfaceKind==="image"||w.id==="see:image"),S=e&&n!==!1&&!x,D=t||o,H=D?d:void 0;return O(()=>{e?t&&i(!0):i(!1)},[e,t]),O(()=>{if(!S)return;let w=Sg({recognition:H?{cacheKey:H.cacheKey,configurationKey:H.configurationKey,detect:z=>H.detect(z),reconcile:(...z)=>H.reconcile(...z)}:void 0,hydrateOnly:!D,selector:c,root:p,observe:u,store:h??s,imageHasher:m,onError:g});return l(w),()=>{l(null),w.destroy()}},[S,H,D,c,p,u,h,s,m,g]),Se(()=>S&&a?[a,...r]:r,[S,a,r])}function Ay({enabled:e,configuration:t=!0,adapters:n}){let[r,o]=j(null),i=Se(()=>Ig(),[]),{segmentation:a,tracking:l,selector:s,root:d,observe:c,store:p,onError:u}=typeof t=="object"?t:{},h=n.some(g=>g.surfaceKind==="video"||g.id==="see:video"),m=e&&t!==!1&&!h;return O(()=>{if(!m)return;let g=kg({tracking:l,segmentation:a,selector:s,root:d,observe:c,store:p??i,onError:u});return o(g),()=>{o(null),g.destroy()}},[m,l,a,s,d,c,p,i,u]),Se(()=>m&&r?[r,...n]:n,[m,r,n])}function qu(e,t){return JSON.stringify([e,t.adapter,t.key])}async function Uu(e,t,n,r){for(let o of t){if(!o.target)continue;let i=qu(n,o.target);if(!r.has(i))try{r.set(i,await e.captureFeedback(o.target))}catch{r.set(i,null)}}}function Cy(e,t,n){let r=new Map;for(let o of e.annotations){let i=t.find(l=>l.id===o.id),a=(i?.groupId?t.filter(l=>l.groupId===i.groupId):t.filter(l=>l.id===o.id)).flatMap(l=>n.get(l.id)??[]);a.length&&r.set(o.id,a)}return r}function My(e,t,n,r){for(let o of e.annotations){if(!o.target)continue;let i=n.get(qu(o.pathname||r,o.target));if(!i){o.subjectFeedback={warning:"Live object unavailable; the following object context is the draft-time snapshot, not a refreshed detection. No object crop is attached."};continue}if(o.elements=[i.elementInfo],o.subjectFeedback=i.warning?{warning:i.warning}:void 0,i.crop){let a=t.get(o.id)??[];o.subjectFeedback={...o.subjectFeedback,cropImageIndex:a.length},t.set(o.id,[...a,i.crop])}}}function Ry(e){let t=e?.requestItems?.flatMap(r=>r.kind==="annotation"&&r.text.trim()?[r.text.trim()]:[]);if(t?.length)return t.join("; ");let n=e?.requestItems?.flatMap(r=>r.kind==="changes"?[`${r.elementLabel} [${r.changes.join(", ")}]`]:[]);return n?.length?n.join("; "):e?.requestText?.trim()||void 0}function Ly(e,t){if(!e?.frames?.length)return[];let n=new Map;for(let r of e.steps){let o=r.visuals?.afterFrameId;o&&!n.has(o)&&n.set(o,r.action?.label?`After ${r.action.label}`:"Resulting state")}return e.frames.flatMap((r,o)=>{let i=t[r.imageIndex];return i?[{id:r.id,imageIndex:r.imageIndex,label:o===0?"Initial state":n.get(r.id)??"State",url:i}]:[]})}function Yu(e){let t=e.instruction?.trim();return t?e.attachments?.some(n=>n.name?.trim()===t)?null:t:null}function Py(e,t){let n=e?.tagName?.toLowerCase(),r=e?.id?`#${e.id}`:"",o=e?.className?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=n?`${n}${r}${o}`:t;return e?.reactComponent?`<${e.reactComponent}> ${i}`:i}function jy(e){let t=e.elements?.[0]?.reactComponent||e.elements?.[0]?.tagName||e.linkedSelector,n=e.type&&e.type!=="annotation"?`${e.type} annotation`:"Annotation";return t?`${n} on ${t}`:n}function zy(e){let t=e.annotations.map(o=>{let i=o.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:o.id,pathname:o.pathname,text:Yu(o)??jy(o),...i>0?{interactionEpisodeStepCount:i}:{}}}),n=new Map,r=o=>{let i=`${o.pathname??""}:${o.durableSelector??o.selector}`,a=n.get(i);if(a){a.changes.push(o.text),o.annotationNumber!==void 0&&(a.annotationNumber===void 0||o.annotationNumber<a.annotationNumber)&&(a.annotationNumber=o.annotationNumber);return}let l={kind:"changes",elementKey:i,elementLabel:Py(o.element,o.selector),...o.annotationNumber!==void 0?{annotationNumber:o.annotationNumber}:{},pathname:o.pathname,changes:[o.text]};n.set(i,l),t.push(l)};for(let o of e.styleModifications??[])for(let i of o.changes)r({...o,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let o of e.textModifications??[])r({...o,text:`Text: ${o.original||"empty"} \u2192 ${o.modified||"empty"}`});for(let o of e.domModifications??[])r({...o,text:o.operation==="copy"?"Copied element":"Moved element"});return e.spacingTokenChanges?.length&&t.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:e.spacingTokenChanges.map(o=>`${o.tokenName}: ${o.originalPx}px \u2192 ${o.newPx}px`)}),t}function $y(e){let t=e.annotations.flatMap(r=>{let o=Yu(r);return o?[{instruction:o,pathname:r.pathname}]:[]});if(t.length===0)return;if(new Set(t.map(r=>r.pathname).filter(Boolean)).size<=1)return t.map(r=>r.instruction).join(`
|
|
4
|
+
`}catch{d.add("An inaccessible stylesheet was omitted")}return d.add("Static snapshot: no scripts, external assets, event handlers or application runtime"),{revision:n,html:e.tagName==="BODY"?a.innerHTML:a.outerHTML,...e.tagName==="BODY"?{bodyAttributes:Object.fromEntries([...a.attributes].map(u=>[u.name,u.value]))}:{},css:p,width:r,height:o,warnings:[...d]}}function Ou(e,t){let n=[...e.querySelectorAll(`[${Sl}]`)].filter(r=>r.getAttribute(Sl)===t);return n.length===1?n[0]:null}var ay=class{constructor(e){this.generation=0,this.cancelPending=null,this.current=null,this.disposed=!1,this.frame=e.ownerDocument.createElement("iframe"),this.frame.setAttribute("sandbox","allow-same-origin"),this.frame.title="Peer plane preview",this.frame.style.cssText="border:0;display:block;pointer-events:none;",this.frame.tabIndex=-1,e.append(this.frame)}async render(e,t,n){if(this.disposed)throw new Error("Preview surface was disposed");this.cancelPending?.();let r=++this.generation;this.current=null,this.frame.width=String(e.width),this.frame.height=String(e.height);let o=this.frame.ownerDocument.implementation.createHTMLDocument("Peer preview"),i=o.createElement("meta");i.httpEquiv="Content-Security-Policy",i.content="default-src 'none'; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'; script-src 'none'",o.head.prepend(i);let a=o.createElement("style");a.textContent=e.css.replace(/<\/style/gi,"<\\/style"),o.head.append(a),o.body.innerHTML=e.html;for(let[s,d]of Object.entries(e.bodyAttributes??{}))o.body.setAttribute(s,d);let l=o.createElement("style");return l.textContent="*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}",o.head.append(l),o.documentElement.dataset.previewGeneration=String(r),new Promise(s=>{let d=h=>{clearTimeout(u),this.frame.removeEventListener("load",p),this.cancelPending===c&&(this.cancelPending=null),s(h)},c=()=>d(!1),p=()=>{if(r!==this.generation||this.frame.contentDocument?.documentElement.dataset.previewGeneration!==String(r))return;let h=this.frame.contentDocument;n?.(h);for(let m of t.artifacts)m.kind==="style"&&Ou(h,m.targetKey)?.style.setProperty(m.property,m.value,"important");this.current={baseline:e,plane:{...t}},d(!0)},u=setTimeout(c,5e3);this.cancelPending=c,this.frame.addEventListener("load",p),queueMicrotask(()=>{!this.disposed&&r===this.generation&&(this.frame.srcdoc="<!doctype html>"+o.documentElement.outerHTML)})})}inspect(e,t){let n=this.current,r=this.frame.contentDocument;if(!n||!r)return null;let o=Ou(r,e);if(!o)return null;let i=this.frame.contentWindow.getComputedStyle(o),a=o.getBoundingClientRect();return{planeId:n.plane.id,planeRevision:n.plane.revision,sourceRevision:n.baseline.revision,targetKey:e,styles:Object.fromEntries(t.map(l=>[l,i.getPropertyValue(l)])),rect:{x:a.x,y:a.y,width:a.width,height:a.height}}}dispose(){this.disposed=!0,++this.generation,this.cancelPending?.(),this.current=null,this.frame.remove()}};function ly(e,t){return{id:e,ownerId:t,revision:0,artifacts:[],undo:[],redo:[],attention:null}}function Qs(e){return ll(e).flatMap(t=>t==="color"?[...Jc]:[t])}function sy(e,t){if(e===void 0)return{families:Ui.map(n=>({family:n,label:Ms(n)}))};if(!Ui.includes(e))throw new Error("Unknown omnidial family");if(!t)return{family:e,subproperties:Qs(e)};if(!Qs(e).includes(t))throw new Error("Unknown omnidial subproperty");return{family:e,subproperty:t,...e==="transform"&&t==="translate"?{composedToken:"translate-x-<xStep>-y-<yStep>",axisSteps:vi(e,t)}:{},tokens:vi(e,t).map(n=>({token:al(e,n,t),value:qi(e,n,t)}))}}function dy(e,t){if(t!==void 0&&!Ui.includes(t))throw new Error("Unknown omnidial family");let n=/^translate-x-(-?\d+)-y-(-?\d+)$/.exec(e);if(n&&(!t||t==="transform")){let o=vi("transform","translate"),i=o.find(l=>String(l)===n[1]),a=o.find(l=>String(l)===n[2]);if(i!==void 0&&a!==void 0)return{family:"transform",subproperty:"translate",step:i,axisSteps:{x:i,y:a}}}let r=[];for(let o of t?[t]:Ui)for(let i of Qs(o))for(let a of vi(o,i))al(o,a,i)===e&&r.push({family:o,subproperty:i,step:a});if(r.length>1)throw new Error("Ambiguous omnidial token; include its family (for example stack or grid)");if(!r.length)throw new Error("Unknown omnidial token; discover available tokens or use an explicit custom property/value");return r[0]}function Fu(e,t,n,r){let o=e.ownerDocument.defaultView.getComputedStyle(e),i=Rc(t,r),a=qi(t,n,r),l=Pc(t),s=jc(t,r,n),d=t==="border"&&!yi(t,r)&&typeof n=="number"&&n>0?zc(r):null,c={family:t,subproperty:Bc(t,r),step:n},p=[{property:i,original:o.getPropertyValue(i).trim()||"0px",modified:a,token:al(t,n,r),sticker:c}];l&&p.unshift({property:"display",original:o.getPropertyValue("display").trim()||"block",modified:l,token:l,sticker:c});for(let u of s)p.push({property:u.property,original:o.getPropertyValue(u.property).trim(),modified:u.value,token:u.token,sticker:c});if(d){let u=o.getPropertyValue(d).trim();(!u||u==="none")&&p.push({property:d,original:u||"none",modified:"solid",token:al(t,n,r),sticker:c})}return{alreadyApplied:Lc(t,n,r,u=>o.getPropertyValue(u)),changes:p}}function _u(e,t,n){let r=e.ownerDocument.defaultView.getComputedStyle(e),o="translate",i=`${Number(t)*4}px ${Number(n)*4}px`,a={family:"transform",subproperty:"translate",step:t,axisSteps:{x:t,y:n}};return{alreadyApplied:r.getPropertyValue(o).trim()===i,changes:[{property:o,original:r.getPropertyValue(o).trim()||"none",modified:i,token:`translate-x-${t}-y-${n}`,sticker:a}]}}function cy(e,t){for(let n of t.changes)it(e,n.property,n.modified)}var uy=new Set(["text","transform","opacity"]),py=new Set(["padding","margin","border","radius","color"]);function fy(e){return e instanceof SVGSVGElement&&!(e.parentElement instanceof SVGElement)}function hy(e){return e!=="text-align"}function Il(e,t,n){return Dr(e)?e instanceof HTMLElement?!0:t==="text"&&!hy(n)?!1:uy.has(t)||fy(e)&&py.has(t):!1}function ja(e){return[...new Set([...e?.annotations.flatMap(t=>t.linkedSelector?[t.linkedSelector]:[])??[],...e?.styleModifications.map(t=>t.selector)??[],...e?.textModifications.map(t=>t.selector)??[]])]}function my(e,t){return Object.keys(t).filter(n=>e[n]!==void 0&&e[n]!==t[n])}function Wu(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(t).every(n=>e[n]===t[n])}function Zs(e,t,n,r){let o={...e};for(let i of r){if(n[i]===void 0){delete o[i];continue}o[i]=t[i]??e[i]??n[i]}return o}function gy(e){let t=e.ownerDocument.defaultView.getComputedStyle(e),n=Array.from(t).filter(i=>!i.startsWith("--")).map(i=>`${i}:${t.getPropertyValue(i)}`).join(";"),r=e.outerHTML+n,o=2166136261;for(let i=0;i<r.length;i++)o=Math.imul(o^r.charCodeAt(i),16777619);return`target-v2:${(o>>>0).toString(16)}`}var sr=()=>location.origin+location.pathname;function kl(e){let t=document.querySelectorAll(e),n=t[0];if(t.length!==1||!(n instanceof HTMLElement||n instanceof SVGElement)||n.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-canvas-block]"))throw new Error("Target must resolve to exactly one app element");if(n.matches("input,textarea,select,[contenteditable],script,style")||n.closest("[data-private], [data-sensitive]"))throw new Error("Private/editable controls are outside the peer preview");return n}var Bu=class{constructor(){this.sources={},this.changed=[],this.container=document.createElement("div"),this.container.dataset.popmeltPeerSurface="",this.container.setAttribute("aria-hidden","true"),this.container.style.cssText="position:fixed;left:-100000px;top:0;pointer-events:none;",document.body.append(this.container),this.surface=new ay(this.container)}async render(e,t,n,r=!1){if(t.domModifications.length||t.spacingTokenChanges.length)throw new Error("Independent previews do not yet support staged structure or spacing-token edits; your draft is preserved");let o=e.state??pl,i=new Set([...n?[n]:[],...ja(o)]),a=new Map;for(let c of i)a.set(c,kl(c));let l=new Map;for(let c of t.textModifications){let p=document.querySelector(c.selector);p&&l.set(p,[...l.get(p)??[],c])}let s=iy({root:document.body,targets:a,revision:sr(),width:innerWidth,height:innerHeight,cleanClone:(c,p)=>{if(!r){eg(c,p);for(let u of l.get(c)??[]){let h=p;for(let m of u.textNodePath)h=h?.childNodes[m];h?.nodeType===Node.TEXT_NODE&&(h.nodeValue=u.original)}}}}),d=ly(e.identity.id,e.identity.id);if(d.revision=e.revision,r||(d.artifacts=o.styleModifications.flatMap(c=>c.changes.map(p=>({kind:"style",id:c.selector+p.property,targetKey:c.selector,property:p.property,value:p.modified})))),!await this.surface.render(s,d,c=>{this.sources=Object.fromEntries([...i].map(p=>[p,gy(c.querySelector(`[data-popmelt-preview-target="${CSS.escape(p)}"]`))])),this.changed=my(e.basis??{},this.sources)}))throw new Error("Preview superseded or unavailable");return this.surface.frame.contentWindow?.scrollTo(scrollX,scrollY),s.warnings}async execute(e,t){let{action:n}=e,r=structuredClone(e.peer);if(n.type==="prepare-send"){if(!ja(r.state).length)throw new Error("There are no peer changes to send");if(await this.render(r,t),!e.observedSources||Object.keys(this.sources).some(s=>e.observedSources[s]!==this.sources[s]))throw new Error("Source changed since the last preview. Take another look, then send again.");return this.changed.length&&r.revision++,r.basis={...this.sources},delete r.pendingRevision,{peer:r,sources:this.sources}}if(n.type==="check-source"){let s={...r,state:{...structuredClone(pl),annotations:Object.keys(n.sources).map((d,c)=>({id:`source-${c}`,type:"text",text:"",points:[],strokeWidth:1,color:r.color,timestamp:0,linkedSelector:d}))}};if(await this.render(s,t),!Wu(n.sources,this.sources))throw new Error("Source changed since Send. Preview the current source and send again.");return{peer:r,evidence:{status:"source-current"}}}if(n.type==="tokens")return{peer:r,evidence:sy(n.family,n.subproperty)};let o=r.state??{...structuredClone(pl),isAnnotating:!0,activeColor:r.color},i=o,a,l=s=>{i=_m(i,s)};if(n.type==="send")throw new Error("Send requires the implementation bridge");if(n.type==="rebase")await this.render(r,t),r.basis={...this.sources},r.revision++,delete r.pendingRevision,a={status:"rebased",note:"Draft preserved against current source; Send requires a new approval if in Suggest."};else if(n.type==="undo"||n.type==="redo"){l({type:n.type==="undo"?"UNDO":"REDO"}),await this.render({...r,state:i},t);let s=[...new Set([...ja(o),...ja(i)])].filter(d=>{let c=p=>JSON.stringify([p.annotations.filter(u=>u.linkedSelector===d),p.styleModifications.filter(u=>u.selector===d)]);return c(o)!==c(i)});r.basis=Zs(r.basis??{},e.observedSources??{},this.sources,s)}else if(n.type==="attention"&&!n.selector)r.attention=null;else if(n.type==="clear"){let s=n.kind!=="style"&&o.annotations.some(c=>c.linkedSelector===n.selector),d=n.kind!=="comment"&&o.styleModifications.some(c=>c.selector===n.selector);if(!s&&!d)return{peer:r,evidence:{status:"nothing-to-clear"}};i={...o,annotations:n.kind==="style"?o.annotations:o.annotations.filter(c=>c.linkedSelector!==n.selector),styleModifications:n.kind==="comment"?o.styleModifications:o.styleModifications.filter(c=>c.selector!==n.selector),undoStack:[...o.undoStack,{annotations:o.annotations,styleModifications:o.styleModifications,textModifications:o.textModifications,domModifications:o.domModifications,spacingTokenChanges:o.spacingTokenChanges,spacingTokenMods:o.spacingTokenMods}],redoStack:[]},await this.render({...r,state:i},t),r.basis=Zs(r.basis??{},e.observedSources??{},this.sources,[n.selector])}else if("selector"in n&&n.selector){let s=kl(n.selector),d=mn(s),c=n.selector;if(n.type==="inspect"){let p=await this.render(r,t,c,n.plane==="host");a={...this.surface.inspect(c,n.properties??[]),element:d,warnings:p,view:n.plane??"own",url:sr(),changedSourceTargets:n.plane==="host"?void 0:this.changed}}else if(n.type==="style")if("token"in n){let p=dy(n.token,n.family);if(!Il(s,p.family,p.subproperty))throw new Error("This omnidial token does not support the target");await this.render(r,t,c);let u=this.surface.frame.contentDocument?.querySelector(c);if(!u)throw new Error("Could not inspect original style");let h=p.axisSteps?_u(u,p.axisSteps.x,p.axisSteps.y):Fu(u,p.family,p.step,p.subproperty);h.alreadyApplied||l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:h.changes}}),a={token:n.token,selection:p,alreadyApplied:h.alreadyApplied}}else{if(!CSS.supports(n.property,n.value))throw new Error("Unsupported CSS property/value");await this.render(r,t,c);let p=this.surface.inspect(c,[n.property])?.styles[n.property];if(p===void 0)throw new Error("Could not inspect original style");l({type:"MODIFY_STYLES_BATCH",payload:{selector:c,element:{...d,selector:c},changes:[{property:n.property,original:p,modified:n.value}]}})}else if(n.type==="comment"){await this.render(r,t,c);let p=s.getBoundingClientRect();l({type:"ADD_TEXT",payload:{id:`peer-note-${e.id}`,point:{x:p.x+scrollX,y:p.y+scrollY-26},text:n.text,linkedSelector:c,elements:[{...d,selector:c}]}})}r.attention=null,(n.type==="comment"||n.type==="style")&&(r.basis=Zs(r.basis??{},e.observedSources??{},this.sources,[c]))}if(i!==o){if(i.annotations.length+i.styleModifications.length>100)throw new Error("Peer draft is full; submit or undo before adding more");i={...i,undoStack:i.undoStack.slice(-50),redoStack:i.redoStack.slice(-50)},r.state=i,r.revision++,r.url=sr(),delete r.pendingRevision}return{peer:r,evidence:a,...["inspect","style","comment","clear","undo","redo","rebase"].includes(n.type)&&!(n.type==="inspect"&&n.plane==="host")?{sources:this.sources}:{}}}dispose(){this.surface.dispose(),this.container.remove()}};async function yy(e,t,n){let r=!0,o,i=new Set,a=async c=>{let p=new AbortController;i.add(p);let u=setTimeout(()=>p.abort(),1500);try{return await e(c,p.signal)}catch{return!1}finally{clearTimeout(u),i.delete(p)}},l=()=>{r=!1,clearTimeout(o);for(let c of i)c.abort()},s=()=>{l(),a("finish")},d=async()=>{if(!r)return;let c=await a("renew");r&&c&&(o=setTimeout(()=>{d()},1e3))};n.addEventListener("abort",s,{once:!0});try{if(n.aborted)throw new Error("Canvas disconnected before action");let c=await a("start");if(n.aborted)throw new Error("Canvas disconnected before action");return r&&c&&(o=setTimeout(()=>{d()},1e3)),await t()}finally{l(),n.removeEventListener("abort",s),await a("finish")}}function vy(e){let t=`popmelt-peer-seen:${e}`,[n,r]=j({key:"",revisions:{}});return O(()=>{let o={};try{let i=JSON.parse(localStorage.getItem(t)??"{}");i&&typeof i=="object"&&!Array.isArray(i)&&(o=Object.fromEntries(Object.entries(i).filter(([,a])=>Number.isSafeInteger(a)&&a>=0)))}catch{}r({key:t,revisions:o})},[t]),{markSeen:J((o,i)=>{r(a=>{if(a.key!==t||(a.revisions[o]??0)>=i)return a;let l={key:t,revisions:{...a.revisions,[o]:i}};try{localStorage.setItem(t,JSON.stringify(l.revisions))}catch{}return l})},[t]),isUnseen:(o,i)=>n.key===t&&i>(n.revisions[o]??0)}}function by(e,t){let n,r=l=>(l instanceof Element?l:l.parentElement)?.closest("[data-devtools], [data-popmelt-peer-surface], [data-popmelt-root], popmelt-root"),o=()=>{n===void 0&&(n=setTimeout(()=>{n=void 0,t()},400))},i=new MutationObserver(l=>{document.hidden||!e.length||l.some(s=>{if(r(s.target)||s.type==="childList"&&[...s.addedNodes,...s.removedNodes].every(c=>r(c)))return!1;let d=s.target instanceof Element?s.target:s.target.parentElement;return d?.closest("style,head")?!0:e.some(c=>{let p=document.querySelector(c);return!p||p.contains(s.target)||d?.contains(p)})})&&o()});i.observe(document.documentElement,{subtree:!0,attributes:!0,childList:!0,characterData:!0}),window.addEventListener("resize",o);let a=()=>{document.hidden||o()};return document.addEventListener("visibilitychange",a),()=>{i.disconnect(),clearTimeout(n),window.removeEventListener("resize",o),document.removeEventListener("visibilitychange",a)}}function Ju(e){if(!e)return 0;let t=em(e.annotations);return bc({annotations:e.annotations.filter(n=>!n.captured&&!t.has(n)),styleModifications:e.styleModifications.filter(n=>!n.captured),textModifications:e.textModifications.filter(n=>!n.captured)}).count}function xy(e,t,n,r,o){let[i,a]=j([]),[l,s]=j([]),d=Ph(l,e&&r.isAnnotating),c=jh(e&&r.isAnnotating),{viewedId:p,isPeeking:u}=c,[h,m]=j(),[g,x]=j(),[S,D]=j([]),H=W(null),{markSeen:w,isUnseen:z}=vy(n),Z=Se(()=>new Map(i.map(U=>[U.identity.id,Ju(U.state)])),[i]),{annotations:k,styleModifications:G,textModifications:N}=r,Y=Se(()=>Ju({annotations:k,styleModifications:G,textModifications:N}),[k,G,N]),[q,ie]=j(null),I=W(null),Q=W({human:r,settings:o});Q.current={human:r,settings:o};let L=W({clientId:crypto.randomUUID()}),F=W(async()=>{throw new Error("Canvas is disconnected")}),R=e?i.find(U=>U.identity.id===p):void 0,$=i.find(U=>U.identity.id===c.selectedId)?.state,P=Se(()=>zh($),[$]);O(()=>{if(!e||!n)return;L.current.token||(L.current={clientId:crypto.randomUUID()});let U=!1,fe,ge=-1,K=-1,Te=new AbortController,Me="",Ee=!1,Ge=new Bu,X=new Map,Oe=je=>{U||typeof je.presenceVersion!="number"||je.presenceVersion<=K||!Array.isArray(je.presence)||(K=je.presenceVersion,s(je.presence))},ve=async(je,$e={},ce=AbortSignal.any([Te.signal,AbortSignal.timeout(5e4)]))=>{let rt=L.current.token,at=await Yt(`${t}/peers/${je}`,{method:"POST",headers:{"Content-Type":"application/json","X-Popmelt-Project-Id":n},body:JSON.stringify({...L.current,...$e}),signal:ce}),Be=await at.json();if(je!=="host"&&rt!==L.current.token)throw new Error("Canvas session changed during request");if(!at.ok||Be.error)throw new Error(Be.error??`Peer request failed (${at.status})`);return Be};F.current=ve;async function Fe(je){if(je.url&&je.url!==sr())throw new Error("Canvas navigated before the operation could run");if(je.action.type!=="send"){let kt=pm(je.action);return kt?(kl(kt.selector),yy(async(lt,Ke)=>{let jt=await ve("activity",{id:je.id,phase:lt},Ke);return Oe(jt),jt.accepted===!0},()=>Ge.execute(je,Q.current.human),Te.signal)):Ge.execute(je,Q.current.human)}if(!je.grant)throw new Error("No host-approved Send grant");let $e=structuredClone(je.peer);if($e.url!==sr())throw new Error("Return to the proposal\u2019s page before sending");let ce=$e.state;if(!ce||!ce.annotations.length&&!ce.styleModifications.length)throw new Error("There are no peer changes to send");await Ge.render($e,Q.current.human);let rt={...Ge.sources};if(!je.observedSources||Object.keys(rt).some(kt=>je.observedSources[kt]!==rt[kt]))throw new Error("Source changed since the last preview. Take another look, then send again.");let at=Ge.surface.frame.contentDocument;if(!at)throw new Error("Peer preview is unavailable");let[Be]=await Wi(at.body,null,[],{viewportOnly:!0});if(!Be)throw new Error("Could not capture the peer preview");if(await Ge.render($e,Q.current.human),!Wu(rt,Ge.sources))throw new Error("Source changed while preparing Send. Take another look, then send again.");await ve("source",{grant:je.grant,sources:rt});let Ie=pc(ce.annotations,ce.styleModifications,void 0,void 0,ce.textModifications),{provider:_e,model:_t,agentSettings:wt}=Q.current.settings,Pt=await bu(Be,JSON.stringify(Ie),t,$e.color,_e,_t,void 0,void 0,wt,void 0,void 0,void 0,je.grant);return $e.state={...structuredClone(pl),isAnnotating:!0,activeColor:$e.color},$e.revision++,$e.basis={},delete $e.pendingRevision,$e.lastJob={jobId:Pt.jobId,threadId:Pt.threadId},{peer:$e,evidence:{status:"submitted",...Pt}}}async function qe(){try{if(!L.current.token||Me!==sr()){let $e=await ve("host",{url:sr()});if(U)return;L.current.token=String($e.token),Me=sr()}let je=await ve("poll",{version:ge,presenceVersion:K});if(U)return;Oe(je),je.peers&&(a(je.peers),Ee=je.peers.length>0,ge=Number(je.version));for(let $e of je.requests){let ce=X.get($e.id);if(!ce){try{ce=await Fe($e)}catch(rt){ce={error:rt instanceof Error?rt.message:String(rt)}}X.set($e.id,ce),X.size>100&&X.delete(X.keys().next().value)}await ve("response",{id:$e.id,result:ce})}}catch(je){!U&&je instanceof Error&&je.message.includes("Host capability")&&(L.current.token=void 0,ge=-1,K=-1,U||s([]))}finally{U||(fe=setTimeout(()=>{qe()},document.hidden||!Ee?2e3:600))}}return qe(),()=>{U=!0,Te.abort(),clearTimeout(fe),Ge.dispose(),a([]),s([]),F.current=async()=>{throw new Error("Canvas is disconnected")}}},[e,t,n]),O(()=>{if(x(void 0),D([]),H.current=null,!R||!r.isAnnotating||!I.current){ie(null);return}let U=new Bu;I.current.append(U.container),ie(null),U.container.removeAttribute("aria-hidden"),U.container.style.cssText="position:absolute;inset:0;pointer-events:none;";let fe=!1;R.url&&R.url!==sr()&&x("This draft belongs to another page. Return to it to preview.");let ge=!1,K=!1,Te=()=>{if(!fe){if(ge){K=!0;return}ge=!0,U.render(R,Q.current.human).then(()=>{fe||(x(void 0),D(U.changed),H.current={id:R.identity.id,revision:R.revision,values:{...U.sources}},ie(U.surface.frame),w(R.identity.id,R.revision))}).catch(X=>{fe||(H.current=null,ie(null),x(X.message))}).finally(()=>{ge=!1,K&&(K=!1,Te())})}},Me=!R.url||R.url===sr();Me&&Te();let Ee=Me?by(ja(R.state),Te):()=>{},Ge=()=>U.surface.frame.contentWindow?.scrollTo(scrollX,scrollY);return window.addEventListener("scroll",Ge,{passive:!0}),()=>{fe=!0,Ee(),window.removeEventListener("scroll",Ge),U.dispose()}},[R,r.isAnnotating,w]);let A=async U=>{try{return await U(),m(void 0),!0}catch(fe){return m(fe instanceof Error?fe.message:String(fe)),!1}},ne=e&&i.length?{peers:[{identity:{id:"host",name:"You",kind:"human",relationship:"host"},permission:"direct",color:r.activeColor,stagedCount:Y},...i.map(U=>({...U,stagedCount:Z.get(U.identity.id)??0,unseenActivity:z(U.identity.id,U.revision)}))],viewedPeerId:p,selectedPeerId:c.selectedId,onPeek:c.peek,onPeekEnd:c.leave,onPreview:U=>{c.select(U),m(void 0)},onPermissionChange:(U,fe)=>A(()=>F.current("permission",{peerId:U,permission:fe}))}:null,re=R?.pendingRevision!==void 0?()=>A(()=>{let U=H.current;if(!U||U.id!==p||U.revision!==R.revision)throw new Error("Wait for this draft\u2019s preview before sending.");return F.current("approve",{peerId:p,revision:R.pendingRevision,sources:U.values})}):void 0,ee=!!(R&&r.isAnnotating),oe=e&&(h??(ee?g:void 0));return O(()=>{if(!ee)return;let U=fe=>{fe.composedPath().some(ge=>ge instanceof Element&&ge.hasAttribute("data-devtools"))||(fe.metaKey||fe.ctrlKey)&&fe.key==="Enter"||(fe.key.length===1||["Backspace","Delete","Enter"].includes(fe.key))&&(fe.preventDefault(),fe.stopPropagation())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[ee]),{toolbar:ne,selectedId:c.selectedId,threadAnnotationNumbers:P,activePreview:ee,isPeeking:u,viewed:R,approve:re,overlay:M(ct,{children:[ee&&f("div",{ref:I,"data-devtools":"peer-preview","data-peer-revision":R?.revision,"data-pending-revision":R?.pendingRevision,"data-popmelt-peer-surface":!0,style:{position:"fixed",inset:0,zIndex:1e4,background:"#111",pointerEvents:"auto"}}),d.map(({presence:U,engaged:fe})=>{if(u)return null;let ge=i.find(Te=>Te.identity.id===U.peerId);if(!ge||U.clientId!==L.current.clientId||U.url!==sr()||ee&&ge.identity.id!==p)return null;let K=null;try{K=ee?q?.contentDocument?.querySelector(U.selector)??null:kl(U.selector)}catch{}return f(Xc,{element:K,engaged:fe,label:`${ge.identity.name} is looking at this element`},`${ge.identity.id}:${U.operationId}`)}),!u&&ee&&R&&q?.contentDocument&&f($h,{peer:R,targetDocument:q.contentDocument,onApprove:re?()=>{re()}:void 0}),ee&&R&&p===c.selectedId&&f("div",{"data-devtools":"peer-plane-border","data-plane-owner":R.identity.id,"aria-hidden":"true",style:{position:"fixed",inset:0,border:`2px solid ${R.color}`,boxSizing:"border-box",pointerEvents:"none",zIndex:10002}}),ee&&R&&p===c.selectedId&&f(Dh,{name:R.identity.name,isOwnPlane:R.identity.id==="host",color:R.color,changed:S.length>0}),oe&&f("div",{"data-devtools":"peer-error",role:"status",style:{position:"fixed",bottom:100,right:24,maxWidth:360,padding:12,background:"#222",color:"#ddd",borderRadius:12,fontFamily:Fs,fontSize:12,lineHeight:1.4,zIndex:10002},children:oe})]})}}function wy(e,t,n,r,o,i,a){let[l,s]=j(),d=W({navigation:e,selectedId:t});O(()=>{if(!e||!n||l?.navigation===e)return;let c=e.read(),p=o.current,u=!1;if(!c.threadId||c.selectedId!==t){s({navigation:e});return}return i(c.threadId).then(h=>{if(!u){if(p===o.current&&e.read()===c)if(h>=200&&h<300)a(c.threadId);else if(h===403||h===404||h===410)e.rememberThread(t,null);else{s({navigation:e,unresolvedRevision:p});return}s({navigation:e})}}).catch(()=>{u||s({navigation:e,unresolvedRevision:p})}),()=>{u=!0}},[e,t,n,l,o,i,a]),O(()=>{let c=d.current.navigation!==e||d.current.selectedId!==t;d.current={navigation:e,selectedId:t},!(!e||l?.navigation!==e||c)&&(l.unresolvedRevision===o.current&&!r||e.rememberThread(t,r))},[e,t,r,l,o])}var Sy=hl(()=>import("./ParticipantRuntime-BGVZAWZH.mjs")),Iy=hl(()=>import("./PreviewRuntime-QDA4OF67.mjs"));function ky({children:e,projectId:t,adapters:n,multiplayer:r=!1}){let[o,i]=j(!1);if(O(()=>{i(!0)},[]),!o)return null;let a=window.__POPMELT_PARTICIPANTS__;if(!r)return xu()?null:a?f("p",{role:"status","data-devtools":"participant-disabled",children:"Multiplayer is disabled. Enable the multiplayer option in your Popmelt integration to use this participant page."}):e;if(a)try{xg(a,t)}catch(l){return f("p",{role:"alert","data-devtools":"participant-error",children:l.message})}return xu()?a?f(ml,{fallback:null,children:f(Iy,{config:a,adapters:n})}):null:a?f(ml,{fallback:null,children:f(Sy,{config:a,children:Pg(e,{bridgeUrl:a.url,projectId:a.projectId})},a.projectId)}):e}function Ty(e,t,n,r){let o=W(e);o.current=e;let[i,a]=j([]),l=W(null),[s,d]=j(null),[c,p]=j(null),u=i.filter(x=>x.scope===e),h=x=>a(S=>S.filter(D=>D.id!==x)),m=(x,S)=>{let D=Symbol(x);p(null);let H=t(x).then(()=>!0,()=>(o.current===e&&(S(),p({scope:e,message:"Could not dismiss thread. Please try again."})),h(D),!1));a(w=>[...w.filter(z=>z.scope===e),{id:D,threadId:x,rollback:S,saved:H,scope:e,undoHead:r}])},g=async()=>{let x=u.at(-1);if(!(!x||l.current===e)){l.current=e,d(e),p(null);try{if(!await x.saved||o.current!==e||(await n(x.threadId),o.current!==e))return;x.rollback(),h(x.id)}catch{o.current===e&&p({scope:e,message:"Could not restore thread. Try Undo again."})}finally{l.current===e&&(l.current=null,d(null))}}};return{dismiss:m,undo:g,tryUndo:()=>{let x=u.at(-1);return!x||x.undoHead!==r?!1:(g(),!0)},busy:s===e,count:u.length,error:c?.scope===e?c.message:null}}function Ey({enabled:e,active:t,configuration:n=!0,adapters:r}){let[o,i]=j(!1),[a,l]=j(null),s=Se(()=>wg(),[]),{recognition:d,selector:c,root:p,observe:u,store:h,imageHasher:m,onError:g}=typeof n=="object"?n:{},x=r.some(w=>w.surfaceKind==="image"||w.id==="see:image"),S=e&&n!==!1&&!x,D=t||o,H=D?d:void 0;return O(()=>{e?t&&i(!0):i(!1)},[e,t]),O(()=>{if(!S)return;let w=Sg({recognition:H?{cacheKey:H.cacheKey,configurationKey:H.configurationKey,detect:z=>H.detect(z),reconcile:(...z)=>H.reconcile(...z)}:void 0,hydrateOnly:!D,selector:c,root:p,observe:u,store:h??s,imageHasher:m,onError:g});return l(w),()=>{l(null),w.destroy()}},[S,H,D,c,p,u,h,s,m,g]),Se(()=>S&&a?[a,...r]:r,[S,a,r])}function Ay({enabled:e,configuration:t=!0,adapters:n}){let[r,o]=j(null),i=Se(()=>Ig(),[]),{segmentation:a,tracking:l,selector:s,root:d,observe:c,store:p,onError:u}=typeof t=="object"?t:{},h=n.some(g=>g.surfaceKind==="video"||g.id==="see:video"),m=e&&t!==!1&&!h;return O(()=>{if(!m)return;let g=kg({tracking:l,segmentation:a,selector:s,root:d,observe:c,store:p??i,onError:u});return o(g),()=>{o(null),g.destroy()}},[m,l,a,s,d,c,p,i,u]),Se(()=>m&&r?[r,...n]:n,[m,r,n])}function qu(e,t){return JSON.stringify([e,t.adapter,t.key])}async function Uu(e,t,n,r){for(let o of t){if(!o.target)continue;let i=qu(n,o.target);if(!r.has(i))try{r.set(i,await e.captureFeedback(o.target))}catch{r.set(i,null)}}}function Cy(e,t,n){let r=new Map;for(let o of e.annotations){let i=t.find(l=>l.id===o.id),a=(i?.groupId?t.filter(l=>l.groupId===i.groupId):t.filter(l=>l.id===o.id)).flatMap(l=>n.get(l.id)??[]);a.length&&r.set(o.id,a)}return r}function My(e,t,n,r){for(let o of e.annotations){if(!o.target)continue;let i=n.get(qu(o.pathname||r,o.target));if(!i){o.subjectFeedback={warning:"Live object unavailable; the following object context is the draft-time snapshot, not a refreshed detection. No object crop is attached."};continue}if(o.elements=[i.elementInfo],o.subjectFeedback=i.warning?{warning:i.warning}:void 0,i.crop){let a=t.get(o.id)??[];o.subjectFeedback={...o.subjectFeedback,cropImageIndex:a.length},t.set(o.id,[...a,i.crop])}}}function Ry(e){let t=e?.requestItems?.flatMap(r=>r.kind==="annotation"&&r.text.trim()?[r.text.trim()]:[]);if(t?.length)return t.join("; ");let n=e?.requestItems?.flatMap(r=>r.kind==="changes"?[`${r.elementLabel} [${r.changes.join(", ")}]`]:[]);return n?.length?n.join("; "):e?.requestText?.trim()||void 0}function Ly(e,t){if(!e?.frames?.length)return[];let n=new Map;for(let r of e.steps){let o=r.visuals?.afterFrameId;o&&!n.has(o)&&n.set(o,r.action?.label?`After ${r.action.label}`:"Resulting state")}return e.frames.flatMap((r,o)=>{let i=t[r.imageIndex];return i?[{id:r.id,imageIndex:r.imageIndex,label:o===0?"Initial state":n.get(r.id)??"State",url:i}]:[]})}function Yu(e){let t=e.instruction?.trim();return t?e.attachments?.some(n=>n.name?.trim()===t)?null:t:null}function Py(e,t){let n=e?.tagName?.toLowerCase(),r=e?.id?`#${e.id}`:"",o=e?.className?`.${e.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=n?`${n}${r}${o}`:t;return e?.reactComponent?`<${e.reactComponent}> ${i}`:i}function jy(e){let t=e.elements?.[0]?.reactComponent||e.elements?.[0]?.tagName||e.linkedSelector,n=e.type&&e.type!=="annotation"?`${e.type} annotation`:"Annotation";return t?`${n} on ${t}`:n}function zy(e){let t=e.annotations.map(o=>{let i=o.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:o.id,pathname:o.pathname,text:Yu(o)??jy(o),...i>0?{interactionEpisodeStepCount:i}:{}}}),n=new Map,r=o=>{let i=`${o.pathname??""}:${o.durableSelector??o.selector}`,a=n.get(i);if(a){a.changes.push(o.text),o.annotationNumber!==void 0&&(a.annotationNumber===void 0||o.annotationNumber<a.annotationNumber)&&(a.annotationNumber=o.annotationNumber);return}let l={kind:"changes",elementKey:i,elementLabel:Py(o.element,o.selector),...o.annotationNumber!==void 0?{annotationNumber:o.annotationNumber}:{},pathname:o.pathname,changes:[o.text]};n.set(i,l),t.push(l)};for(let o of e.styleModifications??[])for(let i of o.changes)r({...o,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let o of e.textModifications??[])r({...o,text:`Text: ${o.original||"empty"} \u2192 ${o.modified||"empty"}`});for(let o of e.domModifications??[])r({...o,text:o.operation==="copy"?"Copied element":"Moved element"});return e.spacingTokenChanges?.length&&t.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:e.spacingTokenChanges.map(o=>`${o.tokenName}: ${o.originalPx}px \u2192 ${o.newPx}px`)}),t}function $y(e){let t=e.annotations.flatMap(r=>{let o=Yu(r);return o?[{instruction:o,pathname:r.pathname}]:[]});if(t.length===0)return;if(new Set(t.map(r=>r.pathname).filter(Boolean)).size<=1)return t.map(r=>r.instruction).join(`
|
|
5
5
|
|
|
6
6
|
`);let n=new Map;for(let r of t){let o=r.pathname||"(unknown)",i=n.get(o)??[];i.push(r.instruction),n.set(o,i)}return[...n.entries()].map(([r,o])=>`\`${r}\`
|
|
7
7
|
${o.map(i=>`- ${i}`).join(`
|
|
@@ -105,9 +105,6 @@ ${dg}
|
|
|
105
105
|
--popmelt-selection-background: #626262;
|
|
106
106
|
--popmelt-selection-color: #ffffff;
|
|
107
107
|
}
|
|
108
|
-
/* Host stylesheets are mirrored for previews, including page-wide selection
|
|
109
|
-
colors. Keep chrome labels inert and give editable/thread text a Popmelt
|
|
110
|
-
selection treatment instead of inheriting the page's highlight. */
|
|
111
108
|
:host * {
|
|
112
109
|
-webkit-user-select: none;
|
|
113
110
|
user-select: none;
|
|
@@ -115,7 +112,6 @@ ${dg}
|
|
|
115
112
|
:host [data-popmelt-theme="light"] {
|
|
116
113
|
--popmelt-selection-background: #a3a3a3;
|
|
117
114
|
--popmelt-selection-color: #171717;
|
|
118
|
-
/* Keep the native scrollbar width, but soften its high-contrast light thumb. */
|
|
119
115
|
scrollbar-color: rgba(0, 0, 0, 0.06) transparent;
|
|
120
116
|
}
|
|
121
117
|
:host [data-popmelt-theme="dark"],
|
|
@@ -131,12 +127,6 @@ ${dg}
|
|
|
131
127
|
-webkit-user-select: text;
|
|
132
128
|
user-select: text;
|
|
133
129
|
}
|
|
134
|
-
/* Direct reset for all Popmelt chrome elements.
|
|
135
|
-
Beats broad selectors from mirrored host stylesheets (e.g. div, span, *).
|
|
136
|
-
Inline styles on individual elements still win (higher specificity).
|
|
137
|
-
color: inherit (not a fixed value) so children properly inherit inline
|
|
138
|
-
colors set by parents \u2014 e.g. thread header sets color:#fff, child spans
|
|
139
|
-
should get white, not this reset gray. */
|
|
140
130
|
:host *:not([data-popmelt-panel]):not([data-popmelt-panel] *):not([data-popmelt-font="sans"]):not([data-popmelt-font="sans"] *) {
|
|
141
131
|
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
142
132
|
font-size: 12px;
|
|
@@ -144,16 +134,11 @@ ${dg}
|
|
|
144
134
|
line-height: 1.5;
|
|
145
135
|
-webkit-font-smoothing: antialiased;
|
|
146
136
|
}
|
|
147
|
-
/* Thread typography has its own role-based type system. Let descendants
|
|
148
|
-
inherit the nearest thread style so conversational UI can use Geist while
|
|
149
|
-
explicitly monospaced headers, code, and tool payloads remain monospaced. */
|
|
150
137
|
:host [data-devtools="thread-panel"]:not([data-popmelt-panel]) * {
|
|
151
138
|
font-family: inherit;
|
|
152
139
|
font-size: inherit;
|
|
153
140
|
line-height: inherit;
|
|
154
141
|
}
|
|
155
|
-
/* Break font inheritance for component previews \u2014 let mirrored host
|
|
156
|
-
page styles (Tailwind, globals) apply instead of Popmelt's monospace. */
|
|
157
142
|
[data-popmelt-panel] {
|
|
158
143
|
font: 16px / 1.5 system-ui, -apple-system, sans-serif;
|
|
159
144
|
color: initial;
|
|
@@ -11,7 +11,7 @@ import{readFile as Ec,readdir as wI,realpath as vI,stat as bI}from"fs/promises";
|
|
|
11
11
|
`),a=Dr(r),c=xd(i,o),d=[s,a,c].filter(Boolean).join(`
|
|
12
12
|
`);return{additionalContext:d,contextBudget:{protocolEstimatedTokens:to(s),memoryEstimatedTokens:to(a),imprintEstimatedTokens:to(c),totalEstimatedTokens:to(d)}}}function xd(n,e){return n?Nr(n,{requestText:e,delivery:"ambient"}):["","## Continuous imprinting","","An imprint is provisional, advisory shared understanding; accepted product decisions always win. Ordinary completion, implementation, praise, silence, and ambiguity are not learning.","Before finishing, ask one level above the exact task whether human-supplied evidence established a reusable intention, rationale, relationship, or applicability boundary that would change a future decision. The default is no Imprint action.","Call `popmelt_assess_turn` only when reusable understanding changed. Before mutating, require all six: reusable, novel, durable, atomic, scoped, and supported by the human anywhere in the thread. If overlap with project knowledge is plausible, expand context before adding so the result can be consolidated or related instead of duplicated.",'For a genuinely new root, pass `assessmentText` as `<resolution>{"annotations":[],"imprint":{"decision":"mutate","summary":{"kind":"added","title":"<short title>","detail":"<what changed>"},"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one atomic claim>","rationale":"<human-supported reason>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<why no existing explanation is related>"}]}}</resolution>`.','Include `appliedExplanationIds:["new-1"]` and a `grounding` question only when completed implementation or another observable action genuinely tested the new explanation; otherwise omit them.',"When context expansion surfaces related explanations, follow its complete relationship, application, correction, and topology contract. Do not print a machine-readable resolution envelope in the visible response."].join(`
|
|
13
13
|
`)}function Vr(n){if(!n)return;if(n.decision==="recognize")return[n.explanationId];let e=[...new Set([...n.usedExplanationIds??[],...n.appliedExplanationIds??[]])];return e.length?e:void 0}function rh(n,e){let t=e.flatMap((r,i)=>{let o=n[i];return o?[{packetId:`ambient:${r}`,proposalId:r,claim:o.claim.trim(),proposedKind:o.proposedKind,authority:"unaccepted",presentation:"advisory",subjectLabels:["Project"],evidenceCount:1,expansionRefs:[{kind:"proposal",id:r}]}]:[]});return t.length>0?{source:"journal",packets:t,truncated:!1,estimatedTokens:0}:void 0}var no=class{constructor(e){this.options=e;this.turns=new Map;let t={storeId:e.storeId,projectRoot:e.projectRoot,projectId:e.projectId};this.knowledgeViewReader=e.knowledgeViewReader??new eo(t,{memory:e.memoryService,imprint:e.imprintService})}knowledgeDiagnostics(){return this.knowledgeViewReader.diagnostics()}key(e,t){return`${e}:${t}`}async findThread(e){return this.options.threadStore.findContinuationThread([wd(e)])}async prepare(e){if(e.executionOwner===Tn)return{status:"managed_by_bridge",protocolVersion:kn};let t=this.key(e.sessionId,e.turnId),r=this.turns.get(t);if(r){let m=Id(r.sessionId,r.threadId,r.jobId,r.memoryContext,r.imprintContext,r.prompt);return{status:"already_prepared",protocolVersion:kn,threadId:r.threadId,jobId:r.jobId,...m}}let i=await this.findThread(e.sessionId);i||(i=await this.options.threadStore.createThread(`thread-${Zf()}`,[wd(e.sessionId)]));let o=nh(e.sessionId,e.turnId),s=i.messages.find(m=>m.jobId===o&&m.role==="human"),a=vd(e.prompt,Wt(e.sessionId)),c=s?.memoryReview??await this.knowledgeViewReader.memoryContext(e.knowledgeView,a,[]),d=s?.imprintContext??await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.prompt,pendingGroundingExplanationIds:i.messages.flatMap(m=>m.role==="assistant"&&m.imprintSummary?.grounding&&!m.imprintSummary.resolvedAction?[m.imprintSummary.grounding.explanationId]:[])});s||await this.options.threadStore.appendMessage(i.id,{role:"human",timestamp:Date.now(),jobId:o,requestText:e.prompt,feedbackSummary:e.prompt,sessionId:e.sessionId,...c?{memoryReview:c}:{},...d?{imprintContext:d}:{}});let u={sessionId:e.sessionId,turnId:e.turnId,threadId:i.id,jobId:o,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:c,imprintContext:d,events:[]};this.turns.set(t,u);let p=Id(e.sessionId,i.id,o,c,d,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:kn,threadId:i.id,jobId:o,...p}}async recordEvent(e){if(e.executionOwner===Tn)return{status:"ignored"};let t=this.turns.get(this.key(e.sessionId,e.turnId));return t?e.toolUseId&&t.events.some(r=>r.toolUseId===e.toolUseId)?{status:"recorded"}:(t.events.push({toolName:e.toolName,toolUseId:e.toolUseId,toolInput:e.toolInput,toolResponse:e.toolResponse,occurredAt:Date.now()}),{status:"recorded"}):{status:"turn_not_prepared"}}async assess(e){let t=[...this.turns.values()].find(d=>d.threadId===e.threadId&&d.jobId===e.jobId);if(!t)return{status:"turn_not_found"};let r=await this.options.threadStore.getThread(t.threadId);if(r?.messages.some(d=>d.role==="assistant"&&d.jobId===t.jobId))return{status:"turn_completed"};if(t.assessmentEvaluation?.receipt.status==="committed")return t.assessmentEvaluation.receipt;t.assessment={assessmentText:e.assessmentText,semanticCandidates:e.semanticCandidates.slice(0,8)};let i=t.assessment.semanticCandidates.length?{status:"queued_for_turn_completion",count:t.assessment.semanticCandidates.length}:void 0,o=bd(t.events,this.options.projectRoot,Wt(t.sessionId)).length>0,s=Ji(t.imprintContext,r?.messages.find(d=>d.role==="human"&&d.jobId===t.jobId)?.imprintExpandedContext),a=Or(t.assessment.assessmentText,{context:s,requestText:t.prompt,applicationOccurred:o}),c;if(a.error)c={receipt:{status:"rejected",reason:a.error},imprintAssessment:{state:a.error.includes("missing")?"missing":"invalid",reason:a.error}};else if(a.draft?.decision==="none")this.options.imprintService.recordNoop(a.draft.reason),c={receipt:{status:"assessed",outcome:"no_change",reason:a.draft.reason,...i?{semanticCandidates:i}:{}},imprintAssessment:{state:"none",reason:a.draft.reason},imprintUsedExplanationIds:Vr(a.draft),imprintAppliedExplanationIds:a.draft.appliedExplanationIds};else if(a.draft?.decision==="recognize")c={receipt:{status:"assessed",outcome:"recognized",...i?{semanticCandidates:i}:{}},imprintAssessment:{state:"none",reason:"recognized existing grounded understanding"},imprintUsedExplanationIds:Vr(a.draft)};else if(a.draft?.decision==="mutate"||a.draft?.decision==="apply")try{let d=await this.options.imprintService.capture(a.draft,{threadId:t.threadId,jobId:t.jobId,concreteModel:await this.options.loadConcreteModel?.()??null,pendingGroundingExplanationIds:s?.pendingGroundingExplanationIds,applicationOccurred:o,storeId:this.options.storeId,context:s});if(d)await this.options.memoryService.recordImprintEvidence({summary:d,threadId:t.threadId,jobId:t.jobId,qualifiedExplanationMemoryIds:Object.fromEntries((s?.explanations??[]).flatMap(u=>u.storeId&&u.memoryId?[[`${u.storeId}:${u.id}`,u.memoryId]]:[]))}).catch(()=>{}),c={receipt:{status:"committed",transactionId:d.transactionId,changes:d.changes,...i?{semanticCandidates:i}:{}},imprintSummary:d,imprintAssessment:{state:"mutated"},imprintUsedExplanationIds:Vr(a.draft),imprintAppliedExplanationIds:a.draft.appliedExplanationIds};else{let u="imprint mutation failed admission or produced no durable change";c={receipt:{status:"rejected",reason:u},imprintAssessment:{state:"invalid",reason:u},imprintUsedExplanationIds:Vr(a.draft),imprintAppliedExplanationIds:a.draft.appliedExplanationIds}}}catch(d){let u=d instanceof Error?d.message:"imprint mutation failed";c={receipt:{status:"rejected",reason:u},imprintAssessment:{state:"invalid",reason:u},imprintUsedExplanationIds:Vr(a.draft),imprintAppliedExplanationIds:a.draft.appliedExplanationIds}}else{let d="imprint assessment is missing";c={receipt:{status:"rejected",reason:d},imprintAssessment:{state:"missing",reason:d}}}return t.assessmentEvaluation=c,(c.imprintAssessment.state==="missing"||c.imprintAssessment.state==="invalid")&&this.options.imprintService.recordAssessmentFailure(c.imprintAssessment.state),c.receipt}async complete(e){if(e.executionOwner===Tn)return{status:"managed_by_bridge",protocolVersion:kn};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:kn};let i=(await this.options.threadStore.getThread(t.threadId))?.messages.find(h=>h.role==="assistant"&&h.jobId===t.jobId);if(i)return e.lastAssistantMessage&&e.lastAssistantMessage!==i.responseText&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{responseText:e.lastAssistantMessage}),{status:"already_completed",protocolVersion:kn,threadId:t.threadId,jobId:t.jobId};let o=bd(t.events,this.options.projectRoot,Wt(e.sessionId)),s=o.length>0,a=t.assessmentEvaluation?.imprintSummary,c=t.assessmentEvaluation?.imprintAssessment??{state:"not_applicable"},d=t.assessmentEvaluation?.imprintUsedExplanationIds,u=t.assessmentEvaluation?.imprintAppliedExplanationIds,p=s?"completed":"no_change",m=Gr({changedFiles:o}),v={role:"assistant",timestamp:Date.now(),jobId:t.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:t.events.map(h=>h.toolName),turn:{phase:"complete",orientation:[],result:m},result:m,provider:Wt(e.sessionId),model:e.model,imprintSummary:a,imprintUsedExplanationIds:d,imprintAppliedExplanationIds:u};await this.options.threadStore.appendMessage(t.threadId,v);let b=await this.options.memoryService.captureCompletedJob({jobId:t.jobId,threadId:t.threadId,createdAt:t.createdAt,completedAt:Date.now(),requestSummary:t.prompt,responseSummary:e.lastAssistantMessage,outcome:p,execution:{provider:Wt(e.sessionId),model:e.model,sessionId:e.sessionId},subjectHints:[],filePaths:o,resolutions:s?[{status:"resolved",summary:`Changed ${o.join(", ")}`}]:[],semanticCandidates:t.assessment?.semanticCandidates,governingDecisionIds:t.memoryContext?.acceptedTruth?.decisions.map(h=>h.id),imprintAssessment:c}),f=rh(t.assessment?.semanticCandidates??[],b.proposalIds);return f&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:f}),{status:"completed",protocolVersion:kn,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=[...this.turns.values()].filter(d=>!!e.sessionId&&d.sessionId===e.sessionId&&(!(e.threadId||e.jobId)||d.threadId===e.threadId&&d.jobId===e.jobId)),r=(await Promise.all(t.map(async d=>{let u=await this.options.threadStore.getThread(d.threadId);return u?.messages.some(p=>p.role==="human"&&p.jobId===d.jobId&&p.sessionId===e.sessionId)&&!u.messages.some(p=>p.role==="assistant"&&p.jobId===d.jobId)?d:void 0}))).filter(d=>!!d),i=r.length===1?r[0]:void 0,o=vd(e.query),s=await this.knowledgeViewReader.memoryContext(e.knowledgeView,o,e.subjectHints??[]),a=await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.query,subjectHints:e.subjectHints}),c=!!(i&&a&&await this.options.threadStore.registerAmbientImprintContext(i.threadId,i.jobId,i.sessionId,a));return{memoryContext:s,imprintContext:a,assessmentContext:c&&i?{status:"registered",threadId:i.threadId,jobId:i.jobId}:{status:"not_registered",reason:a?"No matching open turn. Supply this session\u2019s exact threadId and jobId; completed turns cannot receive context.":"No Imprint references returned."},formattedContext:[Dr(s),xd(a,e.query)].filter(Boolean).join(`
|
|
14
|
-
`)}}};function ro(n,e=process.env.POPMELT_EXPERIMENTAL_EVENT_TRANSPORT){let t=n??e??"websocket";if(t==="sse"||t==="websocket")return t;throw new Error("POPMELT_EXPERIMENTAL_EVENT_TRANSPORT must be sse or websocket")}import{spawn as oI}from"child_process";import{closeSync as sI,openSync as aI}from"fs";import{appendFile as cI,mkdir as dI,readFile as lI,realpath as pI}from"fs/promises";import{dirname as uI,join as Pc}from"path";import{fileURLToPath as mI}from"url";var Sd={name:"@popmelt.com/core",version:"0.31.
|
|
14
|
+
`)}}};function ro(n,e=process.env.POPMELT_EXPERIMENTAL_EVENT_TRANSPORT){let t=n??e??"websocket";if(t==="sse"||t==="websocket")return t;throw new Error("POPMELT_EXPERIMENTAL_EVENT_TRANSPORT must be sse or websocket")}import{spawn as oI}from"child_process";import{closeSync as sI,openSync as aI}from"fs";import{appendFile as cI,mkdir as dI,readFile as lI,realpath as pI}from"fs/promises";import{dirname as uI,join as Pc}from"path";import{fileURLToPath as mI}from"url";var Sd={name:"@popmelt.com/core",version:"0.31.2",description:"A tiny, powerful design layer for humans and AI",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,packageManager:"pnpm@9.12.0",engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint . && node scripts/check-eslint-suppressions.mjs","pack:smoke":"node scripts/pack-smoke.mjs","peer:smoke":"node scripts/peer-compat-smoke.mjs","vue:smoke":"pnpm run build && node scripts/vue-install-smoke.mjs","nuxt:smoke":"pnpm run build && node scripts/nuxt-install-smoke.mjs","astro:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs astro","svelte:smoke":"pnpm run build && node scripts/framework-install-smoke.mjs svelte && node scripts/framework-install-smoke.mjs sveltekit",prepublishOnly:"pnpm run verify",test:"vitest run","test:coverage":"vitest run --coverage.enabled","test:browser":"pnpm run build && tsc --noEmit -p tsconfig.browser.json && vitest run --config vitest.browser.config.ts","test:browser:mutation":"node e2e/check-lifecycle-mutation.mjs","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run format && pnpm run lint && pnpm run test:coverage && pnpm run build && pnpm run pack:smoke"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./browser":{types:"./dist/browser.d.mts",import:"./dist/browser.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./vite/client":{types:"./dist/vite-client.d.ts"},"./astro":{types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"},"./nuxt":{types:"./dist/plugin-nuxt.d.mts",import:"./dist/plugin-nuxt.mjs",default:"./dist/plugin-nuxt.mjs"},"./media":{types:"./dist/media.d.mts",import:"./dist/media.mjs"},"./three":{types:"./dist/adapter-three.d.mts",import:"./dist/adapter-three.mjs"},"./react-three-fiber":{types:"./dist/adapter-react-three-fiber.d.mts",import:"./dist/adapter-react-three-fiber.mjs"}},files:["dist","codex-plugin","claude-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.3"},optionalDependencies:{"@napi-rs/keyring":"2.1.0"},peerDependencies:{nuxt:">=4.5.2 <5","lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0","@react-three/fiber":">=8.0.0",three:">=0.150.0"},peerDependenciesMeta:{nuxt:{optional:!0},next:{optional:!0},"@react-three/fiber":{optional:!0},three:{optional:!0}},devDependencies:{nuxt:"4.6.3","@kit/eslint-config":"workspace:^","@react-three/fiber":"9.7.0","@tanstack/react-router":"1.120.5","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/three":"^0.185.4","@types/ws":"8.18.1","@vitejs/plugin-react":"^5.1.1","@vitejs/plugin-vue":"6.0.8","@vitest/coverage-v8":"4.1.12",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.5.28",prettier:"3.5.3",react:"19.1.0","react-dom":"19.1.0",three:"^0.185.1",tsup:"^8.5.1",typescript:"^5.8.3",vite:"7.3.7",vitest:"4.1.12",vue:"3.5.44","vue-router":"5.3.1"},pnpm:{overrides:{"postcss@<8.5.23":"8.5.23","source-map-js@<1.2.2":"1.2.2","esbuild@<0.28.1":"0.28.1","sharp@<0.35.5":"0.35.5"}}};var Ft=Sd.version;import{spawn as oh}from"child_process";import{createInterface as sh}from"readline";async function io(n,e){let t=oh(process.env.CODEX_APP_RUNTIME_CLI_PATH||"codex",["app-server","--stdio"],{stdio:["pipe","pipe","ignore"]}),r=sh({input:t.stdout});try{return await new Promise((i,o)=>{let s=()=>o(new Error("Codex did not confirm "+n)),a=setTimeout(()=>{s(),t.kill()},1e4);t.once("close",()=>{clearTimeout(a),s()}),t.once("error",s),t.stdin.on("error",s);let c=d=>t.stdin.write(JSON.stringify(d)+`
|
|
15
15
|
`);r.on("line",d=>{let u;try{u=JSON.parse(d)}catch{return}if(u.error&&(u.id===1||u.id===2)){s();return}u.id===1&&u.result?(c({method:"initialized"}),c({id:2,method:n,params:e})):u.id===2&&u.result&&i(u.result)}),c({id:1,method:"initialize",params:{clientInfo:{name:"popmelt-canvas-notes",version:"1"},capabilities:{experimentalApi:!0}}})})}finally{r.close(),t.kill()}}async function kd({threadId:n,clientUserMessageId:e,input:t}){let{queuedSubmission:r}=await io("thread/queue/add",{threadId:n,clientUserMessageId:e,input:t});if(r?.clientUserMessageId!==e)throw new Error("Codex returned an unexpected canvas note ID")}async function Vx(n,e){let t=new Set,r=null;do{let i=await io("thread/items/list",{threadId:n,turnId:e,limit:64,sortDirection:"asc",cursor:r});for(let{turnId:o,item:s}of i.data)o===e&&s.type==="userMessage"&&s.clientId&&t.add(s.clientId);r=i.nextCursor}while(r);return[...t]}async function Td(n,e){return(await io("thread/queue/list",{threadId:n,limit:100})).data.some(i=>i.clientUserMessageId===e)?!0:(await io("thread/items/list",{threadId:n,sortDirection:"desc",limit:100})).data.some(({item:i})=>i.type==="userMessage"&&i.clientId===e)}import{readFile as Ih}from"fs/promises";import{join as xh}from"path";import{randomUUID as _d}from"crypto";function Qn(n){let e=n?.requestItems?.flatMap(r=>r.kind==="annotation"&&r.text.trim()?[r.text.trim()]:[]);if(e?.length)return e.join("; ");let t=n?.requestItems?.flatMap(r=>r.kind==="changes"?[`${r.elementLabel} [${r.changes.join(", ")}]`]:[]);return t?.length?t.join("; "):n?.requestText?.trim()||void 0}function Pd(n){let e=n.instruction?.trim();return e?n.attachments?.some(r=>r.name?.trim()===e)?null:e:null}function qs(n,e){let t=n?.tagName?.toLowerCase(),r=n?.id?`#${n.id}`:"",i=n?.className?`.${n.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",o=t?`${t}${r}${i}`:e;return n?.reactComponent?`<${n.reactComponent}> ${o}`:o}function ah(n){let e=n.elements?.[0]?.reactComponent||n.elements?.[0]?.tagName||n.linkedSelector,t=n.type&&n.type!=="annotation"?`${n.type} annotation`:"Annotation";return e?`${t} on ${e}`:t}function Xn(n){let e=n.annotations.map(i=>{let o=i.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:i.id,pathname:i.pathname,text:Pd(i)??ah(i),...o>0?{interactionEpisodeStepCount:o}:{}}}),t=new Map,r=i=>{let o=`${i.pathname??""}:${i.durableSelector??i.selector}`,s=t.get(o);if(s){s.changes.push(i.text),i.annotationNumber!==void 0&&(s.annotationNumber===void 0||i.annotationNumber<s.annotationNumber)&&(s.annotationNumber=i.annotationNumber);return}let a={kind:"changes",elementKey:o,elementLabel:qs(i.element,i.selector),...i.annotationNumber!==void 0?{annotationNumber:i.annotationNumber}:{},pathname:i.pathname,changes:[i.text]};t.set(o,a),e.push(a)};for(let i of n.styleModifications??[])for(let o of i.changes)r({...i,text:`${o.property}: ${o.original||"unset"} \u2192 ${o.modified||"unset"}${o.token?` (${o.token})`:""}`});for(let i of n.textModifications??[])r({...i,text:`Text: ${i.original||"empty"} \u2192 ${i.modified||"empty"}`});for(let i of n.domModifications??[])r({...i,text:i.operation==="copy"?"Copied element":"Moved element"});return n.spacingTokenChanges?.length&&e.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:n.spacingTokenChanges.map(i=>`${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`)}),e}function oo(n){let e=n.annotations.flatMap(i=>{let o=Pd(i);return o?[{instruction:o,pathname:i.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(i=>i.pathname).filter(Boolean)).size<=1)return e.map(i=>i.instruction).join(`
|
|
16
16
|
|
|
17
17
|
`);let r=new Map;for(let i of e){let o=i.pathname||"(unknown)",s=r.get(o)??[];s.push(i.instruction),r.set(o,s)}return[...r.entries()].map(([i,o])=>`\`${i}\`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{c as v}from"./chunk-
|
|
2
|
+
import{c as v}from"./chunk-MTQ5IWIK.mjs";import{a as P,l as R,h as $,j as x,k as g,i as b,m as y}from"./chunk-F6AMPRUB.mjs";import{v as A}from"./chunk-RCVAPQ7X.mjs";var O="__popmelt_code_preview";function C(a,n){let t=new URL(a,n);if(t.origin!==new URL(n).origin||!/^https?:$/.test(t.protocol))throw new Error("Code previews must use the same application origin");return t.hash="",t.searchParams.delete("popmelt"),t.searchParams.set(O,"1"),t.href}function T(a,n){if(!new URL(location.href).searchParams.has(O))return!1;if(parent===window)return!0;window.__POPMELT_CODE_PREVIEW__?.dispose();let t=P,w="",s=!1,u=0,d=new Map,h=()=>{for(let[e,i]of d)i===null?e.removeAttribute("data-pm"):e.setAttribute("data-pm",i);d.clear()},r=new v(n?.get()??[]),m=()=>{for(let e of t.annotations)e.target&&r.resolve(e.target)},_=()=>{R(t.domModifications),$(t.styleModifications),x(t.textModifications),m();for(let e of t.annotations){let i=e.linkedSelector?.match(/^\[data-pm="([^"]+)"\]$/)?.[1];if(!i)continue;let o=A(e.linkedSelector,e.elements?.[0]);o&&(d.has(o)||d.set(o,o.getAttribute("data-pm")),o.setAttribute("data-pm",i))}},c=new MutationObserver(e=>{e.some(i=>i.addedNodes.length)&&(cancelAnimationFrame(u),u=requestAnimationFrame(()=>{c.disconnect(),_(),p()}))}),p=()=>c.observe(document.body,{childList:!0,subtree:!0}),E=()=>{let e=r;e.whenReady().then(()=>{!s&&r===e&&(m(),document.dispatchEvent(new Event("popmelt-subjects-ready")))})},L=n?.subscribe(()=>{r.destroy(),r=new v(n.get()),m(),E()});E();let f={dispose(){s||(s=!0,c.disconnect(),L?.(),r.destroy(),cancelAnimationFrame(u),window.removeEventListener("pagehide",f.dispose),window.__POPMELT_CODE_PREVIEW__===f&&delete window.__POPMELT_CODE_PREVIEW__,g(t.textModifications),b(t.styleModifications,!0),y(t.domModifications),h())},source:a,getSubjects:()=>r,update(e){if(s)throw new Error("Preview runtime closed");if(e.draft.source&&e.draft.source.sourceId!==a.sourceId)throw new Error("This draft belongs to a different source");let i=JSON.stringify([e.planeId,e.draft.revision,e.draft.source?.sourceId,e.draft.source?.revision]);if(w===i)return;let o=structuredClone(e.draft.state??P),l=M=>!M.pathname||M.pathname===location.pathname,I={...o,annotations:o.annotations.filter(l),styleModifications:o.styleModifications.filter(l),textModifications:o.textModifications.filter(l),domModifications:o.domModifications.filter(l)};c.disconnect(),g(t.textModifications),b(t.styleModifications,!0),y(t.domModifications),h(),t=I,_(),p(),w=i}};return window.__POPMELT_CODE_PREVIEW__=f,p(),window.addEventListener("pagehide",f.dispose,{once:!0}),!0}export{C as a,T as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
function m(t){try{let e=t.defaultView?.frameElement;return e?.localName==="iframe"?e:null}catch{return null}}function w(t){if(t.localName!=="iframe"||t.closest("[data-devtools],[data-popmelt-peer-surface]"))return null;try{let e=t.contentDocument;return e?.documentElement?e:null}catch{return null}}function D(t){let e=t.getBoundingClientRect(),r=t.offsetWidth?e.width/t.offsetWidth:1,u=t.offsetHeight?e.height/t.offsetHeight:1;return{x:e.left+t.clientLeft*r,y:e.top+t.clientTop*u,sx:r,sy:u}}function v(t,e){let{left:r,top:u,width:o,height:n}=t,l=m(e);for(;l;){let a=D(l);r=a.x+r*a.sx,u=a.y+u*a.sy,o*=a.sx,n*=a.sy,l=m(l.ownerDocument)}return new DOMRect(r,u,o,n)}function V(t){return v(t.getBoundingClientRect(),t.ownerDocument)}function M(t,e,r){let u=[],o=m(r);for(;o;)u.unshift(o),o=m(o.ownerDocument);for(let n of u){let l=D(n);t=(t-l.x)/l.sx,e=(e-l.y)/l.sy}return{x:t,y:e}}function k(t){return t.ownerDocument.defaultView??window}function z(t){return!!(t&&t.namespaceURI==="http://www.w3.org/1999/xhtml")}function A(t,e=document){if(t===e)return!0;let r=m(t);return!!(r?.isConnected&&r.contentDocument===t&&A(r.ownerDocument,e))}function B(t,e){if(!A(e))return new DOMRect(0,0,0,0);let r=t.left,u=t.top,o=t.right,n=t.bottom;for(let l=m(e);l;l=m(l.ownerDocument)){let a=v({left:0,top:0,width:l.clientWidth,height:l.clientHeight},l.contentDocument);r=Math.max(r,a.left),u=Math.max(u,a.top),o=Math.min(o,a.right),n=Math.min(n,a.bottom)}return new DOMRect(r,u,Math.max(0,o-r),Math.max(0,n-u))}var g="@frame(";function I(t,e){return`${g}${encodeURIComponent(JSON.stringify({selector:t,url:e.URL}))}) `}function O(t){if(!t.startsWith(g))return null;let e=t.indexOf(") ");if(e<0)return null;try{let r=JSON.parse(decodeURIComponent(t.slice(g.length,e)));return typeof r.selector!="string"||typeof r.url!="string"?null:{...r,rest:t.slice(e+2)}}catch{return null}}var b=" >>> ";function N(t){return Array.from(t.querySelectorAll("*")).flatMap(e=>e.shadowRoot?[e.shadowRoot]:[])}function S(t=document){let e=[t];for(let r of e)e.push(...N(r));return e}function p(t,e=document){if(t.startsWith(g)){let o=O(t);if(!o)return null;let n=o.selector.startsWith(g)||o.selector.includes(b)?[p(o.selector,e)].filter(s=>!!s):S(e).flatMap(s=>Array.from(s.querySelectorAll(o.selector))),l=n.length===1?n[0]:null,a=l&&w(l);return!a||a.URL!==o.url?null:p(o.rest,a)}let r=t.split(b);if(r.length>1){let o=e,n=null;for(let l=0;l<r.length;l+=1){if(n=o.querySelector(r[l]),!n)return null;if(l<r.length-1){if(!n.shadowRoot)return null;o=n.shadowRoot}}return n}let u=[e];for(let o of u){let n=o.querySelector(t);if(n)return n;u.push(...N(o))}return null}function R(t){if(t.parentElement)return t.parentElement;let e=t.getRootNode();return"host"in e?e.host:null}function _(t,e){return e.startsWith(g)||e.includes(b)?p(e)===t:t.matches(e)}function $(t,e){let r=t;for(;r;){if(r.matches(e))return r;r=R(r)}return null}function H(t,e){let r=e;for(;r;){if(r===t)return!0;r=R(r)}return!1}var W=new WeakMap;function E(t){let e=t.getAttribute("style");return t.style.setProperty("pointer-events","auto","important"),()=>{e===null?t.removeAttribute("style"):t.setAttribute("style",e)}}function J(t){let e=t.nodeType===9?t:t.ownerDocument,r="* { pointer-events: auto !important; }",u=[];try{let o=e.defaultView?.CSSStyleSheet;if(o?.prototype.replaceSync&&"adoptedStyleSheets"in t){let n=W.get(e);n||(n=new o,n.replaceSync(r),W.set(e,n));let l=[...t.adoptedStyleSheets];t.adoptedStyleSheets=[...l,n],u.push(()=>{t.adoptedStyleSheets=l})}else{let n=e.createElement("style");n.textContent=r,(t.nodeType===9?e.head??e.documentElement:t).appendChild(n),u.push(()=>n.remove())}for(let n of t.querySelectorAll('[style*="pointer-events"]'))n.style.getPropertyValue("pointer-events")!=="none"||n.style.getPropertyPriority("pointer-events")!=="important"||u.push(E(n))}catch(o){throw u.reverse().forEach(n=>n()),o}return()=>u.reverse().forEach(o=>o())}function G(t,e,r,u=n=>[n],o){let n=[];for(let l of t.querySelectorAll("iframe")){if(!w(l))continue;let a=l.getBoundingClientRect();e<a.left||e>a.right||r<a.top||r>a.bottom||l.ownerDocument.defaultView?.getComputedStyle(l).pointerEvents==="none"&&n.push(E(l))}try{let l=()=>{let c=typeof t.elementsFromPoint=="function"?t.elementsFromPoint(e,r):[],i=t.elementFromPoint?.(e,r)??null;return(i&&!c.includes(i)?[i,...c]:c).filter(f=>t.nodeType===9||f.getRootNode()===t)},a=l(),s=a;if(o){let c=J(t);try{s=l()}finally{c()}s=s.filter(i=>a.includes(i)||o(i))}return s.flatMap(u)}finally{n.forEach(l=>l())}}function q(t,e,r=document,u){let o=[],n=new Set,l=r.nodeType===9?r:r.ownerDocument,a=M(t,e,l);for(let s of S(r).reverse())for(let c of G(s,a.x,a.y,i=>{let f=w(i);return f?[...q(t,e,f,u),i]:[i]},u))n.has(c)||(n.add(c),o.push(c));return o}function K(){return b}var Q=["id","data-testid","data-test","data-cy","data-popmelt-media-id","aria-label","name","href"],j=t=>t.replace(/\s+/g," ").trim();function y(t){return t==="id"||t==="data-popmelt-media-id"||/^data-(?:testid|test|cy)(?:-[a-z0-9_-]+)?$/.test(t)}function F(t,e){return!!(e&&e.length<=200&&!(t==="id"&&/^(radix-|:|_r_)/.test(e)))}function P(t){let e={},r=new Set([...Q,...t.getAttributeNames().filter(y)]);for(let n of r){let l=t.getAttribute(n);l&&F(n,l)&&(e[n]=l)}let u=j(t.querySelector("h1,h2,h3,h4,h5,h6")?.textContent??""),o=j(Array.from(t.childNodes).filter(n=>n.nodeType===3).map(n=>n.textContent).join(" "));return{tag:t.tagName.toLowerCase(),...Object.keys(e).length?{attributes:e}:{},...u&&u.length<=200?{heading:u}:{},...o&&o.length<=200?{text:o}:{}}}function L(t,e,r=document){let u=S(r),o=i=>{try{return u.flatMap(f=>Array.from(f.querySelectorAll(i)))}catch{return[]}},n=!!(e&&(e.heading||e.text||Object.keys(e.attributes??{}).length)),l=i=>{if(!e||!n)return!0;let f=P(i);return f.tag===e.tag&&(!e.heading||f.heading===e.heading)&&(!e.text||f.text===e.text)&&Object.entries(e.attributes??{}).every(([h,d])=>i.getAttribute(h)===d)};for(let i of t){if(i.includes(" >>> ")||i.startsWith("@frame(")){try{let h=p(i,r),d=O(i),C=Object.entries(e?.attributes??{}).filter(([x])=>y(x)),T=d&&h&&(d.rest.startsWith("[data-pm=")||C.length>0&&h.tagName.toLowerCase()===e?.tag&&C.every(([x,U])=>h.getAttribute(x)===U));if(h&&(T||l(h)))return{status:"matched",element:h}}catch{}continue}let f=o(i);if(f.length===1&&(/^\[data-pm=/.test(i)||!n))return{status:"matched",element:f[0]}}if(!n||t.some(i=>i.includes(" >>> ")||i.startsWith("@frame("))||!/^[a-z][a-z0-9-]*$/.test(e.tag))return{status:"missing"};let a=o(e.tag);if(a.length>500)return{status:"ambiguous"};let s=Object.entries(e.attributes??{}).filter(([i])=>y(i));if(s.length){let i=a.filter(f=>s.every(([h,d])=>f.getAttribute(h)===d));return i.length===1?{status:"matched",element:i[0]}:{status:i.length?"ambiguous":"missing"}}let c=a.filter(l);return c.length===1?{status:"matched",element:c[0]}:{status:c.length?"ambiguous":"missing"}}function X(t,e,r=document){let u={};if(e)for(let[a,s]of Object.entries({...e.dataAttributes,...e.id?{id:e.id}:{}}))y(a)&&F(a,s)&&(u[a]=s);let o=e?.targetFingerprint?.tag??e?.tagName?.toLowerCase(),n=e&&o?{...e.targetFingerprint,tag:o,attributes:{...u,...e.targetFingerprint?.attributes}}:e?.targetFingerprint,l=L([t,e?.selector].filter(a=>!!a),n,r);return l.status==="matched"?l.element:null}export{m as a,w as b,v as c,V as d,M as e,k as f,z as g,A as h,B as i,I as j,S as k,p as l,R as m,_ as n,$ as o,H as p,q,K as r,y as s,P as t,L as u,X as v};
|