@enhance-eng/enhance-dev 0.1.41-dev.sha-bff70900f577 → 0.1.41-dev.sha-bc50fb27e791

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{$n as e,A as t,An as n,Ar as r,At as i,Bn as a,C as o,Cn as s,Cr as c,Ct as l,D as u,Dn as d,Dr as f,E as p,En as m,Er as h,Et as g,F as _,G as ee,Gn as v,Gt as te,Hn as y,Ht as ne,In as re,J as ie,Jn as ae,Jt as b,K as oe,Kn as se,Kt as ce,L as le,Ln as ue,M as de,Mn as fe,Mt as x,Nt as pe,On as me,Or as he,P as ge,Pn as _e,Pr as ve,Q as ye,Qt as be,Rn as xe,Sn as Se,Sr as Ce,T as we,Tn as Te,Tr as Ee,Tt as S,Ut as De,V as Oe,Vt as ke,W as Ae,Wn as je,Wt as Me,X as Ne,Xt as Pe,Y as Fe,Yn as Ie,Yt as Le,Z as Re,Zn as ze,Zt as Be,_r as Ve,_t as He,at as Ue,b as We,bn as Ge,br as Ke,cr as qe,ct as Je,d as Ye,dr as Xe,dt as Ze,en as Qe,er as $e,et,ft as tt,gt as nt,it as rt,jn as it,jr as at,jt as ot,kr as st,kt as ct,lr as lt,mr as ut,or as dt,pr as ft,pt,q as mt,qn as ht,qt as gt,rr as _t,rt as vt,sr as yt,st as bt,tr as xt,ur as St,ut as Ct,vr as wt,w as Tt,wr as Et,xn as Dt,xr as Ot,xt as kt,yr as At,yt as jt,zn as Mt,zt as Nt}from"./cli-output-identity.lib-a7FnosDV.mjs";import C from"node:process";import{z as w}from"zod";import{homedir as Pt,tmpdir as Ft}from"node:os";import{generateKeyBetween as It,generateNKeysBetween as Lt}from"fractional-indexing";import{chmodSync as Rt,constants as zt,createReadStream as Bt,createWriteStream as Vt,mkdirSync as Ht,writeFileSync as Ut}from"node:fs";import T from"node:path";import{createHash as E,randomBytes as Wt,randomUUID as Gt}from"node:crypto";import{setTimeout as Kt}from"node:timers/promises";import{access as qt,chmod as Jt,mkdir as Yt,mkdtemp as Xt,open as Zt,readFile as Qt,realpath as $t,rename as en,rm as tn,stat as nn,unlink as rn,writeFile as an}from"node:fs/promises";import{isDeepStrictEqual as on}from"node:util";import{generate as sn,parse as cn}from"css-tree";import{parseFragment as ln,serialize as un,serializeOuter as dn}from"parse5";import{performance as fn}from"node:perf_hooks";import{Readable as pn,Transform as mn}from"node:stream";import{pipeline as hn}from"node:stream/promises";import{ZipFile as gn}from"yazl";import{createTRPCUntypedClient as _n,httpLink as vn}from"@trpc/client";import{spawn as yn}from"node:child_process";import{createServer as bn}from"node:http";const xn=(e,t)=>e<t?-1:+(e>t),Sn=(e,t)=>{let n=new Set(t),r=[],i=new Map,a=r;for(let t of e)n.has(t.id)&&(a=[],i.set(t.id,a)),a.push(t);return[...r,...t.flatMap(e=>i.get(e)??[])]},Cn=(e,t)=>{let n=new Set(t.clear),r=new Map((e?.declarations??[]).filter(e=>!n.has(e.id)).map(e=>[e.id,e])),i=t.set??[];for(let e of i)r.set(e.id,e);let a=Array.from(r,([,e])=>e);return a.length===0&&(t.empty===`remove`||e===void 0&&t.empty!==`keep`)?null:{declarations:t.order===void 0?a:Sn(a,t.order)}},wn=(e,t)=>{let n=new Map(e?.declarations.map(e=>[e.id,e])),r=t?.declarations??[],i=new Set(r.map(e=>e.id)),a=Array.from(n,([e])=>e).filter(e=>!i.has(e)),o=r.filter(e=>{let t=n.get(e.id);return t?.property!==e.property||t.value!==e.value||t.enabled!==e.enabled}),s={...a.length>0&&{clear:a},...o.length>0&&{set:o}},c=Cn(e,s),l=r.map(e=>e.id),u=JSON.stringify(c?.declarations.map(e=>e.id)??[])!==JSON.stringify(l),d=t===void 0&&e!==void 0?`remove`:e===void 0&&t!==void 0&&r.length===0?`keep`:void 0;return d===void 0&&!u&&o.length===0&&a.length===0?null:{...s,...u&&{order:l},...d!==void 0&&{empty:d}}},Tn=1e6,En=e=>Math.round(e*255*Tn)/Tn,D=(e,t=1)=>{let n=e.alpha*t;if(e.space===`srgb`){let t=[e.red,e.green,e.blue].map(e=>String(En(e))).join(` `);return n===1?`rgb(${t})`:`rgb(${t} / ${String(n)})`}let r=`${String(e.red)} ${String(e.green)} ${String(e.blue)}`;return`color(${e.space} ${r} / ${String(n)})`},Dn={x:0,y:0,width:1,height:1},On=(e,t)=>{let[n,r,i,a,o,s]=e.transform,c=n*a-r*i,l=t.x-o,u=t.y-s;return{x:(a*l-i*u)/c,y:(n*u-r*l)/c}},kn=(e,t=Dn)=>[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x,y:t.y+t.height},{x:t.x+t.width,y:t.y+t.height}].flatMap(t=>{let n=On(e,t);return[n.x,n.y]}),An=1024,jn=(e,t,n)=>{let r=e.stops.map(t=>`${n?`rgb(255 255 255 / ${String(t.color.alpha*e.opacity)})`:D({...t.color,alpha:1})} ${String(t.position*360)}deg`);return`conic-gradient(from 90deg at ${String(t)}% ${String(t)}% in srgb, ${r.join(`, `)})`},Mn=(e,t)=>{let n=kn(e,t),r=Math.min(0,...n),i=Math.max(1,...n)-r,a=(.5-r)/i*100,o=e.transform.map((e,t)=>t<4?e/An:e),s=`width:100%;height:100%;background-image:${jn(e,a,!1)};mask-image:${jn(e,a,!0)};`;return`<g transform="matrix(${o.map(String).join(` `)})"><foreignObject x="${String(r*An)}" y="${String(r*An)}" width="${String(i*An)}" height="${String(i*An)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${s}"></div></foreignObject></g>`},Nn=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Mn(e)}</svg>`,Pn=(e,t)=>e===void 0||t===void 0?!1:e.x===t.x&&e.y===t.y,Fn=e=>{let t=[...e];for(;t.length>1&&Pn(t[0],t.at(-1));)t.pop();for(;t.length>1&&Pn(t[0],t[1]);)t.splice(1,1);return t},In=e=>{let t=e.match(/[MLHVZ]|[+-]?\d*\.?\d+(?:e[+-]?\d+)?/giu)??[];return t.join(``)!==e.replaceAll(/[\s,]/gu,``)||!/^M/iu.test(t[0]??``)||!/^Z$/iu.test(t.at(-1)??``)?null:t},Ln=(e,t,n,r)=>{let i=e.toUpperCase(),a=Number(t[n]),o=[`M`,`L`].includes(i)?Number(t[n+1]):a;if(!Number.isFinite(a)||!Number.isFinite(o))return null;let s=e===e.toLowerCase()?r:{x:0,y:0},c={x:i===`V`?r.x:s.x+a,y:i===`H`?r.y:s.y+o};return Number.isFinite(c.x)&&Number.isFinite(c.y)?c:null},Rn=e=>{let t=In(e);if(t===null)return null;let n=[],r=`M`,i=0,a={x:0,y:0};for(;i<t.length-1;){let e=t[i]??``;/^[MLHV]$/iu.test(e)&&(r=e,i+=1);let o=r.toUpperCase();if(o===`M`&&n.length>0)return null;let s=Ln(r,t,i,a);if(s===null)return null;a=s,n.push(a),i+=[`M`,`L`].includes(o)?2:1,r=r.replace(`M`,`L`).replace(`m`,`l`)}return i===t.length-1?Fn(n):null},zn=Math.PI/2,Bn=1e6,Vn=e=>String(Math.round(e*Bn)/Bn),O=([e,t])=>`${Vn(e)} ${Vn(t)}`,Hn=(e,[t,n],{width:r,height:i},a)=>{if(e<=0)return{radius:0,reach:0,smoothing:0};let o=(t,n)=>{let r=t*e,i=e+n;if(Number.isFinite(r)&&Number.isFinite(i))return r/i;let a=Math.min(e,n)/Math.max(e,n);return(e>=n?t:t*a)/(1+a)},s=Math.min(o(r,t),o(i,n)),c=Math.min(e,s);if(c===0)return{radius:0,reach:0,smoothing:0};let l=Math.max(0,Math.min(a,s/c-1));return{radius:c,reach:c*(1+l),smoothing:l}},Un=(e,t)=>{let{radius:n,reach:r,smoothing:i}=e,a=O(t([r,0]));if(n===0)return`L${a}`;let o=i*zn/2,s=n*(1-Math.sin(o)),c=n*(1-Math.cos(o)),l=o===0?0:c/Math.tan(o),u=(r-s-l)/3,d=O(t([r-2*u,0])),f=O(t([s+l,0])),p=O(t([s,c])),m=O(t([c,s])),h=O(t([0,s+l])),g=O(t([0,r-2*u])),_=O(t([0,r]));return`L${a}C${d} ${f} ${p}${i===1?``:`A${Vn(n)} ${Vn(n)} 0 0 1 ${m}`}C${h} ${g} ${_}`},Wn=(e,t)=>{let{topLeft:n,topRight:r,bottomRight:i,bottomLeft:a,smoothing:o=0}=e;return[Hn(n,[r,a],t,o),Hn(r,[n,i],t,o),Hn(i,[a,r],t,o),Hn(a,[i,n],t,o)]},Gn=(e,t)=>{let[n,r,i,a]=Wn(e,{width:Math.max(0,t.width),height:Math.max(0,t.height)});return{topLeft:n.radius,topRight:r.radius,bottomRight:i.radius,bottomLeft:a.radius}},Kn=(e,t,n=[0,0])=>{let r=Math.max(0,t.width),i=Math.max(0,t.height);if(r===0||i===0)return`M0 0Z`;let[a,o,s,c]=Wn(e,{width:r,height:i});return[`M${O([n[0],a.reach+n[1]])}`,Un(a,([e,t])=>[t+n[0],e+n[1]]),Un(o,([e,t])=>[r-e+n[0],t+n[1]]),Un(s,([e,t])=>[r-t+n[0],i-e+n[1]]),Un(c,([e,t])=>[e+n[0],i-t+n[1]]),`Z`].join(``)},qn=1e5,Jn=.01,Yn=1e-9,k=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],A=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Xn=(e,t)=>e[0]*t[1]-e[1]*t[0],j=(e,t)=>[e[0]-t[0],e[1]-t[1]],Zn=e=>String(Math.round(e*qn)/qn),Qn=(e,t,n=0)=>{let[r,i,a,o]=e,s=A(r,o);if(n>=16||A(r,i)+A(i,a)+A(a,o)-s<=Jn/8){t.push(o);return}let c=k(r,i),l=k(i,a),u=k(a,o),d=k(c,l),f=k(l,u),p=k(d,f);Qn([r,c,d,p],t,n+1),Qn([p,f,u,o],t,n+1)},$n=(e,t,n,r)=>{let i=j(t,e),a=A(e,t);if(a<Yn)return;let o=Math.sqrt(Math.max(0,n*n-a*a/4)),s=[(e[0]+t[0])/2-i[1]*o/a,(e[1]+t[1])/2+i[0]*o/a],c=Math.atan2(e[1]-s[1],e[0]-s[0]),l=Math.atan2(t[1]-s[1],t[0]-s[0])-c;l<0&&(l+=2*Math.PI);let u=Math.max(1,Math.ceil(l/(2*Math.acos(Math.max(-1,1-Jn/n)))));for(let e=1;e<=u;e+=1){let t=c+l*e/u;r.push([s[0]+n*Math.cos(t),s[1]+n*Math.sin(t)])}},er=e=>{let t=e.match(/[MLCAZ]|-?(?:\d*\.)?\d+(?:e[-+]?\d+)?/giu)??[],n=[],r=0,i=()=>Number(t[r++]),a=()=>[i(),i()],o=e=>{let t=n.at(-1)??[0,0];if(e===`M`||e===`L`){n.push(a());return}if(e===`C`){Qn([t,a(),a(),a()],n);return}if(e===`A`){let e=i();r+=4,$n(t,a(),e,n)}};for(;r<t.length;)o(t[r++]??`Z`);return n.filter((e,t)=>A(e,n[(t+1)%n.length]??e)>Yn)},tr=(e,t,n)=>{let[r,i]=j(t,e),a=Math.hypot(r,i),o=[i*n/a,-r*n/a];return[[e[0]+o[0],e[1]+o[1]],[t[0]+o[0],t[1]+o[1]]]},nr=(e,t,n,r)=>{let i=j(t,e),a=j(r,n),o=Xn(i,a);if(Math.abs(o)<Yn)return k(t,n);let s=Xn(j(n,e),a)/o;return[e[0]+s*i[0],e[1]+s*i[1]]},rr=(e,t)=>{let n=[...e];for(let[r,i]of e.entries()){let a=e[(r+1)%e.length];if(a===void 0)continue;let[o,s]=tr(i,a,t),c=j(s,o),l=[];for(let[e,t]of n.entries()){let r=n[(e+1)%n.length]??t,i=Xn(c,j(t,o))>=-1e-9,a=Xn(c,j(r,o))>=-1e-9;i&&l.push(t),i!==a&&l.push(nr(t,r,o,s))}if(n=l,n.length===0)break}return n},ir=(e,t)=>{if(t===0)return e;let n=er(e),r=t<0?rr(n,t):n.map((e,r)=>{let i=n[(r+n.length-1)%n.length]??e,a=n[(r+1)%n.length]??e,o=tr(i,e,t),s=tr(e,a,t);return nr(...o,...s)});return r.length<3?``:r.map((e,t)=>`${t===0?`M`:`L`}${Zn(e[0])} ${Zn(e[1])}`).join(``)+`Z`},ar=(e,t,n)=>t.width<=0||t.height<=0?``:ir(Kn(e,t),n),or=(e,t,n)=>{let r=(t.rotation??0)*Math.PI/180,i=Math.cos(r),a=Math.sin(r),o=t.flipHorizontal===!0?-1:1,s=t.flipVertical===!0?-1:1,c=i*o,l=a*o,u=-a*s,d=i*s,f=n===void 0?c:c*n.a+u*n.b,p=n===void 0?l:l*n.a+d*n.b,m=n===void 0?u:c*n.c+u*n.d,h=n===void 0?d:l*n.c+d*n.d,g=e.width/2,_=e.height/2;return{a:f,b:p,c:m,d:h,e:e.x+g-f*g-m*_,f:e.y+_-p*g-h*_}},sr=e=>{let t=e.additionalStyles?.declarations.find(e=>e.enabled&&e.property===`--enhance-group-affine-residual`)?.value;if(t===void 0)return;let n=/^matrix\(([^)]*)\)$/iu.exec(t)?.[1]?.split(`,`).map(e=>Number(e.trim()));if(n?.length!==6||n.some(e=>!Number.isFinite(e)))return null;let[r,i,a,o]=n;return r===void 0||i===void 0||a===void 0||o===void 0?null:{a:r,b:i,c:a,d:o}},cr=e=>{let t=sr(e);return t===null||e.box===void 0?null:or(e.box,e.layout??{},t)},M=(e,t,n)=>({x:e.x+t.x*n,y:e.y+t.y*n}),lr=e=>`${String(e.x)} ${String(e.y)}`,ur=(e,t,n)=>({x:(t.x-e.x)/n,y:(t.y-e.y)/n}),dr=(e,t,n)=>{let r=e.innerRatio!==void 0,i=e.count,a=e.innerRatio??1,o=r?i*2:i;return Array.from({length:o},(e,r)=>{let i=r%2==0?1:a,s=-Math.PI/2+r*Math.PI*2/o;return{x:t/2+Math.cos(s)*t*i/2,y:n/2+Math.sin(s)*n*i/2}})},fr=(e,t)=>{let n=e[t],r=e[(t+e.length-1)%e.length],i=e[(t+1)%e.length];if(n===void 0||r===void 0||i===void 0)return;let a=Math.hypot(r.x-n.x,r.y-n.y),o=Math.hypot(i.x-n.x,i.y-n.y);if(a===0||o===0)return;let s=ur(n,r,a),c=ur(n,i,o),l=Math.acos(Math.min(1,Math.max(-1,s.x*c.x+s.y*c.y)));if(l!==0&&l!==Math.PI)return{vertex:n,before:s,after:c,previousLength:a,nextLength:o,angle:l,cotangent:1/Math.tan(l/2)}},pr=(e,t,n,r)=>{let i=n*e.cotangent,a=M(e.vertex,t,i*(1+r)),o=M(e.vertex,t,i),s=M(e.vertex,{x:e.before.x+e.after.x,y:e.before.y+e.after.y},n/Math.sin(e.angle)),c=ur(o,s,n),l=(Math.PI-e.angle)*r/2,u=M(M(o,t,-n*Math.sin(l)),c,n*(1-Math.cos(l))),d={x:-t.x*Math.cos(l)+c.x*Math.sin(l),y:-t.y*Math.cos(l)+c.y*Math.sin(l)},f=M(u,d,-n*Math.tan(l/2));return{start:a,first:{x:a.x+(f.x-a.x)*2/3,y:a.y+(f.y-a.y)*2/3},second:f,end:u,travel:d}},mr=(e,t,n)=>{let r=pr(e,e.before,t,n),i=pr(e,e.after,t,n),a=4/3*t*Math.tan((Math.PI-e.angle)*(1-n)/4),o=M(r.end,r.travel,a),s=M(i.end,i.travel,a),c=(e,t,n)=>`C${lr(e)} ${lr(t)} ${lr(n)}`;return lr(r.start)+(n>0?c(r.first,r.second,r.end):``)+c(o,s,i.end)+(n>0?c(i.second,i.first,i.start):``)},hr=(e,t,n)=>{let r=e.map((t,n)=>fr(e,n)),i=e=>typeof t==`number`?t:t[e]??0;return`${e.map((t,a)=>{let o=r[a],s=(a+e.length-1)%e.length,c=(a+1)%e.length,l=r[s],u=r[c],d=i(a),f=a===0?`M`:`L`;if(d===0||o===void 0)return f+lr(t);let p=Math.min(o.previousLength/(o.cotangent+(l?.cotangent??0)*(i(s)/d)),o.nextLength/(o.cotangent+(u?.cotangent??0)*(i(c)/d))),m=Math.min(d,p),h=Math.min(n,Math.max(0,p/m-1));return f+mr(o,m,h)}).join(``)}Z`},gr=(e,t,n)=>hr(dr(e,t,n),e.cornerRadius,e.cornerSmoothing),_r=new WeakMap,vr=new WeakMap,yr=e=>{if(vr.has(e))return vr.get(e)??null;let t=e.result.path.match(/M[^M]*/gu)??[],n=t.map(e=>{let t=Rn(e);return{path:e,vertices:t!==null&&t.length>=3?t:null}}),r=t.length>0&&t.join(``)===e.result.path?n:null;return vr.set(e,r),r},br=(e,t,n)=>{let r={kind:`path`,path:e.result.path,fillRule:e.result.fillRule,viewBox:{x:0,y:0,width:t.width,height:t.height}};if(n===void 0||n.topLeft===0||[n.topRight,n.bottomLeft,n.bottomRight].some(e=>e!==n.topLeft))return r;let i=yr(e);return i===null?r:{...r,path:i.map(e=>e.vertices===null?e.path:hr(e.vertices,n.topLeft,n.smoothing??0)).join(``)}},xr=e=>{if(_r.has(e))return _r.get(e)??null;let t=Rn(e.path),n=t?.length===4&&t.every((e,n)=>{let r=t[(n+1)%4],i=t[(n+2)%4];return r!==void 0&&i!==void 0&&(r.x-e.x)*(i.y-r.y)>(r.y-e.y)*(i.x-r.x)})?t:null;return _r.set(e,n),n},Sr=(e,t,n)=>{if(n.width<=0||n.height<=0)return e;let r=[t.topLeft,t.topRight,t.bottomRight,t.bottomLeft];if(r.every(e=>e===0)&&e.viewBox.x===0&&e.viewBox.y===0&&n.width===e.viewBox.width&&n.height===e.viewBox.height)return e;let i=xr(e);if(i===null)return e;let a=i.map(t=>({x:(t.x-e.viewBox.x)*n.width/e.viewBox.width,y:(t.y-e.viewBox.y)*n.height/e.viewBox.height}));return{...e,path:hr(a,r,t.smoothing??0),viewBox:{x:0,y:0,width:n.width,height:n.height}}},Cr={topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},wr=[`border-top-left-radius`,`border-top-right-radius`,`border-bottom-right-radius`,`border-bottom-left-radius`],Tr=(e,t)=>{if(e===void 0)return 0;if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:null;let n=/^\s*(\d+(?:\.\d+)?)(px|%)?\s*$/u.exec(e);if(n===null)return null;let r=Number(n[1]);return n[2]===`%`?t*r/100:r},Er=e=>{if(e.appearance?.radius!==void 0)return e.appearance.radius;if(e.box===void 0)return null;let t=e.styles[`border-radius`],[n,r,i,a]=wr.map(n=>Tr(e.styles[n]??t,Math.min(e.box?.width??0,e.box?.height??0)));return n===null||r===null||i===null||a===null?null:{topLeft:n??0,topRight:r??0,bottomRight:i??0,bottomLeft:a??0}},Dr=(e,t)=>{let n=e/2,r=t/2;return`M0 ${String(r)}A${String(n)} ${String(r)} 0 1 0 ${String(e)} ${String(r)}A${String(n)} ${String(r)} 0 1 0 0 ${String(r)}Z`},Or=(e,t)=>{if(e.geometry?.kind===`path`)return e.geometry;let n=e.box;if(n!==void 0&&e.geometry?.kind===`polygon`&&n.width>0&&n.height>0)return{kind:`path`,path:gr(e.geometry,n.width,n.height),fillRule:`nonzero`,viewBox:{x:0,y:0,width:n.width,height:n.height}};if(n===void 0||![`rectangle`,`frame`].includes(e.component)||n.width<=0||n.height<=0)return`Choose a closed shape or an editable vector path.`;let r=Er(e);return r===null?`This shape uses a corner expression that cannot be edited as a path.`:{kind:`path`,fillRule:`nonzero`,path:e.styles[`border-radius`]===`50%`&&e.appearance?.radius===void 0&&wr.every(t=>e.styles[t]===void 0)?Dr(n.width,n.height):Kn(t&&e.component===`rectangle`&&e.appearance?.radius!==void 0?Cr:{...Cr,...r},n),viewBox:{x:0,y:0,width:n.width,height:n.height}}},kr=e=>{if(e.geometry?.kind===`boolean`&&e.box!==void 0)return e.geometry.result.isEmpty?`This shape has no closed geometry.`:br(e.geometry,e.box,e.appearance?.radius);let t=Or(e,!1);return typeof t!=`string`&&e.geometry?.kind===`path`&&e.component===`rectangle`&&e.appearance?.radius!==void 0&&e.box!==void 0?Sr(t,e.appearance.radius,e.box):t},Ar=e=>{let t=kr(e);if(typeof t==`string`)return t;if(e.box===void 0)return`The shape has no settled local box.`;let n=cr(e);if(n===null)return`The shape has an invalid affine transform.`;let r=e.box.width/t.viewBox.width,i=e.box.height/t.viewBox.height;return{path:t.path,fillRule:t.fillRule,matrix:[n.a*r,n.b*r,n.c*i,n.d*i,n.e-n.a*r*t.viewBox.x-n.c*i*t.viewBox.y,n.f-n.b*r*t.viewBox.x-n.d*i*t.viewBox.y]}},jr=.5,Mr=.25,Nr=(e,t=`field`,n)=>{let r=kn(e,n),i=Math.max(jr,...r.map(e=>Math.abs(e-jr)))+1,a=jr-i,o=jr+i,s=[{x:.75,y:.75,points:`.5,.5 ${String(o)},.5 ${String(o)},${String(o)} .5,${String(o)}`},{x:Mr,y:.75,points:`.5,.5 .5,${String(o)} ${String(a)},${String(o)} ${String(a)},.5`},{x:Mr,y:Mr,points:`.5,.5 ${String(a)},.5 ${String(a)},${String(a)} .5,${String(a)}`},{x:.75,y:Mr,points:`.5,.5 .5,${String(a)} ${String(o)},${String(a)} ${String(o)},.5`}],c=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${D({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``),l=s.map((e,n)=>`<linearGradient id="${t}-${String(n)}" gradientUnits="userSpaceOnUse" x1=".5" y1=".5" x2="${String(e.x)}" y2="${String(e.y)}" color-interpolation="sRGB">${c}</linearGradient>`).join(``),u=s.map((e,n)=>`<polygon points="${e.points}" fill="url(#${t}-${String(n)})" shape-rendering="crispEdges" />`).join(``);return`<defs>${l}</defs><g transform="matrix(${e.transform.map(String).join(` `)})">${u}</g>`},Pr=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Nr(e)}</svg>`,Fr=e=>e.parameter===`radius`?e.value/2:e.value,Ir=e=>{switch(e.kind){case`blur`:return`blur(${String(Fr(e))}px)`;case`brightness`:case`contrast`:case`saturate`:return`${e.kind}(${String(e.value)})`;case`grayscale`:case`invert`:case`sepia`:return`${e.kind}(${String(e.value*100)}%)`;case`hue-rotate`:return`hue-rotate(${String(e.value)}deg)`}},Lr=e=>e.filter(e=>e.visible).map(e=>Ir(e)).join(` `),Rr=new Set([`base`,`embed`,`iframe`,`link`,`meta`,`object`,`script`]),zr=/^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu,Br=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,Vr=e=>!Rr.has(e.toLowerCase()),Hr=e=>!Br.test(e),Ur=(e,t)=>{let n=e.toLowerCase();return n===`srcdoc`||/^on/iu.test(n)?!1:n===`style`?Hr(t):![`href`,`src`,`action`,`formaction`,`xlink:href`].includes(n)||!zr.test(t.replaceAll(/[\p{Control}\s]/gu,``))},Wr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gr=(e,t)=>{if(!Wr(e)||e.kind!==`image`||typeof e.assetId!=`string`)return e;let n=t(e.assetId);return n===e.assetId?e:{...e,assetId:n}},Kr=(e,t)=>{let n=Gr(e,t);if(!Wr(n)||!Wr(n.alternatives))return n;let r=n.alternatives,i=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,Gr(n,t)]));return Object.entries(i).every(([e,t])=>r[e]===t)?n:{...n,alternatives:i}},qr=(e,t)=>Array.isArray(e)?e.map(e=>{if(!Wr(e)||e.kind!==`span`)return e;let n=Array.isArray(e.fills)?e.fills:void 0;return{...e,...n!==void 0&&{fills:n.map(e=>Kr(e,t))},...Wr(e.stroke)&&{stroke:{...e.stroke,paint:Kr(e.stroke.paint,t)}},...Array.isArray(e.children)&&{children:qr(e.children,t)}}}):e,Jr=(e,t)=>{let n=e.appearance,r=e.props?.src;return{...e,...n!==void 0&&{appearance:{...n,...n.fills!==void 0&&{fills:n.fills.map(e=>Kr(e,t))},...n.border!==void 0&&{border:{...n.border,paints:n.border.paints.map(e=>Kr(e,t))}},...n.outline!==void 0&&{outline:{...n.outline,paints:n.outline.paints.map(e=>Kr(e,t))}}}},...e.typography?.stroke!==void 0&&{typography:{...e.typography,stroke:{...e.typography.stroke,paint:Kr(e.typography.stroke.paint,t)}}},...e.props!==void 0&&{props:{...e.props,...e.component===`image`&&typeof r==`string`&&{src:t(r)},...e.component===`text`&&e.props.richText!==void 0&&{richText:qr(e.props.richText,t)}}}}},Yr=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${D({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``);return`<linearGradient id="${t}" gradientUnits="${n}" x1="0" y1=".5" x2="1" y2=".5" gradientTransform="matrix(${e.transform.map(String).join(` `)})" color-interpolation="sRGB">${r}</linearGradient>`},Xr=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${Yr(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,Zr=e=>({id:e,visible:!1,opacity:1,kind:`solid`,color:{space:`srgb`,red:0,green:0,blue:0,alpha:0}}),Qr=()=>({opacity:1,blendMode:`normal`,fills:[],border:{visible:!1,width:{top:0,right:0,bottom:0,left:0},style:`solid`,paints:[Zr(`empty-border`)]},outline:{visible:!1,width:0,offset:0,style:`solid`,paints:[Zr(`empty-outline`)]},radius:{topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},shadows:[],filters:[],backdropFilters:[]}),$r=e=>e.transform??[e.radius.x*2,0,0,e.radius.y*2,e.center.x-e.radius.x,e.center.y-e.radius.y],ei=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${D({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``);return`<radialGradient id="${t}" gradientUnits="${n}" cx=".5" cy=".5" r=".5" gradientTransform="matrix(${$r(e).map(String).join(` `)})" color-interpolation="sRGB">${r}</radialGradient>`},ti=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${ei(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,ni=/^enh_[\w-]{43}$/,ri=e=>{let t=Pe.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new x(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:t.person.id,displayName:t.person.displayName,tokenId:t.authentication.tokenId,tokenLabel:t.authentication.tokenLabel,expiresAt:t.authentication.expiresAt}},ii=(e,t,n)=>({loginWithToken:async n=>{if(!ni.test(n))throw new x(`BAD_REQUEST`,`Agent tokens begin with enh_ and contain 32 base64url bytes.`,`Pass a manual token from Settings to 'enhance auth login' through stdin.`);let r=ri(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=Be.parse(await t.authenticationConfig());if(i.method===`token`)throw new x(`BAD_REQUEST`,`Browser authentication is not configured for this Enhance environment.`,`Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.`);let a=await n.authorize({issuer:i.issuer,clientId:i.clientId,scope:i.scope,openBrowser:r.openBrowser,onReady:r.onReady,...r.signal!==void 0&&{signal:r.signal}});r.signal?.throwIfAborted();let o=be.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=ri(await t.queryWithToken(`person.me`,{},o.token));return r.signal?.throwIfAborted(),await e.write(o.token),s},status:async(n=t)=>{if(await e.read()===null)throw new x(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return ri(await n.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),ai=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),oi=e=>{if(e.byteLength<24||ai.some((t,n)=>e[n]!==t))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}},si=async(e,t)=>{if(t.result.canvasId!==t.canvasId||t.result.requestedVersion!==t.requestedVersion||t.result.loadedVersion!==t.requestedVersion||JSON.stringify(t.result.target)!==JSON.stringify(t.target))throw new x(`INTERNAL`,`The completed render evidence does not match its requested canvas, revision or target.`,`Do not use the image. Report render job ${t.id}.`);if(t.maxOutputPixels!==void 0&&t.result.width*t.result.height>t.maxOutputPixels)throw new x(`INTERNAL`,`The completed render exceeds its authorised output pixel limit.`,`Do not use the image. Report render job ${t.id}.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});let n=qe.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success||n.data.jobId!==t.id||n.data.download.bytes!==t.result.bytes)throw new x(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let r=await e.download(n.data.download.url),i=oi(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new x(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return{body:r,...n.data.source!==void 0&&{source:n.data.source}}},ci=e=>{let t=`enhance canvas inspect --canvas ${e.canvasId}`;return e.result.sourceState===void 0?e.target.kind===`node`?[t,`enhance canvas node --canvas ${e.canvasId} --node-id ${e.target.nodeId}`]:[t]:[`Inspect the PNG at path before persisting this moment.`,`enhance recording snapshot --canvas ${e.canvasId} --recording-id ${e.result.sourceState.recordingId} --at-ms ${String(e.result.sourceState.settledAtMs)}`,t]},li=(e,t,n)=>({...n!==void 0&&{source:n},jobId:e.id,operation:{kind:`canvas-render`,canvasId:e.canvasId,jobId:e.id},canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:ci(e)}),ui=async(e,t,n,r)=>{let i=await si(e,n);return li(n,t.write({body:i.body,...r}),i.source)},di=[`canvas.render.create`,`canvas.render.get`],fi=e=>new x(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),pi=e=>{let t=e.failure;if(t===null)return fi(`render job`);let n=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,r=t.reason===`VERSION_CHANGED`?`Run 'enhance canvas inspect --canvas ${e.canvasId}', then render its returned version.`:t.reason===`TARGET_NOT_FOUND`?`Run 'enhance canvas tree --canvas ${e.canvasId}' and choose a current node id.`:t.retryable?"Retry the render. If it repeats, run `enhance doctor` and report the job id.":`Change the target or scale using the failure details, then retry.`;return new x(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase,renderState:e.state})},mi=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),hi=async(e,t)=>{let n=lt.safeParse(await e.query(di[1],{jobId:t}));if(!n.success||n.data.job.id!==t)throw fi(`render status`);return n.data.job},gi=async(e,t)=>{let n=Date.now(),r=0,i=``,a=t.initial;for(;a.state===`queued`||a.state===`running`;){let o=Date.now(),s=`${a.state}:${a.phase}`;if((s!==i||o-r>=5e3)&&(t.progress({event:`render.progress`,jobId:a.id,state:a.state,phase:a.phase,elapsedMs:o-n,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),r=o,i=s),o>=t.deadline){if(t.timeoutOutcome===`pending`)return a;throw new x(`INTERNAL`,`Render ${a.id} did not finish before the local timeout.`,`Retry the exact command with --client-token ${t.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`,{jobId:a.id,phase:a.phase})}await mi(250),a=a.purpose===`inspection`&&a.state===`queued`&&a.attempt>0?await t.resume():await hi(e,a.id)}if(a.state!==`succeeded`)throw pi(a);return a},_i=async(e,t)=>{let n=dt.safeParse(await e.mutate(di[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.scope!==void 0&&{scope:t.scope},...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,...t.maxOutputPixels!==void 0&&{maxOutputPixels:t.maxOutputPixels},format:`png`}));if(!n.success)throw fi(`render creation`);if(n.data.job.canvasId!==t.canvasId||t.expectedVersion!==null&&n.data.job.requestedVersion!==t.expectedVersion||JSON.stringify(n.data.job.target)!==JSON.stringify(t.target)||n.data.job.scale!==t.scale)throw fi(`render identity`);return n.data.job},vi=(e,t)=>{if(t.maxOutputPixels!==void 0&&e.maxOutputPixels!==t.maxOutputPixels)throw new x(`INTERNAL`,`This API does not preserve the requested render pixel budget.`,`Update the API and renderer together before rendering a batch.`,{reason:`RENDER_BUDGET_UNSUPPORTED`})},yi=async(e,t)=>{let n=await _i(e.remote,t);try{vi(n,t);let r=await gi(e.remote,{initial:n,resume:async()=>_i(e.remote,t),deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress,timeoutOutcome:t.timeoutOutcome});return vi(r,t),r.state===`succeeded`?await ui(e.remote,e.files,r,{outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()}):{state:r.state,phase:r.phase,canvasId:r.canvasId,requestedVersion:r.requestedVersion,target:r.target,operation:{kind:`canvas-render`,canvasId:r.canvasId,jobId:r.id},pixelsDelivered:!1,next:[`Read operation_status with includeImage true. Do not create another render.`,`If it stays queued with attempt above 0, an attempt failed: repeat this exact request with the same clientToken to retry it.`]}}catch(e){let r=JSON.stringify({kind:`canvas-render`,canvasId:t.canvasId,jobId:n.id});throw e instanceof x?new x(e.code,e.message,e.remediation,{...e.fields,jobId:n.id,operation:r}):new x(`INTERNAL`,`The native render outcome could not be confirmed.`,`Read operation_status or retry with the identical request and clientToken.`,{jobId:n.id,operation:r})}},bi=(e,t,n,r=()=>null)=>({execute:async i=>yi({remote:e,files:t,now:n,progress:r},i)}),xi={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},Si=async e=>{try{return await e(),!0}catch{return!1}},Ci=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await Si(async()=>e.mutate(xi.renew,{...i,nodeIds:[...i.nodeIds],activityId:n})),o=!1)},c=setInterval(()=>void s(),r);return{activityId:n,update:async e=>{a||(i={...i,...e},await s())},finish:async()=>{a||(a=!0,clearInterval(c),await Si(async()=>e.mutate(xi.end,{canvasId:i.canvasId,activityId:n})))}}},wi=e=>({begin:async t=>{try{let n=fe.safeParse(await e.mutate(xi.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?Ci(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>Si(async()=>e.mutate(xi.end,{canvasId:t,activityId:n}))}),Ti=new Set([`insertPrototype`,`insertText`,`setBox`]),Ei=e=>Ti.has(e.op),Di=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,Oi=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],ki=e=>[...new Set(e.operations.flatMap(e=>Oi(e)))].slice(0,100),Ai=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:Ei(e)?e.box==="default"?null:e.box:null,ji=e=>{let t=e[0];if(t===void 0)return null;let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}},Mi=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:14}),r=v.safeParse(n);if(!r.success)throw new x(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},Ni=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Mi(e,t);let r=await wi(e).begin({canvasId:t.canvasId,phase:Di(t),nodeIds:ki(t),bounds:ji(t.operations.flatMap(e=>{let t=Ai(e);return t===null?[]:[t]}))});try{return await Mi(e,t)}finally{await r?.finish()}}}),Pi=async(e,t,n)=>{let r=ze.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!r.success)throw new x(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(r.data.version!==n)throw new x(`CONFLICT`,`Canvas version ${String(r.data.version)} no longer matches --base-version ${String(n)}.`,`An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(r.data.version)} before submitting a new edit.`);let i=St.safeParse(r.data.document);if(i.success)return i.data;throw new x(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},Fi=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):xn(t.sortKey,r.sortKey)).map(([e])=>e),Ii=e=>{let t=new Map;for(let[n,r]of Object.entries(e.relationships)){let e=t.get(r.parentId)??[];e.push(n),t.set(r.parentId,e)}for(let n of t.values())n.sort((t,n)=>{let r=e.relationships[t]?.sortKey??``,i=e.relationships[n]?.sortKey??``;return r===i?t.localeCompare(n):r.localeCompare(i)});return t},Li=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),N=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new x(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Ri=(e,t)=>{let n=new Set,r=t=>{for(let i of Fi(e,t))n.add(i),r(i)};return r(t),n},zi=(e,t)=>{let n=new Set,r=t;for(;r!==void 0;){if(n.has(r))throw new x(`BAD_REQUEST`,`The canvas contains a parent cycle.`,`Repair the canvas topology before editing.`);if(n.add(r),N(e,r).locked===!0)return!0;r=e.relationships[r]?.parentId}return!1},Bi=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},Vi=e=>{let t=0;return n=>(t+=1,`${Bi(e)}_${Bi(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},Hi=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of Fi(e,t))r(n)};return r(t),n},Ui=(e,t,n)=>Object.fromEntries(Hi(e,t).map(t=>[t,n(N(e,t).label)])),Wi=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=N(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Gi=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=N(t,n.id);if(n.id===`root`)throw new x(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let o=t.relationships[n.id];if(o===void 0)throw new x(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!Li(t.nodes[s]))throw new x(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=Ui(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=Hi(t,n.id).map(e=>Wi(l,e)),d=c[n.id];if(d===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:u,summary:{sourceId:n.id,newId:d,name:a.label,component:a.component,descendantIdMap:Object.fromEntries(Object.entries(c).filter(([e])=>e!==n.id))}}},Ki=(e,t,n)=>{if(t.length===0)throw new x(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=Vi(n),i=t.map((t,n)=>Gi({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},qi=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,Fi(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Ji=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},Yi=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new x(`BAD_REQUEST`,`Sibling ${n} is not a valid move target.`,`Choose another current sibling node.`);let r=t.parentOf.get(n);if(r===void 0)throw new x(`BAD_REQUEST`,`Sibling ${n} is detached.`,`Choose a reachable sibling from canvas tree.`);let i=(t.children.get(r)??[]).filter(t=>t!==e.nodeId).indexOf(n);return{parentId:r,index:`before`in e?i:i+1}},Xi=(e,t)=>`parentId`in e?Ji(e,t):Yi(e,t),Zi=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new x(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Ri(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!Li(n.document.nodes[t.parentId]))throw new x(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Qi=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]],a=[],o={...n.document.relationships},s=e=>{let t=i[e];return t===void 0?null:o[t]?.sortKey??null},c=null;try{let e=s(t.index-1),n=s(t.index),r=It(e,n);(e===null||e.localeCompare(r)<0)&&(n===null||r.localeCompare(n)<0)&&(c=r)}catch{c=null}if(c===null){let n=[...i];n.splice(t.index,0,e.nodeId);let r=Lt(null,null,n.length).toSorted((e,t)=>e.localeCompare(t));for(let[e,i]of n.entries()){let n=r[e];if(n===void 0)throw Error(`Missing generated move sort key.`);let s={parentId:t.parentId,sortKey:n};o[i]=s,a.push({op:`setParentage`,nodeId:i,parentage:s})}}else{let n={parentId:t.parentId,sortKey:c};o[e.nodeId]=n,a.push({op:`setParentage`,nodeId:e.nodeId,parentage:n})}return i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId),{operations:a,document:{...n.document,relationships:o}}},$i=(e,t)=>{if(t.length===0)throw new x(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=qi(e),r=[];return{operations:t.flatMap(e=>{let t=Xi(e,n);Zi(e,t,n),r.push({nodeId:e.nodeId,...t});let i=Qi(e,t,n);return n.document=i.document,i.operations}),moves:r,affectedParents:Array.from(n.affected,e=>({parentId:e,children:[...n.children.get(e)??[]]}))}},P=e=>Math.min(1,Math.max(0,e)),ea=e=>P(Number(e)/255),ta=e=>{let t=e.slice(1);if(![3,4,6,8].includes(t.length)||!/^[\da-f]+$/iu.test(t))return null;let n=t.length<=4?t.replaceAll(/([\da-f])/giu,`$1$1`):t,r=e=>Number.parseInt(n.slice(e,e+2),16)/255;return{space:`srgb`,red:r(0),green:r(2),blue:r(4),alpha:n.length===8?r(6):1}},na=e=>{let t=/^rgba?\(\s*([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*[,/]\s*([\d.]+)(%?))?\s*\)$/iu.exec(e);if(t===null)return null;let n=(e,t)=>t===`%`?P(Number(e)/100):ea(e??`0`),r=t[7]===void 0?1:P(Number(t[7])/(t[8]===`%`?100:1));return{space:`srgb`,red:n(t[1],t[2]),green:n(t[3],t[4]),blue:n(t[5],t[6]),alpha:r}},ra=e=>{let t=/^color\(\s*(srgb|display-p3)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\s*\)$/iu.exec(e);return t===null?null:{space:t[1]===`display-p3`?`display-p3`:`srgb`,red:P(Number(t[2])),green:P(Number(t[3])),blue:P(Number(t[4])),alpha:P(t[5]===void 0?1:Number(t[5]))}},ia=e=>{let t=e.trim().toLowerCase();return t===`transparent`?{space:`srgb`,red:0,green:0,blue:0,alpha:0}:t.startsWith(`#`)?ta(t):t.startsWith(`rgb`)?na(t):t.startsWith(`color(`)?ra(t):null},aa=(e,t)=>({id:e,visible:!0,opacity:1,kind:`solid`,color:t}),F=(e,t)=>{let n=ia(t);return n===null?null:aa(e,n)},oa=e=>e/2**32|0,sa=e=>e>>>0;function ca(e,t,n,r){let i=oa(n),a=sa(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function la(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const ua=e=>e?`"${e}" `:``;function da(e,t=``){if(typeof e!=`number`)throw TypeError(ua(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ua(t)+`expected integer >= 0, got `+e);return e}function fa(e,t,n=``){if(la(e)&&(t===void 0||e.length===t))return e;t!==void 0&&da(t,`length`);let r=la(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ua(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const pa=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)};function ma(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function ha(e,t){fa(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function ga(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _a(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function I(e,t){return e<<32-t|e>>>t}const va=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,ya=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ba(e){if(fa(e),va)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=ya[e[n]];return t}function xa(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function Sa(e,t,n=`opts`){return pa(e,`defaults`),t!==void 0&&pa(t,n),Object.assign(e,t)}function Ca(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=Sa({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}const wa=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ta(e,t,n){return e&t^~e&n}function Ea(e,t,n){return e&t^e&n^t&n}var Da=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=_a(this.buffer)}update(e){ma(this),fa(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=_a(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0;continue}n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){ma(this),ha(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),ca(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:_a(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};const Oa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ka=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),L=new Uint32Array(64);var Aa=class extends Da{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)L[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=L[e-15],n=L[e-2],r=I(t,7)^I(t,18)^t>>>3,i=I(n,17)^I(n,19)^n>>>10;L[e]=i+L[e-7]+r+L[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=I(o,6)^I(o,11)^I(o,25),u=l+t+Ta(o,s,c)+ka[e]+L[e]|0,d=(I(n,2)^I(n,13)^I(n,22))+Ea(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){ga(L)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ga(this.buffer)}},ja=class extends Aa{constructor(){super(32,Oa)}};const Ma=Ca(()=>new ja,wa(1)),Na=new Map,Pa=new Map,Fa={depth:0},Ia=(e,t=1)=>{let n=Fa.depth>0?Pa:Na;n.set(e,(n.get(e)??0)+t)},La=(e,t)=>e.sortKey===t.sortKey?e.childId.localeCompare(t.childId):e.sortKey<t.sortKey?-1:1,Ra=e=>{Ia(`child index builds`);let t=new Map;for(let[n,r]of Object.entries(e)){let e={childId:n,sortKey:r.sortKey},i=t.get(r.parentId);i===void 0?t.set(r.parentId,[e]):i.push(e)}let n=new Map;for(let[e,r]of t)n.set(e,r.toSorted(La).map(e=>e.childId));return n},za=new WeakMap,Ba=new WeakMap,Va=e=>{let t=za.get(e);if(t!==void 0)return t;let n=Ba.get(e)?.()??Ra(e);return Object.isFrozen(e)&&za.set(e,n),n},Ha=[],Ua=(e,t)=>e.get(t)??Ha,Wa=(e,t)=>Ua(Va(e),t),Ga=e=>e.trim()===``||e.trim()===`about:blank`,Ka=e=>typeof e==`string`&&e.startsWith(`enhance-pending-image:`),qa=e=>Ka(e.assetId)||e.opacity!==1||e.fit===`crop`&&e.transform!==void 0||(e.rotation??0)!==0||e.fit===`tile`&&(e.tileScale??1)!==1,Ja=e=>`--canvas-image-paint-${ba(Ma(xa(JSON.stringify([e.assetId,e.opacity,e.rotation??0,e.fit===`tile`?e.tileScale??1:1,e.fit===`crop`?e.transform:void 0]))))}`,Ya=e=>`--canvas-text-paints-${ba(Ma(xa(JSON.stringify(e.filter(e=>e.visible),(e,t)=>e===`id`?void 0:t))))}`,Xa=(e,t=1)=>`${D(e.color,t)} ${String(e.position*100)}%`,Za=e=>encodeURI(e).replaceAll(`"`,`%22`),Qa=e=>`url("${Za(e)}")`,$a=e=>{switch(e.kind){case`solid`:{let t=D(e.color,e.opacity);return`linear-gradient(${t}, ${t})`}case`linear-gradient`:return e.transform===void 0?`linear-gradient(${String(e.angle)}deg, ${e.stops.map(t=>Xa(t,e.opacity)).join(`, `)})`:`url("data:image/svg+xml,${encodeURIComponent(Xr({...e,transform:e.transform}))}")`;case`radial-gradient`:{if(e.transform!==void 0)return`url("data:image/svg+xml,${encodeURIComponent(ti(e))}")`;let t=`${String(e.center.x*100)}% ${String(e.center.y*100)}%`;return`radial-gradient(ellipse ${String(e.radius.x*100)}% ${String(e.radius.y*100)}% at ${t}, ${e.stops.map(t=>Xa(t,e.opacity)).join(`, `)})`}case`angular-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Nn(e))}")`;case`diamond-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Pr(e))}")`;case`image`:return Ga(e.assetId)?`none`:qa(e)?`var(${Ja(e)}, none)`:Qa(e.assetId)}},eo=(e,t)=>t>=1?0:e/(1-t)*100,to=e=>{if(e===void 0)return{"background-position":`center`,"background-size":`cover`};let t=Math.max(e.width,2**-52),n=Math.max(e.height,2**-52);return{"background-position":`${String(eo(e.x,t))}% ${String(eo(e.y,n))}%`,"background-size":`${String(100/t)}% ${String(100/n)}%`}},no=e=>{if(e.kind!==`image`)return{"background-size":e.kind===`angular-gradient`||e.kind===`diamond-gradient`||(e.kind===`linear-gradient`||e.kind===`radial-gradient`)&&e.transform!==void 0?`100% 100%`:`auto`,"background-position":`center`,"background-repeat":`no-repeat`,"background-origin":`border-box`};let t={fill:`100% 100%`,cover:`cover`,fit:`contain`,crop:`cover`,tile:`auto`}[e.fit];return{...e.fit===`crop`&&e.transform!==void 0?{"background-position":`0% 0%`,"background-size":`100% 100%`}:e.fit===`crop`?to(e.crop):{"background-position":e.fit===`tile`&&e.tileOrigin===`top-left`?`0% 0%`:`center`,"background-size":t},"background-repeat":e.fit===`tile`?`repeat`:`no-repeat`,"background-origin":`padding-box`}},ro=e=>{if(e.length===0)return{};let t=e.toReversed().map(e=>no(e));return Object.fromEntries([`background-size`,`background-position`,`background-repeat`,`background-origin`].map(e=>[e,t.map(t=>t[e]).join(`, `)]))},io=e=>e.kind===`solid`&&e.visible?D(e.color,e.opacity):void 0,ao=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,oo=e=>ao(e)?void 0:io(e),so=e=>{let t=e.filter(e=>e.visible),[n]=t;return n===void 0||t.length!==1?`transparent`:oo(n)??`transparent`},co=e=>({"background-image":e.toReversed().map(e=>$a(e)).join(`, `),...ro(e)}),lo=e=>{let t=e.filter(e=>e.visible);if(t.length===0||t.some(e=>ao(e)))return{background:`none`};let[n]=t,r=n===void 0?void 0:oo(n);return r!==void 0&&t.length===1?{background:r,"background-image":`none`}:{"background-color":`transparent`,...co(t)}},uo=e=>{let t=e.filter(e=>e.visible),[n]=t;return t.length===1&&n?.kind===`solid`?{color:D(n.color,n.opacity)}:t.length===0?{color:`transparent`}:{color:`transparent`,...t.length>1?{"background-image":`var(${Ya(t)}, none)`,"background-size":`100% 100%`,"background-position":`center`,"background-repeat":`no-repeat`}:co(t),...t.some(e=>e.kind===`image`&&e.fit===`crop`&&e.transform!==void 0)&&{"background-size":`100% var(--canvas-text-paint-height, 100%)`,"background-position":`0% var(--canvas-text-paint-y, 0%)`},"background-clip":`text`,"-webkit-background-clip":`text`}},fo=new Set(e.keyof().options.filter(e=>/^(?:border|outline)(?:-|$)/u.test(e)&&!e.includes(`radius`))),po=(e,t)=>{let n=t.toLowerCase();return fo.has(n)&&(n===e||n.startsWith(`${e}-`))},mo=[`top`,`right`,`bottom`,`left`],ho=[`solid`,`dashed`,`dotted`],go=[`width`,`style`,`color`],_o=(e,t=0)=>{if(e===void 0||!/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?:px)?$/iu.test(e))return;let n=Number(e.replace(/px$/iu,``));if(!(n!==0&&!/px$/iu.test(e)))return Number.isFinite(n)&&n>=t?n:void 0},vo=(e,t)=>{let n=Ve(t);if(/^(?:border(?:-(?:top|right|bottom|left))?|outline)$/u.test(e)){let t=n.find(e=>_o(e)!==void 0),r=n.find(e=>/^(?:none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/u.test(e)),i=n.find(e=>F(`probe`,e)!==null);if(t===void 0||r===void 0||i===void 0||n.length!==go.length)return null;let a=e===`border`?mo.map(e=>`border-${e}`):[e];return Object.fromEntries(a.flatMap(e=>go.map(n=>[`${e}-${n}`,{width:t,style:r,color:i}[n]])))}if(/^border-(?:width|style|color)$/u.test(e)){if(n.length===0||n.length>mo.length)return null;let[t=``,r=t,i=t,a=r]=n;return Object.fromEntries(mo.map((n,o)=>[`border-${n}-${e.slice(7)}`,[t,r,i,a][o]??``]))}return/^(?:border-(?:top|right|bottom|left)-(?:width|style|color)|outline-(?:width|style|color|offset))$/u.test(e)?{[e]:t}:null},yo=(e,t)=>e.additionalStyles?.declarations.filter(({property:n,value:r,enabled:i})=>po(t,n)&&(!i||r.trim()!==``||e.appearance?.[t]===void 0))??[],bo=(e,t)=>{let n=yo(e,t);if(n.some(({enabled:e})=>!e))return null;let r=new Set(n.map(({property:e})=>e.toLowerCase())),i=[...Object.entries(e.styles).filter(([e])=>!r.has(e.toLowerCase())),...n.map(({property:e,value:t})=>[e,t])],a={};for(let[e,n]of i){if(!po(t,e))continue;let r=vo(e.toLowerCase(),wt(e,n).trim());if(r===null||String(n).includes(`!`))return null;Object.assign(a,r)}return a},xo=e=>{let t=bo(e,`border`);if(t===null)return{kind:`custom`};if(e.appearance?.border!==void 0&&yo(e,`border`).length===0)return{kind:`native`,value:e.appearance.border};if(e.appearance?.border!==void 0)return{kind:`custom`};if(Object.keys(t).length===0)return{kind:`absent`};let n=mo.map(n=>({width:_o(t[`border-${n}-width`]??`0`),authoredStyle:t[`border-${n}-style`],authoredColor:t[`border-${n}-color`],style:ho.find(e=>e===t[`border-${n}-style`]),paint:F(`${e.id}-border`,t[`border-${n}-color`]??``)})),r=n.find(e=>e.width!==0)??n[0];if(r?.style===void 0||r.paint===null||n.some(e=>e.width===void 0||e.authoredStyle!==void 0&&e.style===void 0||e.authoredColor!==void 0&&e.paint===null||e.width!==0&&(e.style!==r.style||JSON.stringify(e.paint)!==JSON.stringify(r.paint))||e.width===0&&(e.style!==void 0&&e.style!==r.style||e.paint!==null&&JSON.stringify(e.paint)!==JSON.stringify(r.paint))))return{kind:`custom`};let[i=0,a=0,o=0,s=0]=n.map(e=>e.width);return{kind:`native`,value:{visible:!0,width:{top:i,right:a,bottom:o,left:s},style:r.style,paints:[r.paint]}}},So=e=>{let t=bo(e,`outline`);if(t===null)return{kind:`custom`};if(e.appearance?.outline!==void 0&&yo(e,`outline`).length===0)return{kind:`native`,value:e.appearance.outline};if(e.appearance?.outline!==void 0)return{kind:`custom`};if(Object.keys(t).length===0)return{kind:`absent`};let n=_o(t[`outline-width`]),r=_o(t[`outline-offset`]??`0`,-1/0),i=ho.find(e=>e===t[`outline-style`]),a=F(`${e.id}-outline`,t[`outline-color`]??``);return n===void 0||r===void 0||i===void 0||a===null?{kind:`custom`}:{kind:`native`,value:{visible:!0,width:n,offset:r,style:i,paints:[a]}}},Co=Object.freeze({top:0,right:0,bottom:0,left:0}),R=e=>e.alignment!==void 0&&e.alignment!==`inside`||e.layoutInclusion===`none`||e.layoutInclusion===`visible`&&(!e.visible||e.paints.every(e=>!e.visible))?Co:e.width,wo=e=>{let t=e.visible?so(e.paints):`transparent`,n=R(e);return{"border-style":e.style,"border-top-width":n.top,"border-right-width":n.right,"border-bottom-width":n.bottom,"border-left-width":n.left,"border-color":t}},To=e=>{if(!e.visible)return{"outline-style":`none`};let t=so(e.paints);return{"outline-style":e.style,"outline-width":e.width,"outline-offset":e.offset,"outline-color":t}},Eo=e=>({...e.border!==void 0&&wo(e.border),...e.outline!==void 0&&To(e.outline)}),Do=e=>{if(e.geometry?.kind===`boolean`||(e.appearance?.radius?.smoothing??0)<=0)return!1;let t=xo(e);return t.kind===`custom`||t.kind===`native`&&t.value.style!==`solid`},Oo=(e,t=e.box)=>{let n=e.appearance?.radius;if(n===void 0||t===void 0||e.geometry?.kind===`path`||e.geometry?.kind===`boolean`)return{};if((n.smoothing??0)<=0&&n.topLeft===n.topRight&&n.topLeft===n.bottomRight&&n.topLeft===n.bottomLeft)return ko(n);let r=Gn(n,t),i=ko(r);if((n.smoothing??0)<=0)return i;if(Do(e))return{};let a=`path("${Kn(n,t)}") border-box`,o=xo(e);if(o.kind!==`native`||Object.values(R(o.value)).every(e=>e===0))return{...i,"border-shape":a};let{top:s,right:c,bottom:l,left:u}=R(o.value),d=[r.topLeft,r.topRight,r.bottomRight,r.bottomLeft],f=e=>d.map((t,n)=>`max(0px, ${String(t)}px - ${String(e[n]??0)}px)`).join(` `),p=f([u,c,c,u]),m=f([s,s,l,l]);return{...i,"border-shape":`${a} inset(0 round ${p} / ${m}) padding-box`}},ko=e=>({"border-top-left-radius":e.topLeft,"border-top-right-radius":e.topRight,"border-bottom-right-radius":e.bottomRight,"border-bottom-left-radius":e.bottomLeft}),Ao=new Set([xe,y]),jo=e=>e.visible&&e.kind===`blur`&&e.progression!==void 0,Mo=e=>e.geometry===void 0&&Ao.has(e.component)?(e.appearance?.backdropFilters??[]).find(e=>jo(e))??null:null,No=(e,t)=>{let n=Mo(e);return n===null?t:t.filter(e=>e!==n)},Po=new Set([xe,Mt,y,a]),Fo=new Set([xe,Mt,y]),z=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,Io=e=>!e.visible||e.opacity<=0?!1:e.kind===`solid`?e.color.alpha>0:e.kind===`image`||e.stops.some(e=>e.color.alpha>0),Lo=e=>{let t=e.props?.source;if(typeof t!=`object`||!t)return!1;if(typeof Reflect.get(t,`pseudo`)==`string`)return!0;let n=Reflect.get(t,`layout`);return typeof Reflect.get(t,`path`)==`string`&&typeof n==`object`&&!!n&&typeof Reflect.get(n,`tag`)==`string`},Ro=e=>{if(e.component!==`rectangle`||e.geometry!==void 0||Lo(e))return!1;let{fills:t=[],border:n,outline:r}=e.appearance??{},i=[n,r].filter(e=>e?.visible===!0);return[...t,...i.flatMap(e=>e?.paints??[])].every(e=>!Io(e))},zo=e=>e.geometry===void 0&&Po.has(e.component)&&(e.component!==`image`||(typeof e.props?.src!=`string`||e.props.src===``)&&e.appearance?.fills!==void 0),Bo=e=>e?.visible===!0?e.paints.filter(e=>e.visible):[],Vo=e=>z(e)||e.kind===`image`&&(e.filters?.some(e=>e.visible)??!1),Ho=e=>{if(!zo(e))return[];let t=(e.appearance?.fills??[]).filter(e=>e.visible);return t.some(e=>Vo(e))||t.length>0&&Mo(e)!==null?t:[]},Uo=e=>e.style===`solid`||e.dashOrigin===`css`&&e.dashPattern===void 0&&e.dashCap===void 0,Wo=e=>{let t=Bo(e);return t.length>0&&((e.alignment??`inside`)!==`inside`||!Uo(e)||t.length>1||t.some(e=>e.kind!==`solid`))},Go=(e,t)=>{let n=e.appearance?.border;if(n===void 0||e.geometry!==void 0||!Fo.has(e.component))return[];let r=Bo(n);return r.some(e=>z(e))?r.map(e=>({kind:`border`,paints:[e]})):n.layoutInclusion===`none`||n.layoutInclusion===`visible`||Wo(n)||t&&r.length>0?[{kind:`border`,paints:r}]:[]},Ko=e=>{let[t,...n]=Bo(e.appearance?.outline);return(e.appearance?.radius?.smoothing??0)>0&&n.length===0&&t?.kind===`solid`&&!z(t)},qo=e=>{let t=e.appearance?.outline;if(t===void 0||e.geometry!==void 0||!Fo.has(e.component)||t.width<=0||Ko(e))return[];let n=Bo(t);return n.some(e=>z(e))?n.map(e=>({kind:`outline`,paints:[e]})):n.length>1||t.style!==`solid`||n.some(e=>e.kind!==`solid`)?[{kind:`outline`,paints:n}]:[]},B=e=>{let t=Ho(e),n=zo(e)&&!Ro(e)?(e.appearance?.shadows??[]).filter(e=>e.visible):[],r=n.filter(e=>e.kind===`outer`&&z(e)),i=n.filter(e=>e.kind===`inner`&&(t.length>0||z(e))),a=[...r.map(e=>({kind:`outer-shadow`,shadow:e})),...t.map(e=>({kind:`fill`,paint:e})),...i.map(e=>({kind:`inner-shadow`,shadow:e}))];return{elements:[...a,...Go(e,t.length>0),...qo(e)],hasPaintElements:a.length>0}},Jo=e=>e.elements.flatMap(e=>e.kind===`fill`?[e.paint]:[]),Yo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.shadow]:[]),Xo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.paints]:[]),Zo=(e,t,n={})=>e===`solid`?{dash:void 0,linecap:`butt`}:n.dashPattern===void 0?e===`dotted`?{dash:`0 ${String(t*2)}`,linecap:`round`}:{dash:`${String(t*3)} ${String(t*2)}`,linecap:`butt`}:{dash:n.dashPattern.map(String).join(` `),linecap:n.dashCap===`round`?`round`:n.dashCap===`square`?`square`:`butt`},Qo={top:0,right:0,bottom:0,left:0},$o={inside:0,center:.5,outside:1},es=[[`topLeft`,`top-left`,`left`,`top`],[`topRight`,`top-right`,`right`,`top`],[`bottomRight`,`bottom-right`,`right`,`bottom`],[`bottomLeft`,`bottom-left`,`left`,`bottom`]],ts=e=>Xo(B(e),`border`).length>0,ns=(e,t=e.box)=>{if(!ts(e))return{};let n={"border-color":`transparent`},r=e.appearance?.border,i=e.appearance?.radius;if(i===void 0||t===void 0||r?.style!==`solid`||e.geometry?.kind===`path`)return n;let a=R(r);if((i.smoothing??0)<=0||Object.values(a).every(e=>e===0))return n;let o=Kn(i,t),s=Kn(i,t,[-a.left,-a.top]);return{...n,"border-shape":`path("${o}") border-box path("${s}") padding-box`}},rs=(e,t)=>{let n=e.appearance?.radius;return n===void 0?{"border-radius":`inherit`}:Object.fromEntries(es.map(([e,r,i,a])=>{let o=n[e];return[`border-${r}-radius`,o<=0?0:`${String(o+t[i])}px ${String(o+t[a])}px`]}))},is=1e3,V=e=>String(Math.round(e*is)/is),as=(e,t,n)=>{let r=([n,r])=>[Math.min(n,e/2),Math.min(r,t/2)],[i,a,o,s]=[r(n.topLeft),r(n.topRight),r(n.bottomRight),r(n.bottomLeft)],c=([e,t],n,r)=>e===0||t===0?`L${V(n)} ${V(r)}`:`A${V(e)} ${V(t)} 0 0 1 ${V(n)} ${V(r)}`;return[`M${V(i[0])} 0`,`H${V(e-a[0])}`,c(a,e,a[1]),`V${V(t-o[1])}`,c(o,e-o[0],t),`H${V(s[0])}`,c(s,0,t-s[1]),`V${V(i[1])}`,c(i,i[0],0),`Z`].join(``)},os=e=>{if(e.stroke.style===`solid`)return{};let t=Zo(e.stroke.style,e.widest,e.stroke),n=`<svg xmlns="http://www.w3.org/2000/svg" width="${V(e.width)}" height="${V(e.height)}"><path d="${as(e.width,e.height,e.corners)}" fill="none" stroke="#000" stroke-width="${V(e.widest*2)}" stroke-dasharray="${t.dash??`none`}" stroke-linecap="${t.linecap}"/></svg>`;return{"border-style":`solid`,"mask-image":`url("data:image/svg+xml,${encodeURIComponent(n)}")`,"mask-size":`100% 100%`,"mask-repeat":`no-repeat`,"mask-origin":`border-box`}},ss=(e,t,n,r)=>{if(n===void 0)return{};let i=e.appearance?.radius,a=([e,,t,n])=>{let a=i?.[e]??0;return a<=0?[0,0]:[a+r[t],a+r[n]]};return os({width:n.width+r.left+r.right,height:n.height+r.top+r.bottom,corners:{topLeft:a(es[0]),topRight:a(es[1]),bottomRight:a(es[2]),bottomLeft:a(es[3])},widest:Math.max(...Object.values(t.width)),stroke:t})},cs=(e,t=e.box,n)=>{let r=e.appearance?.border,[i]=Xo(B(e),`border`);if(r===void 0||i===void 0)return null;let a=n??i,o=R(r),s=$o[r.alignment??`inside`],c={top:r.width.top*s,right:r.width.right*s,bottom:r.width.bottom*s,left:r.width.left*s},l={border:{...r,alignment:`inside`,layoutInclusion:`always`},radius:e.appearance?.radius},[u]=a,d=a.length===1&&u?.kind===`solid`&&(u.blendMode??`normal`)===`normal`&&Uo(r)&&s===0;return{position:`absolute`,inset:0,top:-(o.top+c.top),right:-(o.right+c.right),bottom:-(o.bottom+c.bottom),left:-(o.left+c.left),"box-sizing":`border-box`,"pointer-events":`none`,...s===0?{"border-radius":`inherit`}:rs(e,c),...Eo({...l,border:{...l.border,paints:[...a]}}),...!d&&{"border-color":`transparent`,...co(a),"background-origin":`border-box`,"background-clip":`border-area`},...a.length===1&&u?.blendMode!==void 0&&u.blendMode!==`normal`&&{"mix-blend-mode":u.blendMode},...s===0&&Oo({...e,styles:{},additionalStyles:void 0,appearance:l},t),...!d&&ss(e,r,t,s===0?Qo:c)}},ls=(e,t)=>{if(Ro(e))return[];let n=B(e),r=[...Yo(n,`outer-shadow`),...Yo(n,`inner-shadow`)];return r.length===0?t:t.filter(e=>!r.includes(e))},us=e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${D(e.color)}`,ds=e=>`${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${D(e.color)}`,fs=(e,t)=>{let n=ls(e,t).filter(e=>e.visible);if(e.component===`text`){let e=n.filter(e=>e.kind===`outer`&&e.spread===0).map(e=>ds(e)).join(`, `);return{"box-shadow":`none`,"text-shadow":e===``?`none`:e}}let r=n.map(e=>us(e)).join(`, `);return{"box-shadow":r===``?`none`:r}},ps=(e,t)=>{let n=e.appearance?.border,r=n===void 0?{top:0,right:0,bottom:0,left:0}:R(n);return{position:`absolute`,top:-r.top,right:-r.right,bottom:-r.bottom,left:-r.left,"border-radius":`inherit`,"pointer-events":`none`,"box-shadow":us(t),"mix-blend-mode":t.blendMode??`normal`}},ms=(e,t)=>{let n=t.map((n,r)=>{let[i=``,a,...o]=Ve(n),s=ia(i),c=a===void 0?r/(t.length-1):/^\d+(?:\.\d+)?%$/u.test(a)?Number(a.slice(0,-1))/100:NaN;return s===null||o.length>0?null:{id:`${e}-stop-${String(r)}`,color:s,position:c}});return n.includes(null)?null:n.filter(e=>e!==null)},hs=(e,t)=>{let n=/^(linear|radial)-gradient\((.*)\)$/su.exec(t);if(n===null)return null;let r=[...Ve(n[2]??``,`,`)],i=r[0]??``,a=/^(-?(?:\d+(?:\.\d*)?|\.\d+))deg$/u.exec(i),o=/^ellipse ([\d.]+)% ([\d.]+)% at (-?[\d.]+)% (-?[\d.]+)%$/u.exec(i);if(a!==null&&n[1]!==`linear`||o!==null&&n[1]!==`radial`)return null;(a!==null||o!==null)&&r.shift();let s=r.map(e=>Ve(e).length>1);if(s.some(Boolean)&&!s.every(Boolean))return null;let c=ms(e,r);if(c===null)return null;let l={id:e,visible:!0,opacity:1,stops:c},u=at.safeParse(n[1]===`linear`?{...l,kind:`linear-gradient`,angle:Number(a?.[1]??180)}:o===null?null:{...l,kind:`radial-gradient`,radius:{x:Number(o[1])/100,y:Number(o[2])/100},center:{x:Number(o[3])/100,y:Number(o[4])/100}});if(!u.success)return null;let d=u.data,f=`stops`in d?d.stops[0]:void 0;return f!==void 0&&d.kind===`linear-gradient`&&d.stops.every(e=>JSON.stringify(e.color)===JSON.stringify(f.color))?{id:e,kind:`solid`,visible:!0,opacity:1,color:f.color}:d},gs=(e,t,n,r)=>{let i=Ve(e[t]??r,`,`);return i[n%i.length]??r},_s=(e,t,n,r)=>{let i=/^url\((?:"([^"\\]*)"|'([^'\\]*)'|([^\s'"()\\]+))\)$/u.exec(t),a=i?.[1]??i?.[2]??i?.[3];if(a===void 0||a===``||a.startsWith(`data:image/svg+xml`))return null;let o=gs(n,`background-position`,r,`0% 0%`),s=gs(n,`background-size`,r,`auto`),c=gs(n,`background-repeat`,r,`repeat`),l=[`center`,`center center`,`50% 50%`].includes(o),u={id:e,kind:`image`,visible:!0,opacity:1,assetId:a};if(c===`repeat`&&s===`auto`&&(o===`0% 0%`||l))return{...u,fit:`tile`,tileOrigin:l?`center`:`top-left`};if(c!==`no-repeat`||!l)return null;let d=Object.entries({cover:`cover`,contain:`fit`,"100% 100%":`fill`}).find(([e])=>e===s)?.[1];return d===void 0?null:{...u,fit:d}},vs=(e,t)=>{let n=t.background,i=t[`background-color`]??n,a=i===void 0||i===`none`?null:F(`${e}-background`,i);if(i!==void 0&&i!==`none`&&a===null)return null;let o=t[`background-image`];if(o===void 0||o===`none`)return a===null?[]:[a];let s=Ve(o,`,`).map((n,i)=>{let a=`${e}-fill-${String(i)}`,o=hs(a,n),s=gs(t,`background-size`,i,`auto`);if(o!==null&&![`auto`,`auto auto`,`100% 100%`].includes(s))return null;let c=o??_s(a,n,t,i),l=r.safeParse(gs(t,`background-blend-mode`,i,`normal`));return c===null||!l.success?null:{...c,blendMode:l.data}});return s.includes(null)?null:[...a===null?[]:[a],...s.filter(e=>e!==null).toReversed()]},ys=[[`fills`,/^background(?:-color|-image)?$/u],[`radius`,/^border(?:-(?:top|bottom)-(?:left|right))?-radius$/u],[`border`,/^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u],[`outline`,/^outline(?:-(?:width|style|color|offset))?$/u],[`shadows`,/^(?:box|text)-shadow$/u],[`filters`,/^filter$/u],[`backdropFilters`,/^backdrop-filter$/u],[`opacity`,/^opacity$/u],[`blendMode`,/^mix-blend-mode$/u]],bs=new Set([`color`,`-webkit-text-fill-color`]),xs=(e,t)=>{let n=new Set;for(let r of t){let t=r.toLowerCase(),i=e.component===`text`;i&&bs.has(t)&&n.add(`fills`);for(let[e,r]of ys)r.test(t)&&(!i||e!==`fills`)&&n.add(e)}return[...n].filter(t=>e.appearance?.[t]!==void 0)},Ss=new Set([`background`,`background-color`,`background-image`]),Cs=new Set([`background-position`,`background-size`,`background-repeat`,`background-origin`,`background-blend-mode`]),ws=e=>{if((e.additionalStyles?.declarations??[]).some(({property:e,enabled:t})=>e.toLowerCase().startsWith(`background`)&&!t)||Object.keys(e.styles).some(e=>e.toLowerCase().startsWith(`background`)&&e!==e.toLowerCase()))return null;let t=Object.entries(ft(e)).filter(([e,t])=>e.toLowerCase().startsWith(`background`)&&t!==``).map(([e,t])=>[e.toLowerCase(),String(t).trim()]);if(t.some(([,e])=>e.includes(`!`)))return null;let n={};for(let[e,r]of t){if(e===`background`){let e=n[`background-blend-mode`];n=e===void 0?{}:{"background-blend-mode":e}}n[e]=r}return n},Ts=e=>{let t=ws(e);if(t===null)return{kind:`custom`};let n=e.appearance?.fills;if(n!==void 0&&n.every(e=>!e.visible)&&t.background!==void 0&&t[`background-image`]!==void 0&&t[`background-image`]!==`none`)return{kind:`custom`};if(n!==void 0)return{kind:`native`,fills:n,owned:Ss};if(Object.entries(t).some(([e,t])=>!Ss.has(e)&&!Cs.has(e)&&![`background-blend-mode`,`background-clip`].includes(e)&&t!==``)||t[`background-origin`]!==void 0&&t[`background-origin`]!==`padding-box`||t[`background-clip`]!==void 0&&t[`background-clip`]!==`border-box`)return{kind:`custom`};let r=vs(e.id,t);if(r===null||t[`background-image`]!==void 0&&r.some(e=>e.kind!==`image`)&&(e.appearance?.border!==void 0||Object.keys(e.styles).some(e=>/^border(?:-|$)/u.test(e))))return{kind:`custom`};let i=new Set(Ss);for(let e of Cs)i.add(e);return{kind:`native`,fills:r,owned:i}},Es=e=>({...Jo(B(e)).length>0&&{background:`none`},...Mo(e)!==null&&{isolation:`isolate`}}),Ds=e=>({position:`absolute`,inset:0,...co([e]),...e.kind===`image`&&e.filters!==void 0&&{filter:Lr(e.filters)},...e.blendMode!==void 0&&e.blendMode!==`normal`&&{"mix-blend-mode":e.blendMode}}),Os=[[`topLeft`,`top-left`],[`topRight`,`top-right`],[`bottomRight`,`bottom-right`],[`bottomLeft`,`bottom-left`]],ks=e=>Xo(B(e),`outline`).length>0,As=e=>ks(e)?{"outline-style":`none`}:{},js=(e,t,n)=>{let r=e.appearance?.radius;if(r===void 0)return{};let i=t.offset+t.width,a=Zo(t.style,t.width,t),o=ar(r,n,t.offset+t.width/2),s=`<svg xmlns="http://www.w3.org/2000/svg" width="${String(n.width+2*i)}" height="${String(n.height+2*i)}"><path d="${o}" transform="translate(${String(i)} ${String(i)})" fill="none" stroke="#000" stroke-width="${String(t.width)}" stroke-dasharray="${a.dash??`none`}" stroke-linecap="${a.linecap}"/></svg>`;return{"background-clip":`border-box`,"mask-image":`url("data:image/svg+xml,${encodeURIComponent(s)}")`,"mask-size":`100% 100%`,"mask-repeat":`no-repeat`,"mask-origin":`border-box`}},Ms=(e,t=e.box,n)=>{let r=e.appearance?.outline,[i]=Xo(B(e),`outline`);if(r===void 0||i===void 0)return null;let a=r.offset+r.width,o=e.appearance?.radius,s=n??i,[c]=s,l=e.appearance?.border,u=l===void 0?{top:0,right:0,bottom:0,left:0}:R(l),d=e=>{let t=o?.[e]??0;return t<=0?0:t+a};return{position:`absolute`,top:-(u.top+a),right:-(u.right+a),bottom:-(u.bottom+a),left:-(u.left+a),"box-sizing":`border-box`,"pointer-events":`none`,"border-style":r.style,"border-width":r.width,"border-color":`transparent`,...Object.fromEntries(Os.map(([e,t])=>[`border-${t}-radius`,d(e)])),...co(s),"background-origin":`border-box`,"background-clip":`border-area`,...s.length===1&&c?.blendMode!==void 0&&c.blendMode!==`normal`&&{"mix-blend-mode":c.blendMode},...t!==void 0&&(o?.smoothing??0)>0&&js(e,r,t),...t!==void 0&&(o?.smoothing??0)<=0&&os({width:t.width+2*a,height:t.height+2*a,corners:{topLeft:[d(`topLeft`),d(`topLeft`)],topRight:[d(`topRight`),d(`topRight`)],bottomRight:[d(`bottomRight`),d(`bottomRight`)],bottomLeft:[d(`bottomLeft`),d(`bottomLeft`)]},widest:r.width,stroke:r})}},Ns=e=>{if(h(e))return!0;if(e.typography?.decoration===void 0)return!1;let t=e.appearance?.fills?.filter(e=>e.visible)??[];return t.length>1||t.some(e=>e.kind!==`solid`)},Ps=(e,t)=>{let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)?Math.min(1,Math.max(0,n)):t},Fs=e=>st.find(t=>t===e)??`normal`,Is=(e,t)=>{let n=Number(String(e??``).replace(`px`,``));return Number.isFinite(n)?Math.max(t,n):0},Ls=e=>Is(e,0),Rs=(e,t)=>e===0?t:e,zs=e=>{let[t=0,n=t,r=t,i=n]=String(e[`border-radius`]??`0`).split(/\s+/u).map(e=>Ls(e));return{topLeft:Rs(Ls(e[`border-top-left-radius`]),t),topRight:Rs(Ls(e[`border-top-right-radius`]),n),bottomRight:Rs(Ls(e[`border-bottom-right-radius`]),r),bottomLeft:Rs(Ls(e[`border-bottom-left-radius`]),i)}},H=e=>{let t=Qr(),n=xo(e),r=So(e),i=F(`${e.id}-fill`,String(e.styles[e.component===`text`?`color`:`background`]??``)),a=e.component===`text`?null:Ts(e);return{...t,opacity:e.appearance?.opacity??Ps(e.styles.opacity,1),blendMode:e.appearance?.blendMode??Fs(e.styles[`mix-blend-mode`]),fills:a?.kind===`native`?[...a.fills]:e.appearance?.fills??(i===null?[]:[i]),border:n.kind===`native`?n.value:e.appearance?.border??t.border,outline:r.kind===`native`?r.value:e.appearance?.outline??t.outline,radius:e.appearance?.radius??zs(e.styles),...e.appearance?.retainedBorder!==void 0&&{retainedBorder:e.appearance.retainedBorder},shadows:e.appearance?.shadows??[],filters:e.appearance?.filters??[],backdropFilters:e.appearance?.backdropFilters??[]}},Bs=e=>{let t=e.appearance?.fills;return e.component===`text`&&Ns(e)?{...t!==void 0&&{color:uo(t).color??`transparent`},"background-image":`none`}:t===void 0?{}:e.component===`text`?uo(t):lo(t)},Vs=e=>{let t=e.appearance,n={...Bs(e),...Es(e)};return(t?.opacity??Ps(e.styles.opacity,1))===0&&(n[`pointer-events`]=`none`),t===void 0?n:(t.opacity!==void 0&&(n.opacity=t.opacity),t.blendMode!==void 0&&(n[`mix-blend-mode`]=t.blendMode),t.radius!==void 0&&e.geometry?.kind!==`path`&&Object.assign(n,ko(t.radius),Oo(e)),Object.assign(n,Eo(t),ns(e),As(e)),t.filters!==void 0&&(n.filter=Lr(t.filters)),t.shadows!==void 0&&Object.assign(n,fs(e,t.shadows)),t.backdropFilters!==void 0&&(n[`backdrop-filter`]=Lr(No(e,t.backdropFilters))),n)},Hs=e=>{let t=H(e).radius;return t.topLeft===0&&t.topRight===0&&t.bottomRight===0&&t.bottomLeft===0},Us=e=>{let t=H(e);return xo(e).kind!==`native`&&So(e).kind!==`native`&&t.shadows.every(e=>!e.visible)&&t.filters.every(e=>!e.visible)&&t.backdropFilters.every(e=>!e.visible)},Ws=e=>e!==void 0&&e.geometry===void 0&&(e.component===`image`||e.component===`rectangle`&&Hs(e))&&Us(e),Gs=e=>{let t=e.props?.naturalWidth,n=e.props?.naturalHeight;return typeof t==`number`&&typeof n==`number`&&t>0&&n>0?{width:t,height:n}:void 0},Ks=(e,t)=>{if(t.component!==`text`)return;let n=e.relationships[t.id]?.parentId,r=n===void 0?void 0:e.nodes[n];return r?.geometry?.kind===`mask`&&r.geometry.maskId===t.id?r:void 0},qs=(e,t)=>{let n=Ks(e,t);if(n===void 0)return null;let r=Wa(e.relationships,n.id).flatMap(n=>n===t.id?[]:e.nodes[n]??[]),i=t.box;return i!==void 0&&r.length>0&&r.every(e=>Ws(e)&&Zs(e,i)!==null)?r:null},Js=(e,t,n)=>{let r=(e===`cover`?Math.max:Math.min)(t.width/n.width,t.height/n.height),i=n.width*r,a=n.height*r;return{x:t.x+(t.width-i)/2,y:t.y+(t.height-a)/2,width:i,height:a}},Ys=(e,t)=>{let n=$a(e);if(e.fit===`fill`)return{image:n,box:t};if(e.fit===`crop`&&e.crop!==void 0){let r=t.width/Math.max(e.crop.width,2**-52),i=t.height/Math.max(e.crop.height,2**-52);return{image:n,box:{x:t.x-e.crop.x*r,y:t.y-e.crop.y*i,width:r,height:i}}}let r=e.naturalSize;if(r===void 0)return null;if(e.fit===`tile`){let i=e.tileScale??1;return{image:n,box:{x:t.x,y:t.y,width:r.width*i,height:r.height*i},repeat:`repeat`}}return{image:n,box:Js(e.fit===`fit`?`fit`:`cover`,t,r)}},Xs=(e,t)=>{let n=e.props?.src;if(typeof n!=`string`||n===``)return[];let r=Qa(n),i=e.props?.fit;if(i!==`cover`&&i!==`contain`)return[{image:r,box:t}];let a=Gs(e);return a===void 0?null:[{image:r,box:Js(i===`cover`?`cover`:`fit`,t,a)}]},Zs=(e,t)=>{if(e.box===void 0)return[];let n={...e.box,x:e.box.x-t.x,y:e.box.y-t.y};if(e.component===`image`&&e.appearance?.fills===void 0)return Xs(e,n);let{opacity:r}=H(e),i=[],a=H(e).fills.filter(e=>e.visible).toReversed();for(let e of a)if(e.kind===`image`){let t=Ys(e,n);if(t===null)return null;i.push(t)}else i.push({image:$a({...e,opacity:e.opacity*r}),box:n});return i},Qs=(e,t)=>t.geometry?.kind===`mask`?e.nodes[t.geometry.maskId]:void 0,$s={a:1,b:0,c:0,d:1,e:0,f:0},ec=(e,t)=>({a:e.a*t.a+e.c*t.b,b:e.b*t.a+e.d*t.b,c:e.a*t.c+e.c*t.d,d:e.b*t.c+e.d*t.d,e:e.a*t.e+e.c*t.f+e.e,f:e.b*t.e+e.d*t.f+e.f}),tc=e=>{let{fills:t,opacity:n}=H(e);return(1-t.filter(e=>e.visible).reduce((e,t)=>e*(1-t.opacity*(t.kind===`solid`?t.color.alpha:1)),1))*n},nc=(e,t,n)=>{let[r,i,a,o,s,c]=e.matrix,l=ec(t,{a:r,b:i,c:a,d:o,e:s,f:c});return{path:e.path,fillRule:e.fillRule,transform:`matrix(${[l.a,l.b,l.c,l.d,l.e,l.f].map(String).join(` `)})`,opacity:n}},rc=(e,t)=>{if(t.component!==`group`||t.geometry!==void 0)return null;let n=[],r=(t,i,a)=>{if(t.visible===!1)return;let o=t.component===`group`&&t.geometry===void 0,s=o?null:Ar(t);if(s!==null&&typeof s!=`string`&&n.push(nc(s,i,a*tc(t))),!o&&t.component!==`frame`)return;let c=cr(t);if(c===null)return;let l=ec(i,c),u=a*H(t).opacity;for(let n of Wa(e.relationships,t.id)){let t=e.nodes[n];t!==void 0&&r(t,l,u)}};return r(t,$s,1),n},ic=e=>{let t=2166136261;for(let n of e)t=Math.imul(t^(n.codePointAt(0)??0),16777619);return(t>>>0).toString(16)},ac=(e,t,n)=>{if(qs(e,t)!==null)return null;let r=t.box;if(r===void 0)return{path:``,fillRule:`nonzero`,matrix:[1,0,0,1,0,0]};let{width:i,height:a}=r;return{path:`M0 0H${String(i)}V${String(a)}H0Z`,fillRule:`nonzero`,matrix:[1/n.width,0,0,1/n.height,r.x/n.width,r.y/n.height]}},oc=(e,t,n)=>{let r=t.geometry,i=t.box;if(r===void 0||i===void 0||i.width<=0||i.height<=0)return null;if(r.kind===`path`||r.kind===`polygon`){let e=kr(t);if(typeof e==`string`)return null;let n=e.viewBox;return{path:e.path,fillRule:e.fillRule,matrix:[1/n.width,0,0,1/n.height,-n.x/n.width,-n.y/n.height]}}if(r.kind===`boolean`){let e=kr(t);return{path:typeof e==`string`?``:e.path,fillRule:r.result.fillRule,matrix:[1/i.width,0,0,1/i.height,0,0]}}let a=n??Qs(e,t);if(a?.component===`text`&&a.visible!==!1)return ac(e,a,i);let o=a===void 0||a.visible===!1?null:rc(e,a);if(o!==null)return{path:``,fillRule:`nonzero`,matrix:[1/i.width,0,0,1/i.height,0,0],shapes:o};let s=a===void 0||a.visible===!1?null:Ar(a);if(s===null||typeof s==`string`)return{path:``,fillRule:`nonzero`,matrix:[1,0,0,1,0,0]};let[c,l,u,d,f,p]=s.matrix;return{path:s.path,fillRule:s.fillRule,matrix:[c/i.width,l/i.height,u/i.width,d/i.height,f/i.width,p/i.height]}},sc=(e,t,n)=>{let r=oc(e,t,n);if(r===null)return null;let{path:i,fillRule:a,matrix:o,shapes:s}=r,c=`matrix(${o.map(String).join(` `)})`;return{id:`canvas-geometry-${encodeURIComponent(t.id).replaceAll(`%`,`_`)}-${ic(JSON.stringify([i,a,c,s]))}`,path:i,fillRule:a,transform:c,matrix:o,...s!==void 0&&{shapes:s}}},cc=(e,t)=>{let n=Dt(new Set(Object.keys(t))).filter(t=>e.typography?.[t]!==void 0);return n.length===0?null:{op:`patchTypography`,nodeId:e.id,typography:{clear:n}}},lc=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),uc=(t,n)=>{let r=new Map((t.additionalStyles?.declarations??[]).map(e=>[e.id,e]));for(let[t,i]of Object.entries(n)){let n=Array.from(r,([,e])=>e).filter(e=>(t.startsWith(`--`)?e.property:e.property.toLowerCase())===t);for(let e of n)r.delete(e.id);if(i===null||e.safeParse({[t]:i}).success)continue;let a=n[0]?.id??`css-${t}`.slice(0,190),o=a;for(let e=1;r.has(o);e+=1)o=`${a}-${String(e)}`;let s=he.safeParse({id:o,property:t,value:String(i),enabled:!0});if(!s.success)throw new x(`BAD_REQUEST`,`Style ${t} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);r.set(o,s.data)}let i=r.values().toArray(),a=i.length===0&&t.additionalStyles===void 0?void 0:{declarations:i},o=wn(t.additionalStyles,a);return o===null?null:{op:`patchAdditionalStyles`,nodeId:t.id,additionalStyles:o}},dc=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...ut(t,r,e),...ut(n,r,e)],o=ht(t.layout??{},i,{horizontal:a(`horizontal`),vertical:a(`vertical`)});for(let[e,t]of[[`width`,`horizontal`],[`height`,`vertical`]]){let n=r[e];(n===`fill`||n===`hug`)&&(o[t]={mode:n})}return JSON.stringify(o)===JSON.stringify(t.layout??{})?null:{op:`setLayout`,nodeId:t.id,layout:Object.keys(o).length===0?`default`:o}},fc=(e,t,n)=>{let r={...n};for(let[i,a]of[[`width`,`horizontal`],[`height`,`vertical`]])if(n[i]===`fill`||n[i]===`hug`){r[i]=null;for(let n of ut(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},pc=(t,n,r)=>{let i=fc(t,n,r),a=uc(n,i),o=Object.fromEntries(Object.entries(i).filter(([t,n])=>e.safeParse({[t]:n}).success)),s={...n,styles:{...n.styles},...a!==null&&{additionalStyles:Cn(n.additionalStyles,a.additionalStyles)??void 0}};for(let[e,t]of Object.entries(o))t===null?Reflect.deleteProperty(s.styles,e):s.styles[e]=t;let c=dc(t,n,s,r),l=cc(n,i),u=xs(n,Object.keys(i)),d=u.length>0?[{op:`setAppearance`,nodeId:n.id,appearance:{clear:[...u]}}]:[];return[...Object.keys(o).length>0?[{op:`setStyles`,nodeId:n.id,styles:e.parse(o)}]:[],...d,...l===null?[]:[l],...c===null?[]:[c],...a===null?[]:[a]]},mc=e=>{let t=new Map;for(let n of e)for(let e of n.nodeIds){let r=t.get(e)??{};for(let[e,t]of Object.entries(n.styles)){let n=lc(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},hc=(e,t)=>{let n=[...mc(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new x(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return pc(e,r,n)});if(n.length===0)throw new x(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},gc=(e,t)=>{let n={...e.styles};for(let[e,r]of Object.entries(t.styles))r==null?Reflect.deleteProperty(n,e):n[e]=r;let r=t.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i=Ge(e.typography,{clear:[...Dt(new Set([...Object.keys(t.styles),...r]))]});return U({...e,styles:n},`typography`,i??`default`)},_c=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),vc=e=>_c.has(e.op),U=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},yc=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new x(`BAD_REQUEST`,`Canvas node ${e.id} is not editable text.`,`Use the text node id from canvas tree.`);return{...e,props:{...e.props,text:t.text}};case`setLabel`:return{...e,label:t.label,labelOrigin:`user`};case`setStyles`:return gc(e,t);case`setAppearance`:{let n={...e.appearance},r=t.appearance.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i={...e,appearance:n};return Object.keys(n).length===0&&Reflect.deleteProperty(i,`appearance`),i}case`patchTypography`:return U(e,`typography`,Ge(e.typography,t.typography)??`default`);case`setTypography`:return U(e,`typography`,t.typography);case`setLayout`:return U(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=Cn(e.additionalStyles,t.additionalStyles);return U(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return U(e,`additionalStyles`,t.additionalStyles)}},bc=(e,t)=>{if(!vc(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new x(`BAD_REQUEST`,`Duplicate id ${t.node.id} already exists.`,`Use a new client token for a new duplication.`);return{...e,nodes:{...e.nodes,[t.node.id]:t.node},relationships:{...e.relationships,[t.node.id]:t.parentage}}}let n=N(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:yc(n,t)}}},xc=e=>{let{nodeId:t,destination:n}=e;switch(n.kind){case`before`:return{nodeId:t,before:n.nodeId};case`after`:return{nodeId:t,after:n.nodeId};case`parent`:return{nodeId:t,parentId:n.parentId,...n.index!==void 0&&{index:n.index}}}},Sc=(e,t,n,r)=>{switch(e.kind){case`set_text`:return[{op:`setText`,nodeId:e.nodeId,text:e.text}];case`rename`:return[{op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}];case`set_styles`:return hc(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Ki(t.scene,e.nodeIds.map(t=>({id:t,...e.parentId!==void 0&&{parentId:e.parentId}})),i);return t.duplicatedNodes.push(...a.duplicatedNodes),a.operations}case`move`:{let n=$i(t.scene,[xc(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},Cc=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=Sc(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=bc(r.scene,e);r.operations.push(...t)}return{operations:r.operations,duplicatedNodes:r.duplicatedNodes,moves:r.moves,affectedParents:[...r.affectedParents].map(e=>({parentId:e,children:Fi(r.scene,e)}))}},W=e=>{throw new x(`BAD_REQUEST`,`These nodes are outside the link selection: ${e.join(`, `)}.`,`Keep the complete link. Edit only its page or selection and preserve the destination page.`)},wc=(e,t)=>{if(e.op===`insertNode`)return[e.parentage.parentId];if(e.op===`insertText`||e.op===`insertPrototype`)return[e.parentId,...e.afterId===void 0?[]:[e.afterId]];if(e.op===`insertConvertedSubtree`)return e.destination.kind===`adjacent`?W([`adjacent conversion`]):[e.destination.targetNodeId];if(e.op===`move`||e.op===`setParentage`){let n=e.op===`move`?e.parentId:e.parentage.parentId;return[e.nodeId,...n===t.relationships[e.nodeId]?.parentId?[]:[n],...e.op===`move`&&e.afterId!==void 0?[e.afterId]:[]]}return[e.nodeId]},Tc=e=>e.op===`insertNode`?[e.node.id]:e.op===`insertText`||e.op===`insertPrototype`?[e.nodeId]:e.op===`insertConvertedSubtree`?Object.keys(e.nodes):[],Ec=(e,t)=>{let r=t.destination;if(r.kind===`adjacent`)return W([`adjacent conversion`]);let i=r.kind===`replace`?e.relationships[r.targetNodeId]?.parentId:r.targetNodeId;if(i===void 0)return W([r.targetNodeId]);let a=r.kind===`insert-children`&&r.targetNodeId===`root`?r.pageId??`canvas-page-default`:n(e,r.targetNodeId),o=t.nodes[t.rootNodeId];return o===void 0?W([t.rootNodeId]):{nodes:{...t.nodes,[t.rootNodeId]:{...o,...i===`root`&&a!==null&&{props:{...o.props,canvasPageId:a}}}},relationships:{...t.relationships,[t.rootNodeId]:{parentId:i,sortKey:``}}}},Dc=e=>({component:e.op===`insertText`?`text`:`prototype`,props:{...e.op===`insertPrototype`&&e.canvasPageId!==void 0&&{canvasPageId:e.canvasPageId}}}),Oc=(e,t)=>{if(t.op===`insertNode`)return{nodes:{[t.node.id]:t.node},relationships:{[t.node.id]:t.parentage}};if(t.op===`insertText`||t.op===`insertPrototype`)return{nodes:{[t.nodeId]:Dc(t)},relationships:{[t.nodeId]:{parentId:t.parentId,sortKey:``}}};if(t.op===`insertConvertedSubtree`)return Ec(e,t);if(t.op===`move`||t.op===`setParentage`)return{nodes:{},relationships:{[t.nodeId]:t.op===`move`?{parentId:t.parentId,sortKey:``}:t.parentage}};if(t.op===`setProps`){let n=e.nodes[t.nodeId];if(n!==void 0)return{nodes:{[t.nodeId]:{...n,props:t.props==="default"?{}:t.props}},relationships:{}}}return{nodes:{},relationships:{}}},kc=(e,t,n,r)=>{let i=Tc(r),a=e.nodeIds.length===0&&(i.length>0||r.op===`move`||r.op===`setParentage`),o=[...wc(r,t).filter(e=>!a||e!==`root`),...i.filter(e=>t.nodes[e]!==void 0)].filter(e=>!n.has(e));return o.length>0&&W(o),i},Ac=(e,t,r)=>{if(!ct(e))return;let i=new Set(g(e,t)),a=it(e,t);if(!a.ok)return W(e.nodeIds);let o={nodes:{...t.nodes},relationships:{...t.relationships}};for(let t of r){let r=kc(e,o,i,t),s=Oc(o,t);Object.assign(o.nodes,s.nodes),Object.assign(o.relationships,s.relationships);let c=[...Object.keys(s.nodes),...Object.keys(s.relationships)].filter(e=>o.nodes[e]?.component===`page`||n(o,e)!==a.pageId);c.length>0&&W(c);for(let e of r)i.add(e);if(t.op!==`remove`)continue;let l=it({...e,nodeIds:[t.nodeId]},o);if(l.ok)for(let e of l.nodeIds)i.delete(e),Reflect.deleteProperty(o.nodes,e),Reflect.deleteProperty(o.relationships,e)}},jc=e=>{switch(e.kind){case`set_text`:case`rename`:return[e.nodeId];case`set_styles`:return e.nodeIds;case`duplicate`:return[...e.nodeIds,...e.parentId===void 0?[]:[e.parentId]];case`move`:return[e.nodeId,e.destination.kind===`parent`?e.destination.parentId:e.destination.nodeId]}},Mc=(e,t)=>e.kind===`duplicate`?[...e.nodeIds,...e.parentId===void 0||e.nodeIds.every(n=>t.relationships[n]?.parentId===e.parentId)?[]:[e.parentId]]:e.kind===`move`&&e.destination.kind===`parent`&&t.relationships[e.nodeId]?.parentId===e.destination.parentId?[e.nodeId]:jc(e),Nc=(e,t)=>{let n=new Set(e.edits.flatMap(e=>jc(e)));for(let e of n)N(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[],...e.pageId!==void 0&&{pageId:e.pageId}};for(let n of e.edits)S(r,t,Mc(n,t))},Pc=e=>({execute:async t=>{let n=await Pi({remote:e},t.canvasId,t.baseVersion);Nc(t,n);let r=Cc(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);Ac({canvasId:t.canvasId,nodeIds:t.nodeIds??[],...t.pageId!==void 0&&{pageId:t.pageId}},n,r.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let i=je.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:14,baseVersion:t.baseVersion,operations:r.operations});if(!i.success)throw new x(`BAD_REQUEST`,`The edit contains an invalid canvas operation.`,i.error.issues[0]?.message??`Check the edit’s node references and values.`);let a=v.parse(await Ni(e).execute(i.data));return{...a,next:[`Reuse version ${String(a.version)} as baseVersion for the next edit; no extra read is required.`,`Render the affected screen at version ${String(a.version)} when ready for visual review.`],...r.duplicatedNodes.length>0&&{duplicatedNodes:r.duplicatedNodes},...r.moves.length>0&&{moves:r.moves,affectedParents:r.affectedParents}}}}),Fc=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw TypeError(`${t} is missing from the capability catalogue`);return n},G=(e,t,n,r=48e3)=>{if(t>e.length)throw new x(`BAD_REQUEST`,`The result page offset is out of range.`,`Restart pagination at offset 0.`);let i=[],a=2,o=e.slice(t,t+n);for(let e of o){let t=Buffer.byteLength(JSON.stringify(e))+1;if(i.length>0&&a+t>r)break;i.push(e),a+=t}let s=t+i.length;return{entries:i,total:e.length,offset:t,nextOffset:s<e.length?s:null,complete:s===e.length}},Ic=e=>e.state===`succeeded`?[...e.result.insertedNodeIds.map(e=>({kind:`inserted`,nodeId:e})),...e.result.removedNodeIds.map(e=>({kind:`removed`,nodeId:e})),...Object.entries(e.result.idMap).map(([e,t])=>({kind:`identity`,temporaryId:e,nodeId:t})),...e.result.report.issues.map(e=>({kind:`issue`,issue:e}))]:[],Lc=e=>e.state===`succeeded`?{mutationId:e.result.mutationId,previousVersion:e.result.previousVersion,version:e.result.version,rootNodeId:e.result.rootNodeId,affectedBounds:e.result.affectedBounds,insertedCount:e.result.insertedNodeIds.length,removedCount:e.result.removedNodeIds.length,identityCount:Object.keys(e.result.idMap).length,issueCount:e.result.report.issues.length}:null,Rc=(e,t)=>({kind:`canvas-conversion`,operation:{kind:`canvas-conversion`,canvasId:e.canvasId,jobId:e.id},state:e.state,phase:e.phase,requestedVersion:e.requestedVersion,destination:e.destination,result:Lc(e),failure:e.failure,details:G(Ic(e),t.offset,t.limit),warnings:e.state===`succeeded`?[`This receipt does not verify visual fidelity. Render the committed root to inspect it.`]:[]}),K=e=>new x(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),zc=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Bc=e=>{let t=e.failure;return new x(t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`CONVERSION_FAILED`?`BAD_REQUEST`:`INTERNAL`,t.message,t.retryable?"Retry the exact write. If it repeats, run `enhance doctor` and report the job id.":`Inspect the current canvas and correct the conversion source or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},Vc=async(e,t)=>{let n=xt.safeParse(await e.query(`canvas.render.getImport`,{jobId:t}));if(!n.success)throw K(`conversion status`);if(n.data.job.id!==t)throw K(`conversion identity`);return n.data.job},Hc=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){if(Date.now()>=r)return i;await zc(250),i=await Vc(e,i.id)}if(i.state!==`succeeded`)throw Bc(i);return i},Uc=(e,t)=>{let n=e.destination,r=t.request.destination;return n.kind===r.kind?n.kind===`adjacent`||r.kind===`adjacent`||n.targetNodeId===r.targetNodeId&&(n.kind!==`insert-children`||r.kind!==`insert-children`||n.pageId===r.pageId):!1},Wc=(e,t)=>{let n=t.request;if(e.canvasId!==n.canvasId||e.requestedVersion!==n.expectedVersion||!Uc(e,t))throw K(`conversion destination or revision`);let r=e.source;if(r.kind!==n.source.kind||r.kind===`screen`&&n.source.kind===`screen`&&r.nodeId!==n.source.nodeId||r.kind===`html`&&n.source.kind===`html`&&r.label!==n.source.label)throw K(`conversion source`);if(e.state===`succeeded`&&(e.result.canvasId!==n.canvasId||n.revisionPolicy===`strict`&&e.result.previousVersion!==n.expectedVersion))throw K(`conversion commitment`)},Gc=async(e,t)=>{let n=$e.safeParse(await e.mutate(`canvas.render.importSource`,t.request));if(!n.success)throw K(`conversion creation`);Wc(n.data.job,t);let r=await Hc(e,n.data.job,t.waitMs);return Wc(r,t),r},Kc=async(e,t)=>{let n=kt.parse(t),r=i(n.canvasRef);return Rc(await Gc(e,{request:{canvasId:r.canvasId,expectedVersion:n.baseVersion,revisionPolicy:`strict`,scope:{pageId:r.pageId,nodeIds:[...r.nodeIds]},source:{kind:`screen`,nodeId:n.sourceNodeId},destination:n.placement},waitMs:n.waitMs}),{offset:0,limit:40})},qc=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof x?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`The post-write review render failed.`,remediation:`Render the committed version and affected area again; do not replay the write.`},next:[`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(n)}`,`Do not replay the committed write with a new mutation id.`]}),Jc=async(e,t,n)=>{try{return await e.execute({canvasId:t.canvasId,expectedVersion:n.result.version,target:{kind:`node`,nodeId:n.result.rootNodeId},sourceState:null,scale:t.renderScale,outputPath:t.renderOutputPath,overwrite:t.overwriteRender,timeoutMs:t.renderTimeoutMs,retryClientToken:t.renderClientToken})}catch(e){return qc(e,t,n.result.version)}},Yc=async(e,t)=>{let n=await Pi({remote:e},t.canvasId,t.result.version);return t.result.insertedNodeIds.map(e=>{let t=n.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},Xc=(e,t)=>({canvasId:e.canvasId,mutationCommitted:!0,jobId:t.id,mutationId:t.result.mutationId,rootNodeId:t.result.rootNodeId,mode:e.mode,targetNodeId:e.targetNodeId,previousVersion:t.result.previousVersion,version:t.result.version,insertedNodeIds:t.result.insertedNodeIds,removedNodeIds:t.result.removedNodeIds,affected:{inserted:t.result.insertedNodeIds.length,changed:0,removed:t.result.removedNodeIds.length},affectedBounds:t.result.affectedBounds}),Zc=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:`canvas.render.getImport`,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),Qc=e=>({waitMs:e.renderTimeoutMs,request:{canvasId:e.canvasId,expectedVersion:e.baseVersion,...e.revisionPolicy!==void 0&&{revisionPolicy:e.revisionPolicy},...(e.pageId!==void 0||(e.selectionNodeIds?.length??0)>0)&&{scope:{pageId:e.pageId,nodeIds:[...e.selectionNodeIds??[]]}},source:{kind:`html`,html:e.html,label:`Agent-authored HTML`,...e.idPrefix!==void 0&&{idPrefix:e.idPrefix}},destination:{kind:e.mode,targetNodeId:e.targetNodeId,...e.mode===`insert-children`&&e.pageId!==void 0&&{pageId:e.pageId}}}}),$c=(e,t)=>({execute:async n=>{let r=await wi(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await Gc(e,Qc(n));if(n.responseMode===`bounded`)return Rc(i,{offset:0,limit:40});if(i.state!==`succeeded`)return Zc(i);if(n.review===`none`)return Xc(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await Jc(t,n,i),o=[];try{o=await Yc(e,i)}catch{o=[]}return{...Xc(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),el=async(e,t)=>{let n=i(t.canvas),r=ze.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),a=St.parse(r.document);ct(n)&&g(n,a),t.nodeId!==void 0&&S(n,a,[t.nodeId]);let o=it(t.nodeId===void 0?n:{...n,nodeIds:[t.nodeId]},a);if(!o.ok)throw new x(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link. Do not broaden the request.`);let s=Object.groupBy(Object.entries(a.relationships),([,e])=>e.parentId),c=Object.values(a.nodes).filter(e=>o.nodeIds.has(e.id)).map(e=>({...e,kind:e.component,parentId:a.relationships[e.id]?.parentId??null,children:(s[e.id]??[]).map(([e])=>e)}));return{canvasId:n.canvasId,version:r.version,pageId:o.pageId,source:n.nodeIds.length>0?`selection-link`:n.pageId===void 0?`canvas-link`:`page-link`,selectedNodeIds:n.nodeIds,rootNodeIds:o.rootNodeIds,nodeCount:c.length,nodes:c,next:[`Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants.`]}},tl=(e,t,n)=>{try{Ut(e,t,{flag:n?`w`:`wx`,mode:384}),Rt(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new x(n,n===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,n===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},nl=e=>({write:t=>{if(t.outputPath!==null){let e=T.resolve(t.outputPath);return tl(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=T.join(e,`sensitive`);Ht(n,{recursive:!0,mode:448}),Rt(n,448);let r=T.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return tl(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),rl=[`canvas.asset.reserve`,`canvas.asset.complete`,`canvas.document.get`],il=(e,t)=>new x(e instanceof x?e.code:`INTERNAL`,e instanceof x?e.message:`The asset import did not return a confirmed result.`,e instanceof x?e.remediation:`Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.`,{...e instanceof x&&e.fields,operation:JSON.stringify(t),outcome:`not_confirmed`}),al=(e,t)=>{if(e.canvasId!==t.canvasId||e.clientToken!==t.clientToken||e.kind!==t.kind||e.contentType!==t.contentType||e.bytes!==t.bytes||e.sha256!==t.sha256)throw new x(`INTERNAL`,`The returned asset does not match this import intent.`,`Check the API and CLI versions. Do not insert an unverified resource.`)},ol=(e,t)=>({execute:async n=>{let r=i(n.canvasRef);if(ct(r)){let t=ze.parse(await e.query(rl[2],{canvasId:r.canvasId}));g(r,St.parse(t.document))}let{body:a,...o}=await t.read(),s=Ke.parse({...o,canvasId:r.canvasId,clientToken:n.clientToken}),c={kind:`canvas-asset`,canvasId:r.canvasId,clientToken:n.clientToken};try{let t=Ot.parse(await e.mutate(rl[0],s));al(t,s),t.upload!==null&&await e.upload({...t.upload,body:a});let i=At.parse(await e.mutate(rl[1],{canvasId:r.canvasId,clientToken:n.clientToken}));if(al(i,s),i.assetId!==t.assetId||i.path!==t.path)throw new x(`INTERNAL`,`The completed asset identity changed.`,`Read operation_status and do not place an unconfirmed resource.`);return ge.parse({operation:c,resource:i,placement:`not_requested`})}catch(e){throw il(e,c)}}}),sl=15e3,cl=async e=>new Promise(t=>setTimeout(t,e)),ll=new Set([`ready`,`failed`,`abandoned`]),ul=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`],dl=e=>new x(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,`Check the existing deployment status before retrying with the same publication token.`),fl=async(e,t,n,r)=>{let i=De.safeParse(await e.mutate(ul[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,...t.targetMode!==void 0&&{targetMode:t.targetMode},...t.canvasPageId!==void 0&&{canvasPageId:t.canvasPageId},title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw dl(`artifact creation`);if(r(i.data.deploymentId),i.data.state===`uploading`&&await e.upload({url:i.data.upload.url,headers:i.data.upload.headers,body:n.open()}),i.data.state===`uploading`||i.data.state===`queued`){let n=Le.safeParse(await e.mutate(ul[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId}));if(!n.success||n.data.deploymentId!==i.data.deploymentId)throw dl(`artifact submission`)}return i.data},pl=async(e,t,n,r)=>{let i=te.safeParse(await e.query(ul[0],{}));if(!i.success)throw dl(`capabilities`);let a=await t.package({entryPath:n.entryPath,limits:i.data.limits});try{return await fl(e,n,a,r)}finally{await a.dispose()}},ml=async(e,t,n)=>{let r=new AbortController,i=Promise.withResolvers(),a=setTimeout(()=>{r.abort(),i.reject(new x(`INTERNAL`,`The prototype status request timed out.`,`Check this deployment again; keep its existing client token.`,{reason:`STATUS_TIMEOUT`,deploymentId:t.deploymentId}))},n);try{let n=await Promise.race([e.query(ul[3],t,{signal:r.signal}),i.promise]),a=ce.safeParse(n);if(!a.success||a.data.deploymentId!==t.deploymentId)throw dl(`status`);return a.data}finally{clearTimeout(a)}},hl=async(e,t,n)=>{let r=performance.now()+n,i=50,a=await ml(e,t,n>0?Math.min(sl,n):sl);for(;!ll.has(a.state);){let n=r-performance.now();if(n<=0)return a;await cl(Math.min(i,n)),i=Math.min(i*2,1e3);let o=r-performance.now();if(o<=0)return a;try{a=await ml(e,t,Math.min(sl,o))}catch(e){if(e instanceof x&&e.fields?.reason===`STATUS_TIMEOUT`)return a;throw e}}return a},gl=[`BAD_ARTIFACT`,`ARTIFACT_INTEGRITY`,`FILE_INTEGRITY`,`FILE_TOO_LARGE`,`FILE_COUNT_`,`MANIFEST_`,`PATH_`,`ENTRY_`,`EXPANDED_`,`ZIP_INVALID`,`ZIP_ENCRYPTED`,`ZIP_PATH_ENCODING`,`ZIP_COMPRESSION`,`ZIP_ENTRY_TYPE`],_l=e=>{let t=e.failure,n=gl.some(e=>t.code.startsWith(e));return{isBuildFailure:n,nextAction:n?`fix_build`:`retry_new_publication`,failure:{code:t.code,message:t.message,remediation:n?`Correct the named build problem and publish a new artifact with a new clientToken.`:`This ingestion attempt is terminal. Restore storage or service access, then explicitly publish the same valid build with a new clientToken. Do not change the source to repair a service failure.`}}},vl=e=>e.unavailableFiles?.map(e=>`Unavailable published file: ${e.path} (${e.code}).`)??[],yl=[`prototype.getArtifactCapabilities`,`prototype.attach`],bl=new Set([`BAD_REQUEST`,`FORBIDDEN`,`UNAUTHORIZED`,`NOT_FOUND`]),xl=async e=>{let t=te.safeParse(await e.query(yl[0],{}));if(!t.success||t.data.attachmentProtocolVersion!==1)throw new x(`BAD_REQUEST`,`This API does not advertise revision-checked prototype attachment.`,`Upgrade the API before publishing through the canvas profile. No artifact was created or attached.`)},Sl=e=>e instanceof x?{code:e.code,message:e.message,remediation:e.remediation}:{code:`INTERNAL`,message:`The publication request did not return a confirmed outcome.`,remediation:`Retry the identical request with its original clientToken; do not assume the canvas is unchanged.`},Cl=async(e,t,n)=>{let r=i(t.canvasRef),a=ne.safeParse(await e.mutate(yl[1],{canvasId:r.canvasId,deploymentId:n.deploymentId,baseVersion:t.baseVersion,...r.pageId!==void 0&&{canvasPageId:r.pageId},attachment:{clientToken:t.clientToken,scope:{...r.pageId!==void 0&&{pageId:r.pageId},nodeIds:r.nodeIds}}}));if(!a.success)throw Error(`Invalid prototype attachment response`);let o=a.data,s=o.attachment;if(s===void 0||o.canvasId!==r.canvasId||o.deploymentId!==n.deploymentId||o.prototypeId!==n.prototypeId||o.nodeId!==n.nodeId||o.version!==s.version||s.outcome===`committed`&&(s.mutationId!==t.clientToken||s.version!==s.previousVersion+1)||s.outcome===`no_op`&&s.version!==t.baseVersion)throw Error(`Unconfirmed prototype attachment receipt`);return{...o,attachment:s}},wl=async(e,t,n,r)=>{try{let i=await Cl(e,t,r);return{...n,attachmentStatus:i.attachment.outcome,attachment:i,nextAction:`inspect_result`}}catch(e){let t=Sl(e),r=t.code===`CONFLICT`,i=bl.has(t.code);return{...n,attachmentStatus:r?`conflict`:i?`not_attempted`:`not_confirmed`,failure:t,nextAction:t.code===`UNAUTHORIZED`||t.code===`FORBIDDEN`?`restore_access`:r||i?`replan_attachment`:`retry_same_request`,warnings:[...n.warnings,`The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent; refresh baseVersion after an unrelated canvas edit and keep the same clientToken. A changed scope or destination requires a new attachment intent.`]}}},Tl=async(e,t,n,r)=>{let i={operation:{kind:`prototype-deployment`,canvasId:n,deploymentId:r.deploymentId},deploymentStatus:r.state,publication:r,attachmentStatus:`pending`,attachment:null,failure:null,nextAction:`check_status`,warnings:vl(r)};if(r.state===`failed`){let{nextAction:e,failure:t}=_l(r);return{...i,attachmentStatus:`not_attempted`,nextAction:e,failure:t}}return r.state===`abandoned`?{...i,attachmentStatus:`not_attempted`,nextAction:`retry_new_publication`,failure:{code:`NOT_FOUND`,message:`The deployment was abandoned.`,remediation:`Publish the same build explicitly with a new clientToken if it is still needed.`}}:r.state===`ready`?wl(e,t,i,r):i},El=(e,t)=>({execute:async n=>{let r=i(n.canvasRef);await xl(e);let a=n.source.kind===`deployment`?n.source.deploymentId:null;try{if(n.source.kind===`build`&&(a=(await pl(e,t,{...n.source,canvasId:r.canvasId,...r.pageId!==void 0&&{canvasPageId:r.pageId},clientToken:n.clientToken},e=>{a=e})).deploymentId),a===null)throw Error(`Publication has no deployment`);let i=await hl(e,{canvasId:r.canvasId,deploymentId:a},n.waitMs);return await Tl(e,n,r.canvasId,i)}catch(e){if(a===null)throw e;return{operation:{kind:`prototype-deployment`,canvasId:r.canvasId,deploymentId:a},deploymentStatus:`unknown`,publication:null,attachmentStatus:`not_attempted`,attachment:null,failure:Sl(e),nextAction:e instanceof x&&(e.code===`UNAUTHORIZED`||e.code===`FORBIDDEN`)?`restore_access`:`retry_same_request`,warnings:[`An existing deployment may still be processing. Retry the same source and clientToken to recover or finish upload; do not reserve a new publication.`]}}}}),Dl=[`prototype.attach`],Ol=e=>new x(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),kl=e=>{if(e.state===`failed`){let t=_l(e);throw new x(t.isBuildFailure?`BAD_REQUEST`:`INTERNAL`,t.failure.message,t.failure.remediation,{reason:t.failure.code,deploymentId:e.deploymentId,nextAction:t.nextAction,...e.failure.path!==void 0&&{path:e.failure.path}})}if(e.state===`abandoned`)throw new x(`NOT_FOUND`,`Prototype deployment ${e.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);if(e.state!==`ready`)throw new x(`INTERNAL`,`Prototype ingestion is still processing.`,`Check this deployment status, then resume the same source and client token; do not reserve a second publication.`,{reason:`INGESTION_PENDING`,state:e.state,processedFiles:String(e.processedFiles),deploymentId:e.deploymentId})},Al=async(e,t,n)=>{let r={deploymentId:null};try{let i=await pl(e,t,n,e=>{r.deploymentId=e}),a=await hl(e,{canvasId:n.canvasId,deploymentId:i.deploymentId},3e5);kl(a);let o=ne.safeParse(await e.mutate(Dl[0],{canvasId:n.canvasId,deploymentId:i.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw Ol(`attachment`);return{...o.data,fileCount:a.fileCount,totalBytes:a.totalBytes,alreadyExists:i.alreadyExists,warnings:vl(a),next:[o.data.canvasUrl??o.data.openUrl,`enhance canvas render --canvas ${n.canvasId} --node-id ${o.data.nodeId} --expected-version ${String(o.data.version)}`]}}catch(e){throw e instanceof x&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||r.deploymentId===null?e:new ot(e instanceof x?e.message:`Prototype deployment ${r.deploymentId} has no confirmed completion.`,`${e instanceof x?`${e.remediation} `:``}Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`,{code:e instanceof x?e.code:`INTERNAL`,fields:{...e instanceof x&&e.fields,canvasId:n.canvasId,deploymentId:r.deploymentId,clientToken:n.clientToken}})}},jl=(e,t)=>({execute:async n=>Al(e,t,n)}),Ml=(e,t)=>{if(e.id!==t.jobId||e.canvasId!==t.canvasId)throw new x(`NOT_FOUND`,`The preparation does not belong to this operation.`,`Use the complete operation reference returned by the original action.`);return{kind:`canvas-preparation`,operation:t,state:e.state,phase:e.phase,requestedVersion:e.requestedVersion,failure:e.failure,outcome:`not_confirmed`,prepared:e.state===`succeeded`,warnings:[`Preparation is not a canvas commit. Repeat the original tool with identical arguments and clientToken to finish; status reads never commit.`]}},Nl=async(e,t)=>{let{job:n}=ue.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.jobId}));return Ml(n,t)},Pl=(e,t)=>{let n=40,r=e=>{let t=e.slice(0,n);return n-=t.length,t},i=r(e.insertedNodeIds),a=r(e.changedNodeIds),o=r(e.removedNodeIds),s=e.insertedNodeIds.length+e.changedNodeIds.length+e.removedNodeIds.length;return{outcome:`committed`,canvasId:e.canvasId,mutationId:e.mutationId,previousVersion:e.previousVersion,version:e.version,operation:{kind:`canvas-mutation`,canvasId:e.canvasId,mutationId:e.mutationId,fingerprint:t},affected:{insertedNodeIds:i,changedNodeIds:a,removedNodeIds:o,complete:s<=40,total:s},...e.copiedNodeIds!==void 0&&{identities:{entries:Object.entries(e.copiedNodeIds).toSorted(([e],[t])=>e.localeCompare(t,`en`)).slice(0,40).map(([e,t])=>({sourceNodeId:e,nodeId:t})),complete:Object.keys(e.copiedNodeIds).length<=40,total:Object.keys(e.copiedNodeIds).length}},verification:{rendered:!1},warnings:[]}},Fl=async(e,t,n)=>{if(n.kind!==`canvas-render`||n.state!==`succeeded`)return n;try{let{job:r}=lt.parse(await e.query(`canvas.render.get`,{jobId:n.operation.jobId}));return r.id!==n.operation.jobId||r.canvasId!==n.operation.canvasId||r.state!==`succeeded`?{...n,warnings:[`The stored result is unavailable for image delivery. Read this operation again.`]}:{status:n,localImage:await ui(e,t,r,{at:new Date,outputPath:null,overwrite:!1})}}catch{return{...n,warnings:[`The render completed, but its image could not be delivered. Check access and artifact expiry before retrying this operation reference.`]}}},Il=[`canvas.mutation.get`,`canvas.render.get`,`canvas.render.getImport`,`prototype.getPublishStatus`,`canvas.asset.get`],Ll=(e,t)=>{if(e!==t)throw new x(`NOT_FOUND`,`The operation does not belong to this canvas.`,`Use the operation reference returned by the original action.`)},Rl=e=>[...e.insertedNodeIds.map(e=>({nodeId:e,change:`inserted`})),...e.changedNodeIds.map(e=>({nodeId:e,change:`changed`})),...e.removedNodeIds.map(e=>({nodeId:e,change:`removed`})),...Object.entries(e.copiedNodeIds??{}).toSorted(([e],[t])=>e.localeCompare(t,`en`)).map(([e,t])=>({nodeId:t,sourceNodeId:e,change:`copied`}))],zl=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,a=se.parse(await e.query(Il[0],{canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}));return a.state===`not-found`?{kind:`canvas-mutation`,state:`not_found`,operation:n,outcome:`unknown`,warnings:[`No durable receipt was found. The original request may still be running.`]}:{kind:`canvas-mutation`,state:`committed`,receipt:Pl(a.result,n.fingerprint),affected:G(Rl(a.result),r,i)}},Bl=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,{job:a}=lt.parse(await e.query(Il[1],{jobId:n.jobId}));Ll(a.canvasId,n.canvasId);let o=a.result===null?null:Vl(a.result);return{kind:`canvas-render`,operation:n,state:a.state,phase:a.phase,requestedVersion:a.requestedVersion,attempt:a.attempt,target:a.target,sourceState:a.sourceState??null,evidence:o,details:G(Hl(a),r,i),failure:a.failure,pixelsDelivered:!1,warnings:[`Status reports stored render evidence. It does not deliver or inspect the image.`]}},Vl=e=>{let{warnings:t,timings:n,...r}=e;return{...r,warningCount:t.length,timingCount:n.length}},Hl=e=>e.result===null?[]:[...e.result.warnings.map(e=>({kind:`warning`,warning:e})),...e.result.timings.map(e=>({kind:`timing`,timing:e}))],Ul=async(e,t)=>{let n=At.parse(await e.query(Il[4],{canvasId:t.canvasId,clientToken:t.clientToken}));if(Ll(n.canvasId,t.canvasId),n.clientToken!==t.clientToken)throw new x(`NOT_FOUND`,`The resource does not belong to this import.`,`Use the operation reference returned by the original import.`);return{kind:`canvas-asset`,operation:t,resource:n,placement:`not_checked`}},Wl=async(e,t)=>{let{operation:n,offset:r,limit:i}=t;switch(n.kind){case`canvas-asset`:return G([],r,i),Ul(e,n);case`canvas-mutation`:return zl(e,{...t,operation:n});case`canvas-preparation`:{let r=await zl(e,{...t,operation:{kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}});return r.kind===`canvas-mutation`&&r.state===`committed`?r:Nl(e,n)}case`canvas-render`:return Bl(e,{...t,operation:n});case`canvas-conversion`:{let{job:t}=xt.parse(await e.query(Il[2],{jobId:n.jobId}));return Ll(t.canvasId,n.canvasId),Rc(t,{offset:r,limit:i})}case`prototype-deployment`:return G([],r,i),{kind:`prototype-deployment`,operation:n,publication:ce.parse(await e.query(Il[3],{canvasId:n.canvasId,deploymentId:n.deploymentId})),attachment:`not_checked`,warnings:[`Publication readiness does not establish canvas attachment or successful interactive verification.`]}}},Gl=(e,t)=>({execute:async n=>{let r=await Wl(e,n);return t!==void 0&&n.includeImage?Fl(e,t,r):r}}),Kl=[`transcript.get`],ql=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),Jl=e=>({execute:async t=>{let n=pe.safeParse(await e.query(Kl[0],t));if(!n.success)throw new x(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return n.data.state===`ready`?{...n.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:ql(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Yl=[`canvas.render.get`,`canvas.render.snapshot`],Xl=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Zl=e=>new x(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),Ql=async(e,t)=>{let n=lt.safeParse(await e.query(Yl[0],{jobId:t}));if(!n.success)throw new x(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},$l=async(e,t,n,r)=>{let i=Date.now()+n.timeoutMs,a=Date.now(),o=t,s=0,c=``;for(;o.state===`queued`||o.state===`running`;){let l=Date.now(),u=`${o.state}:${o.phase}`;if((u!==c||l-s>=5e3)&&(r({event:`snapshot.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:l-a,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),s=l,c=u),l>=i){if(n.bounded===!0)return o;throw new x(`INTERNAL`,`Snapshot ${o.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${n.retryClientToken} and a larger --timeout-ms.`,{jobId:o.id,phase:o.phase})}await Xl();let d=await Ql(e,o.id);if(d.id!==t.id)throw eu();tu(d,n),o=d}return o},eu=()=>new x(`INTERNAL`,`The snapshot response does not match the requested source or revision.`,`Run enhance doctor and report the capture job ID.`),tu=(e,t)=>{if(e.canvasId!==t.canvasId||e.purpose!==`snapshot`||e.sourceState?.recordingId!==t.recordingId||e.sourceState.atMs!==t.atMs||t.context!==void 0&&e.requestedVersion!==t.context.expectedVersion)throw eu();if(e.state!==`succeeded`)return;let n=e.result.snapshot,r=e.result.sourceState;if(e.result.canvasId!==t.canvasId||e.result.loadedVersion!==e.requestedVersion||e.result.requestedVersion!==e.requestedVersion||r?.recordingId!==t.recordingId||r.requestedAtMs!==t.atMs||r.settledAtMs!==t.atMs||n?.recordingId!==t.recordingId||n.atMs!==t.atMs||n.screenId!==e.id||n.screenNodeId!==`scr_${t.recordingId}_${String(t.atMs)}`||t.context!==void 0&&n.version!==t.context.expectedVersion+1)throw eu()},nu=(e,t)=>({operation:{kind:`canvas-render`,canvasId:e.canvasId,jobId:e.id},state:e.state,requestedVersion:e.requestedVersion,source:{kind:`recording`,recordingId:t.recordingId,atMs:t.atMs},attachment:e.state===`succeeded`?`committed`:e.state===`queued`||e.state===`running`?`pending`:`not_confirmed`,result:e.result?.snapshot??null,failure:e.failure,warningCount:e.result?.warnings.length??0,warnings:[e.state===`succeeded`?`The durable screen is attached. Render the returned node at its committed version to verify placement; use operation_status for source warnings.`:`Follow operation_status for this job. An incomplete job is not proof of attachment or proof that no durable screen was created.`]}),ru=async(e,t,n)=>{let r=Oe.parse(t),a=i(r.canvasRef);return au(e,()=>null).execute({canvasId:a.canvasId,recordingId:r.source.recordingId,atMs:r.source.atMs,retryClientToken:n,timeoutMs:r.waitMs,bounded:!0,context:{expectedVersion:r.baseVersion,request:{previewJobId:r.previewJobId,scope:{pageId:a.pageId,nodeIds:[...a.nodeIds]},placement:r.placement}}})},iu=async(e,t,n)=>{let r=yt.safeParse(await e.mutate(Yl[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs,...n.context!==void 0&&{context:n.context}}));if(!r.success)throw new x(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");tu(r.data.job,n);let i=await $l(e,r.data.job,n,t);if(n.bounded===!0)return nu(i,n);if(i.state!==`succeeded`||i.result.snapshot===void 0)throw Zl(i);let a={...i,result:{...i.result,snapshot:i.result.snapshot}},o=a.result.snapshot;return{jobId:a.id,canvasId:a.canvasId,...o,warnings:a.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${a.canvasId} --node-id ${o.screenNodeId}`,`enhance canvas render --canvas ${a.canvasId} --node-id ${o.screenNodeId} --expected-version ${String(o.version)}`]}},au=(e,t)=>({execute:async n=>iu(e,t,n)}),ou={".avif":`image/avif`,".gif":`image/gif`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".webp":`image/webp`,".ttf":`font/ttf`,".otf":`font/otf`,".woff":`font/woff`,".woff2":`font/woff2`},su=()=>new x(`BAD_REQUEST`,`Choose one supported regular image or font file.`,`Use an explicit local PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2 file.`),cu=async e=>{let t=ou[T.extname(e).toLowerCase()];if(t===void 0)throw su();let n=await Zt(e,zt.O_RDONLY|zt.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size===0)throw su();let r=Buffer.alloc(e.size+1),i=0;for(;i<r.byteLength;){let e=await n.read(r,i,r.byteLength-i,i);if(e.bytesRead===0)break;i+=e.bytesRead}if(i!==e.size)throw new x(`CONFLICT`,`The selected asset changed while it was being read.`,`Finish writing the file, then retry the unchanged import intent.`);let a=r.subarray(0,i);return{body:a,kind:t.startsWith(`image/`)?`image`:`font`,contentType:t,bytes:i,sha256:E(`sha256`).update(a).digest(`hex`)}}finally{await n.close()}},lu=e=>({read:async()=>{try{return await cu(e)}catch(e){throw e instanceof x?e:new x(`BAD_REQUEST`,`The selected asset file cannot be read.`,`Choose an existing readable image or font file on this computer.`)}}}),uu=[`canvas.list`,`organisation.list`],du=async(e,t)=>{let[n,r]=await Promise.all([e.query(uu[0],{collection:t.collection,...t.title!==void 0&&{title:t.title},scope:`all`,deleted:!1,hasUnresolved:!1}),t.includeDestinations?e.query(uu[1],{}):{items:[],truncated:!1}]),i=ve.parse(n),a=Qe.parse(r),o=i.items.map(e=>({kind:`canvas`,canvasRef:e.id,title:e.title,organisationId:e.organisationId,accessState:e.accessState,viewerCan:e.viewerCan,openPath:`/c/${e.id}`}));return t.includeDestinations&&o.push({kind:`destination`,destination:{kind:`personal`},name:`Personal`},...a.items.filter(e=>t.collection===`everything`||t.collection===e.id).map(e=>({kind:`destination`,destination:{kind:`team`,organisationId:e.id},name:e.name}))),{items:o,sourceTruncated:{canvases:i.truncated,destinations:a.truncated}}},fu=e=>{let t=[],n=2;for(let r of e){let e=Buffer.byteLength(JSON.stringify(r))+1;if(n+e>48e3)break;t.push(r),n+=e}return t},pu=e=>({execute:async t=>{let{items:n,sourceTruncated:r}=await du(e,t),{cursor:i,...a}=t,s=o(a),c=o({items:n,sourceTruncated:r}),l=i===void 0?null:we(i,nt);if(l!==null&&l.queryDigest!==s)throw new x(`BAD_REQUEST`,`This cursor belongs to another canvas search.`,`Restart discovery with the requested query.`);if(l!==null&&l.snapshotDigest!==c)throw new x(`CONFLICT`,`The accessible canvases or destinations changed between pages.`,`Restart discovery so results are not silently skipped or combined across permissions.`);let u=l?.offset??0;if(u>n.length)throw new x(`BAD_REQUEST`,`The discovery cursor is out of range.`,`Restart discovery.`);let d=fu(n.slice(u,u+t.limit)),f=u+d.length,m=f<n.length,h=r.canvases||r.destinations;return{items:d,returnedCount:d.length,totalAvailable:n.length,complete:!m&&!h,sourceTruncated:r,nextCursor:m?p({protocol:`enhance-canvas-find/1`,queryDigest:s,snapshotDigest:c,offset:f}):null,warnings:h?[`The source collection reached its existing limit. Refine the title or team; these results are not a complete inventory.`]:[]}}}),mu=async(e,t)=>{try{return{value:await e.query(`canvas.render.preparation.get`,{jobId:t})}}catch(e){if(e instanceof x&&![`INTERNAL`,`RATE_LIMITED`].includes(e.code))throw e;return null}},hu=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){let n=r-Date.now();if(n<=0)break;await Kt(Math.min(250,n));let a=await mu(e,t.id);if(a===null)return i;if(i=ue.parse(a.value).job,i.id!==t.id)throw new x(`INTERNAL`,`Preparation identity changed.`,`Retry the original request.`)}return i},gu=async(e,t,n)=>{let r=re.parse(await e.mutate(`canvas.render.preparation.create`,t)),i=await hu(e,r.job,n);if(i.canvasId!==t.canvasId||i.requestedVersion!==t.expectedVersion||!on(i.scope,t.scope)||!on(i.request,t.request))throw new x(`CONFLICT`,`The native preparation does not match this request.`,`Read the canvas and prepare a new intent; do not apply this plan.`);if(i.state===`succeeded`&&i.result.loadedVersion!==t.expectedVersion)throw new x(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);return i},_u=async(e,t)=>{try{return v.parse(await Ni(e).execute(t))}catch(e){throw new x(e instanceof x?e.code:`INTERNAL`,e instanceof x?e.message:`The canvas commit could not be confirmed.`,`Read operation_status or repeat the original action with identical arguments and clientToken.`,{...e instanceof x&&e.fields,outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:t.canvasId,mutationId:t.mutationId,fingerprint:t.requestContext?.fingerprint})})}},vu=async(e,t,n,r)=>{if(n.result.loadedVersion!==t.baseVersion)throw new x(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);if(n.result.operations.length===0)return{outcome:`no_op`,canvasId:n.canvasId,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let i=je.parse({canvasId:n.canvasId,mutationId:t.clientToken,documentFormatVersion:14,baseVersion:t.baseVersion,operations:n.result.operations,requestContext:{fingerprint:r,revisionPolicy:`strict`,...t.request.kind===`duplicate`&&{copiedNodeIds:n.result.idMap}}}),a=await _u(e,i);if(a.canvasId!==n.canvasId||a.mutationId!==t.clientToken||a.previousVersion!==t.baseVersion||a.version!==t.baseVersion+1||t.request.kind===`duplicate`&&!on(a.copiedNodeIds,n.result.idMap))throw new x(`INTERNAL`,`The canvas commit receipt could not be verified.`,`Check operation_status using the original mutation reference before retrying.`,{outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:r})});return Pl(a,r)},yu=e=>({execute:async t=>{let n=i(t.canvasRef),r={...n.pageId!==void 0&&{pageId:n.pageId},nodeIds:[...n.nodeIds]},a=o({operation:`canvas.prepare/1`,reference:n,baseVersion:t.baseVersion,request:t.request}),s=se.parse(await e.query(`canvas.mutation.get`,{canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:a}));if(s.state===`committed`)return Pl(s.result,a);let c=await gu(e,{canvasId:n.canvasId,expectedVersion:t.baseVersion,request:t.request,scope:r},t.waitMs),l={kind:`canvas-preparation`,canvasId:n.canvasId,jobId:c.id,mutationId:t.clientToken,fingerprint:a};return c.state===`succeeded`?vu(e,t,c,a):Ml(c,l)}}),bu=/^[MLHVCSQTAZ]$/iu,xu=/[MLHVCSQTAZ]|[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/giu,Su={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},Cu=e=>{let t=e.match(xu)??[];if(t.join(``)!==e.replaceAll(/[\s,]/gu,``))return null;let n=[],r=``,i=0;for(;i<t.length;){let e=t[i]??``;if(bu.test(e))r=e,i+=1;else if(r===``||r.toUpperCase()===`Z`)return null;let a=Su[r.toUpperCase()]??0,o=t.slice(i,i+a).map(Number);if(o.length!==a||o.some(e=>!Number.isFinite(e)))return null;i+=a,n.push({command:r,values:o}),r.toUpperCase()===`M`&&(r=r===`M`?`L`:`l`)}return n},q=([e,t,n,r,i,a],{x:o,y:s})=>({x:e*o+n*s+i,y:t*o+r*s+a}),wu=e=>`${String(e.x)} ${String(e.y)}`,Tu=Math.PI/2,Eu=Math.PI*2,Du=(e,t,n,r)=>Math.atan2(e*r-t*n,e*n+t*r),Ou=(e,t,n)=>{let[r=0,i=0,a=0,o=0,s=0]=t,c=a*Math.PI/180,[l,u]=[Math.cos(c),Math.sin(c)],[d,f]=[(e.x-n.x)/2,(e.y-n.y)/2],[p,m]=[l*d+u*f,-u*d+l*f],h=Math.max(1,Math.hypot(p/r,m/i)),[g,_]=[Math.abs(r)*h,Math.abs(i)*h],ee=g*g*m*m+_*_*p*p,v=(o===s?-1:1)*Math.sqrt(Math.max(0,(g*g*_*_-ee)/ee)),[te,y]=[v*g*m/_,-v*_*p/g],[ne,re,ie,ae]=[(p-te)/g,(m-y)/_,(-p-te)/g,(-m-y)/_],b=Du(ne,re,ie,ae);return s===0&&b>0&&(b-=Eu),s===1&&b<0&&(b+=Eu),{ellipse:[l*g,u*g,-u*_,l*_,l*te-u*y+(e.x+n.x)/2,u*te+l*y+(e.y+n.y)/2],start:Du(1,0,ne,re),turn:b}},ku=(e,t,n)=>{let[r=0,i=0]=t;if(r===0||i===0||e.x===n.x&&e.y===n.y)return[e,n,n];let{ellipse:a,start:o,turn:s}=Ou(e,t,n),c=Math.ceil(Math.abs(s)/Tu-1e-9),l=s/c,u=4/3*Math.tan(l/4),d=(e,t)=>({x:Math.cos(e)-Math.sin(e)*t,y:Math.sin(e)+Math.cos(e)*t}),f=[];for(let e=0;e<c;e+=1){let[t,r]=[o+l*e,o+l*(e+1)];f.push(q(a,d(t,u)),q(a,d(r,-u)),e===c-1?n:q(a,d(r,0)))}return f},Au=(e,t,n)=>{let r=e.command.toUpperCase(),i=e.command!==r,{current:a}=t,o=(e=0,t=0)=>i?{x:a.x+e,y:a.y+t}:{x:e,y:t},[s=0]=e.values;if(r===`Z`)return{data:`Z`,pen:{...t,current:t.start}};if(r===`A`){let r=o(e.values[5],e.values[6]),i=ku(a,e.values,r),s=[];for(let e=0;e<i.length;e+=3)s.push(`C${i.slice(e,e+3).map(e=>wu(q(n,e))).join(` `)}`);return{data:s.join(``),pen:{...t,current:r}}}if(r===`H`||r===`V`){let e=r===`H`?o(s,i?0:a.y):o(i?0:a.x,s);return{data:`L${wu(q(n,e))}`,pen:{...t,current:e}}}let c=[];for(let t=0;t<e.values.length;t+=2)c.push(o(e.values[t],e.values[t+1]));let l=c.at(-1)??a;return{data:`${r}${c.map(e=>wu(q(n,e))).join(` `)}`,pen:{current:l,start:r===`M`?l:t.start}}},ju=(e,t)=>{let n=Cu(e);if(n===null)return null;let r=[],i={current:{x:0,y:0},start:{x:0,y:0}};for(let e of n){let n=Au(e,i,t);r.push(n.data),i=n.pen}return r.join(``)},Mu=(e,t)=>{let n=e.geometry;if(n?.kind!==`mask`||n.mode===`outline`||t?.box===void 0||t.component===`text`)return{};let r=H(t).opacity,i=H(t).fills.filter(e=>e.visible).toReversed().map(e=>$a({...e,opacity:e.opacity*r}));if(i.length===0)return{};let{x:a,y:o,width:s,height:c}=t.box,l=e=>i.map(()=>e).join(`, `);return{"mask-image":i.join(`, `),"mask-mode":l(n.mode===`luminance`?`luminance`:`alpha`),"mask-position":l(`${String(a)}px ${String(o)}px`),"mask-size":l(`${String(s)}px ${String(c)}px`),"mask-repeat":l(`no-repeat`)}},Nu=(e,t)=>{let n=t.geometry?.kind===`mask`?sc(e,t):null,r=t.box;if(r===void 0||n===null||n.shapes!==void 0)return{};if(n.path===``)return{"clip-path":`inset(50%)`};let[i,a,o,s,c,l]=n.matrix,u=ju(n.path,[i*r.width,a*r.height,o*r.width,s*r.height,c*r.width,l*r.height]);return u===null?null:{"clip-path":`path(${n.fillRule}, "${u}")`}},Pu=new Set([`data-enhance-id`,`data-enhance-locked`,`data-enhance-name`,`data-enhance-opaque`,`style`]),J=e=>{throw new x(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},Y=e=>{let t=cn(e,{context:`declarationList`,onParseError:e=>J(e.message)});if(t.type!==`DeclarationList`)return J(`Expected an inline CSS declaration list.`);let n=new Map;return t.children.forEach(e=>{if(e.type!==`Declaration`||e.important!==!1)return J(`Use ordinary inline CSS properties without !important or at-rules.`);let t=e.property.startsWith(`--`)?e.property:e.property.toLowerCase();if(n.has(t))return J(`Duplicate CSS property: ${t}.`);n.set(t,sn(e.value))}),Object.fromEntries(n)},Fu=e=>e.flatMap(e=>`tagName`in e?[e]:e.nodeName===`#text`&&`value`in e&&e.value.trim()===``?[]:J(`Container content must contain identified elements; text belongs inside its retained span.`)),Iu=e=>{let t=ln(e,{sourceCodeLocationInfo:!0,onParseError:e=>J(`Invalid HTML at line ${String(e.startLine)}: ${e.code}.`)}),n=[t];for(;n.length>0;){let e=n.pop();if(e===void 0)break;e.childNodes=e.childNodes.filter(e=>!(`tagName`in e)||Vr(e.tagName));let t=e.childNodes.filter(e=>`tagName`in e);for(let e of t)e.attrs=e.attrs.filter(e=>Ur(e.name,e.value)),n.push(e)}return t},Lu=new Set([...Pu,`viewBox`,`preserveAspectRatio`]),Ru=(e,t)=>{let[n,...r]=Fu(e.childNodes);if(n?.tagName!==`path`||r.length>0)return J(`A vector element must hold exactly one path.`);let i=e=>n.attrs.find(t=>t.name===e)?.value,a=i(`fill-rule`)??`nonzero`;return a!==`nonzero`&&a!==`evenodd`?J(`Unsupported fill-rule: ${a}.`):{d:i(`d`)??``,fillRule:a,fill:i(`fill`)??`none`,viewBox:t}},zu=e=>{let t=e.tagName===`svg`?Lu:Pu;return Object.fromEntries(e.attrs.map(e=>!t.has(e.name)||e.namespace!==void 0?J(`Unsupported attribute: ${e.name}.`):[e.name,e.value]))},Bu=e=>{let t=e[`data-enhance-id`],n=e[`data-enhance-name`];if(t===void 0||t===``||n===void 0)return J(`Every retained element requires its identity and name.`);let r=e[`data-enhance-opaque`];if(r!==void 0&&r!==`true`)return J(`Invalid opaque marker on ${t}.`);let i=e[`data-enhance-locked`];return i!==void 0&&i!==`true`?J(`Invalid locked marker on ${t}.`):{id:t,label:n,opaque:r===`true`,locked:i===`true`,styles:Y(e.style??``)}},Vu=e=>{let t=[],n=[];for(let r of Fu(e.childNodes)){let e=r.attrs.find(e=>e.name===`data-enhance-paint`)?.value;if(e===void 0){n.push(r);continue}let i=r.attrs.find(e=>e.name===`style`)?.value??``;t.push(e===`border`||e===`outline`?{owner:e,styles:Y(i)}:{owner:`paint`,paintId:e,styles:Y(i)})}return[t,n]},Hu=(e,t)=>Fu(e.childNodes).map((e,n)=>{let r=e.attrs.find(e=>e.name===`data-enhance-run`)?.value;if(e.tagName!==`span`||r!==String(n))return J(`Text ${t} holds run spans only, each with its data-enhance-run place.`);let i=e.attrs.find(e=>e.name===`style`)?.value??``;return{text:Uu(e,t),styles:Y(i)}}),Uu=(e,t)=>e.childNodes.map(e=>`value`in e?e.value:J(`Retained text ${t} must contain text only; its existing rich formatting is preserved by the text owner.`)).join(``),Wu=e=>{let t=Iu(e),n=new Set,r=e=>{if(e.tagName!==`div`&&e.tagName!==`span`&&e.tagName!==`svg`)return J(`Unsupported retained element: ${e.tagName}.`);let t=zu(e),i=Bu(t);if(n.has(i.id))return J(`Duplicate node identity: ${i.id}.`);if(n.add(i.id),e.tagName===`svg`)return{...i,tag:`svg`,path:Ru(e,t.viewBox??``),text:``,children:[]};let a=e.tagName===`span`&&e.childNodes.some(e=>`tagName`in e),[o,s]=e.tagName===`span`?[[],[]]:Vu(e);return{...i,tag:e.tagName,...a&&{runs:Hu(e,i.id)},...o.length>0&&{paints:o},text:!a&&e.tagName===`span`?Uu(e,i.id):``,children:s.map(e=>r(e))}},i=Fu(t.childNodes),a=i[0];return a===void 0||i.length!==1?J(`An editable update must contain exactly its original root.`):r(a)},Gu=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Ku={fill:`100% 100%`,cover:`cover`,contain:`contain`,"scale-down":`contain`,none:`auto`},qu={"100% 100%":`fill`,cover:`cover`,contain:`contain`,auto:`none`},Ju=/^background(?:-.+)?$/u,Yu=/^url\((?:"([^"]*)"|'([^']*)'|([^"'()\s]*))\)$/u,Xu=e=>{if(e.component!==`image`)return;let t=e.props?.src;return typeof t==`string`&&t!==``?t:void 0},Zu=e=>{let t=Xu(e);if(t===void 0)return{};let n=e.props?.fit,r=e.props?.position;return{"background-image":`url(${JSON.stringify(t)})`,"background-size":Ku[typeof n==`string`?n:`fill`]??`100% 100%`,"background-position":typeof r==`string`?r:`50% 50%`,"background-repeat":`no-repeat`}},Qu=(e,t)=>Xu(e)!==void 0&&Ju.test(t),$u=(e,t,n)=>{if(Xu(e)===void 0)return[];let r=[...new Set([...Object.keys(t),...Object.keys(n)])].filter(e=>Ju.test(e)&&t[e]!==n[e]);if(r.length===0)return[];if(r.some(e=>![`background-image`,`background-size`,`background-position`].includes(e)))return Gu(`An image paints once from its source on ${e.id}; change only its background-image URL, background-size (100% 100%, cover, contain or auto) and background-position.`);let i=Yu.exec(n[`background-image`]??``),a=i?.[1]??i?.[2]??i?.[3],o=qu[n[`background-size`]??``],s=n[`background-position`];return a===void 0||a===``||o===void 0||s===void 0?Gu(`An image on ${e.id} needs a background-image URL, a background-size of 100% 100%, cover, contain or auto, and a background-position.`):[{op:`setProps`,nodeId:e.id,props:{...e.props,...r.includes(`background-image`)&&{src:a},...r.includes(`background-size`)&&{fit:o},...r.includes(`background-position`)&&{position:s}}}]},X=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},ed={border:/^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u,outline:/^outline(?:-.+)?$/u,paint:/^$/u},td=e=>Object.fromEntries(Object.entries(Y(e)).toSorted(([e],[t])=>e.localeCompare(t))),nd=e=>td(Object.entries(e).flatMap(([e,t])=>{let n=wt(e,t);return e.startsWith(`--`)||n.includes(`var(--canvas`)||n.includes(`url(#`)?[]:[`${e}:${n}`]}).join(`;`)),rd=e=>{let t=B(e),n=n=>Yo(t,n).map(t=>({owner:`paint`,paintId:t.id,styles:nd(ps(e,t))})),r=cs(e),i=Ms(e);return[...n(`outer-shadow`),...Jo(t).map(e=>({owner:`paint`,paintId:e.id,styles:nd(Ds(e))})),...n(`inner-shadow`),...r===null?[]:[{owner:`border`,styles:nd(r)}],...i===null?[]:[{owner:`outline`,styles:nd(i)}]]},id=(e,t)=>e.some(e=>ed[e.owner].test(t)),ad=e=>st.find(t=>t===(e??`normal`))??X(`Unsupported mix-blend-mode: ${e??``}.`),od=/stroke-(?:dasharray|linecap)="[^"]*"/gu,sd=e=>{let t=/^url\(["']?data:image\/svg\+xml,(.*?)["']?\)$/u.exec(e??``)?.[1];return t===void 0?void 0:decodeURIComponent(t)},cd=(e,t,n)=>{let r=sd(t),i=sd(n);if(i===void 0||r?.replaceAll(od,``)!==i.replaceAll(od,``))return X(`Only stroke-dasharray and stroke-linecap of the dash mask can change on ${e.id}.`);let a=(/stroke-dasharray="([^"]*)"/u.exec(i)?.[1]??``).split(/[\s,]+/u).filter(e=>e!==``).map(Number);if(a.length===0||a.some(e=>!Number.isFinite(e)||e<0))return X(`A dash pattern is one or more lengths of 0 or more, on ${e.id}.`);let o=/stroke-linecap="([^"]*)"/u.exec(i)?.[1];return o!==`butt`&&o!==`round`&&o!==`square`?X(`A dash cap is butt, round or square, on ${e.id}.`):{dashPattern:a,dashCap:o===`butt`?`none`:o}},ld=(e,t,n,r)=>{let i=n.paints.filter(e=>e.visible),[a]=i;if(a===void 0||i.length!==1)return X(`Set a blend on one paint of the ${t} of ${e.id} in the editor.`);let o=ad(r);return n.paints.map(e=>e===a?{...e,blendMode:o}:e)},ud=(e,t)=>{if(t.size===0)return[];let n=e.appearance?.fills??[],r=e.appearance?.shadows??[];for(let i of t.keys())if(n.every(e=>e.id!==i)&&r.every(e=>e.id!==i))return X(`${e.id} has no fill or shadow ${i}.`);let i=e=>e.map(e=>t.has(e.id)?{...e,blendMode:ad(t.get(e.id))}:e);return[...n.some(e=>t.has(e.id))?[{op:`setAppearance`,nodeId:e.id,appearance:{fills:i(n)}}]:[],...r.some(e=>t.has(e.id))?[{op:`setAppearance`,nodeId:e.id,appearance:{shadows:i(r)}}]:[]]},dd=(e,t,n)=>{let r=e=>JSON.stringify(e.map(e=>e.paintId??e.owner)),i=n.find(e=>e.paintId!==void 0&&t.every(t=>t.paintId!==e.paintId));if(i?.paintId!==void 0)return X(`${e.id} has no fill or shadow ${i.paintId}.`);if(r(t)!==r(n))return X(`Keep each paint element of ${e.id}.`);let a=new Map;return[...n.flatMap((n,r)=>{let i=t[r];if(i===void 0||JSON.stringify(i.styles)===JSON.stringify(n.styles))return[];let o=[...new Set([...Object.keys(i.styles),...Object.keys(n.styles)])].filter(e=>i.styles[e]!==n.styles[e]);if(n.owner===`paint`&&n.paintId!==void 0)return o.some(e=>e!==`mix-blend-mode`)?X(`The paint element ${n.paintId} of ${e.id} follows its paint, so only its mix-blend-mode can change there; change ${o.join(`, `)} through the appearance operation.`):(a.set(n.paintId,n.styles[`mix-blend-mode`]),[]);if(o.some(e=>e!==`mix-blend-mode`&&e!==`mask-image`))return X(`The ${n.owner}'s paint element of ${e.id} follows its ${n.owner}, so ${o.join(`, `)} cannot change there; change the ${n.owner} CSS on the layer, or the paint element's mix-blend-mode or dash mask.`);let s=n.owner===`outline`?`outline`:`border`,c=e.appearance?.[s];if(c===void 0)return X(`The ${s} of ${e.id} has no paint element to write.`);let l=o.includes(`mix-blend-mode`)?ld(e,s,c,n.styles[`mix-blend-mode`]):c.paints,u=o.includes(`mask-image`)?cd(e,i.styles[`mask-image`],n.styles[`mask-image`]):{};return[{op:`setAppearance`,nodeId:e.id,appearance:{[s]:{...c,paints:l,...u}}}]}),...ud(e,a)]},fd=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},pd=e=>e.kind===`text`||e.kind===`span`&&e.children.every(e=>e.kind===`text`),md=e=>Ee([e]),hd=e=>e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`),gd=e=>e.replaceAll(/-([a-z])/gu,(e,t)=>t.toUpperCase()),_d=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,n])=>{let r=gd(e);return f.has(r)?[r,n]:fd(`Run ${String(t+1)} cannot hold ${e}; set it on the text layer.`)})),vd=e=>{if(e.kind!==`span`)return{};let[t,...n]=(e.fills??[]).filter(e=>e.visible),r=t===void 0||n.length>0?void 0:io(t),i=[...Object.entries(e.styles).map(([e,t])=>{let n=hd(e);return`${n}:${wt(n,t)}`}),...r===void 0?[]:[`color:${r}`]];return Object.fromEntries(Object.entries(Y(i.join(`;`))).toSorted(([e],[t])=>e.localeCompare(t)))},yd=e=>{let t=Et(e);return t.length===0||t.some(e=>!pd(e))?null:t.map(e=>({text:md(e),styles:vd(e)}))},bd=e=>Et(e).some(e=>!pd(e)),xd=(e,t,n,r)=>{if(`mix-blend-mode`in r.styles)return fd(`Text paints have no blend of their own. Set mix-blend-mode on the text layer.`);let{color:i,...a}=r.styles,o=_d(a,t),s=i===void 0?void 0:F(`${e.id}-run-${String(t)}`,i);if(i!==void 0&&s===null)return fd(`The color of run ${String(t+1)} is not a colour.`);let{fills:c,...l}=n.kind===`span`?n:{kind:`span`,styles:{},children:[]},u=c!==void 0&&vd(n).color===void 0,d=s==null?u?c:void 0:[s];return{...l,styles:o,...d!==void 0&&{fills:d},children:[{kind:`text`,text:r.text}]}},Sd=(e,t,n)=>{if(t.length!==n.length)return fd(`Keep each run span of ${e.id}; change a run's words or CSS in place.`);let r=Et(e),i=r.map((r,i)=>{let a=t[i],o=n[i];return a===void 0||o===void 0||JSON.stringify(a)===JSON.stringify(o)?r:xd(e,i,r,o)});if(i.every((e,t)=>e===r[t]))return[];let a={...e.props,richText:i,text:Ee(i)};return[{op:`editText`,nodeId:e.id,change:Se(e,{...e,props:a})}]},Cd=new Set([`path`,`polygon`,`boolean`]),wd=e=>Cd.has(e.geometry?.kind??``),Td=e=>{let t=(e.appearance?.fills??[]).filter(e=>e.visible);return t.length>1||t.some(e=>e.kind!==`solid`||(e.blendMode??`normal`)!==`normal`)?`A vector with a gradient, image or blended fill keeps its paint in the editor.`:null},Ed=e=>{let t=kr(e);if(typeof t==`string`)return null;let n=(e.appearance?.fills??[]).find(e=>e.visible),{x:r,y:i,width:a,height:o}=t.viewBox;return{d:t.path,fillRule:t.fillRule,fill:n===void 0?`none`:io(n)??`none`,viewBox:[r,i,a,o].map(String).join(` `)}},Dd=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Od=e=>{let[t=0,n=0,r=0,i=0]=e.split(/\s+/u).map(Number);return r>0&&i>0?{x:t,y:n,width:r,height:i}:Dd(`Invalid viewBox: ${e}.`)},kd=(e,t,n)=>n.d.trim()===``?Dd(`The path of ${t.id} is empty.`):[{op:`setGeometry`,nodeId:t.id,geometry:{kind:`path`,path:n.d,fillRule:n.fillRule,viewBox:Od(n.viewBox)}},...t.geometry?.kind===`boolean`?Fi(e,t.id).map(e=>({op:`remove`,nodeId:e})):[]],Ad=(e,t)=>{let n=(e.appearance?.fills??[]).find(e=>e.visible),r=n?.kind===`solid`?n.id:`${e.id}-fill`,i=t===`none`?null:F(r,t);return i===null&&t!==`none`?Dd(`The fill of ${e.id} is not a colour.`):{op:`setAppearance`,nodeId:e.id,appearance:{fills:i===null?[]:[{...i,...n?.kind===`solid`&&n.blendMode!==void 0&&{blendMode:n.blendMode}}]}}},jd=(e,t,n,r)=>[...n.d===r.d&&n.fillRule===r.fillRule&&n.viewBox===r.viewBox?[]:kd(e,t,r),...n.fill===r.fill?[]:[Ad(t,r.fill)]],Md=new Set([`root`,`frame`,`group`,`rectangle`,`image`,`text`]),Nd={screen:`Its pixels come from a recorded page. Use Make editable to edit it as layers.`,recording:`Its pixels come from a recording.`,prototype:`Its pixels come from a running build.`},Pd=/^(?:mask(?:-.+)?|clip-path)$/u,Fd=`This layer kind has no editable HTML form yet; edit it in the editor.`,Id=(e,t,n)=>{let r=Nd[t.component];return r===void 0?Nu(e,t)===null?`This mask's shape cannot be read; edit it in the editor.`:t.component===`text`&&(n>0||bd(t))?`Text with nested layers or nested formatting keeps its formatting in the editor.`:wd(t)?Td(t)??(Ed(t)===null?Fd:null):Md.has(t.component)&&(t.geometry===void 0||t.geometry.kind===`mask`)?null:Fd:r},Ld=(e,t)=>{let n={...Vs(t),...Mu(t,Qs(e,t)),...Nu(e,t)},r=ft(t),i=Object.entries(n).flatMap(([e,n])=>{let r=wt(e,n);return e.startsWith(`--`)||r.includes(`var(--canvas`)||r.includes(`url(#`)||xs(t,[e]).length===0&&!Pd.test(e)?[]:[[e,r]]});return{...Object.fromEntries(i),...Zu(t),...Object.fromEntries(Object.entries(r).map(([e,t])=>[e,wt(e,t)]))}},Rd=e=>{throw new x(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},Z=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`),zd=e=>wd(e)?Ed(e):null,Bd=/^background(?:-.+)?$/u,Vd=e=>`<path d="${Z(e.d)}" fill-rule="${e.fillRule}" fill="${Z(e.fill)}"></path>`,Hd=e=>{let t=Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`);return t===``?``:` style="${Z(t)}"`},Ud=e=>`<div data-enhance-paint="${Z(e.paintId??e.owner)}"${Hd(e.styles)}></div>`,Wd=(e,t)=>`<span data-enhance-run="${String(t)}"${Hd(e.styles)}>${Z(e.text)}</span>`,Gd=e=>{let t=Object.entries(e.styles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`),n=`data-enhance-id="${Z(e.id)}" data-enhance-name="${Z(e.label)}"${e.opaque?` data-enhance-opaque="true"`:``}${e.locked?` data-enhance-locked="true"`:``}${t===``?``:` style="${Z(t)}"`}`;if(e.path!==void 0)return`<svg ${n} viewBox="${Z(e.path.viewBox)}" preserveAspectRatio="none">${Vd(e.path)}</svg>`;let r=(e.runs??[]).map((e,t)=>Wd(e,t)).join(``),i=(e.paints??[]).map(e=>Ud(e)).join(``);return`<${e.tag} ${n}>${Z(e.text)}${r}${i}${e.children.map(e=>Gd(e)).join(``)}</${e.tag}>`},Kd=(e,t)=>{let n=new Set,r=[],i={},a=Ii(e),o=t=>{if(n.has(t))return Rd(`The document contains repeated node identity.`);n.add(t);let s=N(e,t),c=a.get(t)??[],l=Id(e,s,c.length),u=l!==null;u&&(r.push(s.id),i[s.id]=l);let d=u?null:zd(s),f=u||s.component!==`text`?null:yd(s),p=u||d!==null?[]:rd(s),m=u?{}:Y(Object.entries(Ld(e,s)).filter(([e])=>d===null||!Bd.test(e)).filter(([e])=>!id(p,e)).map(([e,t])=>`${e}:${t}`).join(`;`));return{id:s.id,tag:d===null?s.component===`text`?`span`:`div`:`svg`,...d!==null&&{path:d},label:s.label,opaque:u,locked:zi(e,t),styles:m,...f!==null&&{runs:f},...p.length>0&&{paints:p},text:f!==null||u||s.component!==`text`?``:ae(s)??``,children:u||d!==null?[]:c.map(e=>o(e))}},s=o(t);return{projectionVersion:2,root:s,html:Gd(s),opaqueNodeIds:r,sealedReasons:i}},qd=(e,t,n)=>{if(e.rootNodeIds!==void 0)return e.rootNodeIds;if(t.nodeIds.length>0)return t.nodeIds;if(t.pageId===void 0)return[`root`];let r=it(t,n);if(r.ok)return r.rootNodeIds;throw g(t,n),new x(`NOT_FOUND`,`The linked page is unavailable.`,`Copy a current page link.`)},Jd=(e,t)=>{let n=new Set(t);for(let r of t){let t=new Set,i=e.relationships[r]?.parentId;for(;i!==void 0;){if(t.has(i)||n.has(i))throw new x(`BAD_REQUEST`,`Outline roots overlap or contain a parent cycle.`,`Choose disjoint roots so each depth and coverage statement has one meaning.`);t.add(i),i=e.relationships[i]?.parentId}}if(n.size!==t.length)throw new x(`BAD_REQUEST`,`Outline roots repeat.`,`Choose each root once.`)},Yd=(e,t,n,r)=>{let i=[],a=new Set,o=Ii(e),s=(t,c)=>{if(a.has(t))return;a.add(t);let l=N(e,t),u=o.get(t)??[],d=zi(e,t);if(i.push({id:t,label:l.label,kind:l.component,parentId:e.relationships[t]?.parentId??null,sortKey:e.relationships[t]?.sortKey??null,depth:c,childCount:u.length,childrenOmitted:c===n&&u.length>0,locked:d,visible:l.visible!==!1,editable:r&&!d&&[`root`,`frame`,`group`,`text`].includes(l.component),bounds:l.box??null}),c<n)for(let e of u)s(e,c+1)};for(let e of t)s(e,0);return i},Xd=(e,t,n)=>{if(e===void 0)return 0;let r=we(e,bt);if(r.canvasId!==t.reference.canvasId||r.queryDigest!==n)throw new x(`BAD_REQUEST`,`This cursor belongs to another outline query.`,`Restart the outline read with the requested scope.`);if(r.version!==t.version)throw new x(`CONFLICT`,`The canvas changed between outline pages.`,`Restart the scoped read at the current revision. Do not combine pages from different revisions.`,{currentVersion:String(t.version),outcome:`not_committed`});return r.offset},Zd=(e,t)=>{let{reference:n,scene:r,version:i,isCurrent:a}=t,s=qd(e,n,r);S(n,r,s),Jd(r,s);let c=o({reference:n,roots:e.rootNodeIds??null,depth:e.depth,limit:e.limit}),l=Xd(e.cursor,t,c),u=Yd(r,s,e.depth,a);if(l>u.length)throw new x(`BAD_REQUEST`,`The outline cursor is out of range.`,`Restart the outline read.`);let d=u.slice(l,l+e.limit),f=l+d.length,m=u.some(e=>e.childrenOmitted);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[...s]},view:`outline`,complete:f===u.length&&!m,returnedCount:d.length,total:u.length,nodes:d,omittedDescendants:m,nextCursor:f<u.length?p({protocol:`enhance-canvas-outline/1`,canvasId:n.canvasId,version:i,queryDigest:c,offset:f}):null,warnings:a?[]:[`This legacy document is read-only until the normal editor upgrades it.`]}},Qd=e=>{let t=c(e);if(t!==null)return{storage:`canvas-image`,reference:e,ownerId:t.canvasId,assetId:t.assetId};let n=Ce(e);if(n!==null)return{storage:`canvas-font`,reference:e,ownerId:n.canvasId,assetId:n.sha256};let r=/^\/v1\/recording-assets\/([a-f0-9-]{36})\/([a-f0-9]{32,64})$/u.exec(e);return r===null?{storage:e.startsWith(`data:`)?`inline`:/^https?:\/\//u.test(e)?`external`:`opaque`,reference:null,ownerId:null,assetId:null}:{storage:`recording-asset`,reference:e,ownerId:r[1]??null,assetId:r[2]??null}},$d=(e,t)=>typeof e[t]==`string`?e[t]:null,ef=(e,t)=>{let n=new Map,r=[...t].toSorted((e,t)=>e.localeCompare(t));for(let t of r){let r=e.scene.nodes[t];if(r===void 0)continue;let i=(e,r,i)=>{let a={nodeId:t,kind:e,sourceDigest:o(r),...Qd(r),delivery:`not_checked`,metadata:i};return n.set(o(a),a),r};Jr(r,e=>i(`image`,e,null)),Ie(r.props,(e,t)=>i(`font`,e,{family:$d(t,`family`),style:$d(t,`style`),weight:$d(t,`weight`)}))}return Array.from(n,([,e])=>e)},tf=(e,t,n)=>{if(e.cursor===void 0)return 0;let r=we(e.cursor,pt);if(r.canvasId!==t.reference.canvasId||r.digest!==n)throw new x(`BAD_REQUEST`,`The resource cursor belongs to another query.`,`Restart this scoped resource read.`);if(r.version!==t.version)throw new x(`CONFLICT`,`The canvas changed between resource pages.`,`Restart the read at the current revision.`);return r.offset},nf=(e,t)=>{let n=it(t.reference,t.scene);if(!n.ok)throw new x(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link; do not broaden the request.`);let r=o({reference:t.reference,limit:e.limit}),i=tf(e,t,r),a=ef(t,n.nodeIds);if(i>a.length)throw new x(`BAD_REQUEST`,`The resource cursor is out of range.`,`Restart the scoped resource read.`);let s=e=>{let o=i+e.length;return{view:`resources`,canvasId:t.reference.canvasId,version:t.version,scope:{rootNodeIds:[...n.rootNodeIds]},coverage:`authored-resource-slots`,resources:e,total:a.length,returnedCount:e.length,complete:o===a.length,nextCursor:o===a.length?null:p({protocol:`enhance-canvas-resources/1`,canvasId:t.reference.canvasId,version:t.version,digest:r,offset:o}),warnings:[`Inventory includes declared image and font resource slots, including hidden and unused declarations. It does not resolve computed font usage or assets inside opaque screens, recordings, prototypes or raw CSS.`,`Resource delivery and availability have not been checked. Protected paths retain product authorization. External URLs and inline bytes are omitted; their digests identify the original source without exposing credentials or blobs.`,`Scoped reads include declarations on selected nodes and descendants only. A font declaration owned by an ancestor requires a separate explicit read of that scope.`]}},c=48e3-Buffer.byteLength(JSON.stringify(s([])));return s(G(a,i,e.limit,c).entries)},rf=(e,t,n)=>{if(e.state!==`ready`){if(t.cursor!==void 0)throw new x(`CONFLICT`,`The transcript changed during pagination.`,`Restart the read.`);return e}let{cursor:r,...i}=t,a=o({scope:n,range:i,transcript:e}),s=r===void 0?null:we(r,tt);if(s!==null&&s.digest!==a)throw new x(`CONFLICT`,`The transcript cursor no longer matches this source, range or revision.`,`Restart the requested range; do not combine transcript revisions.`);let c=e.cues.filter(e=>e.endMs>=t.startMs&&(t.endMs===void 0||e.startMs<t.endMs)),l=s?.offset??0;if(l>c.length)throw new x(`BAD_REQUEST`,`Transcript cursor offset is out of range.`,`Restart the read.`);let u=G(c,l,t.limit).entries,d=l+u.length;return{state:`ready`,languageCode:e.languageCode,integrity:e.integrity,isRefreshing:e.isRefreshing,requestedRange:{startMs:t.startMs,endMs:t.endMs??null},cues:u,returnedCount:u.length,totalInRange:c.length,omittedOutsideRange:e.cues.length-c.length,complete:d===c.length,nextCursor:d<c.length?p({protocol:`enhance-canvas-transcript/1`,digest:a,offset:d}):null}},af=[`recording.get`,`prototype.getPublishStatus`,`transcript.get`],of=e=>{let t=Te.safeParse(e.node.props?.capture).data;if(t===void 0)return null;let n=e.screens.find(e=>e.screenId===t.screenId);return{kind:`screen`,screenId:t.screenId,availability:n===void 0?t.html===void 0?`unavailable`:`inline-only`:n.download===null?`pending`:`available`,sourceUrl:n?.route??null,title:n?.title??null,viewport:n?.viewport??t.viewport,atMs:n?.atMs??t.atMs,recordingId:n===void 0?t.provenance?.recordingId??null:n.sourceRecordingId,missingAssetCount:n?.assetBundle?.missingAssetCount??null}},sf=e=>{let t=m.safeParse(e.props?.conversion).data;if(t===void 0)return{kind:`none`};let n=new Map,r=t.report?.issues??[];for(let e of r)n.set(e.code,(n.get(e.code)??0)+1);return{kind:`conversion`,recordingId:t.provenance?.recordingId??null,nodeCount:t.report?.nodeCount??null,issueCounts:Object.fromEntries(n)}},cf=async(e,t)=>{let{node:n,canvasId:r}=t;if(n.component===`recording`){let t=me.parse(n.props),i=w.uuid().parse(t.recordingId),a=Nt.parse(await e.query(af[0],{canvasId:r,recordingId:i}));return{kind:`recording`,recordingId:i,durationMs:a.durationMs,viewport:a.viewport,sourceUrl:a.sourceUrl,interrupted:a.interrupted,integrity:a.integrity,chunkCount:a.chunks.length,missingChunkCount:a.chunks.filter(e=>e.state===`missing`).length,hasAudio:a.audio!==null,missingAssetCount:a.missingAssetCount}}if(n.component===`prototype`){let t=d.parse(n.props),i=ce.parse(await e.query(af[1],{canvasId:r,deploymentId:t.deploymentId}));if(i.prototypeId!==t.prototypeId)throw new x(`CONFLICT`,`Prototype identity does not match its deployment.`,`Read the node again.`);return{kind:`prototype`,...t,state:i.state,fileCount:i.fileCount}}return of(t)??sf(n)},lf=e=>({execute:async t=>{let n=await cf(e,t),r=t.input.transcript,i=`recordingId`in n?n.recordingId:null;if(r!==void 0&&i===null)throw new x(`BAD_REQUEST`,`This object has no recording transcript source.`,`Choose a recording or a capture with recording provenance.`);let a=r===void 0?null:rf(pe.parse(await e.query(af[2],{canvasId:t.canvasId,recordingId:w.uuid().parse(i)})),r,{canvasRef:t.input.canvasRef,nodeId:t.node.id,version:t.version}),o=n.kind===`screen`&&[`pending`,`unavailable`].includes(n.availability);return{canvasId:t.canvasId,version:t.version,scope:{rootNodeIds:[t.node.id]},view:`source`,nodeId:t.node.id,source:n,transcript:a,complete:!o&&(a===null||a.state===`empty`||a.state===`ready`&&a.complete),pixelsInspected:!1,warnings:[...o?[`The captured source bytes are not currently available.`]:[],...a===null?[]:[`Transcript times describe speech, not verified visual transitions. Render and inspect candidate moments.`]]}}}),uf=[`canvas.document.get`],df=e=>{throw new x(`CONFLICT`,`Canvas version ${String(e)} no longer matches this read.`,`Restart the scoped read at the current revision. Do not combine pages from different revisions.`,{currentVersion:String(e),outcome:`not_committed`})},ff=(e,t)=>{let{reference:n,scene:r,version:i}=t;if(!t.isCurrent)throw new x(`BAD_REQUEST`,`This document format cannot produce an editable snapshot.`,`Open it in the current editor before editing.`);S(n,r,[e.rootNodeId]);let a=Kd(r,e.rootNodeId);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[e.rootNodeId]},view:`editable`,complete:!0,projectionVersion:a.projectionVersion,rootNodeId:e.rootNodeId,html:a.html,opaqueNodeIds:[...a.opaqueNodeIds],sealedReasons:{...a.sealedReasons},snapshotToken:Tt({reference:n,version:i,rootNodeId:e.rootNodeId,html:a.html}),warnings:a.opaqueNodeIds.length>0?[`Preserve opaque placeholders unchanged; their authored content remains in the canvas.`]:[]}},pf=e=>({execute:async t=>{let n=i(t.canvasRef),r=ze.parse(await e.query(uf[0],{canvasId:n.canvasId}));if(t.expectedVersion!==void 0&&t.expectedVersion!==r.version)return df(r.version);let a=Xe.safeParse(r.document),o=a.success?a.data:St.parse(r.document);return t.view===`resources`?nf(t,{reference:n,scene:o,version:r.version,isCurrent:a.success}):t.view===`outline`?Zd(t,{reference:n,scene:o,version:r.version,isCurrent:a.success}):t.view===`source`?(S(n,o,[t.nodeId]),lf(e).execute({canvasId:n.canvasId,version:r.version,node:N(o,t.nodeId),screens:r.screens,input:t})):ff(t,{reference:n,scene:o,version:r.version,isCurrent:a.success})}}),mf=[`canvas.mutation.get`],hf=e=>({execute:async t=>{let n=t.reference.canvasId,r=se.parse(await e.query(mf[0],{canvasId:n,mutationId:t.clientToken,fingerprint:t.fingerprint}));if(r.state===`committed`)return Pl(r.result,t.fingerprint);let i=await Pi({remote:e},n,t.baseVersion),a=await t.plan(i);if(`outcome`in a)return a;if(Ac(t.reference,i,a),a.length===0)return{outcome:`no_op`,canvasId:n,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let o=je.safeParse({canvasId:n,documentFormatVersion:14,mutationId:t.clientToken,baseVersion:t.baseVersion,operations:a,requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});if(!o.success)throw new x(`BAD_REQUEST`,`The planned edit exceeds the canonical canvas contract.`,o.error.issues[0]?.message??`Reduce the edit scope.`,{outcome:`not_committed`});return Pl(v.parse(await Ni(e).execute(o.data)),t.fingerprint)}}),gf=(e,t)=>{let n=Ii(e),r=new Set(t),i=new Set,a=t=>{if(i.has(t))return;if(i.add(t),N(e,t),zi(e,t))throw new x(`BAD_REQUEST`,`Removing this subtree would remove locked content: ${t}.`,`Keep the locked subtree, or explicitly unlock it before requesting removal.`);let r=n.get(t)??[];for(let e of r)a(e)};for(let e of r){if(e===`root`)throw new x(`BAD_REQUEST`,`The canvas root cannot be removed.`,`Name its children.`);a(e)}return[...r].filter(t=>{let n=e.relationships[t]?.parentId;for(;n!==void 0;){if(r.has(n))return!1;n=e.relationships[n]?.parentId}return!0}).map(e=>({op:`remove`,nodeId:e}))},_f=e=>({execute:async({clientToken:t,...n})=>{let r=i(n.canvasRef);return hf(e).execute({reference:r,baseVersion:n.baseVersion,clientToken:t,fingerprint:o({operation:`canvas.remove/1`,...n,reference:r}),plan:e=>gf(e,n.rootNodeIds)})}}),vf=(e,t,n,r)=>{let i=e.parents.get(t),a=e.children.get(n)??[];if(i===n&&a.indexOf(t)===r)return;if(zi(e.document,t)||zi(e.document,n))throw new x(`BAD_REQUEST`,`Locked node ${t} cannot be rearranged through HTML.`,`Keep locked placeholders in place or unlock them in the editor before editing.`);i!==void 0&&e.children.set(i,(e.children.get(i)??[]).filter(e=>e!==t));let o=e.children.get(n)??[];o.splice(r,0,t),e.children.set(n,o),e.parents.set(t,n),e.moves.push({nodeId:t,parentId:n,index:r})},yf=(e,t,n)=>{let r={...e,nodes:Object.fromEntries(Object.entries(e.nodes).filter(([e])=>!n.has(e))),relationships:Object.fromEntries(Object.entries(e.relationships).filter(([e])=>!n.has(e)))},i={document:r,parents:new Map(Object.entries(r.relationships).map(([e,t])=>[e,t.parentId])),children:new Map([...Ii(r)].map(([e,t])=>[e,[...t]])),moves:[]},a=e=>{for(let[t,n]of e.children.entries())vf(i,n.id,e.id,t),a(n)};return a(t),i.moves.length===0?[]:$i(r,i.moves).operations},bf=e=>{throw new x(`BAD_REQUEST`,e,`Read the current subtree and reduce or correct the edit. No canvas changes were committed.`)},xf=(e,t,n)=>{if(Object.keys(t.idMap).length!==n.fragments.length)return bf(`Native compilation returned unexpected fragment identities.`);if(t.operations.length!==n.fragments.length)return bf(`Native compilation returned an incomplete insertion plan.`);let r={...e,nodes:{...e.nodes},relationships:{...e.relationships}};for(let[e,i]of n.fragments.entries()){let n=t.operations[e];if(n?.op!==`insertConvertedSubtree`||n.destination.kind!==`insert-children`||n.destination.targetNodeId!==i.parentNodeId||n.rootNodeId!==t.idMap[i.id])return bf(`Native compilation returned a mismatched insertion plan.`);for(let e of Object.keys(n.nodes))if(r.nodes[e]!==void 0||Object.hasOwn(r.tombstones,e))return bf(`New HTML identity ${e} already exists.`);let a=Fi(r,i.parentNodeId).at(-1),o=a===void 0?null:r.relationships[a]?.sortKey??null;Object.assign(r.nodes,n.nodes),Object.assign(r.relationships,n.relationships,{[n.rootNodeId]:{parentId:i.parentNodeId,sortKey:It(o,null)}})}return r},Sf=(e,t)=>({...e,id:Object.hasOwn(t,e.id)?t[e.id]??e.id:e.id,children:e.children.map(e=>Sf(e,t))}),Cf={operations:[],idMap:{},rootNodeIds:[]},wf=(e,t,n=Cf)=>{let r=xf(e,n,t),i=Sf(t.root,n.idMap);return[...t.operations,...n.operations,...yf(r,i,t.removed)]},Tf=e=>e.attrs.some(e=>e.name===`data-enhance-paint`),Ef=e=>e.attrs.find(e=>e.name===`data-enhance-id`)?.value,Df=e=>{throw new x(`BAD_REQUEST`,e,`Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.`)},Of=e=>e.flatMap(e=>`tagName`in e?[e,...Of(e.childNodes)]:[]),kf=e=>{let t=Iu(e),n=Of(t.childNodes),r=new Set(n.map(e=>Ef(e))),i=[],a=(e,t)=>{let n=Ef(e);if(n!==void 0&&(e.tagName===`svg`||e.tagName===`span`))return e;if(n!==void 0)return{...e,childNodes:e.childNodes.map(e=>`tagName`in e&&!Tf(e)?a(e,n):e)};if(t===void 0)return Df(`The submitted HTML must retain its original root identity.`);if([e,...Of(e.childNodes)].some(e=>e.attrs.some(e=>[`data-enhance-id`,`data-enhance-opaque`].includes(e.name))))return Df(`A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.`);let o=`new_${String(i.length)}`;for(;r.has(o);)o=`_${o}`;return r.add(o),i.push({id:o,parentNodeId:t,html:dn(e)}),{...e,tagName:`div`,nodeName:`div`,childNodes:[],attrs:[{name:`data-enhance-id`,value:o},{name:`data-enhance-name`,value:`New content`},{name:`data-enhance-opaque`,value:`true`}]}};return t.childNodes=t.childNodes.map(e=>`tagName`in e?a(e):e),{root:Wu(un(t)),fragments:i}},Q=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Af=e=>{let t=new Map,n=e=>{t.set(e.id,e);for(let t of e.children)n(t)};return n(e),t},jf=(e,t)=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n),Mf=(e,t,n,r)=>{let i=new Set,a=e=>{if(i.has(e.id))return Q(`Overlapping removal roots include ${e.id}.`);if(t.has(e.id))return Q(`Removed node ${e.id} is still present in the HTML.`);i.add(e.id);for(let t of e.children)a(t)};for(let t of n){let n=e.get(t);if(n===void 0||t===r)return Q(`Invalid removal root: ${t}.`);a(n)}for(let n of e.keys())if(!t.has(n)&&!i.has(n))return Q(`Missing retained node ${n}; declare intentional deletion in removeNodeIds.`);return i},Nf=(e,t,n,r)=>{let i=new Set([...Object.keys(n.styles),...Object.keys(r.styles)]),a=Object.fromEntries([...i].filter(e=>n.styles[e]!==r.styles[e]).filter(e=>!Qu(t,e)).map(e=>[e,r.styles[e]??null]));return[...t.geometry?.kind===`mask`&&Object.keys(a).some(e=>Pd.test(e))?[{op:`setGeometry`,nodeId:t.id,geometry:`default`}]:[],...$u(t,n.styles,r.styles),...Object.keys(a).length===0?[]:hc(e,[{nodeIds:[t.id],styles:a}])]},Pf=(e,t,n)=>{if(t.tag!==n.tag||t.opaque!==n.opaque||t.locked!==n.locked)return Q(`The kind, opaque marker or locked marker of ${t.id} changed.`);let r=!jf(t.styles,n.styles),i=JSON.stringify(t.path)!==JSON.stringify(n.path)||JSON.stringify(t.runs)!==JSON.stringify(n.runs)||JSON.stringify(t.paints)!==JSON.stringify(n.paints);if(t.locked&&(r||i||t.label!==n.label||t.text!==n.text))return Q(`Locked node ${t.id} cannot be changed through HTML.`);if(t.opaque&&(r||t.label!==n.label||t.text!==n.text||n.children.length>0))return Q(`Opaque node ${t.id} cannot be changed through HTML.`);let a=e.nodes[t.id];if(a===void 0)return Q(`Node ${t.id} no longer exists.`);let o=[];return t.label!==n.label&&o.push({op:`setLabel`,nodeId:t.id,label:n.label,labelOrigin:`user`}),t.text!==n.text&&o.push({op:`editText`,nodeId:t.id,change:Se(a,{...a,props:s(a,n.text)})}),o.push(...dd(a,t.paints??[],n.paints??[])),(t.runs!==void 0||n.runs!==void 0)&&o.push(...Sd(a,t.runs??[],n.runs??[])),t.path!==void 0&&n.path!==void 0&&o.push(...jd(e,a,t.path,n.path)),r&&o.push(...Nf(e,a,t,n)),o},Ff=(e,t,n,r)=>{let i=Kd(e,t).root,a=kf(n),o=a.root;if(o.id!==t)return Q(`The submitted HTML must retain its original root identity.`);let s=new Set(a.fragments.map(e=>e.id)),c=Af(i),l=Af(o),u=Mf(c,l,r,t),d=new Set([...u,...r.flatMap(t=>[...Ri(e,t)])]);for(let t of d)if(zi(e,t))return Q(`Locked node ${t} cannot be removed through HTML.`);let f=r.map(e=>c.get(e)?.opaque===!0?Q(`Use explicit canvas removal for opaque node ${e}.`):{op:`remove`,nodeId:e});for(let[t,n]of l){if(s.has(t))continue;let r=c.get(t);if(r===void 0)return Q(`Unknown or outside-scope identity: ${t}.`);f.push(...Pf(e,r,n))}for(let e of a.fragments){let t=c.get(e.parentNodeId);if(t===void 0||t.opaque||t.locked||t.tag!==`div`)return Q(`Node ${e.parentNodeId} cannot contain new HTML.`)}return{root:o,operations:f,removed:d,fragments:a.fragments}},If=(e,t,n)=>{let r=u(e.snapshotToken,t);S(t,n,[r.rootNodeId]);let i=Kd(n,r.rootNodeId);if(Tt({reference:t,version:r.version,rootNodeId:r.rootNodeId,html:i.html})!==e.snapshotToken)throw new x(`CONFLICT`,`The editable snapshot no longer matches the complete source.`,`Read the requested subtree again and deliberately reapply the intended change.`,{outcome:`not_committed`});return Ff(n,r.rootNodeId,e.html,e.removeNodeIds)},Lf=async(e,t,n)=>{let r=If(t,n.reference,n.scene);if(r.fragments.length===0)return wf(n.scene,r);let i=await gu(e,{canvasId:n.reference.canvasId,expectedVersion:n.version,scope:{nodeIds:[...n.reference.nodeIds],...n.reference.pageId!==void 0&&{pageId:n.reference.pageId}},request:{kind:`compile-html`,fragments:[...r.fragments],contextOperations:r.operations.filter(e=>e.op!==`remove`)}},t.waitMs);return i.state===`succeeded`?wf(n.scene,r,i.result):Ml(i,{kind:`canvas-preparation`,canvasId:n.reference.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:n.fingerprint})},Rf=e=>({execute:async t=>{let n=Ze.parse(t),r=i(n.canvasRef),a=u(n.snapshotToken,r),s=o({operation:`canvas.updateHtml/1`,snapshotToken:n.snapshotToken,html:n.html,removeNodeIds:n.removeNodeIds});return hf(e).execute({reference:r,baseVersion:a.version,clientToken:n.clientToken,fingerprint:s,plan:async t=>Lf(e,n,{reference:r,scene:t,fingerprint:s,version:a.version})})}}),zf=(e,t,n)=>({"canvas.arrange":async()=>{let{changes:r,...i}=_.parse(t);return yu(e).execute({...i,clientToken:n,request:{kind:`arrange`,changes:r}})},"canvas.duplicateNodes":async()=>{let{nodeIds:r,destination:i,...a}=le.parse(t);return yu(e).execute({...a,clientToken:n,request:{kind:`duplicate`,nodeIds:r,destination:i}})},"canvas.find":async()=>pu(e).execute(He.parse(t)),"canvas.remove":async()=>_f(e).execute({...Ue.parse(t),clientToken:n}),"canvas.read":async()=>{let n=ee.safeParse(t);return n.success?el(e,n.data):pf(e).execute(Je.parse(t))},"canvas.updateHtml":async()=>Rf(e).execute({...Ct.parse(t),clientToken:n})}),Bf=(e,t)=>{let n=i(e.canvasRef),r=n.nodeIds;if(e.target.kind===`content`&&r.length>1)throw new x(`BAD_REQUEST`,`Choose an explicit node within this selection.`,`Render the selected screens separately; do not broaden to the whole canvas.`);let a=e.target.kind===`content`?r[0]===void 0?n.pageId===void 0?e.target:{kind:`page`,pageId:n.pageId}:{kind:`node`,nodeId:r[0]}:e.target;return{canvasId:n.canvasId,expectedVersion:e.expectedVersion,target:a,sourceState:e.sourceState,scale:e.scale,scope:{nodeIds:r,...n.pageId!==void 0&&{pageId:n.pageId}},outputPath:null,overwrite:!1,timeoutMs:e.waitMs,timeoutOutcome:`pending`,retryClientToken:t}},Vf=(e,t)=>{let n=et.shape.operation.safeParse({kind:`canvas-render`,canvasId:t.input.canvasId,jobId:e instanceof x?e.fields?.jobId:void 0}),r=_t.extract([`failed`,`cancelled`,`expired`]).safeParse(e instanceof x?e.fields?.renderState:void 0);return{...n.success&&{operation:n.data},state:r.success?r.data:`not_confirmed`,error:e instanceof x?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`This render outcome could not be confirmed.`,remediation:`Retry the identical batch and clientToken to recover its native render jobs.`}}},Hf=(e,t)=>e.targets.map(({id:n,maxOutputPixels:r,...i})=>{let a=t.get(n);if(a===void 0)throw TypeError(`A batch target has no native render request key.`);return{id:n,maxOutputPixels:r,input:Bf({...e,...i},a)}}),Uf=async(e,t)=>{try{let n=await e.execute({...t.input,maxOutputPixels:t.maxOutputPixels}),r=rt.safeParse(n);if(!r.success)return et.parse(n);let i=r.data.width*r.data.height;if(!Number.isSafeInteger(i)||i<=0||t.maxOutputPixels!==void 0&&i>t.maxOutputPixels)throw new x(`INTERNAL`,`The render exceeded its allocated pixel budget.`,`Update the API and renderer together, then retry.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});return r.data}catch(e){return Vf(e,t)}},Wf=e=>({execute:async(t,n)=>{let r=ye.parse(t),i=Hf(r,n),a=[],o=0;for(let t of i){let n=await Uf(e,t);`jobId`in n&&(o+=n.width*n.height),a.push({id:t.id,target:t.input.target,...t.maxOutputPixels!==void 0&&{maxOutputPixels:t.maxOutputPixels},outcome:n})}let s=i[0];if(s===void 0)throw TypeError(`A render batch requires at least one target.`);return{kind:`canvas-render-batch`,canvasId:s.input.canvasId,requestedVersion:r.expectedVersion,complete:a.every(e=>`jobId`in e.outcome),renderedPixels:o,results:a,next:[`Inspect each delivered image alongside its target id. Collect pending images with operation_status and includeImage true. Retry uncertain outcomes with the identical batch and clientToken.`]}}}),Gf=e=>bi(e.remote,nl(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Kf=async(e,t,n)=>{let r=ye.safeParse(t);if(r.success){e.mutationKey.select(n,!0);let t=new Map(r.data.targets.map(t=>[t.id,e.mutationKey.current(`canvas.render.create`,{batch:{canvasRef:r.data.canvasRef,expectedVersion:r.data.expectedVersion,targets:r.data.targets},targetId:t.id})])),i=Gf(e);return Wf({execute:async t=>(e.mutationKey.select(t.retryClientToken,!1),i.execute(t))}).execute(r.data,t)}let i=vt.safeParse(t);if(i.success)return Gf(e).execute(Bf(i.data,n));let a=oe.parse(t);return Gf(e).execute({...a,retryClientToken:n})},qf=e=>({render:Gf(e),execute:async(t,n)=>Kf(e,t,n)}),Jf=new Date(`1980-01-01T00:00:00.000Z`),Yf=33188,Xf=(e,t)=>new x(`BAD_REQUEST`,e,t),Zf=(e,t)=>{let n=E(`sha256`),r=0;return new mn({transform:(e,t,i)=>{r+=e.byteLength,n.update(e),i(null,e)},flush:i=>{if(r!==e.bytes){i(Error(`prototype file ${e.path} changed while it was packaged`));return}try{t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}catch(e){i(e instanceof Error?e:Error(`prototype manifest failed`))}}})},Qf=e=>{let t=gt.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),n=Buffer.from(JSON.stringify(t),`utf8`);if(e.limits.manifestBytes!==void 0&&n.byteLength>e.limits.manifestBytes)throw Xf(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,ke,{mtime:Jf,mode:Yf,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},$f=(e,t,n)=>{let{source:r,content:i}=t,a={mtime:Jf,mode:Yf,compress:i===null,forceDosTimestamp:!0};if(i===null){e.addReadStreamLazy(r.path,{...a,size:r.bytes},t=>{let i=Bt(r.absolutePath),a=Zf(r,n);i.on(`error`,e=>a.destroy(e)),a.on(`error`,t=>e.emit(`error`,t)),a.on(`close`,()=>i.destroy()),t(null,i.pipe(a))});return}if(i.byteLength!==r.bytes)throw Error(`prototype file ${r.path} changed while it was packaged`);e.addBuffer(i,r.path,a),n({path:r.path,contentType:r.contentType,bytes:i.byteLength,sha256:E(`sha256`).update(i).digest(`hex`)})},ep=(e,t,n)=>{let r=[];for(let i of t)i!==null&&($f(e,i,n),r.push(i.source));return r},tp=async(e,t,n)=>{let r=[];for(let i=0;i<t.files.length;i+=32){let a=await Promise.all(t.files.slice(i,i+32).map(async e=>{try{let t=e.bytes<=128?await Qt(e.absolutePath):null;if(t===null&&await qt(e.absolutePath,zt.R_OK),t!==null&&t.byteLength!==e.bytes)throw Error(`prototype file ${e.path} changed while it was packaged`);return{source:e,content:t}}catch(n){if(e.path===t.entryPath)throw n;return null}}));r.push(...ep(e,a,n))}return r},np=async e=>{let t=new gn,n=E(`sha256`),r=new mn({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=hn(t.outputStream,r,Vt(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=null,c=()=>{s!==null&&a.manifest===null&&i.size===s.length&&(a.manifest=Qf({zip:t,completed:i,...e,files:s}))},l=e=>{i.set(e.path,e),c()};try{s=await tp(t,e,l),c()}catch(e){r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)),await o}if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let u=await nn(e.artifactPath);if(u.size>e.limits.artifactBytes)throw Xf(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:u.size,sha256:n.digest(`hex`),unavailableFileCount:e.files.length-i.size}},rp={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".mp3":`audio/mpeg`,".mp4":`video/mp4`,".ogg":`audio/ogg`,".otf":`font/otf`,".png":`image/png`,".svg":`image/svg+xml`,".ttf":`font/ttf`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webm":`video/webm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`,".xml":`application/xml`},ip=e=>rp[T.extname(e).toLowerCase()]??`application/octet-stream`,ap=async e=>{try{return await nn(e)}catch{return null}},op=e=>Buffer.byteLength(e,`utf8`),$=(e,t)=>new x(`BAD_REQUEST`,e,t),sp=(e,t)=>{if(!b.safeParse(e).success)throw $(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(op(e)>t.pathBytes)throw $(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},cp=async(e,t,n,r)=>{let{limits:i,unavailable:a}=r,o=await $t(t);if(n.has(o))return a(),[];let s=new Set(n).add(o),{readdir:c}=await import(`node:fs/promises`),l=await c(t,{withFileTypes:!0}),u=[],d=l.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of d){let o=T.join(t,n.name),c=await ap(o);if(c?.isDirectory()===!0){try{u.push(...await cp(e,o,s,r))}catch{a()}continue}if(c?.isFile()!==!0){a();continue}let l=T.relative(e,o).split(T.sep).join(`/`).normalize(`NFC`);sp(l,i),u.push({absolutePath:o,path:l,bytes:Number(c.size),contentType:ip(o)})}return u},lp=(e,t,n)=>{if(e.length===0)throw $(`The prototype build is empty.`,`Build the app before publishing it.`);if(n.fileCount!==void 0&&e.length>n.fileCount)throw $(`The prototype has ${String(e.length)} files.`,`This environment currently accepts ${String(n.fileCount)} files per deployment.`);let r=new Set,i=0;for(let t of e){let e=Me(t.path);if(r.has(e))throw $(`The prototype path ${t.path} collides by case or Unicode normalization.`,`Rename one of the colliding files so the build is portable.`);if(r.add(e),t.bytes>n.fileBytes)throw $(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,n.expandedBytes!==void 0&&i>n.expandedBytes)throw $(`The prototype build is too large.`,`This environment accepts ${String(n.expandedBytes)} expanded bytes.`)}let a=e.find(e=>e.path===t);if(a===void 0)throw $(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw $(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},up=(e,t)=>{try{fn.mark(`enhance.prototype.packaging`,{detail:{fileCount:e,unavailableFileCount:t}})}catch{}},dp=async e=>{let t=T.resolve(e.directory),n=await ap(t);if(n===null)throw new x(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!n.isDirectory())throw $(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let r=e.entryPath.split(T.sep).join(`/`).normalize(`NFC`);sp(r,e.limits);let i=0,a=await cp(t,t,new Set,{limits:e.limits,unavailable:()=>{i+=1}});lp(a,r,e.limits);let o=await Xt(T.join(Ft(),`enhance-prototype-artifact-`)),s=T.join(o,`artifact.zip`);try{let t=await np({artifactPath:s,files:a,entryPath:r,limits:e.limits});return i+=t.unavailableFileCount,up(t.manifest.files.length,i),{identity:{protocolVersion:1,format:`zip`,bytes:t.bytes,sha256:t.sha256,fileCount:t.manifest.files.length,expandedBytes:t.manifest.files.reduce((e,t)=>e+t.bytes,0)},manifest:t.manifest,open:()=>Bt(s),dispose:async()=>tn(o,{recursive:!0})}}catch(e){throw await tn(o,{recursive:!0}),e}},fp=e=>({package:async t=>{if(e===void 0)throw $(`No build directory was selected.`,`Select a build before publishing.`);return dp({...t,directory:e})}}),pp=async(e,t)=>{let n=Ae.parse(t);return Ni(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},mp=async(e,t)=>{let n=mt.parse(t);return $c(e.remote,qf(e).render).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},hp=async(e,t,n)=>{let r=jt.parse(t),a=i(r.canvasRef);return $c(e.remote,qf(e).render).execute({canvasId:a.canvasId,pageId:a.pageId,selectionNodeIds:a.nodeIds,targetNodeId:r.destination.parentNodeId,mode:`insert-children`,html:r.html,baseVersion:r.baseVersion,revisionPolicy:`strict`,responseMode:`bounded`,review:`none`,renderClientToken:n,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:r.waitMs})},gp=async(e,t)=>{let n=ie.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},_p=async(e,t,n)=>{let r=Fe.parse(t);return jl(e.remote,fp(r.directory)).execute({...r,clientToken:n})},vp=async(e,t,n)=>{let r=Ne.parse(t);return au(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},yp=async(e,t)=>{let n=Re.parse(t);return Jl(e.remote).execute(n)},bp=async(e,t)=>{let n=l.parse(t),r=i(n.canvas);return Pc(e.remote).execute({...r,baseVersion:n.baseVersion,edits:n.edits,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},xp=async(e,n)=>Gl(e.remote,nl(e.configDirectory)).execute(t.parse(n)),Sp=async(e,t,n,r)=>{let i={...zf(e.remote,n,r),"canvas.importAsset":async()=>{let t=de.parse(n);return ol(e.remote,lu(t.source.path)).execute({canvasRef:t.canvasRef,clientToken:r})},"operation.status":async()=>xp(e,n),"canvas.edit":async()=>bp(e,n),"canvas.apply":async()=>pp(e,n),"canvas.render":async()=>qf(e).execute(n,r),"canvas.writeHtml":async()=>mp(e,n),"canvas.insertHtml":async()=>hp(e,n,r),"canvas.capture":async()=>ru(e.remote,n,r),"canvas.makeEditable":async()=>Kc(e.remote,n),"comment.attention":async()=>gp(e,n),"prototype.publishCanvas":async()=>{let t=We.parse(n);return El(e.remote,fp(t.source.kind===`directory`?t.source.directory:void 0)).execute({...t,source:t.source.kind===`directory`?{...t.source,kind:`build`}:t.source,clientToken:r})},"prototype.publish":async()=>_p(e,n,r),"recording.snapshot":async()=>vp(e,n,r),"transcript.read":async()=>yp(e,n)}[t];if(i===void 0)throw TypeError(`${t} has no composite execution`);return i()},Cp=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??Gt();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Sp(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),wp=`/callback`,Tp=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),Ep=e=>{let t=C.platform===`darwin`?{executable:`open`,arguments:[e]}:C.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=yn(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Dp=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==wp){n.writeHead(404).end();return}if(r.searchParams.get(`state`)!==e.state){n.writeHead(400).end(`The OAuth state did not match. Return to the terminal and retry.`);return}let i=r.searchParams.get(`error`),a=r.searchParams.get(`code`);if(i!==null||a===null||a===``){n.writeHead(400).end(`Enhance authentication was not approved.`),e.completion.reject(Error(i??`the authorization response carried no code`));return}n.writeHead(200,{"content-type":`text/html; charset=utf-8`}).end(`<!doctype html><meta charset="utf-8"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>`),e.completion.resolve(a)},Op=e=>{let t=Tp(e.issuer,`oauth/authorize`);return t.search=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,code_challenge:e.challenge,code_challenge_method:`S256`}).toString(),t.href},kp=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=bn((n,r)=>{Dp({state:e.state,completion:t},n,r)});await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,e)});let r=n.address();if(r===null||typeof r==`string`)throw n.close(),Error(`the OAuth callback listener has no TCP port`);let i=`http://127.0.0.1:${String(r.port)}${wp}`,a=Op({...e,redirectUri:i}),o=()=>{t.reject(Error(`browser authorization cancelled`))};e.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return e.signal?.throwIfAborted(),e.onReady(a),e.openBrowser&&Ep(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},Ap=e=>({authorize:async t=>{try{let n=Wt(32).toString(`base64url`),r=E(`sha256`).update(n).digest(`base64url`),i=Wt(32).toString(`base64url`),a=await kp({...t,challenge:r,state:i});return await e.exchangeOauthCode({issuer:t.issuer,clientId:t.clientId,code:a.code,redirectUri:a.redirectUri,verifier:n})}catch(e){throw new x(`UNAUTHORIZED`,e instanceof Error?`Browser authentication failed: ${e.message}.`:`Browser authentication failed.`,`Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.`)}}}),jp={apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`},Mp=e=>URL.canParse(e)?new URL(e).href.replace(/\/+$/u,``):e,Np=(e,t,n,r)=>{let i=URL.canParse(e)?new URL(e).origin:null,a=T.resolve(t),o=jp;if(i===new URL(o.apiUrl).origin&&a===T.resolve(n,`.config`,r.configDirectoryName)||i===new URL(r.apiUrl).origin&&a===T.resolve(n,`.config`,o.configDirectoryName))throw TypeError(`Enhance cannot share credentials between production and development. Use Enhance Development (enhance-dev-mcp) with ~/.config/enhance-development, then reconnect production separately.`)},Pp=e=>e===void 0||e===``?void 0:e,Fp=(e,t,n)=>{let r=Pp(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Pp(e.ENHANCE3_API_URL),a=T.join(t,`.config`,n.configDirectoryName),o=Pp(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&Mp(i)!==Mp(n.apiUrl))throw TypeError(`Enhance development cannot use this API. Use the bundled development endpoint.`);if(o!==void 0&&T.resolve(o)!==T.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}else Np(i??n.apiUrl,o??a,t,n);return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}},Ip=()=>Fp(C.env,Pt(),jp),Lp=()=>{let e=w.enum([`legacy`,`canvas`]).default(`legacy`).parse(C.env.ENHANCE_MCP_PROFILE),t=w.enum([`true`,`false`]).default(`false`).parse(C.env.ENHANCE_MCP_READ_ONLY)===`true`;if(t&&e!==`canvas`)throw Error(`ENHANCE_MCP_READ_ONLY requires the canvas profile.`);return{...Ip(),profile:e,isReadOnly:t,workflowsDirectory:C.env.ENHANCE_WORKFLOWS_DIR}},Rp=w.object({token:w.string().startsWith(`enh_`)}),zp=e=>{let t=T.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Qt(t,`utf8`));return Rp.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Yt(e,{recursive:!0,mode:448}),await Jt(e,448);let r=T.join(e,`credentials.${String(C.pid)}.tmp`);await an(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await en(r,t),await Jt(t,384)},remove:async()=>{try{return await rn(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},Bp={path:`direct_cli`},Vp=w.object({access_token:w.string().min(1)}),Hp=w.object({code:w.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),Up=`Check network access and proxy settings for this API, then run enhance doctor again.`,Wp=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,Gp=e=>{let t=Hp.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?Gp(e.cause):e instanceof Error?e.name:`Network request failed`},Kp=(e,t)=>new x(`INTERNAL`,`${Wp(e)} answered HTTP ${String(t)}.`,Up),qp=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new x(`INTERNAL`,`Could not reach ${Wp(e)}: ${Gp(t)}.`,Up)}},Jp=async(e,t)=>{let n=await qp(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw Kp(e,n.status);return n},Yp=(e,t,n=null,r=Bp)=>_n({links:[vn({url:`${e}/trpc`,fetch:async(e,t)=>Jp(e,{...t,signal:t?.signal??null}),headers:{[_e]:JSON.stringify(r),...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),Xp=async e=>{try{return await e()}catch(e){throw Ye(e)}},Zp=async e=>{let t=await fetch(e);if(!t.ok)throw new x(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},Qp=async e=>{let t=await qp(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new x(`BAD_REQUEST`,`This Enhance API does not support browser authentication.`,`Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.`):new x(`INTERNAL`,`${Wp(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,Up);return t.json()},$p=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await qp(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw Kp(e,n.status);return n.json()},em=async e=>{let t=await qp(new URL(`oauth/token`,e.issuer.endsWith(`/`)?e.issuer:`${e.issuer}/`),{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,client_id:e.clientId,code:e.code,redirect_uri:e.redirectUri,code_verifier:e.verifier})});if(!t.ok)throw new x(`INTERNAL`,`${Wp(e.issuer)} token exchange answered HTTP ${String(t.status)}`,Up);return Vp.parse(await t.json()).access_token},tm=async e=>{try{let t=await qp(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:Kp(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Wp(e)}.`}}},nm=async e=>{let t=!(e.body instanceof Uint8Array),n=t?pn.toWeb(e.body):e.body,r={method:`PUT`,headers:e.headers,body:n,...t&&{duplex:`half`}},i=await fetch(e.url,r);if(!i.ok)throw new x(`INTERNAL`,`Signed upload answered HTTP ${String(i.status)}.`,`Retry the fixture command with the same source file.`);let a=i.headers.get(`etag`);if(a===null||a===``)throw new x(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},rm=(e,t,n,r=Bp)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>Qp(i),oauthMetadata:$p,exchangeOauthCode:em,query:async(e,n,a)=>Xp(async()=>Yp(i,await t.read(),null,r).query(e,n,a)),queryWithToken:async(e,t,n)=>Xp(async()=>Yp(i,n,null,r).query(e,t)),mutate:async(e,a)=>Xp(async()=>Yp(i,await t.read(),n.current(e,a),r).mutation(e,a)),mutateWithToken:async(e,t,n)=>Xp(async()=>Yp(i,n,null,r).mutation(e,t)),download:Zp,upload:nm,health:async()=>tm(i)}},im=e=>Array.isArray(e)?e.map(e=>im(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,im(t)])),am=(e,t,n)=>E(`sha256`).update(`${e}\0${t}\0${JSON.stringify(im(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),om=()=>{let e=Gt(),t=!1;return{current:(n,r)=>t?am(e,n,r):e,select:(n,r)=>{e=n??Gt(),t=r}}};export{Pr as C,xn as E,Lr as S,D as T,wi as _,Lp as a,ti as b,nl as c,G as d,Fc as f,Ni as g,Pi as h,Ip as i,el as l,Ac as m,rm as n,Ap as o,Pc as p,zp as r,Cp as s,om as t,$c as u,bi as v,Nn as w,Xr as x,ii as y};
2
+ import{$n as e,A as t,An as n,Ar as r,At as i,Bn as a,C as o,Cn as s,Cr as c,Ct as l,D as u,Dn as d,Dr as f,E as p,En as m,Er as h,Et as g,F as _,G as ee,Gn as v,Gt as te,Hn as y,Ht as ne,In as re,J as ie,Jn as ae,Jt as b,K as oe,Kn as se,Kt as ce,L as le,Ln as ue,M as de,Mn as fe,Mt as x,Nt as pe,On as me,Or as he,P as ge,Pn as _e,Pr as ve,Q as ye,Qt as be,Rn as xe,Sn as Se,Sr as Ce,T as we,Tn as Te,Tr as Ee,Tt as S,Ut as De,V as Oe,Vt as ke,W as Ae,Wn as je,Wt as Me,X as Ne,Xt as Pe,Y as Fe,Yn as Ie,Yt as Le,Z as Re,Zn as ze,Zt as Be,_r as Ve,_t as He,at as Ue,b as We,bn as Ge,br as Ke,cr as qe,ct as Je,d as Ye,dr as Xe,dt as Ze,en as Qe,er as $e,et,ft as tt,gt as nt,it as rt,jn as it,jr as at,jt as ot,kr as st,kt as ct,lr as lt,mr as ut,or as dt,pr as ft,pt,q as mt,qn as ht,qt as gt,rr as _t,rt as vt,sr as yt,st as bt,tr as xt,ur as St,ut as Ct,vr as wt,w as Tt,wr as Et,xn as Dt,xr as Ot,xt as kt,yr as At,yt as jt,zn as Mt,zt as Nt}from"./cli-output-identity.lib-DqtHQ0LE.mjs";import C from"node:process";import{z as w}from"zod";import{homedir as Pt,tmpdir as Ft}from"node:os";import{generateKeyBetween as It,generateNKeysBetween as Lt}from"fractional-indexing";import{chmodSync as Rt,constants as zt,createReadStream as Bt,createWriteStream as Vt,mkdirSync as Ht,writeFileSync as Ut}from"node:fs";import T from"node:path";import{createHash as E,randomBytes as Wt,randomUUID as Gt}from"node:crypto";import{setTimeout as Kt}from"node:timers/promises";import{access as qt,chmod as Jt,mkdir as Yt,mkdtemp as Xt,open as Zt,readFile as Qt,realpath as $t,rename as en,rm as tn,stat as nn,unlink as rn,writeFile as an}from"node:fs/promises";import{isDeepStrictEqual as on}from"node:util";import{generate as sn,parse as cn}from"css-tree";import{parseFragment as ln,serialize as un,serializeOuter as dn}from"parse5";import{performance as fn}from"node:perf_hooks";import{Readable as pn,Transform as mn}from"node:stream";import{pipeline as hn}from"node:stream/promises";import{ZipFile as gn}from"yazl";import{createTRPCUntypedClient as _n,httpLink as vn}from"@trpc/client";import{spawn as yn}from"node:child_process";import{createServer as bn}from"node:http";const xn=(e,t)=>e<t?-1:+(e>t),Sn=(e,t)=>{let n=new Set(t),r=[],i=new Map,a=r;for(let t of e)n.has(t.id)&&(a=[],i.set(t.id,a)),a.push(t);return[...r,...t.flatMap(e=>i.get(e)??[])]},Cn=(e,t)=>{let n=new Set(t.clear),r=new Map((e?.declarations??[]).filter(e=>!n.has(e.id)).map(e=>[e.id,e])),i=t.set??[];for(let e of i)r.set(e.id,e);let a=Array.from(r,([,e])=>e);return a.length===0&&(t.empty===`remove`||e===void 0&&t.empty!==`keep`)?null:{declarations:t.order===void 0?a:Sn(a,t.order)}},wn=(e,t)=>{let n=new Map(e?.declarations.map(e=>[e.id,e])),r=t?.declarations??[],i=new Set(r.map(e=>e.id)),a=Array.from(n,([e])=>e).filter(e=>!i.has(e)),o=r.filter(e=>{let t=n.get(e.id);return t?.property!==e.property||t.value!==e.value||t.enabled!==e.enabled}),s={...a.length>0&&{clear:a},...o.length>0&&{set:o}},c=Cn(e,s),l=r.map(e=>e.id),u=JSON.stringify(c?.declarations.map(e=>e.id)??[])!==JSON.stringify(l),d=t===void 0&&e!==void 0?`remove`:e===void 0&&t!==void 0&&r.length===0?`keep`:void 0;return d===void 0&&!u&&o.length===0&&a.length===0?null:{...s,...u&&{order:l},...d!==void 0&&{empty:d}}},Tn=1e6,En=e=>Math.round(e*255*Tn)/Tn,D=(e,t=1)=>{let n=e.alpha*t;if(e.space===`srgb`){let t=[e.red,e.green,e.blue].map(e=>String(En(e))).join(` `);return n===1?`rgb(${t})`:`rgb(${t} / ${String(n)})`}let r=`${String(e.red)} ${String(e.green)} ${String(e.blue)}`;return`color(${e.space} ${r} / ${String(n)})`},Dn={x:0,y:0,width:1,height:1},On=(e,t)=>{let[n,r,i,a,o,s]=e.transform,c=n*a-r*i,l=t.x-o,u=t.y-s;return{x:(a*l-i*u)/c,y:(n*u-r*l)/c}},kn=(e,t=Dn)=>[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x,y:t.y+t.height},{x:t.x+t.width,y:t.y+t.height}].flatMap(t=>{let n=On(e,t);return[n.x,n.y]}),An=1024,jn=(e,t,n)=>{let r=e.stops.map(t=>`${n?`rgb(255 255 255 / ${String(t.color.alpha*e.opacity)})`:D({...t.color,alpha:1})} ${String(t.position*360)}deg`);return`conic-gradient(from 90deg at ${String(t)}% ${String(t)}% in srgb, ${r.join(`, `)})`},Mn=(e,t)=>{let n=kn(e,t),r=Math.min(0,...n),i=Math.max(1,...n)-r,a=(.5-r)/i*100,o=e.transform.map((e,t)=>t<4?e/An:e),s=`width:100%;height:100%;background-image:${jn(e,a,!1)};mask-image:${jn(e,a,!0)};`;return`<g transform="matrix(${o.map(String).join(` `)})"><foreignObject x="${String(r*An)}" y="${String(r*An)}" width="${String(i*An)}" height="${String(i*An)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${s}"></div></foreignObject></g>`},Nn=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Mn(e)}</svg>`,Pn=(e,t)=>e===void 0||t===void 0?!1:e.x===t.x&&e.y===t.y,Fn=e=>{let t=[...e];for(;t.length>1&&Pn(t[0],t.at(-1));)t.pop();for(;t.length>1&&Pn(t[0],t[1]);)t.splice(1,1);return t},In=e=>{let t=e.match(/[MLHVZ]|[+-]?\d*\.?\d+(?:e[+-]?\d+)?/giu)??[];return t.join(``)!==e.replaceAll(/[\s,]/gu,``)||!/^M/iu.test(t[0]??``)||!/^Z$/iu.test(t.at(-1)??``)?null:t},Ln=(e,t,n,r)=>{let i=e.toUpperCase(),a=Number(t[n]),o=[`M`,`L`].includes(i)?Number(t[n+1]):a;if(!Number.isFinite(a)||!Number.isFinite(o))return null;let s=e===e.toLowerCase()?r:{x:0,y:0},c={x:i===`V`?r.x:s.x+a,y:i===`H`?r.y:s.y+o};return Number.isFinite(c.x)&&Number.isFinite(c.y)?c:null},Rn=e=>{let t=In(e);if(t===null)return null;let n=[],r=`M`,i=0,a={x:0,y:0};for(;i<t.length-1;){let e=t[i]??``;/^[MLHV]$/iu.test(e)&&(r=e,i+=1);let o=r.toUpperCase();if(o===`M`&&n.length>0)return null;let s=Ln(r,t,i,a);if(s===null)return null;a=s,n.push(a),i+=[`M`,`L`].includes(o)?2:1,r=r.replace(`M`,`L`).replace(`m`,`l`)}return i===t.length-1?Fn(n):null},zn=Math.PI/2,Bn=1e6,Vn=e=>String(Math.round(e*Bn)/Bn),O=([e,t])=>`${Vn(e)} ${Vn(t)}`,Hn=(e,[t,n],{width:r,height:i},a)=>{if(e<=0)return{radius:0,reach:0,smoothing:0};let o=(t,n)=>{let r=t*e,i=e+n;if(Number.isFinite(r)&&Number.isFinite(i))return r/i;let a=Math.min(e,n)/Math.max(e,n);return(e>=n?t:t*a)/(1+a)},s=Math.min(o(r,t),o(i,n)),c=Math.min(e,s);if(c===0)return{radius:0,reach:0,smoothing:0};let l=Math.max(0,Math.min(a,s/c-1));return{radius:c,reach:c*(1+l),smoothing:l}},Un=(e,t)=>{let{radius:n,reach:r,smoothing:i}=e,a=O(t([r,0]));if(n===0)return`L${a}`;let o=i*zn/2,s=n*(1-Math.sin(o)),c=n*(1-Math.cos(o)),l=o===0?0:c/Math.tan(o),u=(r-s-l)/3,d=O(t([r-2*u,0])),f=O(t([s+l,0])),p=O(t([s,c])),m=O(t([c,s])),h=O(t([0,s+l])),g=O(t([0,r-2*u])),_=O(t([0,r]));return`L${a}C${d} ${f} ${p}${i===1?``:`A${Vn(n)} ${Vn(n)} 0 0 1 ${m}`}C${h} ${g} ${_}`},Wn=(e,t)=>{let{topLeft:n,topRight:r,bottomRight:i,bottomLeft:a,smoothing:o=0}=e;return[Hn(n,[r,a],t,o),Hn(r,[n,i],t,o),Hn(i,[a,r],t,o),Hn(a,[i,n],t,o)]},Gn=(e,t)=>{let[n,r,i,a]=Wn(e,{width:Math.max(0,t.width),height:Math.max(0,t.height)});return{topLeft:n.radius,topRight:r.radius,bottomRight:i.radius,bottomLeft:a.radius}},Kn=(e,t,n=[0,0])=>{let r=Math.max(0,t.width),i=Math.max(0,t.height);if(r===0||i===0)return`M0 0Z`;let[a,o,s,c]=Wn(e,{width:r,height:i});return[`M${O([n[0],a.reach+n[1]])}`,Un(a,([e,t])=>[t+n[0],e+n[1]]),Un(o,([e,t])=>[r-e+n[0],t+n[1]]),Un(s,([e,t])=>[r-t+n[0],i-e+n[1]]),Un(c,([e,t])=>[e+n[0],i-t+n[1]]),`Z`].join(``)},qn=1e5,Jn=.01,Yn=1e-9,k=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],A=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Xn=(e,t)=>e[0]*t[1]-e[1]*t[0],j=(e,t)=>[e[0]-t[0],e[1]-t[1]],Zn=e=>String(Math.round(e*qn)/qn),Qn=(e,t,n=0)=>{let[r,i,a,o]=e,s=A(r,o);if(n>=16||A(r,i)+A(i,a)+A(a,o)-s<=Jn/8){t.push(o);return}let c=k(r,i),l=k(i,a),u=k(a,o),d=k(c,l),f=k(l,u),p=k(d,f);Qn([r,c,d,p],t,n+1),Qn([p,f,u,o],t,n+1)},$n=(e,t,n,r)=>{let i=j(t,e),a=A(e,t);if(a<Yn)return;let o=Math.sqrt(Math.max(0,n*n-a*a/4)),s=[(e[0]+t[0])/2-i[1]*o/a,(e[1]+t[1])/2+i[0]*o/a],c=Math.atan2(e[1]-s[1],e[0]-s[0]),l=Math.atan2(t[1]-s[1],t[0]-s[0])-c;l<0&&(l+=2*Math.PI);let u=Math.max(1,Math.ceil(l/(2*Math.acos(Math.max(-1,1-Jn/n)))));for(let e=1;e<=u;e+=1){let t=c+l*e/u;r.push([s[0]+n*Math.cos(t),s[1]+n*Math.sin(t)])}},er=e=>{let t=e.match(/[MLCAZ]|-?(?:\d*\.)?\d+(?:e[-+]?\d+)?/giu)??[],n=[],r=0,i=()=>Number(t[r++]),a=()=>[i(),i()],o=e=>{let t=n.at(-1)??[0,0];if(e===`M`||e===`L`){n.push(a());return}if(e===`C`){Qn([t,a(),a(),a()],n);return}if(e===`A`){let e=i();r+=4,$n(t,a(),e,n)}};for(;r<t.length;)o(t[r++]??`Z`);return n.filter((e,t)=>A(e,n[(t+1)%n.length]??e)>Yn)},tr=(e,t,n)=>{let[r,i]=j(t,e),a=Math.hypot(r,i),o=[i*n/a,-r*n/a];return[[e[0]+o[0],e[1]+o[1]],[t[0]+o[0],t[1]+o[1]]]},nr=(e,t,n,r)=>{let i=j(t,e),a=j(r,n),o=Xn(i,a);if(Math.abs(o)<Yn)return k(t,n);let s=Xn(j(n,e),a)/o;return[e[0]+s*i[0],e[1]+s*i[1]]},rr=(e,t)=>{let n=[...e];for(let[r,i]of e.entries()){let a=e[(r+1)%e.length];if(a===void 0)continue;let[o,s]=tr(i,a,t),c=j(s,o),l=[];for(let[e,t]of n.entries()){let r=n[(e+1)%n.length]??t,i=Xn(c,j(t,o))>=-1e-9,a=Xn(c,j(r,o))>=-1e-9;i&&l.push(t),i!==a&&l.push(nr(t,r,o,s))}if(n=l,n.length===0)break}return n},ir=(e,t)=>{if(t===0)return e;let n=er(e),r=t<0?rr(n,t):n.map((e,r)=>{let i=n[(r+n.length-1)%n.length]??e,a=n[(r+1)%n.length]??e,o=tr(i,e,t),s=tr(e,a,t);return nr(...o,...s)});return r.length<3?``:r.map((e,t)=>`${t===0?`M`:`L`}${Zn(e[0])} ${Zn(e[1])}`).join(``)+`Z`},ar=(e,t,n)=>t.width<=0||t.height<=0?``:ir(Kn(e,t),n),or=(e,t,n)=>{let r=(t.rotation??0)*Math.PI/180,i=Math.cos(r),a=Math.sin(r),o=t.flipHorizontal===!0?-1:1,s=t.flipVertical===!0?-1:1,c=i*o,l=a*o,u=-a*s,d=i*s,f=n===void 0?c:c*n.a+u*n.b,p=n===void 0?l:l*n.a+d*n.b,m=n===void 0?u:c*n.c+u*n.d,h=n===void 0?d:l*n.c+d*n.d,g=e.width/2,_=e.height/2;return{a:f,b:p,c:m,d:h,e:e.x+g-f*g-m*_,f:e.y+_-p*g-h*_}},sr=e=>{let t=e.additionalStyles?.declarations.find(e=>e.enabled&&e.property===`--enhance-group-affine-residual`)?.value;if(t===void 0)return;let n=/^matrix\(([^)]*)\)$/iu.exec(t)?.[1]?.split(`,`).map(e=>Number(e.trim()));if(n?.length!==6||n.some(e=>!Number.isFinite(e)))return null;let[r,i,a,o]=n;return r===void 0||i===void 0||a===void 0||o===void 0?null:{a:r,b:i,c:a,d:o}},cr=e=>{let t=sr(e);return t===null||e.box===void 0?null:or(e.box,e.layout??{},t)},M=(e,t,n)=>({x:e.x+t.x*n,y:e.y+t.y*n}),lr=e=>`${String(e.x)} ${String(e.y)}`,ur=(e,t,n)=>({x:(t.x-e.x)/n,y:(t.y-e.y)/n}),dr=(e,t,n)=>{let r=e.innerRatio!==void 0,i=e.count,a=e.innerRatio??1,o=r?i*2:i;return Array.from({length:o},(e,r)=>{let i=r%2==0?1:a,s=-Math.PI/2+r*Math.PI*2/o;return{x:t/2+Math.cos(s)*t*i/2,y:n/2+Math.sin(s)*n*i/2}})},fr=(e,t)=>{let n=e[t],r=e[(t+e.length-1)%e.length],i=e[(t+1)%e.length];if(n===void 0||r===void 0||i===void 0)return;let a=Math.hypot(r.x-n.x,r.y-n.y),o=Math.hypot(i.x-n.x,i.y-n.y);if(a===0||o===0)return;let s=ur(n,r,a),c=ur(n,i,o),l=Math.acos(Math.min(1,Math.max(-1,s.x*c.x+s.y*c.y)));if(l!==0&&l!==Math.PI)return{vertex:n,before:s,after:c,previousLength:a,nextLength:o,angle:l,cotangent:1/Math.tan(l/2)}},pr=(e,t,n,r)=>{let i=n*e.cotangent,a=M(e.vertex,t,i*(1+r)),o=M(e.vertex,t,i),s=M(e.vertex,{x:e.before.x+e.after.x,y:e.before.y+e.after.y},n/Math.sin(e.angle)),c=ur(o,s,n),l=(Math.PI-e.angle)*r/2,u=M(M(o,t,-n*Math.sin(l)),c,n*(1-Math.cos(l))),d={x:-t.x*Math.cos(l)+c.x*Math.sin(l),y:-t.y*Math.cos(l)+c.y*Math.sin(l)},f=M(u,d,-n*Math.tan(l/2));return{start:a,first:{x:a.x+(f.x-a.x)*2/3,y:a.y+(f.y-a.y)*2/3},second:f,end:u,travel:d}},mr=(e,t,n)=>{let r=pr(e,e.before,t,n),i=pr(e,e.after,t,n),a=4/3*t*Math.tan((Math.PI-e.angle)*(1-n)/4),o=M(r.end,r.travel,a),s=M(i.end,i.travel,a),c=(e,t,n)=>`C${lr(e)} ${lr(t)} ${lr(n)}`;return lr(r.start)+(n>0?c(r.first,r.second,r.end):``)+c(o,s,i.end)+(n>0?c(i.second,i.first,i.start):``)},hr=(e,t,n)=>{let r=e.map((t,n)=>fr(e,n)),i=e=>typeof t==`number`?t:t[e]??0;return`${e.map((t,a)=>{let o=r[a],s=(a+e.length-1)%e.length,c=(a+1)%e.length,l=r[s],u=r[c],d=i(a),f=a===0?`M`:`L`;if(d===0||o===void 0)return f+lr(t);let p=Math.min(o.previousLength/(o.cotangent+(l?.cotangent??0)*(i(s)/d)),o.nextLength/(o.cotangent+(u?.cotangent??0)*(i(c)/d))),m=Math.min(d,p),h=Math.min(n,Math.max(0,p/m-1));return f+mr(o,m,h)}).join(``)}Z`},gr=(e,t,n)=>hr(dr(e,t,n),e.cornerRadius,e.cornerSmoothing),_r=new WeakMap,vr=new WeakMap,yr=e=>{if(vr.has(e))return vr.get(e)??null;let t=e.result.path.match(/M[^M]*/gu)??[],n=t.map(e=>{let t=Rn(e);return{path:e,vertices:t!==null&&t.length>=3?t:null}}),r=t.length>0&&t.join(``)===e.result.path?n:null;return vr.set(e,r),r},br=(e,t,n)=>{let r={kind:`path`,path:e.result.path,fillRule:e.result.fillRule,viewBox:{x:0,y:0,width:t.width,height:t.height}};if(n===void 0||n.topLeft===0||[n.topRight,n.bottomLeft,n.bottomRight].some(e=>e!==n.topLeft))return r;let i=yr(e);return i===null?r:{...r,path:i.map(e=>e.vertices===null?e.path:hr(e.vertices,n.topLeft,n.smoothing??0)).join(``)}},xr=e=>{if(_r.has(e))return _r.get(e)??null;let t=Rn(e.path),n=t?.length===4&&t.every((e,n)=>{let r=t[(n+1)%4],i=t[(n+2)%4];return r!==void 0&&i!==void 0&&(r.x-e.x)*(i.y-r.y)>(r.y-e.y)*(i.x-r.x)})?t:null;return _r.set(e,n),n},Sr=(e,t,n)=>{if(n.width<=0||n.height<=0)return e;let r=[t.topLeft,t.topRight,t.bottomRight,t.bottomLeft];if(r.every(e=>e===0)&&e.viewBox.x===0&&e.viewBox.y===0&&n.width===e.viewBox.width&&n.height===e.viewBox.height)return e;let i=xr(e);if(i===null)return e;let a=i.map(t=>({x:(t.x-e.viewBox.x)*n.width/e.viewBox.width,y:(t.y-e.viewBox.y)*n.height/e.viewBox.height}));return{...e,path:hr(a,r,t.smoothing??0),viewBox:{x:0,y:0,width:n.width,height:n.height}}},Cr={topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},wr=[`border-top-left-radius`,`border-top-right-radius`,`border-bottom-right-radius`,`border-bottom-left-radius`],Tr=(e,t)=>{if(e===void 0)return 0;if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:null;let n=/^\s*(\d+(?:\.\d+)?)(px|%)?\s*$/u.exec(e);if(n===null)return null;let r=Number(n[1]);return n[2]===`%`?t*r/100:r},Er=e=>{if(e.appearance?.radius!==void 0)return e.appearance.radius;if(e.box===void 0)return null;let t=e.styles[`border-radius`],[n,r,i,a]=wr.map(n=>Tr(e.styles[n]??t,Math.min(e.box?.width??0,e.box?.height??0)));return n===null||r===null||i===null||a===null?null:{topLeft:n??0,topRight:r??0,bottomRight:i??0,bottomLeft:a??0}},Dr=(e,t)=>{let n=e/2,r=t/2;return`M0 ${String(r)}A${String(n)} ${String(r)} 0 1 0 ${String(e)} ${String(r)}A${String(n)} ${String(r)} 0 1 0 0 ${String(r)}Z`},Or=(e,t)=>{if(e.geometry?.kind===`path`)return e.geometry;let n=e.box;if(n!==void 0&&e.geometry?.kind===`polygon`&&n.width>0&&n.height>0)return{kind:`path`,path:gr(e.geometry,n.width,n.height),fillRule:`nonzero`,viewBox:{x:0,y:0,width:n.width,height:n.height}};if(n===void 0||![`rectangle`,`frame`].includes(e.component)||n.width<=0||n.height<=0)return`Choose a closed shape or an editable vector path.`;let r=Er(e);return r===null?`This shape uses a corner expression that cannot be edited as a path.`:{kind:`path`,fillRule:`nonzero`,path:e.styles[`border-radius`]===`50%`&&e.appearance?.radius===void 0&&wr.every(t=>e.styles[t]===void 0)?Dr(n.width,n.height):Kn(t&&e.component===`rectangle`&&e.appearance?.radius!==void 0?Cr:{...Cr,...r},n),viewBox:{x:0,y:0,width:n.width,height:n.height}}},kr=e=>{if(e.geometry?.kind===`boolean`&&e.box!==void 0)return e.geometry.result.isEmpty?`This shape has no closed geometry.`:br(e.geometry,e.box,e.appearance?.radius);let t=Or(e,!1);return typeof t!=`string`&&e.geometry?.kind===`path`&&e.component===`rectangle`&&e.appearance?.radius!==void 0&&e.box!==void 0?Sr(t,e.appearance.radius,e.box):t},Ar=e=>{let t=kr(e);if(typeof t==`string`)return t;if(e.box===void 0)return`The shape has no settled local box.`;let n=cr(e);if(n===null)return`The shape has an invalid affine transform.`;let r=e.box.width/t.viewBox.width,i=e.box.height/t.viewBox.height;return{path:t.path,fillRule:t.fillRule,matrix:[n.a*r,n.b*r,n.c*i,n.d*i,n.e-n.a*r*t.viewBox.x-n.c*i*t.viewBox.y,n.f-n.b*r*t.viewBox.x-n.d*i*t.viewBox.y]}},jr=.5,Mr=.25,Nr=(e,t=`field`,n)=>{let r=kn(e,n),i=Math.max(jr,...r.map(e=>Math.abs(e-jr)))+1,a=jr-i,o=jr+i,s=[{x:.75,y:.75,points:`.5,.5 ${String(o)},.5 ${String(o)},${String(o)} .5,${String(o)}`},{x:Mr,y:.75,points:`.5,.5 .5,${String(o)} ${String(a)},${String(o)} ${String(a)},.5`},{x:Mr,y:Mr,points:`.5,.5 ${String(a)},.5 ${String(a)},${String(a)} .5,${String(a)}`},{x:.75,y:Mr,points:`.5,.5 .5,${String(a)} ${String(o)},${String(a)} ${String(o)},.5`}],c=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${D({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``),l=s.map((e,n)=>`<linearGradient id="${t}-${String(n)}" gradientUnits="userSpaceOnUse" x1=".5" y1=".5" x2="${String(e.x)}" y2="${String(e.y)}" color-interpolation="sRGB">${c}</linearGradient>`).join(``),u=s.map((e,n)=>`<polygon points="${e.points}" fill="url(#${t}-${String(n)})" shape-rendering="crispEdges" />`).join(``);return`<defs>${l}</defs><g transform="matrix(${e.transform.map(String).join(` `)})">${u}</g>`},Pr=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Nr(e)}</svg>`,Fr=e=>e.parameter===`radius`?e.value/2:e.value,Ir=e=>{switch(e.kind){case`blur`:return`blur(${String(Fr(e))}px)`;case`brightness`:case`contrast`:case`saturate`:return`${e.kind}(${String(e.value)})`;case`grayscale`:case`invert`:case`sepia`:return`${e.kind}(${String(e.value*100)}%)`;case`hue-rotate`:return`hue-rotate(${String(e.value)}deg)`}},Lr=e=>e.filter(e=>e.visible).map(e=>Ir(e)).join(` `),Rr=new Set([`base`,`embed`,`iframe`,`link`,`meta`,`object`,`script`]),zr=/^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu,Br=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,Vr=e=>!Rr.has(e.toLowerCase()),Hr=e=>!Br.test(e),Ur=(e,t)=>{let n=e.toLowerCase();return n===`srcdoc`||/^on/iu.test(n)?!1:n===`style`?Hr(t):![`href`,`src`,`action`,`formaction`,`xlink:href`].includes(n)||!zr.test(t.replaceAll(/[\p{Control}\s]/gu,``))},Wr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Gr=(e,t)=>{if(!Wr(e)||e.kind!==`image`||typeof e.assetId!=`string`)return e;let n=t(e.assetId);return n===e.assetId?e:{...e,assetId:n}},Kr=(e,t)=>{let n=Gr(e,t);if(!Wr(n)||!Wr(n.alternatives))return n;let r=n.alternatives,i=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,Gr(n,t)]));return Object.entries(i).every(([e,t])=>r[e]===t)?n:{...n,alternatives:i}},qr=(e,t)=>Array.isArray(e)?e.map(e=>{if(!Wr(e)||e.kind!==`span`)return e;let n=Array.isArray(e.fills)?e.fills:void 0;return{...e,...n!==void 0&&{fills:n.map(e=>Kr(e,t))},...Wr(e.stroke)&&{stroke:{...e.stroke,paint:Kr(e.stroke.paint,t)}},...Array.isArray(e.children)&&{children:qr(e.children,t)}}}):e,Jr=(e,t)=>{let n=e.appearance,r=e.props?.src;return{...e,...n!==void 0&&{appearance:{...n,...n.fills!==void 0&&{fills:n.fills.map(e=>Kr(e,t))},...n.border!==void 0&&{border:{...n.border,paints:n.border.paints.map(e=>Kr(e,t))}},...n.outline!==void 0&&{outline:{...n.outline,paints:n.outline.paints.map(e=>Kr(e,t))}}}},...e.typography?.stroke!==void 0&&{typography:{...e.typography,stroke:{...e.typography.stroke,paint:Kr(e.typography.stroke.paint,t)}}},...e.props!==void 0&&{props:{...e.props,...e.component===`image`&&typeof r==`string`&&{src:t(r)},...e.component===`text`&&e.props.richText!==void 0&&{richText:qr(e.props.richText,t)}}}}},Yr=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${D({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``);return`<linearGradient id="${t}" gradientUnits="${n}" x1="0" y1=".5" x2="1" y2=".5" gradientTransform="matrix(${e.transform.map(String).join(` `)})" color-interpolation="sRGB">${r}</linearGradient>`},Xr=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${Yr(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,Zr=e=>({id:e,visible:!1,opacity:1,kind:`solid`,color:{space:`srgb`,red:0,green:0,blue:0,alpha:0}}),Qr=()=>({opacity:1,blendMode:`normal`,fills:[],border:{visible:!1,width:{top:0,right:0,bottom:0,left:0},style:`solid`,paints:[Zr(`empty-border`)]},outline:{visible:!1,width:0,offset:0,style:`solid`,paints:[Zr(`empty-outline`)]},radius:{topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},shadows:[],filters:[],backdropFilters:[]}),$r=e=>e.transform??[e.radius.x*2,0,0,e.radius.y*2,e.center.x-e.radius.x,e.center.y-e.radius.y],ei=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${D({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``);return`<radialGradient id="${t}" gradientUnits="${n}" cx=".5" cy=".5" r=".5" gradientTransform="matrix(${$r(e).map(String).join(` `)})" color-interpolation="sRGB">${r}</radialGradient>`},ti=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${ei(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,ni=/^enh_[\w-]{43}$/,ri=e=>{let t=Pe.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new x(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:t.person.id,displayName:t.person.displayName,tokenId:t.authentication.tokenId,tokenLabel:t.authentication.tokenLabel,expiresAt:t.authentication.expiresAt}},ii=(e,t,n)=>({loginWithToken:async n=>{if(!ni.test(n))throw new x(`BAD_REQUEST`,`Agent tokens begin with enh_ and contain 32 base64url bytes.`,`Pass a manual token from Settings to 'enhance auth login' through stdin.`);let r=ri(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=Be.parse(await t.authenticationConfig());if(i.method===`token`)throw new x(`BAD_REQUEST`,`Browser authentication is not configured for this Enhance environment.`,`Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.`);let a=await n.authorize({issuer:i.issuer,clientId:i.clientId,scope:i.scope,openBrowser:r.openBrowser,onReady:r.onReady,...r.signal!==void 0&&{signal:r.signal}});r.signal?.throwIfAborted();let o=be.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=ri(await t.queryWithToken(`person.me`,{},o.token));return r.signal?.throwIfAborted(),await e.write(o.token),s},status:async(n=t)=>{if(await e.read()===null)throw new x(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return ri(await n.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),ai=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),oi=e=>{if(e.byteLength<24||ai.some((t,n)=>e[n]!==t))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}},si=async(e,t)=>{if(t.result.canvasId!==t.canvasId||t.result.requestedVersion!==t.requestedVersion||t.result.loadedVersion!==t.requestedVersion||JSON.stringify(t.result.target)!==JSON.stringify(t.target))throw new x(`INTERNAL`,`The completed render evidence does not match its requested canvas, revision or target.`,`Do not use the image. Report render job ${t.id}.`);if(t.maxOutputPixels!==void 0&&t.result.width*t.result.height>t.maxOutputPixels)throw new x(`INTERNAL`,`The completed render exceeds its authorised output pixel limit.`,`Do not use the image. Report render job ${t.id}.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});let n=qe.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success||n.data.jobId!==t.id||n.data.download.bytes!==t.result.bytes)throw new x(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let r=await e.download(n.data.download.url),i=oi(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new x(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return{body:r,...n.data.source!==void 0&&{source:n.data.source}}},ci=e=>{let t=`enhance canvas inspect --canvas ${e.canvasId}`;return e.result.sourceState===void 0?e.target.kind===`node`?[t,`enhance canvas node --canvas ${e.canvasId} --node-id ${e.target.nodeId}`]:[t]:[`Inspect the PNG at path before persisting this moment.`,`enhance recording snapshot --canvas ${e.canvasId} --recording-id ${e.result.sourceState.recordingId} --at-ms ${String(e.result.sourceState.settledAtMs)}`,t]},li=(e,t,n)=>({...n!==void 0&&{source:n},jobId:e.id,operation:{kind:`canvas-render`,canvasId:e.canvasId,jobId:e.id},canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:ci(e)}),ui=async(e,t,n,r)=>{let i=await si(e,n);return li(n,t.write({body:i.body,...r}),i.source)},di=[`canvas.render.create`,`canvas.render.get`],fi=e=>new x(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),pi=e=>{let t=e.failure;if(t===null)return fi(`render job`);let n=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,r=t.reason===`VERSION_CHANGED`?`Run 'enhance canvas inspect --canvas ${e.canvasId}', then render its returned version.`:t.reason===`TARGET_NOT_FOUND`?`Run 'enhance canvas tree --canvas ${e.canvasId}' and choose a current node id.`:t.retryable?"Retry the render. If it repeats, run `enhance doctor` and report the job id.":`Change the target or scale using the failure details, then retry.`;return new x(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase,renderState:e.state})},mi=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),hi=async(e,t)=>{let n=lt.safeParse(await e.query(di[1],{jobId:t}));if(!n.success||n.data.job.id!==t)throw fi(`render status`);return n.data.job},gi=async(e,t)=>{let n=Date.now(),r=0,i=``,a=t.initial;for(;a.state===`queued`||a.state===`running`;){let o=Date.now(),s=`${a.state}:${a.phase}`;if((s!==i||o-r>=5e3)&&(t.progress({event:`render.progress`,jobId:a.id,state:a.state,phase:a.phase,elapsedMs:o-n,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),r=o,i=s),o>=t.deadline){if(t.timeoutOutcome===`pending`)return a;throw new x(`INTERNAL`,`Render ${a.id} did not finish before the local timeout.`,`Retry the exact command with --client-token ${t.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`,{jobId:a.id,phase:a.phase})}await mi(250),a=a.purpose===`inspection`&&a.state===`queued`&&a.attempt>0?await t.resume():await hi(e,a.id)}if(a.state!==`succeeded`)throw pi(a);return a},_i=async(e,t)=>{let n=dt.safeParse(await e.mutate(di[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.scope!==void 0&&{scope:t.scope},...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,...t.maxOutputPixels!==void 0&&{maxOutputPixels:t.maxOutputPixels},format:`png`}));if(!n.success)throw fi(`render creation`);if(n.data.job.canvasId!==t.canvasId||t.expectedVersion!==null&&n.data.job.requestedVersion!==t.expectedVersion||JSON.stringify(n.data.job.target)!==JSON.stringify(t.target)||n.data.job.scale!==t.scale)throw fi(`render identity`);return n.data.job},vi=(e,t)=>{if(t.maxOutputPixels!==void 0&&e.maxOutputPixels!==t.maxOutputPixels)throw new x(`INTERNAL`,`This API does not preserve the requested render pixel budget.`,`Update the API and renderer together before rendering a batch.`,{reason:`RENDER_BUDGET_UNSUPPORTED`})},yi=async(e,t)=>{let n=await _i(e.remote,t);try{vi(n,t);let r=await gi(e.remote,{initial:n,resume:async()=>_i(e.remote,t),deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress,timeoutOutcome:t.timeoutOutcome});return vi(r,t),r.state===`succeeded`?await ui(e.remote,e.files,r,{outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()}):{state:r.state,phase:r.phase,canvasId:r.canvasId,requestedVersion:r.requestedVersion,target:r.target,operation:{kind:`canvas-render`,canvasId:r.canvasId,jobId:r.id},pixelsDelivered:!1,next:[`Read operation_status with includeImage true. Do not create another render.`,`If it stays queued with attempt above 0, an attempt failed: repeat this exact request with the same clientToken to retry it.`]}}catch(e){let r=JSON.stringify({kind:`canvas-render`,canvasId:t.canvasId,jobId:n.id});throw e instanceof x?new x(e.code,e.message,e.remediation,{...e.fields,jobId:n.id,operation:r}):new x(`INTERNAL`,`The native render outcome could not be confirmed.`,`Read operation_status or retry with the identical request and clientToken.`,{jobId:n.id,operation:r})}},bi=(e,t,n,r=()=>null)=>({execute:async i=>yi({remote:e,files:t,now:n,progress:r},i)}),xi={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},Si=async e=>{try{return await e(),!0}catch{return!1}},Ci=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await Si(async()=>e.mutate(xi.renew,{...i,nodeIds:[...i.nodeIds],activityId:n})),o=!1)},c=setInterval(()=>void s(),r);return{activityId:n,update:async e=>{a||(i={...i,...e},await s())},finish:async()=>{a||(a=!0,clearInterval(c),await Si(async()=>e.mutate(xi.end,{canvasId:i.canvasId,activityId:n})))}}},wi=e=>({begin:async t=>{try{let n=fe.safeParse(await e.mutate(xi.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?Ci(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>Si(async()=>e.mutate(xi.end,{canvasId:t,activityId:n}))}),Ti=new Set([`insertPrototype`,`insertText`,`setBox`]),Ei=e=>Ti.has(e.op),Di=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,Oi=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],ki=e=>[...new Set(e.operations.flatMap(e=>Oi(e)))].slice(0,100),Ai=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:Ei(e)?e.box==="default"?null:e.box:null,ji=e=>{let t=e[0];if(t===void 0)return null;let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}},Mi=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:15}),r=v.safeParse(n);if(!r.success)throw new x(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},Ni=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Mi(e,t);let r=await wi(e).begin({canvasId:t.canvasId,phase:Di(t),nodeIds:ki(t),bounds:ji(t.operations.flatMap(e=>{let t=Ai(e);return t===null?[]:[t]}))});try{return await Mi(e,t)}finally{await r?.finish()}}}),Pi=async(e,t,n)=>{let r=ze.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!r.success)throw new x(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(r.data.version!==n)throw new x(`CONFLICT`,`Canvas version ${String(r.data.version)} no longer matches --base-version ${String(n)}.`,`An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(r.data.version)} before submitting a new edit.`);let i=St.safeParse(r.data.document);if(i.success)return i.data;throw new x(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},Fi=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):xn(t.sortKey,r.sortKey)).map(([e])=>e),Ii=e=>{let t=new Map;for(let[n,r]of Object.entries(e.relationships)){let e=t.get(r.parentId)??[];e.push(n),t.set(r.parentId,e)}for(let n of t.values())n.sort((t,n)=>{let r=e.relationships[t]?.sortKey??``,i=e.relationships[n]?.sortKey??``;return r===i?t.localeCompare(n):r.localeCompare(i)});return t},Li=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),N=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new x(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Ri=(e,t)=>{let n=new Set,r=t=>{for(let i of Fi(e,t))n.add(i),r(i)};return r(t),n},zi=(e,t)=>{let n=new Set,r=t;for(;r!==void 0;){if(n.has(r))throw new x(`BAD_REQUEST`,`The canvas contains a parent cycle.`,`Repair the canvas topology before editing.`);if(n.add(r),N(e,r).locked===!0)return!0;r=e.relationships[r]?.parentId}return!1},Bi=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},Vi=e=>{let t=0;return n=>(t+=1,`${Bi(e)}_${Bi(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},Hi=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of Fi(e,t))r(n)};return r(t),n},Ui=(e,t,n)=>Object.fromEntries(Hi(e,t).map(t=>[t,n(N(e,t).label)])),Wi=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=N(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Gi=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=N(t,n.id);if(n.id===`root`)throw new x(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let o=t.relationships[n.id];if(o===void 0)throw new x(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!Li(t.nodes[s]))throw new x(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=Ui(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=Hi(t,n.id).map(e=>Wi(l,e)),d=c[n.id];if(d===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:u,summary:{sourceId:n.id,newId:d,name:a.label,component:a.component,descendantIdMap:Object.fromEntries(Object.entries(c).filter(([e])=>e!==n.id))}}},Ki=(e,t,n)=>{if(t.length===0)throw new x(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=Vi(n),i=t.map((t,n)=>Gi({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},qi=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,Fi(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Ji=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},Yi=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new x(`BAD_REQUEST`,`Sibling ${n} is not a valid move target.`,`Choose another current sibling node.`);let r=t.parentOf.get(n);if(r===void 0)throw new x(`BAD_REQUEST`,`Sibling ${n} is detached.`,`Choose a reachable sibling from canvas tree.`);let i=(t.children.get(r)??[]).filter(t=>t!==e.nodeId).indexOf(n);return{parentId:r,index:`before`in e?i:i+1}},Xi=(e,t)=>`parentId`in e?Ji(e,t):Yi(e,t),Zi=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new x(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Ri(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!Li(n.document.nodes[t.parentId]))throw new x(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Qi=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]],a=[],o={...n.document.relationships},s=e=>{let t=i[e];return t===void 0?null:o[t]?.sortKey??null},c=null;try{let e=s(t.index-1),n=s(t.index),r=It(e,n);(e===null||e.localeCompare(r)<0)&&(n===null||r.localeCompare(n)<0)&&(c=r)}catch{c=null}if(c===null){let n=[...i];n.splice(t.index,0,e.nodeId);let r=Lt(null,null,n.length).toSorted((e,t)=>e.localeCompare(t));for(let[e,i]of n.entries()){let n=r[e];if(n===void 0)throw Error(`Missing generated move sort key.`);let s={parentId:t.parentId,sortKey:n};o[i]=s,a.push({op:`setParentage`,nodeId:i,parentage:s})}}else{let n={parentId:t.parentId,sortKey:c};o[e.nodeId]=n,a.push({op:`setParentage`,nodeId:e.nodeId,parentage:n})}return i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId),{operations:a,document:{...n.document,relationships:o}}},$i=(e,t)=>{if(t.length===0)throw new x(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=qi(e),r=[];return{operations:t.flatMap(e=>{let t=Xi(e,n);Zi(e,t,n),r.push({nodeId:e.nodeId,...t});let i=Qi(e,t,n);return n.document=i.document,i.operations}),moves:r,affectedParents:Array.from(n.affected,e=>({parentId:e,children:[...n.children.get(e)??[]]}))}},P=e=>Math.min(1,Math.max(0,e)),ea=e=>P(Number(e)/255),ta=e=>{let t=e.slice(1);if(![3,4,6,8].includes(t.length)||!/^[\da-f]+$/iu.test(t))return null;let n=t.length<=4?t.replaceAll(/([\da-f])/giu,`$1$1`):t,r=e=>Number.parseInt(n.slice(e,e+2),16)/255;return{space:`srgb`,red:r(0),green:r(2),blue:r(4),alpha:n.length===8?r(6):1}},na=e=>{let t=/^rgba?\(\s*([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*[,/]\s*([\d.]+)(%?))?\s*\)$/iu.exec(e);if(t===null)return null;let n=(e,t)=>t===`%`?P(Number(e)/100):ea(e??`0`),r=t[7]===void 0?1:P(Number(t[7])/(t[8]===`%`?100:1));return{space:`srgb`,red:n(t[1],t[2]),green:n(t[3],t[4]),blue:n(t[5],t[6]),alpha:r}},ra=e=>{let t=/^color\(\s*(srgb|display-p3)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\s*\)$/iu.exec(e);return t===null?null:{space:t[1]===`display-p3`?`display-p3`:`srgb`,red:P(Number(t[2])),green:P(Number(t[3])),blue:P(Number(t[4])),alpha:P(t[5]===void 0?1:Number(t[5]))}},ia=e=>{let t=e.trim().toLowerCase();return t===`transparent`?{space:`srgb`,red:0,green:0,blue:0,alpha:0}:t.startsWith(`#`)?ta(t):t.startsWith(`rgb`)?na(t):t.startsWith(`color(`)?ra(t):null},aa=(e,t)=>({id:e,visible:!0,opacity:1,kind:`solid`,color:t}),F=(e,t)=>{let n=ia(t);return n===null?null:aa(e,n)},oa=e=>e/2**32|0,sa=e=>e>>>0;function ca(e,t,n,r){let i=oa(n),a=sa(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function la(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const ua=e=>e?`"${e}" `:``;function da(e,t=``){if(typeof e!=`number`)throw TypeError(ua(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ua(t)+`expected integer >= 0, got `+e);return e}function fa(e,t,n=``){if(la(e)&&(t===void 0||e.length===t))return e;t!==void 0&&da(t,`length`);let r=la(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ua(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const pa=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)};function ma(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function ha(e,t){fa(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function ga(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _a(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function I(e,t){return e<<32-t|e>>>t}const va=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,ya=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ba(e){if(fa(e),va)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=ya[e[n]];return t}function xa(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function Sa(e,t,n=`opts`){return pa(e,`defaults`),t!==void 0&&pa(t,n),Object.assign(e,t)}function Ca(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=Sa({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}const wa=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ta(e,t,n){return e&t^~e&n}function Ea(e,t,n){return e&t^e&n^t&n}var Da=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=_a(this.buffer)}update(e){ma(this),fa(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=_a(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0;continue}n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){ma(this),ha(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),ca(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:_a(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};const Oa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ka=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),L=new Uint32Array(64);var Aa=class extends Da{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)L[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=L[e-15],n=L[e-2],r=I(t,7)^I(t,18)^t>>>3,i=I(n,17)^I(n,19)^n>>>10;L[e]=i+L[e-7]+r+L[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=I(o,6)^I(o,11)^I(o,25),u=l+t+Ta(o,s,c)+ka[e]+L[e]|0,d=(I(n,2)^I(n,13)^I(n,22))+Ea(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){ga(L)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ga(this.buffer)}},ja=class extends Aa{constructor(){super(32,Oa)}};const Ma=Ca(()=>new ja,wa(1)),Na=new Map,Pa=new Map,Fa={depth:0},Ia=(e,t=1)=>{let n=Fa.depth>0?Pa:Na;n.set(e,(n.get(e)??0)+t)},La=(e,t)=>e.sortKey===t.sortKey?e.childId.localeCompare(t.childId):e.sortKey<t.sortKey?-1:1,Ra=e=>{Ia(`child index builds`);let t=new Map;for(let[n,r]of Object.entries(e)){let e={childId:n,sortKey:r.sortKey},i=t.get(r.parentId);i===void 0?t.set(r.parentId,[e]):i.push(e)}let n=new Map;for(let[e,r]of t)n.set(e,r.toSorted(La).map(e=>e.childId));return n},za=new WeakMap,Ba=new WeakMap,Va=e=>{let t=za.get(e);if(t!==void 0)return t;let n=Ba.get(e)?.()??Ra(e);return Object.isFrozen(e)&&za.set(e,n),n},Ha=[],Ua=(e,t)=>e.get(t)??Ha,Wa=(e,t)=>Ua(Va(e),t),Ga=e=>e.trim()===``||e.trim()===`about:blank`,Ka=e=>typeof e==`string`&&e.startsWith(`enhance-pending-image:`),qa=e=>Ka(e.assetId)||e.opacity!==1||e.fit===`crop`&&e.transform!==void 0||(e.rotation??0)!==0||e.fit===`tile`&&(e.tileScale??1)!==1,Ja=e=>`--canvas-image-paint-${ba(Ma(xa(JSON.stringify([e.assetId,e.opacity,e.rotation??0,e.fit===`tile`?e.tileScale??1:1,e.fit===`crop`?e.transform:void 0]))))}`,Ya=e=>`--canvas-text-paints-${ba(Ma(xa(JSON.stringify(e.filter(e=>e.visible),(e,t)=>e===`id`?void 0:t))))}`,Xa=(e,t=1)=>`${D(e.color,t)} ${String(e.position*100)}%`,Za=e=>encodeURI(e).replaceAll(`"`,`%22`),Qa=e=>`url("${Za(e)}")`,$a=e=>{switch(e.kind){case`solid`:{let t=D(e.color,e.opacity);return`linear-gradient(${t}, ${t})`}case`linear-gradient`:return e.transform===void 0?`linear-gradient(${String(e.angle)}deg, ${e.stops.map(t=>Xa(t,e.opacity)).join(`, `)})`:`url("data:image/svg+xml,${encodeURIComponent(Xr({...e,transform:e.transform}))}")`;case`radial-gradient`:{if(e.transform!==void 0)return`url("data:image/svg+xml,${encodeURIComponent(ti(e))}")`;let t=`${String(e.center.x*100)}% ${String(e.center.y*100)}%`;return`radial-gradient(ellipse ${String(e.radius.x*100)}% ${String(e.radius.y*100)}% at ${t}, ${e.stops.map(t=>Xa(t,e.opacity)).join(`, `)})`}case`angular-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Nn(e))}")`;case`diamond-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Pr(e))}")`;case`image`:return Ga(e.assetId)?`none`:qa(e)?`var(${Ja(e)}, none)`:Qa(e.assetId)}},eo=(e,t)=>t>=1?0:e/(1-t)*100,to=e=>{if(e===void 0)return{"background-position":`center`,"background-size":`cover`};let t=Math.max(e.width,2**-52),n=Math.max(e.height,2**-52);return{"background-position":`${String(eo(e.x,t))}% ${String(eo(e.y,n))}%`,"background-size":`${String(100/t)}% ${String(100/n)}%`}},no=e=>{if(e.kind!==`image`)return{"background-size":e.kind===`angular-gradient`||e.kind===`diamond-gradient`||(e.kind===`linear-gradient`||e.kind===`radial-gradient`)&&e.transform!==void 0?`100% 100%`:`auto`,"background-position":`center`,"background-repeat":`no-repeat`,"background-origin":`border-box`};let t={fill:`100% 100%`,cover:`cover`,fit:`contain`,crop:`cover`,tile:`auto`}[e.fit];return{...e.fit===`crop`&&e.transform!==void 0?{"background-position":`0% 0%`,"background-size":`100% 100%`}:e.fit===`crop`?to(e.crop):{"background-position":e.fit===`tile`&&e.tileOrigin===`top-left`?`0% 0%`:`center`,"background-size":t},"background-repeat":e.fit===`tile`?`repeat`:`no-repeat`,"background-origin":`padding-box`}},ro=e=>{if(e.length===0)return{};let t=e.toReversed().map(e=>no(e));return Object.fromEntries([`background-size`,`background-position`,`background-repeat`,`background-origin`].map(e=>[e,t.map(t=>t[e]).join(`, `)]))},io=e=>e.kind===`solid`&&e.visible?D(e.color,e.opacity):void 0,ao=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,oo=e=>ao(e)?void 0:io(e),so=e=>{let t=e.filter(e=>e.visible),[n]=t;return n===void 0||t.length!==1?`transparent`:oo(n)??`transparent`},co=e=>({"background-image":e.toReversed().map(e=>$a(e)).join(`, `),...ro(e)}),lo=e=>{let t=e.filter(e=>e.visible);if(t.length===0||t.some(e=>ao(e)))return{background:`none`};let[n]=t,r=n===void 0?void 0:oo(n);return r!==void 0&&t.length===1?{background:r,"background-image":`none`}:{"background-color":`transparent`,...co(t)}},uo=e=>{let t=e.filter(e=>e.visible),[n]=t;return t.length===1&&n?.kind===`solid`?{color:D(n.color,n.opacity)}:t.length===0?{color:`transparent`}:{color:`transparent`,...t.length>1?{"background-image":`var(${Ya(t)}, none)`,"background-size":`100% 100%`,"background-position":`center`,"background-repeat":`no-repeat`}:co(t),...t.some(e=>e.kind===`image`&&e.fit===`crop`&&e.transform!==void 0)&&{"background-size":`100% var(--canvas-text-paint-height, 100%)`,"background-position":`0% var(--canvas-text-paint-y, 0%)`},"background-clip":`text`,"-webkit-background-clip":`text`}},fo=new Set(e.keyof().options.filter(e=>/^(?:border|outline)(?:-|$)/u.test(e)&&!e.includes(`radius`))),po=(e,t)=>{let n=t.toLowerCase();return fo.has(n)&&(n===e||n.startsWith(`${e}-`))},mo=[`top`,`right`,`bottom`,`left`],ho=[`solid`,`dashed`,`dotted`],go=[`width`,`style`,`color`],_o=(e,t=0)=>{if(e===void 0||!/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?:px)?$/iu.test(e))return;let n=Number(e.replace(/px$/iu,``));if(!(n!==0&&!/px$/iu.test(e)))return Number.isFinite(n)&&n>=t?n:void 0},vo=(e,t)=>{let n=Ve(t);if(/^(?:border(?:-(?:top|right|bottom|left))?|outline)$/u.test(e)){let t=n.find(e=>_o(e)!==void 0),r=n.find(e=>/^(?:none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/u.test(e)),i=n.find(e=>F(`probe`,e)!==null);if(t===void 0||r===void 0||i===void 0||n.length!==go.length)return null;let a=e===`border`?mo.map(e=>`border-${e}`):[e];return Object.fromEntries(a.flatMap(e=>go.map(n=>[`${e}-${n}`,{width:t,style:r,color:i}[n]])))}if(/^border-(?:width|style|color)$/u.test(e)){if(n.length===0||n.length>mo.length)return null;let[t=``,r=t,i=t,a=r]=n;return Object.fromEntries(mo.map((n,o)=>[`border-${n}-${e.slice(7)}`,[t,r,i,a][o]??``]))}return/^(?:border-(?:top|right|bottom|left)-(?:width|style|color)|outline-(?:width|style|color|offset))$/u.test(e)?{[e]:t}:null},yo=(e,t)=>e.additionalStyles?.declarations.filter(({property:n,value:r,enabled:i})=>po(t,n)&&(!i||r.trim()!==``||e.appearance?.[t]===void 0))??[],bo=(e,t)=>{let n=yo(e,t);if(n.some(({enabled:e})=>!e))return null;let r=new Set(n.map(({property:e})=>e.toLowerCase())),i=[...Object.entries(e.styles).filter(([e])=>!r.has(e.toLowerCase())),...n.map(({property:e,value:t})=>[e,t])],a={};for(let[e,n]of i){if(!po(t,e))continue;let r=vo(e.toLowerCase(),wt(e,n).trim());if(r===null||String(n).includes(`!`))return null;Object.assign(a,r)}return a},xo=e=>{let t=bo(e,`border`);if(t===null)return{kind:`custom`};if(e.appearance?.border!==void 0&&yo(e,`border`).length===0)return{kind:`native`,value:e.appearance.border};if(e.appearance?.border!==void 0)return{kind:`custom`};if(Object.keys(t).length===0)return{kind:`absent`};let n=mo.map(n=>({width:_o(t[`border-${n}-width`]??`0`),authoredStyle:t[`border-${n}-style`],authoredColor:t[`border-${n}-color`],style:ho.find(e=>e===t[`border-${n}-style`]),paint:F(`${e.id}-border`,t[`border-${n}-color`]??``)})),r=n.find(e=>e.width!==0)??n[0];if(r?.style===void 0||r.paint===null||n.some(e=>e.width===void 0||e.authoredStyle!==void 0&&e.style===void 0||e.authoredColor!==void 0&&e.paint===null||e.width!==0&&(e.style!==r.style||JSON.stringify(e.paint)!==JSON.stringify(r.paint))||e.width===0&&(e.style!==void 0&&e.style!==r.style||e.paint!==null&&JSON.stringify(e.paint)!==JSON.stringify(r.paint))))return{kind:`custom`};let[i=0,a=0,o=0,s=0]=n.map(e=>e.width);return{kind:`native`,value:{visible:!0,width:{top:i,right:a,bottom:o,left:s},style:r.style,paints:[r.paint]}}},So=e=>{let t=bo(e,`outline`);if(t===null)return{kind:`custom`};if(e.appearance?.outline!==void 0&&yo(e,`outline`).length===0)return{kind:`native`,value:e.appearance.outline};if(e.appearance?.outline!==void 0)return{kind:`custom`};if(Object.keys(t).length===0)return{kind:`absent`};let n=_o(t[`outline-width`]),r=_o(t[`outline-offset`]??`0`,-1/0),i=ho.find(e=>e===t[`outline-style`]),a=F(`${e.id}-outline`,t[`outline-color`]??``);return n===void 0||r===void 0||i===void 0||a===null?{kind:`custom`}:{kind:`native`,value:{visible:!0,width:n,offset:r,style:i,paints:[a]}}},Co=Object.freeze({top:0,right:0,bottom:0,left:0}),R=e=>e.alignment!==void 0&&e.alignment!==`inside`||e.layoutInclusion===`none`||e.layoutInclusion===`visible`&&(!e.visible||e.paints.every(e=>!e.visible))?Co:e.width,wo=e=>{let t=e.visible?so(e.paints):`transparent`,n=R(e);return{"border-style":e.style,"border-top-width":n.top,"border-right-width":n.right,"border-bottom-width":n.bottom,"border-left-width":n.left,"border-color":t}},To=e=>{if(!e.visible)return{"outline-style":`none`};let t=so(e.paints);return{"outline-style":e.style,"outline-width":e.width,"outline-offset":e.offset,"outline-color":t}},Eo=e=>({...e.border!==void 0&&wo(e.border),...e.outline!==void 0&&To(e.outline)}),Do=e=>{if(e.geometry?.kind===`boolean`||(e.appearance?.radius?.smoothing??0)<=0)return!1;let t=xo(e);return t.kind===`custom`||t.kind===`native`&&t.value.style!==`solid`},Oo=(e,t=e.box)=>{let n=e.appearance?.radius;if(n===void 0||t===void 0||e.geometry?.kind===`path`||e.geometry?.kind===`boolean`)return{};if((n.smoothing??0)<=0&&n.topLeft===n.topRight&&n.topLeft===n.bottomRight&&n.topLeft===n.bottomLeft)return ko(n);let r=Gn(n,t),i=ko(r);if((n.smoothing??0)<=0)return i;if(Do(e))return{};let a=`path("${Kn(n,t)}") border-box`,o=xo(e);if(o.kind!==`native`||Object.values(R(o.value)).every(e=>e===0))return{...i,"border-shape":a};let{top:s,right:c,bottom:l,left:u}=R(o.value),d=[r.topLeft,r.topRight,r.bottomRight,r.bottomLeft],f=e=>d.map((t,n)=>`max(0px, ${String(t)}px - ${String(e[n]??0)}px)`).join(` `),p=f([u,c,c,u]),m=f([s,s,l,l]);return{...i,"border-shape":`${a} inset(0 round ${p} / ${m}) padding-box`}},ko=e=>({"border-top-left-radius":e.topLeft,"border-top-right-radius":e.topRight,"border-bottom-right-radius":e.bottomRight,"border-bottom-left-radius":e.bottomLeft}),Ao=new Set([xe,y]),jo=e=>e.visible&&e.kind===`blur`&&e.progression!==void 0,Mo=e=>e.geometry===void 0&&Ao.has(e.component)?(e.appearance?.backdropFilters??[]).find(e=>jo(e))??null:null,No=(e,t)=>{let n=Mo(e);return n===null?t:t.filter(e=>e!==n)},Po=new Set([xe,Mt,y,a]),Fo=new Set([xe,Mt,y]),z=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,Io=e=>!e.visible||e.opacity<=0?!1:e.kind===`solid`?e.color.alpha>0:e.kind===`image`||e.stops.some(e=>e.color.alpha>0),Lo=e=>{let t=e.props?.source;if(typeof t!=`object`||!t)return!1;if(typeof Reflect.get(t,`pseudo`)==`string`)return!0;let n=Reflect.get(t,`layout`);return typeof Reflect.get(t,`path`)==`string`&&typeof n==`object`&&!!n&&typeof Reflect.get(n,`tag`)==`string`},Ro=e=>{if(e.component!==`rectangle`||e.geometry!==void 0||Lo(e))return!1;let{fills:t=[],border:n,outline:r}=e.appearance??{},i=[n,r].filter(e=>e?.visible===!0);return[...t,...i.flatMap(e=>e?.paints??[])].every(e=>!Io(e))},zo=e=>e.geometry===void 0&&Po.has(e.component)&&(e.component!==`image`||(typeof e.props?.src!=`string`||e.props.src===``)&&e.appearance?.fills!==void 0),Bo=e=>e?.visible===!0?e.paints.filter(e=>e.visible):[],Vo=e=>z(e)||e.kind===`image`&&(e.filters?.some(e=>e.visible)??!1),Ho=e=>{if(!zo(e))return[];let t=(e.appearance?.fills??[]).filter(e=>e.visible);return t.some(e=>Vo(e))||t.length>0&&Mo(e)!==null?t:[]},Uo=e=>e.style===`solid`||e.dashOrigin===`css`&&e.dashPattern===void 0&&e.dashCap===void 0,Wo=e=>{let t=Bo(e);return t.length>0&&((e.alignment??`inside`)!==`inside`||!Uo(e)||t.length>1||t.some(e=>e.kind!==`solid`))},Go=(e,t)=>{let n=e.appearance?.border;if(n===void 0||e.geometry!==void 0||!Fo.has(e.component))return[];let r=Bo(n);return r.some(e=>z(e))?r.map(e=>({kind:`border`,paints:[e]})):n.layoutInclusion===`none`||n.layoutInclusion===`visible`||Wo(n)||t&&r.length>0?[{kind:`border`,paints:r}]:[]},Ko=e=>{let[t,...n]=Bo(e.appearance?.outline);return(e.appearance?.radius?.smoothing??0)>0&&n.length===0&&t?.kind===`solid`&&!z(t)},qo=e=>{let t=e.appearance?.outline;if(t===void 0||e.geometry!==void 0||!Fo.has(e.component)||t.width<=0||Ko(e))return[];let n=Bo(t);return n.some(e=>z(e))?n.map(e=>({kind:`outline`,paints:[e]})):n.length>1||t.style!==`solid`||n.some(e=>e.kind!==`solid`)?[{kind:`outline`,paints:n}]:[]},B=e=>{let t=Ho(e),n=zo(e)&&!Ro(e)?(e.appearance?.shadows??[]).filter(e=>e.visible):[],r=n.filter(e=>e.kind===`outer`&&z(e)),i=n.filter(e=>e.kind===`inner`&&(t.length>0||z(e))),a=[...r.map(e=>({kind:`outer-shadow`,shadow:e})),...t.map(e=>({kind:`fill`,paint:e})),...i.map(e=>({kind:`inner-shadow`,shadow:e}))];return{elements:[...a,...Go(e,t.length>0),...qo(e)],hasPaintElements:a.length>0}},Jo=e=>e.elements.flatMap(e=>e.kind===`fill`?[e.paint]:[]),Yo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.shadow]:[]),Xo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.paints]:[]),Zo=(e,t,n={})=>e===`solid`?{dash:void 0,linecap:`butt`}:n.dashPattern===void 0?e===`dotted`?{dash:`0 ${String(t*2)}`,linecap:`round`}:{dash:`${String(t*3)} ${String(t*2)}`,linecap:`butt`}:{dash:n.dashPattern.map(String).join(` `),linecap:n.dashCap===`round`?`round`:n.dashCap===`square`?`square`:`butt`},Qo={top:0,right:0,bottom:0,left:0},$o={inside:0,center:.5,outside:1},es=[[`topLeft`,`top-left`,`left`,`top`],[`topRight`,`top-right`,`right`,`top`],[`bottomRight`,`bottom-right`,`right`,`bottom`],[`bottomLeft`,`bottom-left`,`left`,`bottom`]],ts=e=>Xo(B(e),`border`).length>0,ns=(e,t=e.box)=>{if(!ts(e))return{};let n={"border-color":`transparent`},r=e.appearance?.border,i=e.appearance?.radius;if(i===void 0||t===void 0||r?.style!==`solid`||e.geometry?.kind===`path`)return n;let a=R(r);if((i.smoothing??0)<=0||Object.values(a).every(e=>e===0))return n;let o=Kn(i,t),s=Kn(i,t,[-a.left,-a.top]);return{...n,"border-shape":`path("${o}") border-box path("${s}") padding-box`}},rs=(e,t)=>{let n=e.appearance?.radius;return n===void 0?{"border-radius":`inherit`}:Object.fromEntries(es.map(([e,r,i,a])=>{let o=n[e];return[`border-${r}-radius`,o<=0?0:`${String(o+t[i])}px ${String(o+t[a])}px`]}))},is=1e3,V=e=>String(Math.round(e*is)/is),as=(e,t,n)=>{let r=([n,r])=>[Math.min(n,e/2),Math.min(r,t/2)],[i,a,o,s]=[r(n.topLeft),r(n.topRight),r(n.bottomRight),r(n.bottomLeft)],c=([e,t],n,r)=>e===0||t===0?`L${V(n)} ${V(r)}`:`A${V(e)} ${V(t)} 0 0 1 ${V(n)} ${V(r)}`;return[`M${V(i[0])} 0`,`H${V(e-a[0])}`,c(a,e,a[1]),`V${V(t-o[1])}`,c(o,e-o[0],t),`H${V(s[0])}`,c(s,0,t-s[1]),`V${V(i[1])}`,c(i,i[0],0),`Z`].join(``)},os=e=>{if(e.stroke.style===`solid`)return{};let t=Zo(e.stroke.style,e.widest,e.stroke),n=`<svg xmlns="http://www.w3.org/2000/svg" width="${V(e.width)}" height="${V(e.height)}"><path d="${as(e.width,e.height,e.corners)}" fill="none" stroke="#000" stroke-width="${V(e.widest*2)}" stroke-dasharray="${t.dash??`none`}" stroke-linecap="${t.linecap}"/></svg>`;return{"border-style":`solid`,"mask-image":`url("data:image/svg+xml,${encodeURIComponent(n)}")`,"mask-size":`100% 100%`,"mask-repeat":`no-repeat`,"mask-origin":`border-box`}},ss=(e,t,n,r)=>{if(n===void 0)return{};let i=e.appearance?.radius,a=([e,,t,n])=>{let a=i?.[e]??0;return a<=0?[0,0]:[a+r[t],a+r[n]]};return os({width:n.width+r.left+r.right,height:n.height+r.top+r.bottom,corners:{topLeft:a(es[0]),topRight:a(es[1]),bottomRight:a(es[2]),bottomLeft:a(es[3])},widest:Math.max(...Object.values(t.width)),stroke:t})},cs=(e,t=e.box,n)=>{let r=e.appearance?.border,[i]=Xo(B(e),`border`);if(r===void 0||i===void 0)return null;let a=n??i,o=R(r),s=$o[r.alignment??`inside`],c={top:r.width.top*s,right:r.width.right*s,bottom:r.width.bottom*s,left:r.width.left*s},l={border:{...r,alignment:`inside`,layoutInclusion:`always`},radius:e.appearance?.radius},[u]=a,d=a.length===1&&u?.kind===`solid`&&(u.blendMode??`normal`)===`normal`&&Uo(r)&&s===0;return{position:`absolute`,inset:0,top:-(o.top+c.top),right:-(o.right+c.right),bottom:-(o.bottom+c.bottom),left:-(o.left+c.left),"box-sizing":`border-box`,"pointer-events":`none`,...s===0?{"border-radius":`inherit`}:rs(e,c),...Eo({...l,border:{...l.border,paints:[...a]}}),...!d&&{"border-color":`transparent`,...co(a),"background-origin":`border-box`,"background-clip":`border-area`},...a.length===1&&u?.blendMode!==void 0&&u.blendMode!==`normal`&&{"mix-blend-mode":u.blendMode},...s===0&&Oo({...e,styles:{},additionalStyles:void 0,appearance:l},t),...!d&&ss(e,r,t,s===0?Qo:c)}},ls=(e,t)=>{if(Ro(e))return[];let n=B(e),r=[...Yo(n,`outer-shadow`),...Yo(n,`inner-shadow`)];return r.length===0?t:t.filter(e=>!r.includes(e))},us=e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${D(e.color)}`,ds=e=>`${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${D(e.color)}`,fs=(e,t)=>{let n=ls(e,t).filter(e=>e.visible);if(e.component===`text`){let e=n.filter(e=>e.kind===`outer`&&e.spread===0).map(e=>ds(e)).join(`, `);return{"box-shadow":`none`,"text-shadow":e===``?`none`:e}}let r=n.map(e=>us(e)).join(`, `);return{"box-shadow":r===``?`none`:r}},ps=(e,t)=>{let n=e.appearance?.border,r=n===void 0?{top:0,right:0,bottom:0,left:0}:R(n);return{position:`absolute`,top:-r.top,right:-r.right,bottom:-r.bottom,left:-r.left,"border-radius":`inherit`,"pointer-events":`none`,"box-shadow":us(t),"mix-blend-mode":t.blendMode??`normal`}},ms=(e,t)=>{let n=t.map((n,r)=>{let[i=``,a,...o]=Ve(n),s=ia(i),c=a===void 0?r/(t.length-1):/^\d+(?:\.\d+)?%$/u.test(a)?Number(a.slice(0,-1))/100:NaN;return s===null||o.length>0?null:{id:`${e}-stop-${String(r)}`,color:s,position:c}});return n.includes(null)?null:n.filter(e=>e!==null)},hs=(e,t)=>{let n=/^(linear|radial)-gradient\((.*)\)$/su.exec(t);if(n===null)return null;let r=[...Ve(n[2]??``,`,`)],i=r[0]??``,a=/^(-?(?:\d+(?:\.\d*)?|\.\d+))deg$/u.exec(i),o=/^ellipse ([\d.]+)% ([\d.]+)% at (-?[\d.]+)% (-?[\d.]+)%$/u.exec(i);if(a!==null&&n[1]!==`linear`||o!==null&&n[1]!==`radial`)return null;(a!==null||o!==null)&&r.shift();let s=r.map(e=>Ve(e).length>1);if(s.some(Boolean)&&!s.every(Boolean))return null;let c=ms(e,r);if(c===null)return null;let l={id:e,visible:!0,opacity:1,stops:c},u=at.safeParse(n[1]===`linear`?{...l,kind:`linear-gradient`,angle:Number(a?.[1]??180)}:o===null?null:{...l,kind:`radial-gradient`,radius:{x:Number(o[1])/100,y:Number(o[2])/100},center:{x:Number(o[3])/100,y:Number(o[4])/100}});if(!u.success)return null;let d=u.data,f=`stops`in d?d.stops[0]:void 0;return f!==void 0&&d.kind===`linear-gradient`&&d.stops.every(e=>JSON.stringify(e.color)===JSON.stringify(f.color))?{id:e,kind:`solid`,visible:!0,opacity:1,color:f.color}:d},gs=(e,t,n,r)=>{let i=Ve(e[t]??r,`,`);return i[n%i.length]??r},_s=(e,t,n,r)=>{let i=/^url\((?:"([^"\\]*)"|'([^'\\]*)'|([^\s'"()\\]+))\)$/u.exec(t),a=i?.[1]??i?.[2]??i?.[3];if(a===void 0||a===``||a.startsWith(`data:image/svg+xml`))return null;let o=gs(n,`background-position`,r,`0% 0%`),s=gs(n,`background-size`,r,`auto`),c=gs(n,`background-repeat`,r,`repeat`),l=[`center`,`center center`,`50% 50%`].includes(o),u={id:e,kind:`image`,visible:!0,opacity:1,assetId:a};if(c===`repeat`&&s===`auto`&&(o===`0% 0%`||l))return{...u,fit:`tile`,tileOrigin:l?`center`:`top-left`};if(c!==`no-repeat`||!l)return null;let d=Object.entries({cover:`cover`,contain:`fit`,"100% 100%":`fill`}).find(([e])=>e===s)?.[1];return d===void 0?null:{...u,fit:d}},vs=(e,t)=>{let n=t.background,i=t[`background-color`]??n,a=i===void 0||i===`none`?null:F(`${e}-background`,i);if(i!==void 0&&i!==`none`&&a===null)return null;let o=t[`background-image`];if(o===void 0||o===`none`)return a===null?[]:[a];let s=Ve(o,`,`).map((n,i)=>{let a=`${e}-fill-${String(i)}`,o=hs(a,n),s=gs(t,`background-size`,i,`auto`);if(o!==null&&![`auto`,`auto auto`,`100% 100%`].includes(s))return null;let c=o??_s(a,n,t,i),l=r.safeParse(gs(t,`background-blend-mode`,i,`normal`));return c===null||!l.success?null:{...c,blendMode:l.data}});return s.includes(null)?null:[...a===null?[]:[a],...s.filter(e=>e!==null).toReversed()]},ys=[[`fills`,/^background(?:-color|-image)?$/u],[`radius`,/^border(?:-(?:top|bottom)-(?:left|right))?-radius$/u],[`border`,/^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u],[`outline`,/^outline(?:-(?:width|style|color|offset))?$/u],[`shadows`,/^(?:box|text)-shadow$/u],[`filters`,/^filter$/u],[`backdropFilters`,/^backdrop-filter$/u],[`opacity`,/^opacity$/u],[`blendMode`,/^mix-blend-mode$/u]],bs=new Set([`color`,`-webkit-text-fill-color`]),xs=(e,t)=>{let n=new Set;for(let r of t){let t=r.toLowerCase(),i=e.component===`text`;i&&bs.has(t)&&n.add(`fills`);for(let[e,r]of ys)r.test(t)&&(!i||e!==`fills`)&&n.add(e)}return[...n].filter(t=>e.appearance?.[t]!==void 0)},Ss=new Set([`background`,`background-color`,`background-image`]),Cs=new Set([`background-position`,`background-size`,`background-repeat`,`background-origin`,`background-blend-mode`]),ws=e=>{if((e.additionalStyles?.declarations??[]).some(({property:e,enabled:t})=>e.toLowerCase().startsWith(`background`)&&!t)||Object.keys(e.styles).some(e=>e.toLowerCase().startsWith(`background`)&&e!==e.toLowerCase()))return null;let t=Object.entries(ft(e)).filter(([e,t])=>e.toLowerCase().startsWith(`background`)&&t!==``).map(([e,t])=>[e.toLowerCase(),String(t).trim()]);if(t.some(([,e])=>e.includes(`!`)))return null;let n={};for(let[e,r]of t){if(e===`background`){let e=n[`background-blend-mode`];n=e===void 0?{}:{"background-blend-mode":e}}n[e]=r}return n},Ts=e=>{let t=ws(e);if(t===null)return{kind:`custom`};let n=e.appearance?.fills;if(n!==void 0&&n.every(e=>!e.visible)&&t.background!==void 0&&t[`background-image`]!==void 0&&t[`background-image`]!==`none`)return{kind:`custom`};if(n!==void 0)return{kind:`native`,fills:n,owned:Ss};if(Object.entries(t).some(([e,t])=>!Ss.has(e)&&!Cs.has(e)&&![`background-blend-mode`,`background-clip`].includes(e)&&t!==``)||t[`background-origin`]!==void 0&&t[`background-origin`]!==`padding-box`||t[`background-clip`]!==void 0&&t[`background-clip`]!==`border-box`)return{kind:`custom`};let r=vs(e.id,t);if(r===null||t[`background-image`]!==void 0&&r.some(e=>e.kind!==`image`)&&(e.appearance?.border!==void 0||Object.keys(e.styles).some(e=>/^border(?:-|$)/u.test(e))))return{kind:`custom`};let i=new Set(Ss);for(let e of Cs)i.add(e);return{kind:`native`,fills:r,owned:i}},Es=e=>({...Jo(B(e)).length>0&&{background:`none`},...Mo(e)!==null&&{isolation:`isolate`}}),Ds=e=>({position:`absolute`,inset:0,...co([e]),...e.kind===`image`&&e.filters!==void 0&&{filter:Lr(e.filters)},...e.blendMode!==void 0&&e.blendMode!==`normal`&&{"mix-blend-mode":e.blendMode}}),Os=[[`topLeft`,`top-left`],[`topRight`,`top-right`],[`bottomRight`,`bottom-right`],[`bottomLeft`,`bottom-left`]],ks=e=>Xo(B(e),`outline`).length>0,As=e=>ks(e)?{"outline-style":`none`}:{},js=(e,t,n)=>{let r=e.appearance?.radius;if(r===void 0)return{};let i=t.offset+t.width,a=Zo(t.style,t.width,t),o=ar(r,n,t.offset+t.width/2),s=`<svg xmlns="http://www.w3.org/2000/svg" width="${String(n.width+2*i)}" height="${String(n.height+2*i)}"><path d="${o}" transform="translate(${String(i)} ${String(i)})" fill="none" stroke="#000" stroke-width="${String(t.width)}" stroke-dasharray="${a.dash??`none`}" stroke-linecap="${a.linecap}"/></svg>`;return{"background-clip":`border-box`,"mask-image":`url("data:image/svg+xml,${encodeURIComponent(s)}")`,"mask-size":`100% 100%`,"mask-repeat":`no-repeat`,"mask-origin":`border-box`}},Ms=(e,t=e.box,n)=>{let r=e.appearance?.outline,[i]=Xo(B(e),`outline`);if(r===void 0||i===void 0)return null;let a=r.offset+r.width,o=e.appearance?.radius,s=n??i,[c]=s,l=e.appearance?.border,u=l===void 0?{top:0,right:0,bottom:0,left:0}:R(l),d=e=>{let t=o?.[e]??0;return t<=0?0:t+a};return{position:`absolute`,top:-(u.top+a),right:-(u.right+a),bottom:-(u.bottom+a),left:-(u.left+a),"box-sizing":`border-box`,"pointer-events":`none`,"border-style":r.style,"border-width":r.width,"border-color":`transparent`,...Object.fromEntries(Os.map(([e,t])=>[`border-${t}-radius`,d(e)])),...co(s),"background-origin":`border-box`,"background-clip":`border-area`,...s.length===1&&c?.blendMode!==void 0&&c.blendMode!==`normal`&&{"mix-blend-mode":c.blendMode},...t!==void 0&&(o?.smoothing??0)>0&&js(e,r,t),...t!==void 0&&(o?.smoothing??0)<=0&&os({width:t.width+2*a,height:t.height+2*a,corners:{topLeft:[d(`topLeft`),d(`topLeft`)],topRight:[d(`topRight`),d(`topRight`)],bottomRight:[d(`bottomRight`),d(`bottomRight`)],bottomLeft:[d(`bottomLeft`),d(`bottomLeft`)]},widest:r.width,stroke:r})}},Ns=e=>{if(h(e))return!0;if(e.typography?.decoration===void 0)return!1;let t=e.appearance?.fills?.filter(e=>e.visible)??[];return t.length>1||t.some(e=>e.kind!==`solid`)},Ps=(e,t)=>{let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)?Math.min(1,Math.max(0,n)):t},Fs=e=>st.find(t=>t===e)??`normal`,Is=(e,t)=>{let n=Number(String(e??``).replace(`px`,``));return Number.isFinite(n)?Math.max(t,n):0},Ls=e=>Is(e,0),Rs=(e,t)=>e===0?t:e,zs=e=>{let[t=0,n=t,r=t,i=n]=String(e[`border-radius`]??`0`).split(/\s+/u).map(e=>Ls(e));return{topLeft:Rs(Ls(e[`border-top-left-radius`]),t),topRight:Rs(Ls(e[`border-top-right-radius`]),n),bottomRight:Rs(Ls(e[`border-bottom-right-radius`]),r),bottomLeft:Rs(Ls(e[`border-bottom-left-radius`]),i)}},H=e=>{let t=Qr(),n=xo(e),r=So(e),i=F(`${e.id}-fill`,String(e.styles[e.component===`text`?`color`:`background`]??``)),a=e.component===`text`?null:Ts(e);return{...t,opacity:e.appearance?.opacity??Ps(e.styles.opacity,1),blendMode:e.appearance?.blendMode??Fs(e.styles[`mix-blend-mode`]),fills:a?.kind===`native`?[...a.fills]:e.appearance?.fills??(i===null?[]:[i]),border:n.kind===`native`?n.value:e.appearance?.border??t.border,outline:r.kind===`native`?r.value:e.appearance?.outline??t.outline,radius:e.appearance?.radius??zs(e.styles),...e.appearance?.retainedBorder!==void 0&&{retainedBorder:e.appearance.retainedBorder},shadows:e.appearance?.shadows??[],filters:e.appearance?.filters??[],backdropFilters:e.appearance?.backdropFilters??[]}},Bs=e=>{let t=e.appearance?.fills;return e.component===`text`&&Ns(e)?{...t!==void 0&&{color:uo(t).color??`transparent`},"background-image":`none`}:t===void 0?{}:e.component===`text`?uo(t):lo(t)},Vs=e=>{let t=e.appearance,n={...Bs(e),...Es(e)};return(t?.opacity??Ps(e.styles.opacity,1))===0&&(n[`pointer-events`]=`none`),t===void 0?n:(t.opacity!==void 0&&(n.opacity=t.opacity),t.blendMode!==void 0&&(n[`mix-blend-mode`]=t.blendMode),t.radius!==void 0&&e.geometry?.kind!==`path`&&Object.assign(n,ko(t.radius),Oo(e)),Object.assign(n,Eo(t),ns(e),As(e)),t.filters!==void 0&&(n.filter=Lr(t.filters)),t.shadows!==void 0&&Object.assign(n,fs(e,t.shadows)),t.backdropFilters!==void 0&&(n[`backdrop-filter`]=Lr(No(e,t.backdropFilters))),n)},Hs=e=>{let t=H(e).radius;return t.topLeft===0&&t.topRight===0&&t.bottomRight===0&&t.bottomLeft===0},Us=e=>{let t=H(e);return xo(e).kind!==`native`&&So(e).kind!==`native`&&t.shadows.every(e=>!e.visible)&&t.filters.every(e=>!e.visible)&&t.backdropFilters.every(e=>!e.visible)},Ws=e=>e!==void 0&&e.geometry===void 0&&(e.component===`image`||e.component===`rectangle`&&Hs(e))&&Us(e),Gs=e=>{let t=e.props?.naturalWidth,n=e.props?.naturalHeight;return typeof t==`number`&&typeof n==`number`&&t>0&&n>0?{width:t,height:n}:void 0},Ks=(e,t)=>{if(t.component!==`text`)return;let n=e.relationships[t.id]?.parentId,r=n===void 0?void 0:e.nodes[n];return r?.geometry?.kind===`mask`&&r.geometry.maskId===t.id?r:void 0},qs=(e,t)=>{let n=Ks(e,t);if(n===void 0)return null;let r=Wa(e.relationships,n.id).flatMap(n=>n===t.id?[]:e.nodes[n]??[]),i=t.box;return i!==void 0&&r.length>0&&r.every(e=>Ws(e)&&Zs(e,i)!==null)?r:null},Js=(e,t,n)=>{let r=(e===`cover`?Math.max:Math.min)(t.width/n.width,t.height/n.height),i=n.width*r,a=n.height*r;return{x:t.x+(t.width-i)/2,y:t.y+(t.height-a)/2,width:i,height:a}},Ys=(e,t)=>{let n=$a(e);if(e.fit===`fill`)return{image:n,box:t};if(e.fit===`crop`&&e.crop!==void 0){let r=t.width/Math.max(e.crop.width,2**-52),i=t.height/Math.max(e.crop.height,2**-52);return{image:n,box:{x:t.x-e.crop.x*r,y:t.y-e.crop.y*i,width:r,height:i}}}let r=e.naturalSize;if(r===void 0)return null;if(e.fit===`tile`){let i=e.tileScale??1;return{image:n,box:{x:t.x,y:t.y,width:r.width*i,height:r.height*i},repeat:`repeat`}}return{image:n,box:Js(e.fit===`fit`?`fit`:`cover`,t,r)}},Xs=(e,t)=>{let n=e.props?.src;if(typeof n!=`string`||n===``)return[];let r=Qa(n),i=e.props?.fit;if(i!==`cover`&&i!==`contain`)return[{image:r,box:t}];let a=Gs(e);return a===void 0?null:[{image:r,box:Js(i===`cover`?`cover`:`fit`,t,a)}]},Zs=(e,t)=>{if(e.box===void 0)return[];let n={...e.box,x:e.box.x-t.x,y:e.box.y-t.y};if(e.component===`image`&&e.appearance?.fills===void 0)return Xs(e,n);let{opacity:r}=H(e),i=[],a=H(e).fills.filter(e=>e.visible).toReversed();for(let e of a)if(e.kind===`image`){let t=Ys(e,n);if(t===null)return null;i.push(t)}else i.push({image:$a({...e,opacity:e.opacity*r}),box:n});return i},Qs=(e,t)=>t.geometry?.kind===`mask`?e.nodes[t.geometry.maskId]:void 0,$s={a:1,b:0,c:0,d:1,e:0,f:0},ec=(e,t)=>({a:e.a*t.a+e.c*t.b,b:e.b*t.a+e.d*t.b,c:e.a*t.c+e.c*t.d,d:e.b*t.c+e.d*t.d,e:e.a*t.e+e.c*t.f+e.e,f:e.b*t.e+e.d*t.f+e.f}),tc=e=>{let{fills:t,opacity:n}=H(e);return(1-t.filter(e=>e.visible).reduce((e,t)=>e*(1-t.opacity*(t.kind===`solid`?t.color.alpha:1)),1))*n},nc=(e,t,n)=>{let[r,i,a,o,s,c]=e.matrix,l=ec(t,{a:r,b:i,c:a,d:o,e:s,f:c});return{path:e.path,fillRule:e.fillRule,transform:`matrix(${[l.a,l.b,l.c,l.d,l.e,l.f].map(String).join(` `)})`,opacity:n}},rc=(e,t)=>{if(t.component!==`group`||t.geometry!==void 0)return null;let n=[],r=(t,i,a)=>{if(t.visible===!1)return;let o=t.component===`group`&&t.geometry===void 0,s=o?null:Ar(t);if(s!==null&&typeof s!=`string`&&n.push(nc(s,i,a*tc(t))),!o&&t.component!==`frame`)return;let c=cr(t);if(c===null)return;let l=ec(i,c),u=a*H(t).opacity;for(let n of Wa(e.relationships,t.id)){let t=e.nodes[n];t!==void 0&&r(t,l,u)}};return r(t,$s,1),n},ic=e=>{let t=2166136261;for(let n of e)t=Math.imul(t^(n.codePointAt(0)??0),16777619);return(t>>>0).toString(16)},ac=(e,t,n)=>{if(qs(e,t)!==null)return null;let r=t.box;if(r===void 0)return{path:``,fillRule:`nonzero`,matrix:[1,0,0,1,0,0]};let{width:i,height:a}=r;return{path:`M0 0H${String(i)}V${String(a)}H0Z`,fillRule:`nonzero`,matrix:[1/n.width,0,0,1/n.height,r.x/n.width,r.y/n.height]}},oc=(e,t,n)=>{let r=t.geometry,i=t.box;if(r===void 0||i===void 0||i.width<=0||i.height<=0)return null;if(r.kind===`path`||r.kind===`polygon`){let e=kr(t);if(typeof e==`string`)return null;let n=e.viewBox;return{path:e.path,fillRule:e.fillRule,matrix:[1/n.width,0,0,1/n.height,-n.x/n.width,-n.y/n.height]}}if(r.kind===`boolean`){let e=kr(t);return{path:typeof e==`string`?``:e.path,fillRule:r.result.fillRule,matrix:[1/i.width,0,0,1/i.height,0,0]}}let a=n??Qs(e,t);if(a?.component===`text`&&a.visible!==!1)return ac(e,a,i);let o=a===void 0||a.visible===!1?null:rc(e,a);if(o!==null)return{path:``,fillRule:`nonzero`,matrix:[1/i.width,0,0,1/i.height,0,0],shapes:o};let s=a===void 0||a.visible===!1?null:Ar(a);if(s===null||typeof s==`string`)return{path:``,fillRule:`nonzero`,matrix:[1,0,0,1,0,0]};let[c,l,u,d,f,p]=s.matrix;return{path:s.path,fillRule:s.fillRule,matrix:[c/i.width,l/i.height,u/i.width,d/i.height,f/i.width,p/i.height]}},sc=(e,t,n)=>{let r=oc(e,t,n);if(r===null)return null;let{path:i,fillRule:a,matrix:o,shapes:s}=r,c=`matrix(${o.map(String).join(` `)})`;return{id:`canvas-geometry-${encodeURIComponent(t.id).replaceAll(`%`,`_`)}-${ic(JSON.stringify([i,a,c,s]))}`,path:i,fillRule:a,transform:c,matrix:o,...s!==void 0&&{shapes:s}}},cc=(e,t)=>{let n=Dt(new Set(Object.keys(t))).filter(t=>e.typography?.[t]!==void 0);return n.length===0?null:{op:`patchTypography`,nodeId:e.id,typography:{clear:n}}},lc=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),uc=(t,n)=>{let r=new Map((t.additionalStyles?.declarations??[]).map(e=>[e.id,e]));for(let[t,i]of Object.entries(n)){let n=Array.from(r,([,e])=>e).filter(e=>(t.startsWith(`--`)?e.property:e.property.toLowerCase())===t);for(let e of n)r.delete(e.id);if(i===null||e.safeParse({[t]:i}).success)continue;let a=n[0]?.id??`css-${t}`.slice(0,190),o=a;for(let e=1;r.has(o);e+=1)o=`${a}-${String(e)}`;let s=he.safeParse({id:o,property:t,value:String(i),enabled:!0});if(!s.success)throw new x(`BAD_REQUEST`,`Style ${t} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);r.set(o,s.data)}let i=r.values().toArray(),a=i.length===0&&t.additionalStyles===void 0?void 0:{declarations:i},o=wn(t.additionalStyles,a);return o===null?null:{op:`patchAdditionalStyles`,nodeId:t.id,additionalStyles:o}},dc=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...ut(t,r,e),...ut(n,r,e)],o=ht(t.layout??{},i,{horizontal:a(`horizontal`),vertical:a(`vertical`)});for(let[e,t]of[[`width`,`horizontal`],[`height`,`vertical`]]){let n=r[e];(n===`fill`||n===`hug`)&&(o[t]={mode:n})}return JSON.stringify(o)===JSON.stringify(t.layout??{})?null:{op:`setLayout`,nodeId:t.id,layout:Object.keys(o).length===0?`default`:o}},fc=(e,t,n)=>{let r={...n};for(let[i,a]of[[`width`,`horizontal`],[`height`,`vertical`]])if(n[i]===`fill`||n[i]===`hug`){r[i]=null;for(let n of ut(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},pc=(t,n,r)=>{let i=fc(t,n,r),a=uc(n,i),o=Object.fromEntries(Object.entries(i).filter(([t,n])=>e.safeParse({[t]:n}).success)),s={...n,styles:{...n.styles},...a!==null&&{additionalStyles:Cn(n.additionalStyles,a.additionalStyles)??void 0}};for(let[e,t]of Object.entries(o))t===null?Reflect.deleteProperty(s.styles,e):s.styles[e]=t;let c=dc(t,n,s,r),l=cc(n,i),u=xs(n,Object.keys(i)),d=u.length>0?[{op:`setAppearance`,nodeId:n.id,appearance:{clear:[...u]}}]:[];return[...Object.keys(o).length>0?[{op:`setStyles`,nodeId:n.id,styles:e.parse(o)}]:[],...d,...l===null?[]:[l],...c===null?[]:[c],...a===null?[]:[a]]},mc=e=>{let t=new Map;for(let n of e)for(let e of n.nodeIds){let r=t.get(e)??{};for(let[e,t]of Object.entries(n.styles)){let n=lc(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},hc=(e,t)=>{let n=[...mc(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new x(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return pc(e,r,n)});if(n.length===0)throw new x(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},gc=(e,t)=>{let n={...e.styles};for(let[e,r]of Object.entries(t.styles))r==null?Reflect.deleteProperty(n,e):n[e]=r;let r=t.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i=Ge(e.typography,{clear:[...Dt(new Set([...Object.keys(t.styles),...r]))]});return U({...e,styles:n},`typography`,i??`default`)},_c=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),vc=e=>_c.has(e.op),U=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},yc=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new x(`BAD_REQUEST`,`Canvas node ${e.id} is not editable text.`,`Use the text node id from canvas tree.`);return{...e,props:{...e.props,text:t.text}};case`setLabel`:return{...e,label:t.label,labelOrigin:`user`};case`setStyles`:return gc(e,t);case`setAppearance`:{let n={...e.appearance},r=t.appearance.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i={...e,appearance:n};return Object.keys(n).length===0&&Reflect.deleteProperty(i,`appearance`),i}case`patchTypography`:return U(e,`typography`,Ge(e.typography,t.typography)??`default`);case`setTypography`:return U(e,`typography`,t.typography);case`setLayout`:return U(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=Cn(e.additionalStyles,t.additionalStyles);return U(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return U(e,`additionalStyles`,t.additionalStyles)}},bc=(e,t)=>{if(!vc(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new x(`BAD_REQUEST`,`Duplicate id ${t.node.id} already exists.`,`Use a new client token for a new duplication.`);return{...e,nodes:{...e.nodes,[t.node.id]:t.node},relationships:{...e.relationships,[t.node.id]:t.parentage}}}let n=N(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:yc(n,t)}}},xc=e=>{let{nodeId:t,destination:n}=e;switch(n.kind){case`before`:return{nodeId:t,before:n.nodeId};case`after`:return{nodeId:t,after:n.nodeId};case`parent`:return{nodeId:t,parentId:n.parentId,...n.index!==void 0&&{index:n.index}}}},Sc=(e,t,n,r)=>{switch(e.kind){case`set_text`:return[{op:`setText`,nodeId:e.nodeId,text:e.text}];case`rename`:return[{op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}];case`set_styles`:return hc(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Ki(t.scene,e.nodeIds.map(t=>({id:t,...e.parentId!==void 0&&{parentId:e.parentId}})),i);return t.duplicatedNodes.push(...a.duplicatedNodes),a.operations}case`move`:{let n=$i(t.scene,[xc(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},Cc=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=Sc(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=bc(r.scene,e);r.operations.push(...t)}return{operations:r.operations,duplicatedNodes:r.duplicatedNodes,moves:r.moves,affectedParents:[...r.affectedParents].map(e=>({parentId:e,children:Fi(r.scene,e)}))}},W=e=>{throw new x(`BAD_REQUEST`,`These nodes are outside the link selection: ${e.join(`, `)}.`,`Keep the complete link. Edit only its page or selection and preserve the destination page.`)},wc=(e,t)=>{if(e.op===`insertNode`)return[e.parentage.parentId];if(e.op===`insertText`||e.op===`insertPrototype`)return[e.parentId,...e.afterId===void 0?[]:[e.afterId]];if(e.op===`insertConvertedSubtree`)return e.destination.kind===`adjacent`?W([`adjacent conversion`]):[e.destination.targetNodeId];if(e.op===`move`||e.op===`setParentage`){let n=e.op===`move`?e.parentId:e.parentage.parentId;return[e.nodeId,...n===t.relationships[e.nodeId]?.parentId?[]:[n],...e.op===`move`&&e.afterId!==void 0?[e.afterId]:[]]}return[e.nodeId]},Tc=e=>e.op===`insertNode`?[e.node.id]:e.op===`insertText`||e.op===`insertPrototype`?[e.nodeId]:e.op===`insertConvertedSubtree`?Object.keys(e.nodes):[],Ec=(e,t)=>{let r=t.destination;if(r.kind===`adjacent`)return W([`adjacent conversion`]);let i=r.kind===`replace`?e.relationships[r.targetNodeId]?.parentId:r.targetNodeId;if(i===void 0)return W([r.targetNodeId]);let a=r.kind===`insert-children`&&r.targetNodeId===`root`?r.pageId??`canvas-page-default`:n(e,r.targetNodeId),o=t.nodes[t.rootNodeId];return o===void 0?W([t.rootNodeId]):{nodes:{...t.nodes,[t.rootNodeId]:{...o,...i===`root`&&a!==null&&{props:{...o.props,canvasPageId:a}}}},relationships:{...t.relationships,[t.rootNodeId]:{parentId:i,sortKey:``}}}},Dc=e=>({component:e.op===`insertText`?`text`:`prototype`,props:{...e.op===`insertPrototype`&&e.canvasPageId!==void 0&&{canvasPageId:e.canvasPageId}}}),Oc=(e,t)=>{if(t.op===`insertNode`)return{nodes:{[t.node.id]:t.node},relationships:{[t.node.id]:t.parentage}};if(t.op===`insertText`||t.op===`insertPrototype`)return{nodes:{[t.nodeId]:Dc(t)},relationships:{[t.nodeId]:{parentId:t.parentId,sortKey:``}}};if(t.op===`insertConvertedSubtree`)return Ec(e,t);if(t.op===`move`||t.op===`setParentage`)return{nodes:{},relationships:{[t.nodeId]:t.op===`move`?{parentId:t.parentId,sortKey:``}:t.parentage}};if(t.op===`setProps`){let n=e.nodes[t.nodeId];if(n!==void 0)return{nodes:{[t.nodeId]:{...n,props:t.props==="default"?{}:t.props}},relationships:{}}}return{nodes:{},relationships:{}}},kc=(e,t,n,r)=>{let i=Tc(r),a=e.nodeIds.length===0&&(i.length>0||r.op===`move`||r.op===`setParentage`),o=[...wc(r,t).filter(e=>!a||e!==`root`),...i.filter(e=>t.nodes[e]!==void 0)].filter(e=>!n.has(e));return o.length>0&&W(o),i},Ac=(e,t,r)=>{if(!ct(e))return;let i=new Set(g(e,t)),a=it(e,t);if(!a.ok)return W(e.nodeIds);let o={nodes:{...t.nodes},relationships:{...t.relationships}};for(let t of r){let r=kc(e,o,i,t),s=Oc(o,t);Object.assign(o.nodes,s.nodes),Object.assign(o.relationships,s.relationships);let c=[...Object.keys(s.nodes),...Object.keys(s.relationships)].filter(e=>o.nodes[e]?.component===`page`||n(o,e)!==a.pageId);c.length>0&&W(c);for(let e of r)i.add(e);if(t.op!==`remove`)continue;let l=it({...e,nodeIds:[t.nodeId]},o);if(l.ok)for(let e of l.nodeIds)i.delete(e),Reflect.deleteProperty(o.nodes,e),Reflect.deleteProperty(o.relationships,e)}},jc=e=>{switch(e.kind){case`set_text`:case`rename`:return[e.nodeId];case`set_styles`:return e.nodeIds;case`duplicate`:return[...e.nodeIds,...e.parentId===void 0?[]:[e.parentId]];case`move`:return[e.nodeId,e.destination.kind===`parent`?e.destination.parentId:e.destination.nodeId]}},Mc=(e,t)=>e.kind===`duplicate`?[...e.nodeIds,...e.parentId===void 0||e.nodeIds.every(n=>t.relationships[n]?.parentId===e.parentId)?[]:[e.parentId]]:e.kind===`move`&&e.destination.kind===`parent`&&t.relationships[e.nodeId]?.parentId===e.destination.parentId?[e.nodeId]:jc(e),Nc=(e,t)=>{let n=new Set(e.edits.flatMap(e=>jc(e)));for(let e of n)N(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[],...e.pageId!==void 0&&{pageId:e.pageId}};for(let n of e.edits)S(r,t,Mc(n,t))},Pc=e=>({execute:async t=>{let n=await Pi({remote:e},t.canvasId,t.baseVersion);Nc(t,n);let r=Cc(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);Ac({canvasId:t.canvasId,nodeIds:t.nodeIds??[],...t.pageId!==void 0&&{pageId:t.pageId}},n,r.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let i=je.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:15,baseVersion:t.baseVersion,operations:r.operations});if(!i.success)throw new x(`BAD_REQUEST`,`The edit contains an invalid canvas operation.`,i.error.issues[0]?.message??`Check the edit’s node references and values.`);let a=v.parse(await Ni(e).execute(i.data));return{...a,next:[`Reuse version ${String(a.version)} as baseVersion for the next edit; no extra read is required.`,`Render the affected screen at version ${String(a.version)} when ready for visual review.`],...r.duplicatedNodes.length>0&&{duplicatedNodes:r.duplicatedNodes},...r.moves.length>0&&{moves:r.moves,affectedParents:r.affectedParents}}}}),Fc=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw TypeError(`${t} is missing from the capability catalogue`);return n},G=(e,t,n,r=48e3)=>{if(t>e.length)throw new x(`BAD_REQUEST`,`The result page offset is out of range.`,`Restart pagination at offset 0.`);let i=[],a=2,o=e.slice(t,t+n);for(let e of o){let t=Buffer.byteLength(JSON.stringify(e))+1;if(i.length>0&&a+t>r)break;i.push(e),a+=t}let s=t+i.length;return{entries:i,total:e.length,offset:t,nextOffset:s<e.length?s:null,complete:s===e.length}},Ic=e=>e.state===`succeeded`?[...e.result.insertedNodeIds.map(e=>({kind:`inserted`,nodeId:e})),...e.result.removedNodeIds.map(e=>({kind:`removed`,nodeId:e})),...Object.entries(e.result.idMap).map(([e,t])=>({kind:`identity`,temporaryId:e,nodeId:t})),...e.result.report.issues.map(e=>({kind:`issue`,issue:e}))]:[],Lc=e=>e.state===`succeeded`?{mutationId:e.result.mutationId,previousVersion:e.result.previousVersion,version:e.result.version,rootNodeId:e.result.rootNodeId,affectedBounds:e.result.affectedBounds,insertedCount:e.result.insertedNodeIds.length,removedCount:e.result.removedNodeIds.length,identityCount:Object.keys(e.result.idMap).length,issueCount:e.result.report.issues.length}:null,Rc=(e,t)=>({kind:`canvas-conversion`,operation:{kind:`canvas-conversion`,canvasId:e.canvasId,jobId:e.id},state:e.state,phase:e.phase,requestedVersion:e.requestedVersion,destination:e.destination,result:Lc(e),failure:e.failure,details:G(Ic(e),t.offset,t.limit),warnings:e.state===`succeeded`?[`This receipt does not verify visual fidelity. Render the committed root to inspect it.`]:[]}),K=e=>new x(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),zc=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Bc=e=>{let t=e.failure;return new x(t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`CONVERSION_FAILED`?`BAD_REQUEST`:`INTERNAL`,t.message,t.retryable?"Retry the exact write. If it repeats, run `enhance doctor` and report the job id.":`Inspect the current canvas and correct the conversion source or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},Vc=async(e,t)=>{let n=xt.safeParse(await e.query(`canvas.render.getImport`,{jobId:t}));if(!n.success)throw K(`conversion status`);if(n.data.job.id!==t)throw K(`conversion identity`);return n.data.job},Hc=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){if(Date.now()>=r)return i;await zc(250),i=await Vc(e,i.id)}if(i.state!==`succeeded`)throw Bc(i);return i},Uc=(e,t)=>{let n=e.destination,r=t.request.destination;return n.kind===r.kind?n.kind===`adjacent`||r.kind===`adjacent`||n.targetNodeId===r.targetNodeId&&(n.kind!==`insert-children`||r.kind!==`insert-children`||n.pageId===r.pageId):!1},Wc=(e,t)=>{let n=t.request;if(e.canvasId!==n.canvasId||e.requestedVersion!==n.expectedVersion||!Uc(e,t))throw K(`conversion destination or revision`);let r=e.source;if(r.kind!==n.source.kind||r.kind===`screen`&&n.source.kind===`screen`&&r.nodeId!==n.source.nodeId||r.kind===`html`&&n.source.kind===`html`&&r.label!==n.source.label)throw K(`conversion source`);if(e.state===`succeeded`&&(e.result.canvasId!==n.canvasId||n.revisionPolicy===`strict`&&e.result.previousVersion!==n.expectedVersion))throw K(`conversion commitment`)},Gc=async(e,t)=>{let n=$e.safeParse(await e.mutate(`canvas.render.importSource`,t.request));if(!n.success)throw K(`conversion creation`);Wc(n.data.job,t);let r=await Hc(e,n.data.job,t.waitMs);return Wc(r,t),r},Kc=async(e,t)=>{let n=kt.parse(t),r=i(n.canvasRef);return Rc(await Gc(e,{request:{canvasId:r.canvasId,expectedVersion:n.baseVersion,revisionPolicy:`strict`,scope:{pageId:r.pageId,nodeIds:[...r.nodeIds]},source:{kind:`screen`,nodeId:n.sourceNodeId},destination:n.placement},waitMs:n.waitMs}),{offset:0,limit:40})},qc=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof x?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`The post-write review render failed.`,remediation:`Render the committed version and affected area again; do not replay the write.`},next:[`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(n)}`,`Do not replay the committed write with a new mutation id.`]}),Jc=async(e,t,n)=>{try{return await e.execute({canvasId:t.canvasId,expectedVersion:n.result.version,target:{kind:`node`,nodeId:n.result.rootNodeId},sourceState:null,scale:t.renderScale,outputPath:t.renderOutputPath,overwrite:t.overwriteRender,timeoutMs:t.renderTimeoutMs,retryClientToken:t.renderClientToken})}catch(e){return qc(e,t,n.result.version)}},Yc=async(e,t)=>{let n=await Pi({remote:e},t.canvasId,t.result.version);return t.result.insertedNodeIds.map(e=>{let t=n.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},Xc=(e,t)=>({canvasId:e.canvasId,mutationCommitted:!0,jobId:t.id,mutationId:t.result.mutationId,rootNodeId:t.result.rootNodeId,mode:e.mode,targetNodeId:e.targetNodeId,previousVersion:t.result.previousVersion,version:t.result.version,insertedNodeIds:t.result.insertedNodeIds,removedNodeIds:t.result.removedNodeIds,affected:{inserted:t.result.insertedNodeIds.length,changed:0,removed:t.result.removedNodeIds.length},affectedBounds:t.result.affectedBounds}),Zc=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:`canvas.render.getImport`,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),Qc=e=>({waitMs:e.renderTimeoutMs,request:{canvasId:e.canvasId,expectedVersion:e.baseVersion,...e.revisionPolicy!==void 0&&{revisionPolicy:e.revisionPolicy},...(e.pageId!==void 0||(e.selectionNodeIds?.length??0)>0)&&{scope:{pageId:e.pageId,nodeIds:[...e.selectionNodeIds??[]]}},source:{kind:`html`,html:e.html,label:`Agent-authored HTML`,...e.idPrefix!==void 0&&{idPrefix:e.idPrefix}},destination:{kind:e.mode,targetNodeId:e.targetNodeId,...e.mode===`insert-children`&&e.pageId!==void 0&&{pageId:e.pageId}}}}),$c=(e,t)=>({execute:async n=>{let r=await wi(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await Gc(e,Qc(n));if(n.responseMode===`bounded`)return Rc(i,{offset:0,limit:40});if(i.state!==`succeeded`)return Zc(i);if(n.review===`none`)return Xc(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await Jc(t,n,i),o=[];try{o=await Yc(e,i)}catch{o=[]}return{...Xc(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),el=async(e,t)=>{let n=i(t.canvas),r=ze.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),a=St.parse(r.document);ct(n)&&g(n,a),t.nodeId!==void 0&&S(n,a,[t.nodeId]);let o=it(t.nodeId===void 0?n:{...n,nodeIds:[t.nodeId]},a);if(!o.ok)throw new x(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link. Do not broaden the request.`);let s=Object.groupBy(Object.entries(a.relationships),([,e])=>e.parentId),c=Object.values(a.nodes).filter(e=>o.nodeIds.has(e.id)).map(e=>({...e,kind:e.component,parentId:a.relationships[e.id]?.parentId??null,children:(s[e.id]??[]).map(([e])=>e)}));return{canvasId:n.canvasId,version:r.version,pageId:o.pageId,source:n.nodeIds.length>0?`selection-link`:n.pageId===void 0?`canvas-link`:`page-link`,selectedNodeIds:n.nodeIds,rootNodeIds:o.rootNodeIds,nodeCount:c.length,nodes:c,next:[`Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants.`]}},tl=(e,t,n)=>{try{Ut(e,t,{flag:n?`w`:`wx`,mode:384}),Rt(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new x(n,n===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,n===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},nl=e=>({write:t=>{if(t.outputPath!==null){let e=T.resolve(t.outputPath);return tl(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=T.join(e,`sensitive`);Ht(n,{recursive:!0,mode:448}),Rt(n,448);let r=T.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return tl(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),rl=[`canvas.asset.reserve`,`canvas.asset.complete`,`canvas.document.get`],il=(e,t)=>new x(e instanceof x?e.code:`INTERNAL`,e instanceof x?e.message:`The asset import did not return a confirmed result.`,e instanceof x?e.remediation:`Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.`,{...e instanceof x&&e.fields,operation:JSON.stringify(t),outcome:`not_confirmed`}),al=(e,t)=>{if(e.canvasId!==t.canvasId||e.clientToken!==t.clientToken||e.kind!==t.kind||e.contentType!==t.contentType||e.bytes!==t.bytes||e.sha256!==t.sha256)throw new x(`INTERNAL`,`The returned asset does not match this import intent.`,`Check the API and CLI versions. Do not insert an unverified resource.`)},ol=(e,t)=>({execute:async n=>{let r=i(n.canvasRef);if(ct(r)){let t=ze.parse(await e.query(rl[2],{canvasId:r.canvasId}));g(r,St.parse(t.document))}let{body:a,...o}=await t.read(),s=Ke.parse({...o,canvasId:r.canvasId,clientToken:n.clientToken}),c={kind:`canvas-asset`,canvasId:r.canvasId,clientToken:n.clientToken};try{let t=Ot.parse(await e.mutate(rl[0],s));al(t,s),t.upload!==null&&await e.upload({...t.upload,body:a});let i=At.parse(await e.mutate(rl[1],{canvasId:r.canvasId,clientToken:n.clientToken}));if(al(i,s),i.assetId!==t.assetId||i.path!==t.path)throw new x(`INTERNAL`,`The completed asset identity changed.`,`Read operation_status and do not place an unconfirmed resource.`);return ge.parse({operation:c,resource:i,placement:`not_requested`})}catch(e){throw il(e,c)}}}),sl=15e3,cl=async e=>new Promise(t=>setTimeout(t,e)),ll=new Set([`ready`,`failed`,`abandoned`]),ul=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`],dl=e=>new x(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,`Check the existing deployment status before retrying with the same publication token.`),fl=async(e,t,n,r)=>{let i=De.safeParse(await e.mutate(ul[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,...t.targetMode!==void 0&&{targetMode:t.targetMode},...t.canvasPageId!==void 0&&{canvasPageId:t.canvasPageId},title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw dl(`artifact creation`);if(r(i.data.deploymentId),i.data.state===`uploading`&&await e.upload({url:i.data.upload.url,headers:i.data.upload.headers,body:n.open()}),i.data.state===`uploading`||i.data.state===`queued`){let n=Le.safeParse(await e.mutate(ul[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId}));if(!n.success||n.data.deploymentId!==i.data.deploymentId)throw dl(`artifact submission`)}return i.data},pl=async(e,t,n,r)=>{let i=te.safeParse(await e.query(ul[0],{}));if(!i.success)throw dl(`capabilities`);let a=await t.package({entryPath:n.entryPath,limits:i.data.limits});try{return await fl(e,n,a,r)}finally{await a.dispose()}},ml=async(e,t,n)=>{let r=new AbortController,i=Promise.withResolvers(),a=setTimeout(()=>{r.abort(),i.reject(new x(`INTERNAL`,`The prototype status request timed out.`,`Check this deployment again; keep its existing client token.`,{reason:`STATUS_TIMEOUT`,deploymentId:t.deploymentId}))},n);try{let n=await Promise.race([e.query(ul[3],t,{signal:r.signal}),i.promise]),a=ce.safeParse(n);if(!a.success||a.data.deploymentId!==t.deploymentId)throw dl(`status`);return a.data}finally{clearTimeout(a)}},hl=async(e,t,n)=>{let r=performance.now()+n,i=50,a=await ml(e,t,n>0?Math.min(sl,n):sl);for(;!ll.has(a.state);){let n=r-performance.now();if(n<=0)return a;await cl(Math.min(i,n)),i=Math.min(i*2,1e3);let o=r-performance.now();if(o<=0)return a;try{a=await ml(e,t,Math.min(sl,o))}catch(e){if(e instanceof x&&e.fields?.reason===`STATUS_TIMEOUT`)return a;throw e}}return a},gl=[`BAD_ARTIFACT`,`ARTIFACT_INTEGRITY`,`FILE_INTEGRITY`,`FILE_TOO_LARGE`,`FILE_COUNT_`,`MANIFEST_`,`PATH_`,`ENTRY_`,`EXPANDED_`,`ZIP_INVALID`,`ZIP_ENCRYPTED`,`ZIP_PATH_ENCODING`,`ZIP_COMPRESSION`,`ZIP_ENTRY_TYPE`],_l=e=>{let t=e.failure,n=gl.some(e=>t.code.startsWith(e));return{isBuildFailure:n,nextAction:n?`fix_build`:`retry_new_publication`,failure:{code:t.code,message:t.message,remediation:n?`Correct the named build problem and publish a new artifact with a new clientToken.`:`This ingestion attempt is terminal. Restore storage or service access, then explicitly publish the same valid build with a new clientToken. Do not change the source to repair a service failure.`}}},vl=e=>e.unavailableFiles?.map(e=>`Unavailable published file: ${e.path} (${e.code}).`)??[],yl=[`prototype.getArtifactCapabilities`,`prototype.attach`],bl=new Set([`BAD_REQUEST`,`FORBIDDEN`,`UNAUTHORIZED`,`NOT_FOUND`]),xl=async e=>{let t=te.safeParse(await e.query(yl[0],{}));if(!t.success||t.data.attachmentProtocolVersion!==1)throw new x(`BAD_REQUEST`,`This API does not advertise revision-checked prototype attachment.`,`Upgrade the API before publishing through the canvas profile. No artifact was created or attached.`)},Sl=e=>e instanceof x?{code:e.code,message:e.message,remediation:e.remediation}:{code:`INTERNAL`,message:`The publication request did not return a confirmed outcome.`,remediation:`Retry the identical request with its original clientToken; do not assume the canvas is unchanged.`},Cl=async(e,t,n)=>{let r=i(t.canvasRef),a=ne.safeParse(await e.mutate(yl[1],{canvasId:r.canvasId,deploymentId:n.deploymentId,baseVersion:t.baseVersion,...r.pageId!==void 0&&{canvasPageId:r.pageId},attachment:{clientToken:t.clientToken,scope:{...r.pageId!==void 0&&{pageId:r.pageId},nodeIds:r.nodeIds}}}));if(!a.success)throw Error(`Invalid prototype attachment response`);let o=a.data,s=o.attachment;if(s===void 0||o.canvasId!==r.canvasId||o.deploymentId!==n.deploymentId||o.prototypeId!==n.prototypeId||o.nodeId!==n.nodeId||o.version!==s.version||s.outcome===`committed`&&(s.mutationId!==t.clientToken||s.version!==s.previousVersion+1)||s.outcome===`no_op`&&s.version!==t.baseVersion)throw Error(`Unconfirmed prototype attachment receipt`);return{...o,attachment:s}},wl=async(e,t,n,r)=>{try{let i=await Cl(e,t,r);return{...n,attachmentStatus:i.attachment.outcome,attachment:i,nextAction:`inspect_result`}}catch(e){let t=Sl(e),r=t.code===`CONFLICT`,i=bl.has(t.code);return{...n,attachmentStatus:r?`conflict`:i?`not_attempted`:`not_confirmed`,failure:t,nextAction:t.code===`UNAUTHORIZED`||t.code===`FORBIDDEN`?`restore_access`:r||i?`replan_attachment`:`retry_same_request`,warnings:[...n.warnings,`The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent; refresh baseVersion after an unrelated canvas edit and keep the same clientToken. A changed scope or destination requires a new attachment intent.`]}}},Tl=async(e,t,n,r)=>{let i={operation:{kind:`prototype-deployment`,canvasId:n,deploymentId:r.deploymentId},deploymentStatus:r.state,publication:r,attachmentStatus:`pending`,attachment:null,failure:null,nextAction:`check_status`,warnings:vl(r)};if(r.state===`failed`){let{nextAction:e,failure:t}=_l(r);return{...i,attachmentStatus:`not_attempted`,nextAction:e,failure:t}}return r.state===`abandoned`?{...i,attachmentStatus:`not_attempted`,nextAction:`retry_new_publication`,failure:{code:`NOT_FOUND`,message:`The deployment was abandoned.`,remediation:`Publish the same build explicitly with a new clientToken if it is still needed.`}}:r.state===`ready`?wl(e,t,i,r):i},El=(e,t)=>({execute:async n=>{let r=i(n.canvasRef);await xl(e);let a=n.source.kind===`deployment`?n.source.deploymentId:null;try{if(n.source.kind===`build`&&(a=(await pl(e,t,{...n.source,canvasId:r.canvasId,...r.pageId!==void 0&&{canvasPageId:r.pageId},clientToken:n.clientToken},e=>{a=e})).deploymentId),a===null)throw Error(`Publication has no deployment`);let i=await hl(e,{canvasId:r.canvasId,deploymentId:a},n.waitMs);return await Tl(e,n,r.canvasId,i)}catch(e){if(a===null)throw e;return{operation:{kind:`prototype-deployment`,canvasId:r.canvasId,deploymentId:a},deploymentStatus:`unknown`,publication:null,attachmentStatus:`not_attempted`,attachment:null,failure:Sl(e),nextAction:e instanceof x&&(e.code===`UNAUTHORIZED`||e.code===`FORBIDDEN`)?`restore_access`:`retry_same_request`,warnings:[`An existing deployment may still be processing. Retry the same source and clientToken to recover or finish upload; do not reserve a new publication.`]}}}}),Dl=[`prototype.attach`],Ol=e=>new x(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),kl=e=>{if(e.state===`failed`){let t=_l(e);throw new x(t.isBuildFailure?`BAD_REQUEST`:`INTERNAL`,t.failure.message,t.failure.remediation,{reason:t.failure.code,deploymentId:e.deploymentId,nextAction:t.nextAction,...e.failure.path!==void 0&&{path:e.failure.path}})}if(e.state===`abandoned`)throw new x(`NOT_FOUND`,`Prototype deployment ${e.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);if(e.state!==`ready`)throw new x(`INTERNAL`,`Prototype ingestion is still processing.`,`Check this deployment status, then resume the same source and client token; do not reserve a second publication.`,{reason:`INGESTION_PENDING`,state:e.state,processedFiles:String(e.processedFiles),deploymentId:e.deploymentId})},Al=async(e,t,n)=>{let r={deploymentId:null};try{let i=await pl(e,t,n,e=>{r.deploymentId=e}),a=await hl(e,{canvasId:n.canvasId,deploymentId:i.deploymentId},3e5);kl(a);let o=ne.safeParse(await e.mutate(Dl[0],{canvasId:n.canvasId,deploymentId:i.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw Ol(`attachment`);return{...o.data,fileCount:a.fileCount,totalBytes:a.totalBytes,alreadyExists:i.alreadyExists,warnings:vl(a),next:[o.data.canvasUrl??o.data.openUrl,`enhance canvas render --canvas ${n.canvasId} --node-id ${o.data.nodeId} --expected-version ${String(o.data.version)}`]}}catch(e){throw e instanceof x&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||r.deploymentId===null?e:new ot(e instanceof x?e.message:`Prototype deployment ${r.deploymentId} has no confirmed completion.`,`${e instanceof x?`${e.remediation} `:``}Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`,{code:e instanceof x?e.code:`INTERNAL`,fields:{...e instanceof x&&e.fields,canvasId:n.canvasId,deploymentId:r.deploymentId,clientToken:n.clientToken}})}},jl=(e,t)=>({execute:async n=>Al(e,t,n)}),Ml=(e,t)=>{if(e.id!==t.jobId||e.canvasId!==t.canvasId)throw new x(`NOT_FOUND`,`The preparation does not belong to this operation.`,`Use the complete operation reference returned by the original action.`);return{kind:`canvas-preparation`,operation:t,state:e.state,phase:e.phase,requestedVersion:e.requestedVersion,failure:e.failure,outcome:`not_confirmed`,prepared:e.state===`succeeded`,warnings:[`Preparation is not a canvas commit. Repeat the original tool with identical arguments and clientToken to finish; status reads never commit.`]}},Nl=async(e,t)=>{let{job:n}=ue.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.jobId}));return Ml(n,t)},Pl=(e,t)=>{let n=40,r=e=>{let t=e.slice(0,n);return n-=t.length,t},i=r(e.insertedNodeIds),a=r(e.changedNodeIds),o=r(e.removedNodeIds),s=e.insertedNodeIds.length+e.changedNodeIds.length+e.removedNodeIds.length;return{outcome:`committed`,canvasId:e.canvasId,mutationId:e.mutationId,previousVersion:e.previousVersion,version:e.version,operation:{kind:`canvas-mutation`,canvasId:e.canvasId,mutationId:e.mutationId,fingerprint:t},affected:{insertedNodeIds:i,changedNodeIds:a,removedNodeIds:o,complete:s<=40,total:s},...e.copiedNodeIds!==void 0&&{identities:{entries:Object.entries(e.copiedNodeIds).toSorted(([e],[t])=>e.localeCompare(t,`en`)).slice(0,40).map(([e,t])=>({sourceNodeId:e,nodeId:t})),complete:Object.keys(e.copiedNodeIds).length<=40,total:Object.keys(e.copiedNodeIds).length}},verification:{rendered:!1},warnings:[]}},Fl=async(e,t,n)=>{if(n.kind!==`canvas-render`||n.state!==`succeeded`)return n;try{let{job:r}=lt.parse(await e.query(`canvas.render.get`,{jobId:n.operation.jobId}));return r.id!==n.operation.jobId||r.canvasId!==n.operation.canvasId||r.state!==`succeeded`?{...n,warnings:[`The stored result is unavailable for image delivery. Read this operation again.`]}:{status:n,localImage:await ui(e,t,r,{at:new Date,outputPath:null,overwrite:!1})}}catch{return{...n,warnings:[`The render completed, but its image could not be delivered. Check access and artifact expiry before retrying this operation reference.`]}}},Il=[`canvas.mutation.get`,`canvas.render.get`,`canvas.render.getImport`,`prototype.getPublishStatus`,`canvas.asset.get`],Ll=(e,t)=>{if(e!==t)throw new x(`NOT_FOUND`,`The operation does not belong to this canvas.`,`Use the operation reference returned by the original action.`)},Rl=e=>[...e.insertedNodeIds.map(e=>({nodeId:e,change:`inserted`})),...e.changedNodeIds.map(e=>({nodeId:e,change:`changed`})),...e.removedNodeIds.map(e=>({nodeId:e,change:`removed`})),...Object.entries(e.copiedNodeIds??{}).toSorted(([e],[t])=>e.localeCompare(t,`en`)).map(([e,t])=>({nodeId:t,sourceNodeId:e,change:`copied`}))],zl=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,a=se.parse(await e.query(Il[0],{canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}));return a.state===`not-found`?{kind:`canvas-mutation`,state:`not_found`,operation:n,outcome:`unknown`,warnings:[`No durable receipt was found. The original request may still be running.`]}:{kind:`canvas-mutation`,state:`committed`,receipt:Pl(a.result,n.fingerprint),affected:G(Rl(a.result),r,i)}},Bl=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,{job:a}=lt.parse(await e.query(Il[1],{jobId:n.jobId}));Ll(a.canvasId,n.canvasId);let o=a.result===null?null:Vl(a.result);return{kind:`canvas-render`,operation:n,state:a.state,phase:a.phase,requestedVersion:a.requestedVersion,attempt:a.attempt,target:a.target,sourceState:a.sourceState??null,evidence:o,details:G(Hl(a),r,i),failure:a.failure,pixelsDelivered:!1,warnings:[`Status reports stored render evidence. It does not deliver or inspect the image.`]}},Vl=e=>{let{warnings:t,timings:n,...r}=e;return{...r,warningCount:t.length,timingCount:n.length}},Hl=e=>e.result===null?[]:[...e.result.warnings.map(e=>({kind:`warning`,warning:e})),...e.result.timings.map(e=>({kind:`timing`,timing:e}))],Ul=async(e,t)=>{let n=At.parse(await e.query(Il[4],{canvasId:t.canvasId,clientToken:t.clientToken}));if(Ll(n.canvasId,t.canvasId),n.clientToken!==t.clientToken)throw new x(`NOT_FOUND`,`The resource does not belong to this import.`,`Use the operation reference returned by the original import.`);return{kind:`canvas-asset`,operation:t,resource:n,placement:`not_checked`}},Wl=async(e,t)=>{let{operation:n,offset:r,limit:i}=t;switch(n.kind){case`canvas-asset`:return G([],r,i),Ul(e,n);case`canvas-mutation`:return zl(e,{...t,operation:n});case`canvas-preparation`:{let r=await zl(e,{...t,operation:{kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}});return r.kind===`canvas-mutation`&&r.state===`committed`?r:Nl(e,n)}case`canvas-render`:return Bl(e,{...t,operation:n});case`canvas-conversion`:{let{job:t}=xt.parse(await e.query(Il[2],{jobId:n.jobId}));return Ll(t.canvasId,n.canvasId),Rc(t,{offset:r,limit:i})}case`prototype-deployment`:return G([],r,i),{kind:`prototype-deployment`,operation:n,publication:ce.parse(await e.query(Il[3],{canvasId:n.canvasId,deploymentId:n.deploymentId})),attachment:`not_checked`,warnings:[`Publication readiness does not establish canvas attachment or successful interactive verification.`]}}},Gl=(e,t)=>({execute:async n=>{let r=await Wl(e,n);return t!==void 0&&n.includeImage?Fl(e,t,r):r}}),Kl=[`transcript.get`],ql=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),Jl=e=>({execute:async t=>{let n=pe.safeParse(await e.query(Kl[0],t));if(!n.success)throw new x(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return n.data.state===`ready`?{...n.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:ql(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Yl=[`canvas.render.get`,`canvas.render.snapshot`],Xl=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Zl=e=>new x(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),Ql=async(e,t)=>{let n=lt.safeParse(await e.query(Yl[0],{jobId:t}));if(!n.success)throw new x(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},$l=async(e,t,n,r)=>{let i=Date.now()+n.timeoutMs,a=Date.now(),o=t,s=0,c=``;for(;o.state===`queued`||o.state===`running`;){let l=Date.now(),u=`${o.state}:${o.phase}`;if((u!==c||l-s>=5e3)&&(r({event:`snapshot.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:l-a,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),s=l,c=u),l>=i){if(n.bounded===!0)return o;throw new x(`INTERNAL`,`Snapshot ${o.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${n.retryClientToken} and a larger --timeout-ms.`,{jobId:o.id,phase:o.phase})}await Xl();let d=await Ql(e,o.id);if(d.id!==t.id)throw eu();tu(d,n),o=d}return o},eu=()=>new x(`INTERNAL`,`The snapshot response does not match the requested source or revision.`,`Run enhance doctor and report the capture job ID.`),tu=(e,t)=>{if(e.canvasId!==t.canvasId||e.purpose!==`snapshot`||e.sourceState?.recordingId!==t.recordingId||e.sourceState.atMs!==t.atMs||t.context!==void 0&&e.requestedVersion!==t.context.expectedVersion)throw eu();if(e.state!==`succeeded`)return;let n=e.result.snapshot,r=e.result.sourceState;if(e.result.canvasId!==t.canvasId||e.result.loadedVersion!==e.requestedVersion||e.result.requestedVersion!==e.requestedVersion||r?.recordingId!==t.recordingId||r.requestedAtMs!==t.atMs||r.settledAtMs!==t.atMs||n?.recordingId!==t.recordingId||n.atMs!==t.atMs||n.screenId!==e.id||n.screenNodeId!==`scr_${t.recordingId}_${String(t.atMs)}`||t.context!==void 0&&n.version!==t.context.expectedVersion+1)throw eu()},nu=(e,t)=>({operation:{kind:`canvas-render`,canvasId:e.canvasId,jobId:e.id},state:e.state,requestedVersion:e.requestedVersion,source:{kind:`recording`,recordingId:t.recordingId,atMs:t.atMs},attachment:e.state===`succeeded`?`committed`:e.state===`queued`||e.state===`running`?`pending`:`not_confirmed`,result:e.result?.snapshot??null,failure:e.failure,warningCount:e.result?.warnings.length??0,warnings:[e.state===`succeeded`?`The durable screen is attached. Render the returned node at its committed version to verify placement; use operation_status for source warnings.`:`Follow operation_status for this job. An incomplete job is not proof of attachment or proof that no durable screen was created.`]}),ru=async(e,t,n)=>{let r=Oe.parse(t),a=i(r.canvasRef);return au(e,()=>null).execute({canvasId:a.canvasId,recordingId:r.source.recordingId,atMs:r.source.atMs,retryClientToken:n,timeoutMs:r.waitMs,bounded:!0,context:{expectedVersion:r.baseVersion,request:{previewJobId:r.previewJobId,scope:{pageId:a.pageId,nodeIds:[...a.nodeIds]},placement:r.placement}}})},iu=async(e,t,n)=>{let r=yt.safeParse(await e.mutate(Yl[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs,...n.context!==void 0&&{context:n.context}}));if(!r.success)throw new x(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");tu(r.data.job,n);let i=await $l(e,r.data.job,n,t);if(n.bounded===!0)return nu(i,n);if(i.state!==`succeeded`||i.result.snapshot===void 0)throw Zl(i);let a={...i,result:{...i.result,snapshot:i.result.snapshot}},o=a.result.snapshot;return{jobId:a.id,canvasId:a.canvasId,...o,warnings:a.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${a.canvasId} --node-id ${o.screenNodeId}`,`enhance canvas render --canvas ${a.canvasId} --node-id ${o.screenNodeId} --expected-version ${String(o.version)}`]}},au=(e,t)=>({execute:async n=>iu(e,t,n)}),ou={".avif":`image/avif`,".gif":`image/gif`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".webp":`image/webp`,".ttf":`font/ttf`,".otf":`font/otf`,".woff":`font/woff`,".woff2":`font/woff2`},su=()=>new x(`BAD_REQUEST`,`Choose one supported regular image or font file.`,`Use an explicit local PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2 file.`),cu=async e=>{let t=ou[T.extname(e).toLowerCase()];if(t===void 0)throw su();let n=await Zt(e,zt.O_RDONLY|zt.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size===0)throw su();let r=Buffer.alloc(e.size+1),i=0;for(;i<r.byteLength;){let e=await n.read(r,i,r.byteLength-i,i);if(e.bytesRead===0)break;i+=e.bytesRead}if(i!==e.size)throw new x(`CONFLICT`,`The selected asset changed while it was being read.`,`Finish writing the file, then retry the unchanged import intent.`);let a=r.subarray(0,i);return{body:a,kind:t.startsWith(`image/`)?`image`:`font`,contentType:t,bytes:i,sha256:E(`sha256`).update(a).digest(`hex`)}}finally{await n.close()}},lu=e=>({read:async()=>{try{return await cu(e)}catch(e){throw e instanceof x?e:new x(`BAD_REQUEST`,`The selected asset file cannot be read.`,`Choose an existing readable image or font file on this computer.`)}}}),uu=[`canvas.list`,`organisation.list`],du=async(e,t)=>{let[n,r]=await Promise.all([e.query(uu[0],{collection:t.collection,...t.title!==void 0&&{title:t.title},scope:`all`,deleted:!1,hasUnresolved:!1}),t.includeDestinations?e.query(uu[1],{}):{items:[],truncated:!1}]),i=ve.parse(n),a=Qe.parse(r),o=i.items.map(e=>({kind:`canvas`,canvasRef:e.id,title:e.title,organisationId:e.organisationId,accessState:e.accessState,viewerCan:e.viewerCan,openPath:`/c/${e.id}`}));return t.includeDestinations&&o.push({kind:`destination`,destination:{kind:`personal`},name:`Personal`},...a.items.filter(e=>t.collection===`everything`||t.collection===e.id).map(e=>({kind:`destination`,destination:{kind:`team`,organisationId:e.id},name:e.name}))),{items:o,sourceTruncated:{canvases:i.truncated,destinations:a.truncated}}},fu=e=>{let t=[],n=2;for(let r of e){let e=Buffer.byteLength(JSON.stringify(r))+1;if(n+e>48e3)break;t.push(r),n+=e}return t},pu=e=>({execute:async t=>{let{items:n,sourceTruncated:r}=await du(e,t),{cursor:i,...a}=t,s=o(a),c=o({items:n,sourceTruncated:r}),l=i===void 0?null:we(i,nt);if(l!==null&&l.queryDigest!==s)throw new x(`BAD_REQUEST`,`This cursor belongs to another canvas search.`,`Restart discovery with the requested query.`);if(l!==null&&l.snapshotDigest!==c)throw new x(`CONFLICT`,`The accessible canvases or destinations changed between pages.`,`Restart discovery so results are not silently skipped or combined across permissions.`);let u=l?.offset??0;if(u>n.length)throw new x(`BAD_REQUEST`,`The discovery cursor is out of range.`,`Restart discovery.`);let d=fu(n.slice(u,u+t.limit)),f=u+d.length,m=f<n.length,h=r.canvases||r.destinations;return{items:d,returnedCount:d.length,totalAvailable:n.length,complete:!m&&!h,sourceTruncated:r,nextCursor:m?p({protocol:`enhance-canvas-find/1`,queryDigest:s,snapshotDigest:c,offset:f}):null,warnings:h?[`The source collection reached its existing limit. Refine the title or team; these results are not a complete inventory.`]:[]}}}),mu=async(e,t)=>{try{return{value:await e.query(`canvas.render.preparation.get`,{jobId:t})}}catch(e){if(e instanceof x&&![`INTERNAL`,`RATE_LIMITED`].includes(e.code))throw e;return null}},hu=async(e,t,n)=>{let r=Date.now()+n,i=t;for(;i.state===`queued`||i.state===`running`;){let n=r-Date.now();if(n<=0)break;await Kt(Math.min(250,n));let a=await mu(e,t.id);if(a===null)return i;if(i=ue.parse(a.value).job,i.id!==t.id)throw new x(`INTERNAL`,`Preparation identity changed.`,`Retry the original request.`)}return i},gu=async(e,t,n)=>{let r=re.parse(await e.mutate(`canvas.render.preparation.create`,t)),i=await hu(e,r.job,n);if(i.canvasId!==t.canvasId||i.requestedVersion!==t.expectedVersion||!on(i.scope,t.scope)||!on(i.request,t.request))throw new x(`CONFLICT`,`The native preparation does not match this request.`,`Read the canvas and prepare a new intent; do not apply this plan.`);if(i.state===`succeeded`&&i.result.loadedVersion!==t.expectedVersion)throw new x(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);return i},_u=async(e,t)=>{try{return v.parse(await Ni(e).execute(t))}catch(e){throw new x(e instanceof x?e.code:`INTERNAL`,e instanceof x?e.message:`The canvas commit could not be confirmed.`,`Read operation_status or repeat the original action with identical arguments and clientToken.`,{...e instanceof x&&e.fields,outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:t.canvasId,mutationId:t.mutationId,fingerprint:t.requestContext?.fingerprint})})}},vu=async(e,t,n,r)=>{if(n.result.loadedVersion!==t.baseVersion)throw new x(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);if(n.result.operations.length===0)return{outcome:`no_op`,canvasId:n.canvasId,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let i=je.parse({canvasId:n.canvasId,mutationId:t.clientToken,documentFormatVersion:15,baseVersion:t.baseVersion,operations:n.result.operations,requestContext:{fingerprint:r,revisionPolicy:`strict`,...t.request.kind===`duplicate`&&{copiedNodeIds:n.result.idMap}}}),a=await _u(e,i);if(a.canvasId!==n.canvasId||a.mutationId!==t.clientToken||a.previousVersion!==t.baseVersion||a.version!==t.baseVersion+1||t.request.kind===`duplicate`&&!on(a.copiedNodeIds,n.result.idMap))throw new x(`INTERNAL`,`The canvas commit receipt could not be verified.`,`Check operation_status using the original mutation reference before retrying.`,{outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:r})});return Pl(a,r)},yu=e=>({execute:async t=>{let n=i(t.canvasRef),r={...n.pageId!==void 0&&{pageId:n.pageId},nodeIds:[...n.nodeIds]},a=o({operation:`canvas.prepare/1`,reference:n,baseVersion:t.baseVersion,request:t.request}),s=se.parse(await e.query(`canvas.mutation.get`,{canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:a}));if(s.state===`committed`)return Pl(s.result,a);let c=await gu(e,{canvasId:n.canvasId,expectedVersion:t.baseVersion,request:t.request,scope:r},t.waitMs),l={kind:`canvas-preparation`,canvasId:n.canvasId,jobId:c.id,mutationId:t.clientToken,fingerprint:a};return c.state===`succeeded`?vu(e,t,c,a):Ml(c,l)}}),bu=/^[MLHVCSQTAZ]$/iu,xu=/[MLHVCSQTAZ]|[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/giu,Su={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},Cu=e=>{let t=e.match(xu)??[];if(t.join(``)!==e.replaceAll(/[\s,]/gu,``))return null;let n=[],r=``,i=0;for(;i<t.length;){let e=t[i]??``;if(bu.test(e))r=e,i+=1;else if(r===``||r.toUpperCase()===`Z`)return null;let a=Su[r.toUpperCase()]??0,o=t.slice(i,i+a).map(Number);if(o.length!==a||o.some(e=>!Number.isFinite(e)))return null;i+=a,n.push({command:r,values:o}),r.toUpperCase()===`M`&&(r=r===`M`?`L`:`l`)}return n},q=([e,t,n,r,i,a],{x:o,y:s})=>({x:e*o+n*s+i,y:t*o+r*s+a}),wu=e=>`${String(e.x)} ${String(e.y)}`,Tu=Math.PI/2,Eu=Math.PI*2,Du=(e,t,n,r)=>Math.atan2(e*r-t*n,e*n+t*r),Ou=(e,t,n)=>{let[r=0,i=0,a=0,o=0,s=0]=t,c=a*Math.PI/180,[l,u]=[Math.cos(c),Math.sin(c)],[d,f]=[(e.x-n.x)/2,(e.y-n.y)/2],[p,m]=[l*d+u*f,-u*d+l*f],h=Math.max(1,Math.hypot(p/r,m/i)),[g,_]=[Math.abs(r)*h,Math.abs(i)*h],ee=g*g*m*m+_*_*p*p,v=(o===s?-1:1)*Math.sqrt(Math.max(0,(g*g*_*_-ee)/ee)),[te,y]=[v*g*m/_,-v*_*p/g],[ne,re,ie,ae]=[(p-te)/g,(m-y)/_,(-p-te)/g,(-m-y)/_],b=Du(ne,re,ie,ae);return s===0&&b>0&&(b-=Eu),s===1&&b<0&&(b+=Eu),{ellipse:[l*g,u*g,-u*_,l*_,l*te-u*y+(e.x+n.x)/2,u*te+l*y+(e.y+n.y)/2],start:Du(1,0,ne,re),turn:b}},ku=(e,t,n)=>{let[r=0,i=0]=t;if(r===0||i===0||e.x===n.x&&e.y===n.y)return[e,n,n];let{ellipse:a,start:o,turn:s}=Ou(e,t,n),c=Math.ceil(Math.abs(s)/Tu-1e-9),l=s/c,u=4/3*Math.tan(l/4),d=(e,t)=>({x:Math.cos(e)-Math.sin(e)*t,y:Math.sin(e)+Math.cos(e)*t}),f=[];for(let e=0;e<c;e+=1){let[t,r]=[o+l*e,o+l*(e+1)];f.push(q(a,d(t,u)),q(a,d(r,-u)),e===c-1?n:q(a,d(r,0)))}return f},Au=(e,t,n)=>{let r=e.command.toUpperCase(),i=e.command!==r,{current:a}=t,o=(e=0,t=0)=>i?{x:a.x+e,y:a.y+t}:{x:e,y:t},[s=0]=e.values;if(r===`Z`)return{data:`Z`,pen:{...t,current:t.start}};if(r===`A`){let r=o(e.values[5],e.values[6]),i=ku(a,e.values,r),s=[];for(let e=0;e<i.length;e+=3)s.push(`C${i.slice(e,e+3).map(e=>wu(q(n,e))).join(` `)}`);return{data:s.join(``),pen:{...t,current:r}}}if(r===`H`||r===`V`){let e=r===`H`?o(s,i?0:a.y):o(i?0:a.x,s);return{data:`L${wu(q(n,e))}`,pen:{...t,current:e}}}let c=[];for(let t=0;t<e.values.length;t+=2)c.push(o(e.values[t],e.values[t+1]));let l=c.at(-1)??a;return{data:`${r}${c.map(e=>wu(q(n,e))).join(` `)}`,pen:{current:l,start:r===`M`?l:t.start}}},ju=(e,t)=>{let n=Cu(e);if(n===null)return null;let r=[],i={current:{x:0,y:0},start:{x:0,y:0}};for(let e of n){let n=Au(e,i,t);r.push(n.data),i=n.pen}return r.join(``)},Mu=(e,t)=>{let n=e.geometry;if(n?.kind!==`mask`||n.mode===`outline`||t?.box===void 0||t.component===`text`)return{};let r=H(t).opacity,i=H(t).fills.filter(e=>e.visible).toReversed().map(e=>$a({...e,opacity:e.opacity*r}));if(i.length===0)return{};let{x:a,y:o,width:s,height:c}=t.box,l=e=>i.map(()=>e).join(`, `);return{"mask-image":i.join(`, `),"mask-mode":l(n.mode===`luminance`?`luminance`:`alpha`),"mask-position":l(`${String(a)}px ${String(o)}px`),"mask-size":l(`${String(s)}px ${String(c)}px`),"mask-repeat":l(`no-repeat`)}},Nu=(e,t)=>{let n=t.geometry?.kind===`mask`?sc(e,t):null,r=t.box;if(r===void 0||n===null||n.shapes!==void 0)return{};if(n.path===``)return{"clip-path":`inset(50%)`};let[i,a,o,s,c,l]=n.matrix,u=ju(n.path,[i*r.width,a*r.height,o*r.width,s*r.height,c*r.width,l*r.height]);return u===null?null:{"clip-path":`path(${n.fillRule}, "${u}")`}},Pu=new Set([`data-enhance-id`,`data-enhance-locked`,`data-enhance-name`,`data-enhance-opaque`,`style`]),J=e=>{throw new x(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},Y=e=>{let t=cn(e,{context:`declarationList`,onParseError:e=>J(e.message)});if(t.type!==`DeclarationList`)return J(`Expected an inline CSS declaration list.`);let n=new Map;return t.children.forEach(e=>{if(e.type!==`Declaration`||e.important!==!1)return J(`Use ordinary inline CSS properties without !important or at-rules.`);let t=e.property.startsWith(`--`)?e.property:e.property.toLowerCase();if(n.has(t))return J(`Duplicate CSS property: ${t}.`);n.set(t,sn(e.value))}),Object.fromEntries(n)},Fu=e=>e.flatMap(e=>`tagName`in e?[e]:e.nodeName===`#text`&&`value`in e&&e.value.trim()===``?[]:J(`Container content must contain identified elements; text belongs inside its retained span.`)),Iu=e=>{let t=ln(e,{sourceCodeLocationInfo:!0,onParseError:e=>J(`Invalid HTML at line ${String(e.startLine)}: ${e.code}.`)}),n=[t];for(;n.length>0;){let e=n.pop();if(e===void 0)break;e.childNodes=e.childNodes.filter(e=>!(`tagName`in e)||Vr(e.tagName));let t=e.childNodes.filter(e=>`tagName`in e);for(let e of t)e.attrs=e.attrs.filter(e=>Ur(e.name,e.value)),n.push(e)}return t},Lu=new Set([...Pu,`viewBox`,`preserveAspectRatio`]),Ru=(e,t)=>{let[n,...r]=Fu(e.childNodes);if(n?.tagName!==`path`||r.length>0)return J(`A vector element must hold exactly one path.`);let i=e=>n.attrs.find(t=>t.name===e)?.value,a=i(`fill-rule`)??`nonzero`;return a!==`nonzero`&&a!==`evenodd`?J(`Unsupported fill-rule: ${a}.`):{d:i(`d`)??``,fillRule:a,fill:i(`fill`)??`none`,viewBox:t}},zu=e=>{let t=e.tagName===`svg`?Lu:Pu;return Object.fromEntries(e.attrs.map(e=>!t.has(e.name)||e.namespace!==void 0?J(`Unsupported attribute: ${e.name}.`):[e.name,e.value]))},Bu=e=>{let t=e[`data-enhance-id`],n=e[`data-enhance-name`];if(t===void 0||t===``||n===void 0)return J(`Every retained element requires its identity and name.`);let r=e[`data-enhance-opaque`];if(r!==void 0&&r!==`true`)return J(`Invalid opaque marker on ${t}.`);let i=e[`data-enhance-locked`];return i!==void 0&&i!==`true`?J(`Invalid locked marker on ${t}.`):{id:t,label:n,opaque:r===`true`,locked:i===`true`,styles:Y(e.style??``)}},Vu=e=>{let t=[],n=[];for(let r of Fu(e.childNodes)){let e=r.attrs.find(e=>e.name===`data-enhance-paint`)?.value;if(e===void 0){n.push(r);continue}let i=r.attrs.find(e=>e.name===`style`)?.value??``;t.push(e===`border`||e===`outline`?{owner:e,styles:Y(i)}:{owner:`paint`,paintId:e,styles:Y(i)})}return[t,n]},Hu=(e,t)=>Fu(e.childNodes).map((e,n)=>{let r=e.attrs.find(e=>e.name===`data-enhance-run`)?.value;if(e.tagName!==`span`||r!==String(n))return J(`Text ${t} holds run spans only, each with its data-enhance-run place.`);let i=e.attrs.find(e=>e.name===`style`)?.value??``;return{text:Uu(e,t),styles:Y(i)}}),Uu=(e,t)=>e.childNodes.map(e=>`value`in e?e.value:J(`Retained text ${t} must contain text only; its existing rich formatting is preserved by the text owner.`)).join(``),Wu=e=>{let t=Iu(e),n=new Set,r=e=>{if(e.tagName!==`div`&&e.tagName!==`span`&&e.tagName!==`svg`)return J(`Unsupported retained element: ${e.tagName}.`);let t=zu(e),i=Bu(t);if(n.has(i.id))return J(`Duplicate node identity: ${i.id}.`);if(n.add(i.id),e.tagName===`svg`)return{...i,tag:`svg`,path:Ru(e,t.viewBox??``),text:``,children:[]};let a=e.tagName===`span`&&e.childNodes.some(e=>`tagName`in e),[o,s]=e.tagName===`span`?[[],[]]:Vu(e);return{...i,tag:e.tagName,...a&&{runs:Hu(e,i.id)},...o.length>0&&{paints:o},text:!a&&e.tagName===`span`?Uu(e,i.id):``,children:s.map(e=>r(e))}},i=Fu(t.childNodes),a=i[0];return a===void 0||i.length!==1?J(`An editable update must contain exactly its original root.`):r(a)},Gu=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Ku={fill:`100% 100%`,cover:`cover`,contain:`contain`,"scale-down":`contain`,none:`auto`},qu={"100% 100%":`fill`,cover:`cover`,contain:`contain`,auto:`none`},Ju=/^background(?:-.+)?$/u,Yu=/^url\((?:"([^"]*)"|'([^']*)'|([^"'()\s]*))\)$/u,Xu=e=>{if(e.component!==`image`)return;let t=e.props?.src;return typeof t==`string`&&t!==``?t:void 0},Zu=e=>{let t=Xu(e);if(t===void 0)return{};let n=e.props?.fit,r=e.props?.position;return{"background-image":`url(${JSON.stringify(t)})`,"background-size":Ku[typeof n==`string`?n:`fill`]??`100% 100%`,"background-position":typeof r==`string`?r:`50% 50%`,"background-repeat":`no-repeat`}},Qu=(e,t)=>Xu(e)!==void 0&&Ju.test(t),$u=(e,t,n)=>{if(Xu(e)===void 0)return[];let r=[...new Set([...Object.keys(t),...Object.keys(n)])].filter(e=>Ju.test(e)&&t[e]!==n[e]);if(r.length===0)return[];if(r.some(e=>![`background-image`,`background-size`,`background-position`].includes(e)))return Gu(`An image paints once from its source on ${e.id}; change only its background-image URL, background-size (100% 100%, cover, contain or auto) and background-position.`);let i=Yu.exec(n[`background-image`]??``),a=i?.[1]??i?.[2]??i?.[3],o=qu[n[`background-size`]??``],s=n[`background-position`];return a===void 0||a===``||o===void 0||s===void 0?Gu(`An image on ${e.id} needs a background-image URL, a background-size of 100% 100%, cover, contain or auto, and a background-position.`):[{op:`setProps`,nodeId:e.id,props:{...e.props,...r.includes(`background-image`)&&{src:a},...r.includes(`background-size`)&&{fit:o},...r.includes(`background-position`)&&{position:s}}}]},X=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},ed={border:/^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u,outline:/^outline(?:-.+)?$/u,paint:/^$/u},td=e=>Object.fromEntries(Object.entries(Y(e)).toSorted(([e],[t])=>e.localeCompare(t))),nd=e=>td(Object.entries(e).flatMap(([e,t])=>{let n=wt(e,t);return e.startsWith(`--`)||n.includes(`var(--canvas`)||n.includes(`url(#`)?[]:[`${e}:${n}`]}).join(`;`)),rd=e=>{let t=B(e),n=n=>Yo(t,n).map(t=>({owner:`paint`,paintId:t.id,styles:nd(ps(e,t))})),r=cs(e),i=Ms(e);return[...n(`outer-shadow`),...Jo(t).map(e=>({owner:`paint`,paintId:e.id,styles:nd(Ds(e))})),...n(`inner-shadow`),...r===null?[]:[{owner:`border`,styles:nd(r)}],...i===null?[]:[{owner:`outline`,styles:nd(i)}]]},id=(e,t)=>e.some(e=>ed[e.owner].test(t)),ad=e=>st.find(t=>t===(e??`normal`))??X(`Unsupported mix-blend-mode: ${e??``}.`),od=/stroke-(?:dasharray|linecap)="[^"]*"/gu,sd=e=>{let t=/^url\(["']?data:image\/svg\+xml,(.*?)["']?\)$/u.exec(e??``)?.[1];return t===void 0?void 0:decodeURIComponent(t)},cd=(e,t,n)=>{let r=sd(t),i=sd(n);if(i===void 0||r?.replaceAll(od,``)!==i.replaceAll(od,``))return X(`Only stroke-dasharray and stroke-linecap of the dash mask can change on ${e.id}.`);let a=(/stroke-dasharray="([^"]*)"/u.exec(i)?.[1]??``).split(/[\s,]+/u).filter(e=>e!==``).map(Number);if(a.length===0||a.some(e=>!Number.isFinite(e)||e<0))return X(`A dash pattern is one or more lengths of 0 or more, on ${e.id}.`);let o=/stroke-linecap="([^"]*)"/u.exec(i)?.[1];return o!==`butt`&&o!==`round`&&o!==`square`?X(`A dash cap is butt, round or square, on ${e.id}.`):{dashPattern:a,dashCap:o===`butt`?`none`:o}},ld=(e,t,n,r)=>{let i=n.paints.filter(e=>e.visible),[a]=i;if(a===void 0||i.length!==1)return X(`Set a blend on one paint of the ${t} of ${e.id} in the editor.`);let o=ad(r);return n.paints.map(e=>e===a?{...e,blendMode:o}:e)},ud=(e,t)=>{if(t.size===0)return[];let n=e.appearance?.fills??[],r=e.appearance?.shadows??[];for(let i of t.keys())if(n.every(e=>e.id!==i)&&r.every(e=>e.id!==i))return X(`${e.id} has no fill or shadow ${i}.`);let i=e=>e.map(e=>t.has(e.id)?{...e,blendMode:ad(t.get(e.id))}:e);return[...n.some(e=>t.has(e.id))?[{op:`setAppearance`,nodeId:e.id,appearance:{fills:i(n)}}]:[],...r.some(e=>t.has(e.id))?[{op:`setAppearance`,nodeId:e.id,appearance:{shadows:i(r)}}]:[]]},dd=(e,t,n)=>{let r=e=>JSON.stringify(e.map(e=>e.paintId??e.owner)),i=n.find(e=>e.paintId!==void 0&&t.every(t=>t.paintId!==e.paintId));if(i?.paintId!==void 0)return X(`${e.id} has no fill or shadow ${i.paintId}.`);if(r(t)!==r(n))return X(`Keep each paint element of ${e.id}.`);let a=new Map;return[...n.flatMap((n,r)=>{let i=t[r];if(i===void 0||JSON.stringify(i.styles)===JSON.stringify(n.styles))return[];let o=[...new Set([...Object.keys(i.styles),...Object.keys(n.styles)])].filter(e=>i.styles[e]!==n.styles[e]);if(n.owner===`paint`&&n.paintId!==void 0)return o.some(e=>e!==`mix-blend-mode`)?X(`The paint element ${n.paintId} of ${e.id} follows its paint, so only its mix-blend-mode can change there; change ${o.join(`, `)} through the appearance operation.`):(a.set(n.paintId,n.styles[`mix-blend-mode`]),[]);if(o.some(e=>e!==`mix-blend-mode`&&e!==`mask-image`))return X(`The ${n.owner}'s paint element of ${e.id} follows its ${n.owner}, so ${o.join(`, `)} cannot change there; change the ${n.owner} CSS on the layer, or the paint element's mix-blend-mode or dash mask.`);let s=n.owner===`outline`?`outline`:`border`,c=e.appearance?.[s];if(c===void 0)return X(`The ${s} of ${e.id} has no paint element to write.`);let l=o.includes(`mix-blend-mode`)?ld(e,s,c,n.styles[`mix-blend-mode`]):c.paints,u=o.includes(`mask-image`)?cd(e,i.styles[`mask-image`],n.styles[`mask-image`]):{};return[{op:`setAppearance`,nodeId:e.id,appearance:{[s]:{...c,paints:l,...u}}}]}),...ud(e,a)]},fd=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},pd=e=>e.kind===`text`||e.kind===`span`&&e.children.every(e=>e.kind===`text`),md=e=>Ee([e]),hd=e=>e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`),gd=e=>e.replaceAll(/-([a-z])/gu,(e,t)=>t.toUpperCase()),_d=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,n])=>{let r=gd(e);return f.has(r)?[r,n]:fd(`Run ${String(t+1)} cannot hold ${e}; set it on the text layer.`)})),vd=e=>{if(e.kind!==`span`)return{};let[t,...n]=(e.fills??[]).filter(e=>e.visible),r=t===void 0||n.length>0?void 0:io(t),i=[...Object.entries(e.styles).map(([e,t])=>{let n=hd(e);return`${n}:${wt(n,t)}`}),...r===void 0?[]:[`color:${r}`]];return Object.fromEntries(Object.entries(Y(i.join(`;`))).toSorted(([e],[t])=>e.localeCompare(t)))},yd=e=>{let t=Et(e);return t.length===0||t.some(e=>!pd(e))?null:t.map(e=>({text:md(e),styles:vd(e)}))},bd=e=>Et(e).some(e=>!pd(e)),xd=(e,t,n,r)=>{if(`mix-blend-mode`in r.styles)return fd(`Text paints have no blend of their own. Set mix-blend-mode on the text layer.`);let{color:i,...a}=r.styles,o=_d(a,t),s=i===void 0?void 0:F(`${e.id}-run-${String(t)}`,i);if(i!==void 0&&s===null)return fd(`The color of run ${String(t+1)} is not a colour.`);let{fills:c,...l}=n.kind===`span`?n:{kind:`span`,styles:{},children:[]},u=c!==void 0&&vd(n).color===void 0,d=s==null?u?c:void 0:[s];return{...l,styles:o,...d!==void 0&&{fills:d},children:[{kind:`text`,text:r.text}]}},Sd=(e,t,n)=>{if(t.length!==n.length)return fd(`Keep each run span of ${e.id}; change a run's words or CSS in place.`);let r=Et(e),i=r.map((r,i)=>{let a=t[i],o=n[i];return a===void 0||o===void 0||JSON.stringify(a)===JSON.stringify(o)?r:xd(e,i,r,o)});if(i.every((e,t)=>e===r[t]))return[];let a={...e.props,richText:i,text:Ee(i)};return[{op:`editText`,nodeId:e.id,change:Se(e,{...e,props:a})}]},Cd=new Set([`path`,`polygon`,`boolean`]),wd=e=>Cd.has(e.geometry?.kind??``),Td=e=>{let t=(e.appearance?.fills??[]).filter(e=>e.visible);return t.length>1||t.some(e=>e.kind!==`solid`||(e.blendMode??`normal`)!==`normal`)?`A vector with a gradient, image or blended fill keeps its paint in the editor.`:null},Ed=e=>{let t=kr(e);if(typeof t==`string`)return null;let n=(e.appearance?.fills??[]).find(e=>e.visible),{x:r,y:i,width:a,height:o}=t.viewBox;return{d:t.path,fillRule:t.fillRule,fill:n===void 0?`none`:io(n)??`none`,viewBox:[r,i,a,o].map(String).join(` `)}},Dd=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Od=e=>{let[t=0,n=0,r=0,i=0]=e.split(/\s+/u).map(Number);return r>0&&i>0?{x:t,y:n,width:r,height:i}:Dd(`Invalid viewBox: ${e}.`)},kd=(e,t,n)=>n.d.trim()===``?Dd(`The path of ${t.id} is empty.`):[{op:`setGeometry`,nodeId:t.id,geometry:{kind:`path`,path:n.d,fillRule:n.fillRule,viewBox:Od(n.viewBox)}},...t.geometry?.kind===`boolean`?Fi(e,t.id).map(e=>({op:`remove`,nodeId:e})):[]],Ad=(e,t)=>{let n=(e.appearance?.fills??[]).find(e=>e.visible),r=n?.kind===`solid`?n.id:`${e.id}-fill`,i=t===`none`?null:F(r,t);return i===null&&t!==`none`?Dd(`The fill of ${e.id} is not a colour.`):{op:`setAppearance`,nodeId:e.id,appearance:{fills:i===null?[]:[{...i,...n?.kind===`solid`&&n.blendMode!==void 0&&{blendMode:n.blendMode}}]}}},jd=(e,t,n,r)=>[...n.d===r.d&&n.fillRule===r.fillRule&&n.viewBox===r.viewBox?[]:kd(e,t,r),...n.fill===r.fill?[]:[Ad(t,r.fill)]],Md=new Set([`root`,`frame`,`group`,`rectangle`,`image`,`text`]),Nd={screen:`Its pixels come from a recorded page. Use Make editable to edit it as layers.`,recording:`Its pixels come from a recording.`,prototype:`Its pixels come from a running build.`},Pd=/^(?:mask(?:-.+)?|clip-path)$/u,Fd=`This layer kind has no editable HTML form yet; edit it in the editor.`,Id=(e,t,n)=>{let r=Nd[t.component];return r===void 0?Nu(e,t)===null?`This mask's shape cannot be read; edit it in the editor.`:t.component===`text`&&(n>0||bd(t))?`Text with nested layers or nested formatting keeps its formatting in the editor.`:wd(t)?Td(t)??(Ed(t)===null?Fd:null):Md.has(t.component)&&(t.geometry===void 0||t.geometry.kind===`mask`)?null:Fd:r},Ld=(e,t)=>{let n={...Vs(t),...Mu(t,Qs(e,t)),...Nu(e,t)},r=ft(t),i=Object.entries(n).flatMap(([e,n])=>{let r=wt(e,n);return e.startsWith(`--`)||r.includes(`var(--canvas`)||r.includes(`url(#`)||xs(t,[e]).length===0&&!Pd.test(e)?[]:[[e,r]]});return{...Object.fromEntries(i),...Zu(t),...Object.fromEntries(Object.entries(r).map(([e,t])=>[e,wt(e,t)]))}},Rd=e=>{throw new x(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},Z=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`),zd=e=>wd(e)?Ed(e):null,Bd=/^background(?:-.+)?$/u,Vd=e=>`<path d="${Z(e.d)}" fill-rule="${e.fillRule}" fill="${Z(e.fill)}"></path>`,Hd=e=>{let t=Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`);return t===``?``:` style="${Z(t)}"`},Ud=e=>`<div data-enhance-paint="${Z(e.paintId??e.owner)}"${Hd(e.styles)}></div>`,Wd=(e,t)=>`<span data-enhance-run="${String(t)}"${Hd(e.styles)}>${Z(e.text)}</span>`,Gd=e=>{let t=Object.entries(e.styles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`),n=`data-enhance-id="${Z(e.id)}" data-enhance-name="${Z(e.label)}"${e.opaque?` data-enhance-opaque="true"`:``}${e.locked?` data-enhance-locked="true"`:``}${t===``?``:` style="${Z(t)}"`}`;if(e.path!==void 0)return`<svg ${n} viewBox="${Z(e.path.viewBox)}" preserveAspectRatio="none">${Vd(e.path)}</svg>`;let r=(e.runs??[]).map((e,t)=>Wd(e,t)).join(``),i=(e.paints??[]).map(e=>Ud(e)).join(``);return`<${e.tag} ${n}>${Z(e.text)}${r}${i}${e.children.map(e=>Gd(e)).join(``)}</${e.tag}>`},Kd=(e,t)=>{let n=new Set,r=[],i={},a=Ii(e),o=t=>{if(n.has(t))return Rd(`The document contains repeated node identity.`);n.add(t);let s=N(e,t),c=a.get(t)??[],l=Id(e,s,c.length),u=l!==null;u&&(r.push(s.id),i[s.id]=l);let d=u?null:zd(s),f=u||s.component!==`text`?null:yd(s),p=u||d!==null?[]:rd(s),m=u?{}:Y(Object.entries(Ld(e,s)).filter(([e])=>d===null||!Bd.test(e)).filter(([e])=>!id(p,e)).map(([e,t])=>`${e}:${t}`).join(`;`));return{id:s.id,tag:d===null?s.component===`text`?`span`:`div`:`svg`,...d!==null&&{path:d},label:s.label,opaque:u,locked:zi(e,t),styles:m,...f!==null&&{runs:f},...p.length>0&&{paints:p},text:f!==null||u||s.component!==`text`?``:ae(s)??``,children:u||d!==null?[]:c.map(e=>o(e))}},s=o(t);return{projectionVersion:2,root:s,html:Gd(s),opaqueNodeIds:r,sealedReasons:i}},qd=(e,t,n)=>{if(e.rootNodeIds!==void 0)return e.rootNodeIds;if(t.nodeIds.length>0)return t.nodeIds;if(t.pageId===void 0)return[`root`];let r=it(t,n);if(r.ok)return r.rootNodeIds;throw g(t,n),new x(`NOT_FOUND`,`The linked page is unavailable.`,`Copy a current page link.`)},Jd=(e,t)=>{let n=new Set(t);for(let r of t){let t=new Set,i=e.relationships[r]?.parentId;for(;i!==void 0;){if(t.has(i)||n.has(i))throw new x(`BAD_REQUEST`,`Outline roots overlap or contain a parent cycle.`,`Choose disjoint roots so each depth and coverage statement has one meaning.`);t.add(i),i=e.relationships[i]?.parentId}}if(n.size!==t.length)throw new x(`BAD_REQUEST`,`Outline roots repeat.`,`Choose each root once.`)},Yd=(e,t,n,r)=>{let i=[],a=new Set,o=Ii(e),s=(t,c)=>{if(a.has(t))return;a.add(t);let l=N(e,t),u=o.get(t)??[],d=zi(e,t);if(i.push({id:t,label:l.label,kind:l.component,parentId:e.relationships[t]?.parentId??null,sortKey:e.relationships[t]?.sortKey??null,depth:c,childCount:u.length,childrenOmitted:c===n&&u.length>0,locked:d,visible:l.visible!==!1,editable:r&&!d&&[`root`,`frame`,`group`,`text`].includes(l.component),bounds:l.box??null}),c<n)for(let e of u)s(e,c+1)};for(let e of t)s(e,0);return i},Xd=(e,t,n)=>{if(e===void 0)return 0;let r=we(e,bt);if(r.canvasId!==t.reference.canvasId||r.queryDigest!==n)throw new x(`BAD_REQUEST`,`This cursor belongs to another outline query.`,`Restart the outline read with the requested scope.`);if(r.version!==t.version)throw new x(`CONFLICT`,`The canvas changed between outline pages.`,`Restart the scoped read at the current revision. Do not combine pages from different revisions.`,{currentVersion:String(t.version),outcome:`not_committed`});return r.offset},Zd=(e,t)=>{let{reference:n,scene:r,version:i,isCurrent:a}=t,s=qd(e,n,r);S(n,r,s),Jd(r,s);let c=o({reference:n,roots:e.rootNodeIds??null,depth:e.depth,limit:e.limit}),l=Xd(e.cursor,t,c),u=Yd(r,s,e.depth,a);if(l>u.length)throw new x(`BAD_REQUEST`,`The outline cursor is out of range.`,`Restart the outline read.`);let d=u.slice(l,l+e.limit),f=l+d.length,m=u.some(e=>e.childrenOmitted);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[...s]},view:`outline`,complete:f===u.length&&!m,returnedCount:d.length,total:u.length,nodes:d,omittedDescendants:m,nextCursor:f<u.length?p({protocol:`enhance-canvas-outline/1`,canvasId:n.canvasId,version:i,queryDigest:c,offset:f}):null,warnings:a?[]:[`This legacy document is read-only until the normal editor upgrades it.`]}},Qd=e=>{let t=c(e);if(t!==null)return{storage:`canvas-image`,reference:e,ownerId:t.canvasId,assetId:t.assetId};let n=Ce(e);if(n!==null)return{storage:`canvas-font`,reference:e,ownerId:n.canvasId,assetId:n.sha256};let r=/^\/v1\/recording-assets\/([a-f0-9-]{36})\/([a-f0-9]{32,64})$/u.exec(e);return r===null?{storage:e.startsWith(`data:`)?`inline`:/^https?:\/\//u.test(e)?`external`:`opaque`,reference:null,ownerId:null,assetId:null}:{storage:`recording-asset`,reference:e,ownerId:r[1]??null,assetId:r[2]??null}},$d=(e,t)=>typeof e[t]==`string`?e[t]:null,ef=(e,t)=>{let n=new Map,r=[...t].toSorted((e,t)=>e.localeCompare(t));for(let t of r){let r=e.scene.nodes[t];if(r===void 0)continue;let i=(e,r,i)=>{let a={nodeId:t,kind:e,sourceDigest:o(r),...Qd(r),delivery:`not_checked`,metadata:i};return n.set(o(a),a),r};Jr(r,e=>i(`image`,e,null)),Ie(r.props,(e,t)=>i(`font`,e,{family:$d(t,`family`),style:$d(t,`style`),weight:$d(t,`weight`)}))}return Array.from(n,([,e])=>e)},tf=(e,t,n)=>{if(e.cursor===void 0)return 0;let r=we(e.cursor,pt);if(r.canvasId!==t.reference.canvasId||r.digest!==n)throw new x(`BAD_REQUEST`,`The resource cursor belongs to another query.`,`Restart this scoped resource read.`);if(r.version!==t.version)throw new x(`CONFLICT`,`The canvas changed between resource pages.`,`Restart the read at the current revision.`);return r.offset},nf=(e,t)=>{let n=it(t.reference,t.scene);if(!n.ok)throw new x(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link; do not broaden the request.`);let r=o({reference:t.reference,limit:e.limit}),i=tf(e,t,r),a=ef(t,n.nodeIds);if(i>a.length)throw new x(`BAD_REQUEST`,`The resource cursor is out of range.`,`Restart the scoped resource read.`);let s=e=>{let o=i+e.length;return{view:`resources`,canvasId:t.reference.canvasId,version:t.version,scope:{rootNodeIds:[...n.rootNodeIds]},coverage:`authored-resource-slots`,resources:e,total:a.length,returnedCount:e.length,complete:o===a.length,nextCursor:o===a.length?null:p({protocol:`enhance-canvas-resources/1`,canvasId:t.reference.canvasId,version:t.version,digest:r,offset:o}),warnings:[`Inventory includes declared image and font resource slots, including hidden and unused declarations. It does not resolve computed font usage or assets inside opaque screens, recordings, prototypes or raw CSS.`,`Resource delivery and availability have not been checked. Protected paths retain product authorization. External URLs and inline bytes are omitted; their digests identify the original source without exposing credentials or blobs.`,`Scoped reads include declarations on selected nodes and descendants only. A font declaration owned by an ancestor requires a separate explicit read of that scope.`]}},c=48e3-Buffer.byteLength(JSON.stringify(s([])));return s(G(a,i,e.limit,c).entries)},rf=(e,t,n)=>{if(e.state!==`ready`){if(t.cursor!==void 0)throw new x(`CONFLICT`,`The transcript changed during pagination.`,`Restart the read.`);return e}let{cursor:r,...i}=t,a=o({scope:n,range:i,transcript:e}),s=r===void 0?null:we(r,tt);if(s!==null&&s.digest!==a)throw new x(`CONFLICT`,`The transcript cursor no longer matches this source, range or revision.`,`Restart the requested range; do not combine transcript revisions.`);let c=e.cues.filter(e=>e.endMs>=t.startMs&&(t.endMs===void 0||e.startMs<t.endMs)),l=s?.offset??0;if(l>c.length)throw new x(`BAD_REQUEST`,`Transcript cursor offset is out of range.`,`Restart the read.`);let u=G(c,l,t.limit).entries,d=l+u.length;return{state:`ready`,languageCode:e.languageCode,integrity:e.integrity,isRefreshing:e.isRefreshing,requestedRange:{startMs:t.startMs,endMs:t.endMs??null},cues:u,returnedCount:u.length,totalInRange:c.length,omittedOutsideRange:e.cues.length-c.length,complete:d===c.length,nextCursor:d<c.length?p({protocol:`enhance-canvas-transcript/1`,digest:a,offset:d}):null}},af=[`recording.get`,`prototype.getPublishStatus`,`transcript.get`],of=e=>{let t=Te.safeParse(e.node.props?.capture).data;if(t===void 0)return null;let n=e.screens.find(e=>e.screenId===t.screenId);return{kind:`screen`,screenId:t.screenId,availability:n===void 0?t.html===void 0?`unavailable`:`inline-only`:n.download===null?`pending`:`available`,sourceUrl:n?.route??null,title:n?.title??null,viewport:n?.viewport??t.viewport,atMs:n?.atMs??t.atMs,recordingId:n===void 0?t.provenance?.recordingId??null:n.sourceRecordingId,missingAssetCount:n?.assetBundle?.missingAssetCount??null}},sf=e=>{let t=m.safeParse(e.props?.conversion).data;if(t===void 0)return{kind:`none`};let n=new Map,r=t.report?.issues??[];for(let e of r)n.set(e.code,(n.get(e.code)??0)+1);return{kind:`conversion`,recordingId:t.provenance?.recordingId??null,nodeCount:t.report?.nodeCount??null,issueCounts:Object.fromEntries(n)}},cf=async(e,t)=>{let{node:n,canvasId:r}=t;if(n.component===`recording`){let t=me.parse(n.props),i=w.uuid().parse(t.recordingId),a=Nt.parse(await e.query(af[0],{canvasId:r,recordingId:i}));return{kind:`recording`,recordingId:i,durationMs:a.durationMs,viewport:a.viewport,sourceUrl:a.sourceUrl,interrupted:a.interrupted,integrity:a.integrity,chunkCount:a.chunks.length,missingChunkCount:a.chunks.filter(e=>e.state===`missing`).length,hasAudio:a.audio!==null,missingAssetCount:a.missingAssetCount}}if(n.component===`prototype`){let t=d.parse(n.props),i=ce.parse(await e.query(af[1],{canvasId:r,deploymentId:t.deploymentId}));if(i.prototypeId!==t.prototypeId)throw new x(`CONFLICT`,`Prototype identity does not match its deployment.`,`Read the node again.`);return{kind:`prototype`,...t,state:i.state,fileCount:i.fileCount}}return of(t)??sf(n)},lf=e=>({execute:async t=>{let n=await cf(e,t),r=t.input.transcript,i=`recordingId`in n?n.recordingId:null;if(r!==void 0&&i===null)throw new x(`BAD_REQUEST`,`This object has no recording transcript source.`,`Choose a recording or a capture with recording provenance.`);let a=r===void 0?null:rf(pe.parse(await e.query(af[2],{canvasId:t.canvasId,recordingId:w.uuid().parse(i)})),r,{canvasRef:t.input.canvasRef,nodeId:t.node.id,version:t.version}),o=n.kind===`screen`&&[`pending`,`unavailable`].includes(n.availability);return{canvasId:t.canvasId,version:t.version,scope:{rootNodeIds:[t.node.id]},view:`source`,nodeId:t.node.id,source:n,transcript:a,complete:!o&&(a===null||a.state===`empty`||a.state===`ready`&&a.complete),pixelsInspected:!1,warnings:[...o?[`The captured source bytes are not currently available.`]:[],...a===null?[]:[`Transcript times describe speech, not verified visual transitions. Render and inspect candidate moments.`]]}}}),uf=[`canvas.document.get`],df=e=>{throw new x(`CONFLICT`,`Canvas version ${String(e)} no longer matches this read.`,`Restart the scoped read at the current revision. Do not combine pages from different revisions.`,{currentVersion:String(e),outcome:`not_committed`})},ff=(e,t)=>{let{reference:n,scene:r,version:i}=t;if(!t.isCurrent)throw new x(`BAD_REQUEST`,`This document format cannot produce an editable snapshot.`,`Open it in the current editor before editing.`);S(n,r,[e.rootNodeId]);let a=Kd(r,e.rootNodeId);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[e.rootNodeId]},view:`editable`,complete:!0,projectionVersion:a.projectionVersion,rootNodeId:e.rootNodeId,html:a.html,opaqueNodeIds:[...a.opaqueNodeIds],sealedReasons:{...a.sealedReasons},snapshotToken:Tt({reference:n,version:i,rootNodeId:e.rootNodeId,html:a.html}),warnings:a.opaqueNodeIds.length>0?[`Preserve opaque placeholders unchanged; their authored content remains in the canvas.`]:[]}},pf=e=>({execute:async t=>{let n=i(t.canvasRef),r=ze.parse(await e.query(uf[0],{canvasId:n.canvasId}));if(t.expectedVersion!==void 0&&t.expectedVersion!==r.version)return df(r.version);let a=Xe.safeParse(r.document),o=a.success?a.data:St.parse(r.document);return t.view===`resources`?nf(t,{reference:n,scene:o,version:r.version,isCurrent:a.success}):t.view===`outline`?Zd(t,{reference:n,scene:o,version:r.version,isCurrent:a.success}):t.view===`source`?(S(n,o,[t.nodeId]),lf(e).execute({canvasId:n.canvasId,version:r.version,node:N(o,t.nodeId),screens:r.screens,input:t})):ff(t,{reference:n,scene:o,version:r.version,isCurrent:a.success})}}),mf=[`canvas.mutation.get`],hf=e=>({execute:async t=>{let n=t.reference.canvasId,r=se.parse(await e.query(mf[0],{canvasId:n,mutationId:t.clientToken,fingerprint:t.fingerprint}));if(r.state===`committed`)return Pl(r.result,t.fingerprint);let i=await Pi({remote:e},n,t.baseVersion),a=await t.plan(i);if(`outcome`in a)return a;if(Ac(t.reference,i,a),a.length===0)return{outcome:`no_op`,canvasId:n,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let o=je.safeParse({canvasId:n,documentFormatVersion:15,mutationId:t.clientToken,baseVersion:t.baseVersion,operations:a,requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});if(!o.success)throw new x(`BAD_REQUEST`,`The planned edit exceeds the canonical canvas contract.`,o.error.issues[0]?.message??`Reduce the edit scope.`,{outcome:`not_committed`});return Pl(v.parse(await Ni(e).execute(o.data)),t.fingerprint)}}),gf=(e,t)=>{let n=Ii(e),r=new Set(t),i=new Set,a=t=>{if(i.has(t))return;if(i.add(t),N(e,t),zi(e,t))throw new x(`BAD_REQUEST`,`Removing this subtree would remove locked content: ${t}.`,`Keep the locked subtree, or explicitly unlock it before requesting removal.`);let r=n.get(t)??[];for(let e of r)a(e)};for(let e of r){if(e===`root`)throw new x(`BAD_REQUEST`,`The canvas root cannot be removed.`,`Name its children.`);a(e)}return[...r].filter(t=>{let n=e.relationships[t]?.parentId;for(;n!==void 0;){if(r.has(n))return!1;n=e.relationships[n]?.parentId}return!0}).map(e=>({op:`remove`,nodeId:e}))},_f=e=>({execute:async({clientToken:t,...n})=>{let r=i(n.canvasRef);return hf(e).execute({reference:r,baseVersion:n.baseVersion,clientToken:t,fingerprint:o({operation:`canvas.remove/1`,...n,reference:r}),plan:e=>gf(e,n.rootNodeIds)})}}),vf=(e,t,n,r)=>{let i=e.parents.get(t),a=e.children.get(n)??[];if(i===n&&a.indexOf(t)===r)return;if(zi(e.document,t)||zi(e.document,n))throw new x(`BAD_REQUEST`,`Locked node ${t} cannot be rearranged through HTML.`,`Keep locked placeholders in place or unlock them in the editor before editing.`);i!==void 0&&e.children.set(i,(e.children.get(i)??[]).filter(e=>e!==t));let o=e.children.get(n)??[];o.splice(r,0,t),e.children.set(n,o),e.parents.set(t,n),e.moves.push({nodeId:t,parentId:n,index:r})},yf=(e,t,n)=>{let r={...e,nodes:Object.fromEntries(Object.entries(e.nodes).filter(([e])=>!n.has(e))),relationships:Object.fromEntries(Object.entries(e.relationships).filter(([e])=>!n.has(e)))},i={document:r,parents:new Map(Object.entries(r.relationships).map(([e,t])=>[e,t.parentId])),children:new Map([...Ii(r)].map(([e,t])=>[e,[...t]])),moves:[]},a=e=>{for(let[t,n]of e.children.entries())vf(i,n.id,e.id,t),a(n)};return a(t),i.moves.length===0?[]:$i(r,i.moves).operations},bf=e=>{throw new x(`BAD_REQUEST`,e,`Read the current subtree and reduce or correct the edit. No canvas changes were committed.`)},xf=(e,t,n)=>{if(Object.keys(t.idMap).length!==n.fragments.length)return bf(`Native compilation returned unexpected fragment identities.`);if(t.operations.length!==n.fragments.length)return bf(`Native compilation returned an incomplete insertion plan.`);let r={...e,nodes:{...e.nodes},relationships:{...e.relationships}};for(let[e,i]of n.fragments.entries()){let n=t.operations[e];if(n?.op!==`insertConvertedSubtree`||n.destination.kind!==`insert-children`||n.destination.targetNodeId!==i.parentNodeId||n.rootNodeId!==t.idMap[i.id])return bf(`Native compilation returned a mismatched insertion plan.`);for(let e of Object.keys(n.nodes))if(r.nodes[e]!==void 0||Object.hasOwn(r.tombstones,e))return bf(`New HTML identity ${e} already exists.`);let a=Fi(r,i.parentNodeId).at(-1),o=a===void 0?null:r.relationships[a]?.sortKey??null;Object.assign(r.nodes,n.nodes),Object.assign(r.relationships,n.relationships,{[n.rootNodeId]:{parentId:i.parentNodeId,sortKey:It(o,null)}})}return r},Sf=(e,t)=>({...e,id:Object.hasOwn(t,e.id)?t[e.id]??e.id:e.id,children:e.children.map(e=>Sf(e,t))}),Cf={operations:[],idMap:{},rootNodeIds:[]},wf=(e,t,n=Cf)=>{let r=xf(e,n,t),i=Sf(t.root,n.idMap);return[...t.operations,...n.operations,...yf(r,i,t.removed)]},Tf=e=>e.attrs.some(e=>e.name===`data-enhance-paint`),Ef=e=>e.attrs.find(e=>e.name===`data-enhance-id`)?.value,Df=e=>{throw new x(`BAD_REQUEST`,e,`Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.`)},Of=e=>e.flatMap(e=>`tagName`in e?[e,...Of(e.childNodes)]:[]),kf=e=>{let t=Iu(e),n=Of(t.childNodes),r=new Set(n.map(e=>Ef(e))),i=[],a=(e,t)=>{let n=Ef(e);if(n!==void 0&&(e.tagName===`svg`||e.tagName===`span`))return e;if(n!==void 0)return{...e,childNodes:e.childNodes.map(e=>`tagName`in e&&!Tf(e)?a(e,n):e)};if(t===void 0)return Df(`The submitted HTML must retain its original root identity.`);if([e,...Of(e.childNodes)].some(e=>e.attrs.some(e=>[`data-enhance-id`,`data-enhance-opaque`].includes(e.name))))return Df(`A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.`);let o=`new_${String(i.length)}`;for(;r.has(o);)o=`_${o}`;return r.add(o),i.push({id:o,parentNodeId:t,html:dn(e)}),{...e,tagName:`div`,nodeName:`div`,childNodes:[],attrs:[{name:`data-enhance-id`,value:o},{name:`data-enhance-name`,value:`New content`},{name:`data-enhance-opaque`,value:`true`}]}};return t.childNodes=t.childNodes.map(e=>`tagName`in e?a(e):e),{root:Wu(un(t)),fragments:i}},Q=e=>{throw new x(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Af=e=>{let t=new Map,n=e=>{t.set(e.id,e);for(let t of e.children)n(t)};return n(e),t},jf=(e,t)=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n),Mf=(e,t,n,r)=>{let i=new Set,a=e=>{if(i.has(e.id))return Q(`Overlapping removal roots include ${e.id}.`);if(t.has(e.id))return Q(`Removed node ${e.id} is still present in the HTML.`);i.add(e.id);for(let t of e.children)a(t)};for(let t of n){let n=e.get(t);if(n===void 0||t===r)return Q(`Invalid removal root: ${t}.`);a(n)}for(let n of e.keys())if(!t.has(n)&&!i.has(n))return Q(`Missing retained node ${n}; declare intentional deletion in removeNodeIds.`);return i},Nf=(e,t,n,r)=>{let i=new Set([...Object.keys(n.styles),...Object.keys(r.styles)]),a=Object.fromEntries([...i].filter(e=>n.styles[e]!==r.styles[e]).filter(e=>!Qu(t,e)).map(e=>[e,r.styles[e]??null]));return[...t.geometry?.kind===`mask`&&Object.keys(a).some(e=>Pd.test(e))?[{op:`setGeometry`,nodeId:t.id,geometry:`default`}]:[],...$u(t,n.styles,r.styles),...Object.keys(a).length===0?[]:hc(e,[{nodeIds:[t.id],styles:a}])]},Pf=(e,t,n)=>{if(t.tag!==n.tag||t.opaque!==n.opaque||t.locked!==n.locked)return Q(`The kind, opaque marker or locked marker of ${t.id} changed.`);let r=!jf(t.styles,n.styles),i=JSON.stringify(t.path)!==JSON.stringify(n.path)||JSON.stringify(t.runs)!==JSON.stringify(n.runs)||JSON.stringify(t.paints)!==JSON.stringify(n.paints);if(t.locked&&(r||i||t.label!==n.label||t.text!==n.text))return Q(`Locked node ${t.id} cannot be changed through HTML.`);if(t.opaque&&(r||t.label!==n.label||t.text!==n.text||n.children.length>0))return Q(`Opaque node ${t.id} cannot be changed through HTML.`);let a=e.nodes[t.id];if(a===void 0)return Q(`Node ${t.id} no longer exists.`);let o=[];return t.label!==n.label&&o.push({op:`setLabel`,nodeId:t.id,label:n.label,labelOrigin:`user`}),t.text!==n.text&&o.push({op:`editText`,nodeId:t.id,change:Se(a,{...a,props:s(a,n.text)})}),o.push(...dd(a,t.paints??[],n.paints??[])),(t.runs!==void 0||n.runs!==void 0)&&o.push(...Sd(a,t.runs??[],n.runs??[])),t.path!==void 0&&n.path!==void 0&&o.push(...jd(e,a,t.path,n.path)),r&&o.push(...Nf(e,a,t,n)),o},Ff=(e,t,n,r)=>{let i=Kd(e,t).root,a=kf(n),o=a.root;if(o.id!==t)return Q(`The submitted HTML must retain its original root identity.`);let s=new Set(a.fragments.map(e=>e.id)),c=Af(i),l=Af(o),u=Mf(c,l,r,t),d=new Set([...u,...r.flatMap(t=>[...Ri(e,t)])]);for(let t of d)if(zi(e,t))return Q(`Locked node ${t} cannot be removed through HTML.`);let f=r.map(e=>c.get(e)?.opaque===!0?Q(`Use explicit canvas removal for opaque node ${e}.`):{op:`remove`,nodeId:e});for(let[t,n]of l){if(s.has(t))continue;let r=c.get(t);if(r===void 0)return Q(`Unknown or outside-scope identity: ${t}.`);f.push(...Pf(e,r,n))}for(let e of a.fragments){let t=c.get(e.parentNodeId);if(t===void 0||t.opaque||t.locked||t.tag!==`div`)return Q(`Node ${e.parentNodeId} cannot contain new HTML.`)}return{root:o,operations:f,removed:d,fragments:a.fragments}},If=(e,t,n)=>{let r=u(e.snapshotToken,t);S(t,n,[r.rootNodeId]);let i=Kd(n,r.rootNodeId);if(Tt({reference:t,version:r.version,rootNodeId:r.rootNodeId,html:i.html})!==e.snapshotToken)throw new x(`CONFLICT`,`The editable snapshot no longer matches the complete source.`,`Read the requested subtree again and deliberately reapply the intended change.`,{outcome:`not_committed`});return Ff(n,r.rootNodeId,e.html,e.removeNodeIds)},Lf=async(e,t,n)=>{let r=If(t,n.reference,n.scene);if(r.fragments.length===0)return wf(n.scene,r);let i=await gu(e,{canvasId:n.reference.canvasId,expectedVersion:n.version,scope:{nodeIds:[...n.reference.nodeIds],...n.reference.pageId!==void 0&&{pageId:n.reference.pageId}},request:{kind:`compile-html`,fragments:[...r.fragments],contextOperations:r.operations.filter(e=>e.op!==`remove`)}},t.waitMs);return i.state===`succeeded`?wf(n.scene,r,i.result):Ml(i,{kind:`canvas-preparation`,canvasId:n.reference.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:n.fingerprint})},Rf=e=>({execute:async t=>{let n=Ze.parse(t),r=i(n.canvasRef),a=u(n.snapshotToken,r),s=o({operation:`canvas.updateHtml/1`,snapshotToken:n.snapshotToken,html:n.html,removeNodeIds:n.removeNodeIds});return hf(e).execute({reference:r,baseVersion:a.version,clientToken:n.clientToken,fingerprint:s,plan:async t=>Lf(e,n,{reference:r,scene:t,fingerprint:s,version:a.version})})}}),zf=(e,t,n)=>({"canvas.arrange":async()=>{let{changes:r,...i}=_.parse(t);return yu(e).execute({...i,clientToken:n,request:{kind:`arrange`,changes:r}})},"canvas.duplicateNodes":async()=>{let{nodeIds:r,destination:i,...a}=le.parse(t);return yu(e).execute({...a,clientToken:n,request:{kind:`duplicate`,nodeIds:r,destination:i}})},"canvas.find":async()=>pu(e).execute(He.parse(t)),"canvas.remove":async()=>_f(e).execute({...Ue.parse(t),clientToken:n}),"canvas.read":async()=>{let n=ee.safeParse(t);return n.success?el(e,n.data):pf(e).execute(Je.parse(t))},"canvas.updateHtml":async()=>Rf(e).execute({...Ct.parse(t),clientToken:n})}),Bf=(e,t)=>{let n=i(e.canvasRef),r=n.nodeIds;if(e.target.kind===`content`&&r.length>1)throw new x(`BAD_REQUEST`,`Choose an explicit node within this selection.`,`Render the selected screens separately; do not broaden to the whole canvas.`);let a=e.target.kind===`content`?r[0]===void 0?n.pageId===void 0?e.target:{kind:`page`,pageId:n.pageId}:{kind:`node`,nodeId:r[0]}:e.target;return{canvasId:n.canvasId,expectedVersion:e.expectedVersion,target:a,sourceState:e.sourceState,scale:e.scale,scope:{nodeIds:r,...n.pageId!==void 0&&{pageId:n.pageId}},outputPath:null,overwrite:!1,timeoutMs:e.waitMs,timeoutOutcome:`pending`,retryClientToken:t}},Vf=(e,t)=>{let n=et.shape.operation.safeParse({kind:`canvas-render`,canvasId:t.input.canvasId,jobId:e instanceof x?e.fields?.jobId:void 0}),r=_t.extract([`failed`,`cancelled`,`expired`]).safeParse(e instanceof x?e.fields?.renderState:void 0);return{...n.success&&{operation:n.data},state:r.success?r.data:`not_confirmed`,error:e instanceof x?{code:e.code,message:e.message,remediation:e.remediation,...e.fields!==void 0&&{fields:e.fields}}:{code:`INTERNAL`,message:`This render outcome could not be confirmed.`,remediation:`Retry the identical batch and clientToken to recover its native render jobs.`}}},Hf=(e,t)=>e.targets.map(({id:n,maxOutputPixels:r,...i})=>{let a=t.get(n);if(a===void 0)throw TypeError(`A batch target has no native render request key.`);return{id:n,maxOutputPixels:r,input:Bf({...e,...i},a)}}),Uf=async(e,t)=>{try{let n=await e.execute({...t.input,maxOutputPixels:t.maxOutputPixels}),r=rt.safeParse(n);if(!r.success)return et.parse(n);let i=r.data.width*r.data.height;if(!Number.isSafeInteger(i)||i<=0||t.maxOutputPixels!==void 0&&i>t.maxOutputPixels)throw new x(`INTERNAL`,`The render exceeded its allocated pixel budget.`,`Update the API and renderer together, then retry.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});return r.data}catch(e){return Vf(e,t)}},Wf=e=>({execute:async(t,n)=>{let r=ye.parse(t),i=Hf(r,n),a=[],o=0;for(let t of i){let n=await Uf(e,t);`jobId`in n&&(o+=n.width*n.height),a.push({id:t.id,target:t.input.target,...t.maxOutputPixels!==void 0&&{maxOutputPixels:t.maxOutputPixels},outcome:n})}let s=i[0];if(s===void 0)throw TypeError(`A render batch requires at least one target.`);return{kind:`canvas-render-batch`,canvasId:s.input.canvasId,requestedVersion:r.expectedVersion,complete:a.every(e=>`jobId`in e.outcome),renderedPixels:o,results:a,next:[`Inspect each delivered image alongside its target id. Collect pending images with operation_status and includeImage true. Retry uncertain outcomes with the identical batch and clientToken.`]}}}),Gf=e=>bi(e.remote,nl(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Kf=async(e,t,n)=>{let r=ye.safeParse(t);if(r.success){e.mutationKey.select(n,!0);let t=new Map(r.data.targets.map(t=>[t.id,e.mutationKey.current(`canvas.render.create`,{batch:{canvasRef:r.data.canvasRef,expectedVersion:r.data.expectedVersion,targets:r.data.targets},targetId:t.id})])),i=Gf(e);return Wf({execute:async t=>(e.mutationKey.select(t.retryClientToken,!1),i.execute(t))}).execute(r.data,t)}let i=vt.safeParse(t);if(i.success)return Gf(e).execute(Bf(i.data,n));let a=oe.parse(t);return Gf(e).execute({...a,retryClientToken:n})},qf=e=>({render:Gf(e),execute:async(t,n)=>Kf(e,t,n)}),Jf=new Date(`1980-01-01T00:00:00.000Z`),Yf=33188,Xf=(e,t)=>new x(`BAD_REQUEST`,e,t),Zf=(e,t)=>{let n=E(`sha256`),r=0;return new mn({transform:(e,t,i)=>{r+=e.byteLength,n.update(e),i(null,e)},flush:i=>{if(r!==e.bytes){i(Error(`prototype file ${e.path} changed while it was packaged`));return}try{t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}catch(e){i(e instanceof Error?e:Error(`prototype manifest failed`))}}})},Qf=e=>{let t=gt.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),n=Buffer.from(JSON.stringify(t),`utf8`);if(e.limits.manifestBytes!==void 0&&n.byteLength>e.limits.manifestBytes)throw Xf(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,ke,{mtime:Jf,mode:Yf,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},$f=(e,t,n)=>{let{source:r,content:i}=t,a={mtime:Jf,mode:Yf,compress:i===null,forceDosTimestamp:!0};if(i===null){e.addReadStreamLazy(r.path,{...a,size:r.bytes},t=>{let i=Bt(r.absolutePath),a=Zf(r,n);i.on(`error`,e=>a.destroy(e)),a.on(`error`,t=>e.emit(`error`,t)),a.on(`close`,()=>i.destroy()),t(null,i.pipe(a))});return}if(i.byteLength!==r.bytes)throw Error(`prototype file ${r.path} changed while it was packaged`);e.addBuffer(i,r.path,a),n({path:r.path,contentType:r.contentType,bytes:i.byteLength,sha256:E(`sha256`).update(i).digest(`hex`)})},ep=(e,t,n)=>{let r=[];for(let i of t)i!==null&&($f(e,i,n),r.push(i.source));return r},tp=async(e,t,n)=>{let r=[];for(let i=0;i<t.files.length;i+=32){let a=await Promise.all(t.files.slice(i,i+32).map(async e=>{try{let t=e.bytes<=128?await Qt(e.absolutePath):null;if(t===null&&await qt(e.absolutePath,zt.R_OK),t!==null&&t.byteLength!==e.bytes)throw Error(`prototype file ${e.path} changed while it was packaged`);return{source:e,content:t}}catch(n){if(e.path===t.entryPath)throw n;return null}}));r.push(...ep(e,a,n))}return r},np=async e=>{let t=new gn,n=E(`sha256`),r=new mn({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=hn(t.outputStream,r,Vt(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=null,c=()=>{s!==null&&a.manifest===null&&i.size===s.length&&(a.manifest=Qf({zip:t,completed:i,...e,files:s}))},l=e=>{i.set(e.path,e),c()};try{s=await tp(t,e,l),c()}catch(e){r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)),await o}if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let u=await nn(e.artifactPath);if(u.size>e.limits.artifactBytes)throw Xf(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:u.size,sha256:n.digest(`hex`),unavailableFileCount:e.files.length-i.size}},rp={".avif":`image/avif`,".css":`text/css; charset=utf-8`,".gif":`image/gif`,".html":`text/html; charset=utf-8`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".mp3":`audio/mpeg`,".mp4":`video/mp4`,".ogg":`audio/ogg`,".otf":`font/otf`,".png":`image/png`,".svg":`image/svg+xml`,".ttf":`font/ttf`,".txt":`text/plain; charset=utf-8`,".wasm":`application/wasm`,".webm":`video/webm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`,".xml":`application/xml`},ip=e=>rp[T.extname(e).toLowerCase()]??`application/octet-stream`,ap=async e=>{try{return await nn(e)}catch{return null}},op=e=>Buffer.byteLength(e,`utf8`),$=(e,t)=>new x(`BAD_REQUEST`,e,t),sp=(e,t)=>{if(!b.safeParse(e).success)throw $(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(op(e)>t.pathBytes)throw $(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},cp=async(e,t,n,r)=>{let{limits:i,unavailable:a}=r,o=await $t(t);if(n.has(o))return a(),[];let s=new Set(n).add(o),{readdir:c}=await import(`node:fs/promises`),l=await c(t,{withFileTypes:!0}),u=[],d=l.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of d){let o=T.join(t,n.name),c=await ap(o);if(c?.isDirectory()===!0){try{u.push(...await cp(e,o,s,r))}catch{a()}continue}if(c?.isFile()!==!0){a();continue}let l=T.relative(e,o).split(T.sep).join(`/`).normalize(`NFC`);sp(l,i),u.push({absolutePath:o,path:l,bytes:Number(c.size),contentType:ip(o)})}return u},lp=(e,t,n)=>{if(e.length===0)throw $(`The prototype build is empty.`,`Build the app before publishing it.`);if(n.fileCount!==void 0&&e.length>n.fileCount)throw $(`The prototype has ${String(e.length)} files.`,`This environment currently accepts ${String(n.fileCount)} files per deployment.`);let r=new Set,i=0;for(let t of e){let e=Me(t.path);if(r.has(e))throw $(`The prototype path ${t.path} collides by case or Unicode normalization.`,`Rename one of the colliding files so the build is portable.`);if(r.add(e),t.bytes>n.fileBytes)throw $(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,n.expandedBytes!==void 0&&i>n.expandedBytes)throw $(`The prototype build is too large.`,`This environment accepts ${String(n.expandedBytes)} expanded bytes.`)}let a=e.find(e=>e.path===t);if(a===void 0)throw $(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw $(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},up=(e,t)=>{try{fn.mark(`enhance.prototype.packaging`,{detail:{fileCount:e,unavailableFileCount:t}})}catch{}},dp=async e=>{let t=T.resolve(e.directory),n=await ap(t);if(n===null)throw new x(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!n.isDirectory())throw $(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let r=e.entryPath.split(T.sep).join(`/`).normalize(`NFC`);sp(r,e.limits);let i=0,a=await cp(t,t,new Set,{limits:e.limits,unavailable:()=>{i+=1}});lp(a,r,e.limits);let o=await Xt(T.join(Ft(),`enhance-prototype-artifact-`)),s=T.join(o,`artifact.zip`);try{let t=await np({artifactPath:s,files:a,entryPath:r,limits:e.limits});return i+=t.unavailableFileCount,up(t.manifest.files.length,i),{identity:{protocolVersion:1,format:`zip`,bytes:t.bytes,sha256:t.sha256,fileCount:t.manifest.files.length,expandedBytes:t.manifest.files.reduce((e,t)=>e+t.bytes,0)},manifest:t.manifest,open:()=>Bt(s),dispose:async()=>tn(o,{recursive:!0})}}catch(e){throw await tn(o,{recursive:!0}),e}},fp=e=>({package:async t=>{if(e===void 0)throw $(`No build directory was selected.`,`Select a build before publishing.`);return dp({...t,directory:e})}}),pp=async(e,t)=>{let n=Ae.parse(t);return Ni(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},mp=async(e,t)=>{let n=mt.parse(t);return $c(e.remote,qf(e).render).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},hp=async(e,t,n)=>{let r=jt.parse(t),a=i(r.canvasRef);return $c(e.remote,qf(e).render).execute({canvasId:a.canvasId,pageId:a.pageId,selectionNodeIds:a.nodeIds,targetNodeId:r.destination.parentNodeId,mode:`insert-children`,html:r.html,baseVersion:r.baseVersion,revisionPolicy:`strict`,responseMode:`bounded`,review:`none`,renderClientToken:n,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:r.waitMs})},gp=async(e,t)=>{let n=ie.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},_p=async(e,t,n)=>{let r=Fe.parse(t);return jl(e.remote,fp(r.directory)).execute({...r,clientToken:n})},vp=async(e,t,n)=>{let r=Ne.parse(t);return au(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},yp=async(e,t)=>{let n=Re.parse(t);return Jl(e.remote).execute(n)},bp=async(e,t)=>{let n=l.parse(t),r=i(n.canvas);return Pc(e.remote).execute({...r,baseVersion:n.baseVersion,edits:n.edits,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},xp=async(e,n)=>Gl(e.remote,nl(e.configDirectory)).execute(t.parse(n)),Sp=async(e,t,n,r)=>{let i={...zf(e.remote,n,r),"canvas.importAsset":async()=>{let t=de.parse(n);return ol(e.remote,lu(t.source.path)).execute({canvasRef:t.canvasRef,clientToken:r})},"operation.status":async()=>xp(e,n),"canvas.edit":async()=>bp(e,n),"canvas.apply":async()=>pp(e,n),"canvas.render":async()=>qf(e).execute(n,r),"canvas.writeHtml":async()=>mp(e,n),"canvas.insertHtml":async()=>hp(e,n,r),"canvas.capture":async()=>ru(e.remote,n,r),"canvas.makeEditable":async()=>Kc(e.remote,n),"comment.attention":async()=>gp(e,n),"prototype.publishCanvas":async()=>{let t=We.parse(n);return El(e.remote,fp(t.source.kind===`directory`?t.source.directory:void 0)).execute({...t,source:t.source.kind===`directory`?{...t.source,kind:`build`}:t.source,clientToken:r})},"prototype.publish":async()=>_p(e,n,r),"recording.snapshot":async()=>vp(e,n,r),"transcript.read":async()=>yp(e,n)}[t];if(i===void 0)throw TypeError(`${t} has no composite execution`);return i()},Cp=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??Gt();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Sp(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),wp=`/callback`,Tp=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),Ep=e=>{let t=C.platform===`darwin`?{executable:`open`,arguments:[e]}:C.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=yn(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Dp=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==wp){n.writeHead(404).end();return}if(r.searchParams.get(`state`)!==e.state){n.writeHead(400).end(`The OAuth state did not match. Return to the terminal and retry.`);return}let i=r.searchParams.get(`error`),a=r.searchParams.get(`code`);if(i!==null||a===null||a===``){n.writeHead(400).end(`Enhance authentication was not approved.`),e.completion.reject(Error(i??`the authorization response carried no code`));return}n.writeHead(200,{"content-type":`text/html; charset=utf-8`}).end(`<!doctype html><meta charset="utf-8"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>`),e.completion.resolve(a)},Op=e=>{let t=Tp(e.issuer,`oauth/authorize`);return t.search=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,code_challenge:e.challenge,code_challenge_method:`S256`}).toString(),t.href},kp=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=bn((n,r)=>{Dp({state:e.state,completion:t},n,r)});await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,e)});let r=n.address();if(r===null||typeof r==`string`)throw n.close(),Error(`the OAuth callback listener has no TCP port`);let i=`http://127.0.0.1:${String(r.port)}${wp}`,a=Op({...e,redirectUri:i}),o=()=>{t.reject(Error(`browser authorization cancelled`))};e.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return e.signal?.throwIfAborted(),e.onReady(a),e.openBrowser&&Ep(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},Ap=e=>({authorize:async t=>{try{let n=Wt(32).toString(`base64url`),r=E(`sha256`).update(n).digest(`base64url`),i=Wt(32).toString(`base64url`),a=await kp({...t,challenge:r,state:i});return await e.exchangeOauthCode({issuer:t.issuer,clientId:t.clientId,code:a.code,redirectUri:a.redirectUri,verifier:n})}catch(e){throw new x(`UNAUTHORIZED`,e instanceof Error?`Browser authentication failed: ${e.message}.`:`Browser authentication failed.`,`Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.`)}}}),jp={apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`},Mp=e=>URL.canParse(e)?new URL(e).href.replace(/\/+$/u,``):e,Np=(e,t,n,r)=>{let i=URL.canParse(e)?new URL(e).origin:null,a=T.resolve(t),o=jp;if(i===new URL(o.apiUrl).origin&&a===T.resolve(n,`.config`,r.configDirectoryName)||i===new URL(r.apiUrl).origin&&a===T.resolve(n,`.config`,o.configDirectoryName))throw TypeError(`Enhance cannot share credentials between production and development. Use Enhance Development (enhance-dev-mcp) with ~/.config/enhance-development, then reconnect production separately.`)},Pp=e=>e===void 0||e===``?void 0:e,Fp=(e,t,n)=>{let r=Pp(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Pp(e.ENHANCE3_API_URL),a=T.join(t,`.config`,n.configDirectoryName),o=Pp(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&Mp(i)!==Mp(n.apiUrl))throw TypeError(`Enhance development cannot use this API. Use the bundled development endpoint.`);if(o!==void 0&&T.resolve(o)!==T.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}else Np(i??n.apiUrl,o??a,t,n);return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}},Ip=()=>Fp(C.env,Pt(),jp),Lp=()=>{let e=w.enum([`legacy`,`canvas`]).default(`legacy`).parse(C.env.ENHANCE_MCP_PROFILE),t=w.enum([`true`,`false`]).default(`false`).parse(C.env.ENHANCE_MCP_READ_ONLY)===`true`;if(t&&e!==`canvas`)throw Error(`ENHANCE_MCP_READ_ONLY requires the canvas profile.`);return{...Ip(),profile:e,isReadOnly:t,workflowsDirectory:C.env.ENHANCE_WORKFLOWS_DIR}},Rp=w.object({token:w.string().startsWith(`enh_`)}),zp=e=>{let t=T.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Qt(t,`utf8`));return Rp.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Yt(e,{recursive:!0,mode:448}),await Jt(e,448);let r=T.join(e,`credentials.${String(C.pid)}.tmp`);await an(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await en(r,t),await Jt(t,384)},remove:async()=>{try{return await rn(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},Bp={path:`direct_cli`},Vp=w.object({access_token:w.string().min(1)}),Hp=w.object({code:w.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),Up=`Check network access and proxy settings for this API, then run enhance doctor again.`,Wp=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,Gp=e=>{let t=Hp.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?Gp(e.cause):e instanceof Error?e.name:`Network request failed`},Kp=(e,t)=>new x(`INTERNAL`,`${Wp(e)} answered HTTP ${String(t)}.`,Up),qp=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new x(`INTERNAL`,`Could not reach ${Wp(e)}: ${Gp(t)}.`,Up)}},Jp=async(e,t)=>{let n=await qp(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw Kp(e,n.status);return n},Yp=(e,t,n=null,r=Bp)=>_n({links:[vn({url:`${e}/trpc`,fetch:async(e,t)=>Jp(e,{...t,signal:t?.signal??null}),headers:{[_e]:JSON.stringify(r),...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),Xp=async e=>{try{return await e()}catch(e){throw Ye(e)}},Zp=async e=>{let t=await fetch(e);if(!t.ok)throw new x(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},Qp=async e=>{let t=await qp(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new x(`BAD_REQUEST`,`This Enhance API does not support browser authentication.`,`Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.`):new x(`INTERNAL`,`${Wp(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,Up);return t.json()},$p=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await qp(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw Kp(e,n.status);return n.json()},em=async e=>{let t=await qp(new URL(`oauth/token`,e.issuer.endsWith(`/`)?e.issuer:`${e.issuer}/`),{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,client_id:e.clientId,code:e.code,redirect_uri:e.redirectUri,code_verifier:e.verifier})});if(!t.ok)throw new x(`INTERNAL`,`${Wp(e.issuer)} token exchange answered HTTP ${String(t.status)}`,Up);return Vp.parse(await t.json()).access_token},tm=async e=>{try{let t=await qp(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:Kp(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Wp(e)}.`}}},nm=async e=>{let t=!(e.body instanceof Uint8Array),n=t?pn.toWeb(e.body):e.body,r={method:`PUT`,headers:e.headers,body:n,...t&&{duplex:`half`}},i=await fetch(e.url,r);if(!i.ok)throw new x(`INTERNAL`,`Signed upload answered HTTP ${String(i.status)}.`,`Retry the fixture command with the same source file.`);let a=i.headers.get(`etag`);if(a===null||a===``)throw new x(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},rm=(e,t,n,r=Bp)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>Qp(i),oauthMetadata:$p,exchangeOauthCode:em,query:async(e,n,a)=>Xp(async()=>Yp(i,await t.read(),null,r).query(e,n,a)),queryWithToken:async(e,t,n)=>Xp(async()=>Yp(i,n,null,r).query(e,t)),mutate:async(e,a)=>Xp(async()=>Yp(i,await t.read(),n.current(e,a),r).mutation(e,a)),mutateWithToken:async(e,t,n)=>Xp(async()=>Yp(i,n,null,r).mutation(e,t)),download:Zp,upload:nm,health:async()=>tm(i)}},im=e=>Array.isArray(e)?e.map(e=>im(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,im(t)])),am=(e,t,n)=>E(`sha256`).update(`${e}\0${t}\0${JSON.stringify(im(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),om=()=>{let e=Gt(),t=!1;return{current:(n,r)=>t?am(e,n,r):e,select:(n,r)=>{e=n??Gt(),t=r}}};export{Pr as C,xn as E,Lr as S,D as T,wi as _,Lp as a,ti as b,nl as c,G as d,Fc as f,Ni as g,Pi as h,Ip as i,el as l,Ac as m,rm as n,Ap as o,Pc as p,zp as r,Cp as s,om as t,$c as u,bi as v,Nn as w,Xr as x,ii as y};