@enhance-eng/enhance-dev 0.1.41-dev.sha-9bd1f7fdd251 → 0.1.41-dev.sha-8645e9fc82bb

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,B as a,Bn as o,C as s,Cn as c,Cr as l,Ct as u,D as d,Dn as f,Dr as p,E as m,En as h,Er as g,Et as _,F as ee,G as te,Gn as v,Gt as ne,Hn as re,Ht as ie,In as ae,J as oe,Jn as se,Jt as ce,K as le,Kn as ue,Kt as de,Ln as fe,M as pe,Mn as me,Mt as y,Nt as he,On as ge,Or as _e,P as ve,Pn as ye,Pr as be,Q as xe,Qt as Se,R as Ce,Rn as we,Sn as Te,Sr as Ee,T as De,Tn as Oe,Tr as ke,Tt as b,Ut as Ae,Vt as je,W as Me,Wn as Ne,Wt as Pe,X as Fe,Xt as Ie,Y as Le,Yn as Re,Yt as ze,Z as Be,Zn as Ve,Zt as He,_r as x,_t as Ue,at as We,b as Ge,bn as Ke,br as qe,cr as Je,ct as Ye,d as Xe,dr as Ze,dt as Qe,en as $e,er as et,et as tt,ft as nt,gt as rt,it,jn as at,jr as ot,jt as st,kr as ct,kt as lt,lr as ut,mr as dt,or as ft,pr as pt,pt as mt,q as ht,qn as gt,qt as _t,rr as vt,rt as yt,sr as bt,st as xt,tr as St,ur as Ct,ut as wt,vr as Tt,w as Et,wr as Dt,xn as Ot,xr as kt,xt as At,yr as jt,yt as Mt,zn as Nt,zt as Pt}from"./cli-output-identity.lib-jw8VjWoI.mjs";import S from"node:process";import{z as C}from"zod";import{homedir as Ft,tmpdir as It}from"node:os";import{generateKeyBetween as Lt,generateNKeysBetween as Rt}from"fractional-indexing";import{chmodSync as zt,constants as Bt,createReadStream as Vt,createWriteStream as Ht,mkdirSync as Ut,writeFileSync as Wt}from"node:fs";import w from"node:path";import{createHash as T,randomBytes as Gt,randomUUID as Kt}from"node:crypto";import{setTimeout as qt}from"node:timers/promises";import{isDeepStrictEqual as Jt}from"node:util";import{access as Yt,chmod as Xt,mkdir as Zt,mkdtemp as Qt,open as $t,readFile as en,realpath as tn,rename as nn,rm as rn,stat as an,unlink as on,writeFile as sn}from"node:fs/promises";import{generate as cn,parse as ln}from"css-tree";import{parseFragment as un,serialize as dn,serializeOuter as fn}from"parse5";import{performance as pn}from"node:perf_hooks";import{Readable as mn,Transform as hn}from"node:stream";import{pipeline as gn}from"node:stream/promises";import{ZipFile as _n}from"yazl";import{createTRPCUntypedClient as vn,httpLink as yn}from"@trpc/client";import{spawn as bn}from"node:child_process";import{createServer as xn}from"node:http";const Sn=(e,t)=>e<t?-1:+(e>t),Cn=(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)??[])]},wn=(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:Cn(a,t.order)}},Tn=(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=wn(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}}},En=1e6,Dn=e=>Math.round(e*255*En)/En,E=(e,t=1)=>{let n=e.alpha*t;if(e.space===`srgb`){let t=[e.red,e.green,e.blue].map(e=>String(Dn(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)})`},On={x:0,y:0,width:1,height:1},kn=(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}},An=(e,t=On)=>[{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=kn(e,t);return[n.x,n.y]}),jn=1024,Mn=(e,t,n)=>{let r=e.stops.map(t=>`${n?`rgb(255 255 255 / ${String(t.color.alpha*e.opacity)})`:E({...t.color,alpha:1})} ${String(t.position*360)}deg`);return`conic-gradient(from 90deg at ${String(t)}% ${String(t)}% in srgb, ${r.join(`, `)})`},Nn=(e,t)=>{let n=An(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/jn:e),s=`width:100%;height:100%;background-image:${Mn(e,a,!1)};mask-image:${Mn(e,a,!0)};`;return`<g transform="matrix(${o.map(String).join(` `)})"><foreignObject x="${String(r*jn)}" y="${String(r*jn)}" width="${String(i*jn)}" height="${String(i*jn)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${s}"></div></foreignObject></g>`},Pn=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Nn(e)}</svg>`,Fn=(e,t)=>e===void 0||t===void 0?!1:e.x===t.x&&e.y===t.y,In=e=>{let t=[...e];for(;t.length>1&&Fn(t[0],t.at(-1));)t.pop();for(;t.length>1&&Fn(t[0],t[1]);)t.splice(1,1);return t},Ln=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},Rn=(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},zn=e=>{let t=Ln(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=Rn(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?In(n):null},Bn=Math.PI/2,Vn=1e6,Hn=e=>String(Math.round(e*Vn)/Vn),D=([e,t])=>`${Hn(e)} ${Hn(t)}`,Un=(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}},Wn=(e,t)=>{let{radius:n,reach:r,smoothing:i}=e,a=D(t([r,0]));if(n===0)return`L${a}`;let o=i*Bn/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=D(t([r-2*u,0])),f=D(t([s+l,0])),p=D(t([s,c])),m=D(t([c,s])),h=D(t([0,s+l])),g=D(t([0,r-2*u])),_=D(t([0,r]));return`L${a}C${d} ${f} ${p}${i===1?``:`A${Hn(n)} ${Hn(n)} 0 0 1 ${m}`}C${h} ${g} ${_}`},Gn=(e,t)=>{let{topLeft:n,topRight:r,bottomRight:i,bottomLeft:a,smoothing:o=0}=e;return[Un(n,[r,a],t,o),Un(r,[n,i],t,o),Un(i,[a,r],t,o),Un(a,[i,n],t,o)]},Kn=(e,t)=>{let[n,r,i,a]=Gn(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}},qn=(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]=Gn(e,{width:r,height:i});return[`M${D([n[0],a.reach+n[1]])}`,Wn(a,([e,t])=>[t+n[0],e+n[1]]),Wn(o,([e,t])=>[r-e+n[0],t+n[1]]),Wn(s,([e,t])=>[r-t+n[0],i-e+n[1]]),Wn(c,([e,t])=>[e+n[0],i-t+n[1]]),`Z`].join(``)},Jn=1e5,Yn=.01,Xn=1e-9,O=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],Zn=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Qn=(e,t)=>e[0]*t[1]-e[1]*t[0],k=(e,t)=>[e[0]-t[0],e[1]-t[1]],$n=e=>String(Math.round(e*Jn)/Jn),er=(e,t,n=0)=>{let[r,i,a,o]=e,s=Zn(r,o);if(n>=16||Zn(r,i)+Zn(i,a)+Zn(a,o)-s<=Yn/8){t.push(o);return}let c=O(r,i),l=O(i,a),u=O(a,o),d=O(c,l),f=O(l,u),p=O(d,f);er([r,c,d,p],t,n+1),er([p,f,u,o],t,n+1)},tr=(e,t,n,r)=>{let i=k(t,e),a=Zn(e,t);if(a<Xn)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-Yn/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)])}},nr=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`){er([t,a(),a(),a()],n);return}if(e===`A`){let e=i();r+=4,tr(t,a(),e,n)}};for(;r<t.length;)o(t[r++]??`Z`);return n.filter((e,t)=>Zn(e,n[(t+1)%n.length]??e)>Xn)},rr=(e,t,n)=>{let[r,i]=k(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]]]},ir=(e,t,n,r)=>{let i=k(t,e),a=k(r,n),o=Qn(i,a);if(Math.abs(o)<Xn)return O(t,n);let s=Qn(k(n,e),a)/o;return[e[0]+s*i[0],e[1]+s*i[1]]},ar=(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]=rr(i,a,t),c=k(s,o),l=[];for(let[e,t]of n.entries()){let r=n[(e+1)%n.length]??t,i=Qn(c,k(t,o))>=-1e-9,a=Qn(c,k(r,o))>=-1e-9;i&&l.push(t),i!==a&&l.push(ir(t,r,o,s))}if(n=l,n.length===0)break}return n},or=(e,t)=>{if(t===0)return e;let n=nr(e),r=t<0?ar(n,t):n.map((e,r)=>{let i=n[(r+n.length-1)%n.length]??e,a=n[(r+1)%n.length]??e,o=rr(i,e,t),s=rr(e,a,t);return ir(...o,...s)});return r.length<3?``:r.map((e,t)=>`${t===0?`M`:`L`}${$n(e[0])} ${$n(e[1])}`).join(``)+`Z`},sr=(e,t,n)=>t.width<=0||t.height<=0?``:or(qn(e,t),n),cr=(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*_}},lr=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}},ur=e=>{let t=lr(e);return t===null||e.box===void 0?null:cr(e.box,e.layout??{},t)},A=(e,t,n)=>({x:e.x+t.x*n,y:e.y+t.y*n}),dr=e=>`${String(e.x)} ${String(e.y)}`,fr=(e,t,n)=>({x:(t.x-e.x)/n,y:(t.y-e.y)/n}),pr=(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}})},mr=(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=fr(n,r,a),c=fr(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)}},hr=(e,t,n,r)=>{let i=n*e.cotangent,a=A(e.vertex,t,i*(1+r)),o=A(e.vertex,t,i),s=A(e.vertex,{x:e.before.x+e.after.x,y:e.before.y+e.after.y},n/Math.sin(e.angle)),c=fr(o,s,n),l=(Math.PI-e.angle)*r/2,u=A(A(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=A(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}},gr=(e,t,n)=>{let r=hr(e,e.before,t,n),i=hr(e,e.after,t,n),a=4/3*t*Math.tan((Math.PI-e.angle)*(1-n)/4),o=A(r.end,r.travel,a),s=A(i.end,i.travel,a),c=(e,t,n)=>`C${dr(e)} ${dr(t)} ${dr(n)}`;return dr(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):``)},_r=(e,t,n)=>{let r=e.map((t,n)=>mr(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+dr(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+gr(o,m,h)}).join(``)}Z`},vr=(e,t,n)=>_r(pr(e,t,n),e.cornerRadius,e.cornerSmoothing),yr=new WeakMap,br=new WeakMap,xr=e=>{if(br.has(e))return br.get(e)??null;let t=e.result.path.match(/M[^M]*/gu)??[],n=t.map(e=>{let t=zn(e);return{path:e,vertices:t!==null&&t.length>=3?t:null}}),r=t.length>0&&t.join(``)===e.result.path?n:null;return br.set(e,r),r},Sr=(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=xr(e);return i===null?r:{...r,path:i.map(e=>e.vertices===null?e.path:_r(e.vertices,n.topLeft,n.smoothing??0)).join(``)}},Cr=e=>{if(yr.has(e))return yr.get(e)??null;let t=zn(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 yr.set(e,n),n},wr=(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=Cr(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:_r(a,r,t.smoothing??0),viewBox:{x:0,y:0,width:n.width,height:n.height}}},Tr={topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},Er=[`border-top-left-radius`,`border-top-right-radius`,`border-bottom-right-radius`,`border-bottom-left-radius`],Dr=(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},Or=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]=Er.map(n=>Dr(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}},kr=(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`},Ar=(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:vr(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=Or(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&&Er.every(t=>e.styles[t]===void 0)?kr(n.width,n.height):qn(t&&e.component===`rectangle`&&e.appearance?.radius!==void 0?Tr:{...Tr,...r},n),viewBox:{x:0,y:0,width:n.width,height:n.height}}},jr=e=>{if(e.geometry?.kind===`boolean`&&e.box!==void 0)return e.geometry.result.isEmpty?`This shape has no closed geometry.`:Sr(e.geometry,e.box,e.appearance?.radius);let t=Ar(e,!1);return typeof t!=`string`&&e.geometry?.kind===`path`&&e.component===`rectangle`&&e.appearance?.radius!==void 0&&e.box!==void 0?wr(t,e.appearance.radius,e.box):t},Mr=e=>{let t=jr(e);if(typeof t==`string`)return t;if(e.box===void 0)return`The shape has no settled local box.`;let n=ur(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]}},Nr=.5,Pr=.25,Fr=(e,t=`field`,n)=>{let r=An(e,n),i=Math.max(Nr,...r.map(e=>Math.abs(e-Nr)))+1,a=Nr-i,o=Nr+i,s=[{x:.75,y:.75,points:`.5,.5 ${String(o)},.5 ${String(o)},${String(o)} .5,${String(o)}`},{x:Pr,y:.75,points:`.5,.5 .5,${String(o)} ${String(a)},${String(o)} ${String(a)},.5`},{x:Pr,y:Pr,points:`.5,.5 ${String(a)},.5 ${String(a)},${String(a)} .5,${String(a)}`},{x:.75,y:Pr,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="${E({...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>`},Ir=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Fr(e)}</svg>`,Lr=e=>e.parameter===`radius`?e.value/2:e.value,Rr=e=>{switch(e.kind){case`blur`:return`blur(${String(Lr(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)`}},zr=e=>e.filter(e=>e.visible).map(e=>Rr(e)).join(` `),Br=new Set([`base`,`embed`,`iframe`,`link`,`meta`,`object`,`script`]),Vr=/^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu,Hr=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,Ur=e=>!Br.has(e.toLowerCase()),Wr=e=>!Hr.test(e),Gr=(e,t)=>{let n=e.toLowerCase();return n===`srcdoc`||/^on/iu.test(n)?!1:n===`style`?Wr(t):![`href`,`src`,`action`,`formaction`,`xlink:href`].includes(n)||!Vr.test(t.replaceAll(/[\p{Control}\s]/gu,``))},Kr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),qr=(e,t)=>{if(!Kr(e)||e.kind!==`image`||typeof e.assetId!=`string`)return e;let n=t(e.assetId);return n===e.assetId?e:{...e,assetId:n}},j=(e,t)=>{let n=qr(e,t);if(!Kr(n)||!Kr(n.alternatives))return n;let r=n.alternatives,i=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,qr(n,t)]));return Object.entries(i).every(([e,t])=>r[e]===t)?n:{...n,alternatives:i}},Jr=(e,t)=>Array.isArray(e)?e.map(e=>{if(!Kr(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=>j(e,t))},...Kr(e.stroke)&&{stroke:{...e.stroke,paint:j(e.stroke.paint,t)}},...Array.isArray(e.children)&&{children:Jr(e.children,t)}}}):e,Yr=(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=>j(e,t))},...n.border!==void 0&&{border:{...n.border,paints:n.border.paints.map(e=>j(e,t))}},...n.outline!==void 0&&{outline:{...n.outline,paints:n.outline.paints.map(e=>j(e,t))}}}},...e.typography?.stroke!==void 0&&{typography:{...e.typography,stroke:{...e.typography.stroke,paint:j(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:Jr(e.props.richText,t)}}}}},Xr=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${E({...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>`},Zr=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${Xr(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,Qr=e=>({id:e,visible:!1,opacity:1,kind:`solid`,color:{space:`srgb`,red:0,green:0,blue:0,alpha:0}}),$r=()=>({opacity:1,blendMode:`normal`,fills:[],border:{visible:!1,width:{top:0,right:0,bottom:0,left:0},style:`solid`,paints:[Qr(`empty-border`)]},outline:{visible:!1,width:0,offset:0,style:`solid`,paints:[Qr(`empty-outline`)]},radius:{topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},shadows:[],filters:[],backdropFilters:[]}),ei=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],ti=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${E({...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(${ei(e).map(String).join(` `)})" color-interpolation="sRGB">${r}</radialGradient>`},ni=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${ti(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,ri=/^enh_[\w-]{43}$/,ii=e=>{let t=Ie.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new y(`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}},ai=(e,t,n)=>({loginWithToken:async n=>{if(!ri.test(n))throw new y(`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=ii(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=He.parse(await t.authenticationConfig());if(i.method===`token`)throw new y(`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=Se.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=ii(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 y(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return ii(await n.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),oi=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),si=e=>{if(e.byteLength<24||oi.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)}},ci=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 y(`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 y(`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=Je.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 y(`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=si(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new y(`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}}},li=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]},ui=(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:li(e)}),di=async(e,t,n,r)=>{let i=await ci(e,n);return ui(n,t.write({body:i.body,...r}),i.source)},fi=[`canvas.render.create`,`canvas.render.get`],pi=e=>new y(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),mi=e=>{let t=e.failure;if(t===null)return pi(`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 y(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase,renderState:e.state})},hi=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),gi=async(e,t)=>{let n=ut.safeParse(await e.query(fi[1],{jobId:t}));if(!n.success||n.data.job.id!==t)throw pi(`render status`);return n.data.job},_i=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 y(`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 hi(250),a=a.purpose===`inspection`&&a.state===`queued`&&a.attempt>0?await t.resume():await gi(e,a.id)}if(a.state!==`succeeded`)throw mi(a);return a},vi=async(e,t)=>{let n=ft.safeParse(await e.mutate(fi[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 pi(`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 pi(`render identity`);return n.data.job},yi=(e,t)=>{if(t.maxOutputPixels!==void 0&&e.maxOutputPixels!==t.maxOutputPixels)throw new y(`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`})},bi=async(e,t)=>{let n=await vi(e.remote,t);try{yi(n,t);let r=await _i(e.remote,{initial:n,resume:async()=>vi(e.remote,t),deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress,timeoutOutcome:t.timeoutOutcome});return yi(r,t),r.state===`succeeded`?await di(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 y?new y(e.code,e.message,e.remediation,{...e.fields,jobId:n.id,operation:r}):new y(`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})}},xi=(e,t,n,r=()=>null)=>({execute:async i=>bi({remote:e,files:t,now:n,progress:r},i)}),Si={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},Ci=async e=>{try{return await e(),!0}catch{return!1}},wi=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await Ci(async()=>e.mutate(Si.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 Ci(async()=>e.mutate(Si.end,{canvasId:i.canvasId,activityId:n})))}}},Ti=e=>({begin:async t=>{try{let n=me.safeParse(await e.mutate(Si.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?wi(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>Ci(async()=>e.mutate(Si.end,{canvasId:t,activityId:n}))}),Ei=new Set([`insertPrototype`,`insertText`,`setBox`]),Di=e=>Ei.has(e.op),Oi=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,ki=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],Ai=e=>[...new Set(e.operations.flatMap(e=>ki(e)))].slice(0,100),ji=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:Di(e)?e.box==="default"?null:e.box:null,Mi=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}},Ni=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:15}),r=v.safeParse(n);if(!r.success)throw new y(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},M=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Ni(e,t);let r=await Ti(e).begin({canvasId:t.canvasId,phase:Oi(t),nodeIds:Ai(t),bounds:Mi(t.operations.flatMap(e=>{let t=ji(e);return t===null?[]:[t]}))});try{return await Ni(e,t)}finally{await r?.finish()}}}),Pi=async(e,t,n)=>{let r=Ve.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!r.success)throw new y(`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 y(`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=Ct.safeParse(r.data.document);if(i.success)return i.data;throw new y(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},N=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):Sn(t.sortKey,r.sortKey)).map(([e])=>e),Fi=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},Ii=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),P=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new y(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Li=(e,t)=>{let n=new Set,r=t=>{for(let i of N(e,t))n.add(i),r(i)};return r(t),n},F=(e,t)=>{let n=new Set,r=t;for(;r!==void 0;){if(n.has(r))throw new y(`BAD_REQUEST`,`The canvas contains a parent cycle.`,`Repair the canvas topology before editing.`);if(n.add(r),P(e,r).locked===!0)return!0;r=e.relationships[r]?.parentId}return!1},Ri=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},zi=e=>{let t=0;return n=>(t+=1,`${Ri(e)}_${Ri(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},Bi=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of N(e,t))r(n)};return r(t),n},Vi=(e,t,n)=>Object.fromEntries(Bi(e,t).map(t=>[t,n(P(e,t).label)])),Hi=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=P(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}}},Ui=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=P(t,n.id);if(n.id===`root`)throw new y(`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 y(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!Ii(t.nodes[s]))throw new y(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=Vi(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=Bi(t,n.id).map(e=>Hi(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))}}},Wi=(e,t,n)=>{if(t.length===0)throw new y(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=zi(n),i=t.map((t,n)=>Ui({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},Gi=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,N(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Ki=(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))}},qi=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new y(`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 y(`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}},Ji=(e,t)=>`parentId`in e?Ki(e,t):qi(e,t),Yi=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new y(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Li(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!Ii(n.document.nodes[t.parentId]))throw new y(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Xi=(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=Lt(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=Rt(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}}},Zi=(e,t)=>{if(t.length===0)throw new y(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=Gi(e),r=[];return{operations:t.flatMap(e=>{let t=Ji(e,n);Yi(e,t,n),r.push({nodeId:e.nodeId,...t});let i=Xi(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)??[]]}))}},I=e=>Math.min(1,Math.max(0,e)),Qi=e=>I(Number(e)/255),$i=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}},ea=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===`%`?I(Number(e)/100):Qi(e??`0`),r=t[7]===void 0?1:I(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}},ta=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:I(Number(t[2])),green:I(Number(t[3])),blue:I(Number(t[4])),alpha:I(t[5]===void 0?1:Number(t[5]))}},na=e=>{let t=e.trim().toLowerCase();return t===`transparent`?{space:`srgb`,red:0,green:0,blue:0,alpha:0}:t.startsWith(`#`)?$i(t):t.startsWith(`rgb`)?ea(t):t.startsWith(`color(`)?ta(t):null},ra=(e,t)=>({id:e,visible:!0,opacity:1,kind:`solid`,color:t}),L=(e,t)=>{let n=na(t);return n===null?null:ra(e,n)},ia=e=>e/2**32|0,aa=e=>e>>>0;function oa(e,t,n,r){let i=ia(n),a=aa(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function sa(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const ca=e=>e?`"${e}" `:``;function la(e,t=``){if(typeof e!=`number`)throw TypeError(ca(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ca(t)+`expected integer >= 0, got `+e);return e}function ua(e,t,n=``){if(sa(e)&&(t===void 0||e.length===t))return e;t!==void 0&&la(t,`length`);let r=sa(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ca(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const da=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)};function fa(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function pa(e,t){ua(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function ma(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ha(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function R(e,t){return e<<32-t|e>>>t}const ga=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,_a=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function va(e){if(ua(e),ga)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=_a[e[n]];return t}function ya(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function ba(e,t,n=`opts`){return da(e,`defaults`),t!==void 0&&da(t,n),Object.assign(e,t)}function xa(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=ba({},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 Sa=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ca(e,t,n){return e&t^~e&n}function wa(e,t,n){return e&t^e&n^t&n}var Ta=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=ha(this.buffer)}update(e){fa(this),ua(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=ha(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){fa(this),pa(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)),oa(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:ha(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 Ea=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Da=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]),z=new Uint32Array(64);var Oa=class extends Ta{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)z[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=z[e-15],n=z[e-2],r=R(t,7)^R(t,18)^t>>>3,i=R(n,17)^R(n,19)^n>>>10;z[e]=i+z[e-7]+r+z[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=R(o,6)^R(o,11)^R(o,25),u=l+t+Ca(o,s,c)+Da[e]+z[e]|0,d=(R(n,2)^R(n,13)^R(n,22))+wa(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(){ma(z)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ma(this.buffer)}},ka=class extends Oa{constructor(){super(32,Ea)}};const Aa=xa(()=>new ka,Sa(1)),ja=new Map,Ma=new Map,Na={depth:0},Pa=(e,t=1)=>{let n=Na.depth>0?Ma:ja;n.set(e,(n.get(e)??0)+t)},Fa=(e,t)=>e.sortKey===t.sortKey?e.childId.localeCompare(t.childId):e.sortKey<t.sortKey?-1:1,Ia=e=>{Pa(`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(Fa).map(e=>e.childId));return n},La=new WeakMap,Ra=new WeakMap,za=e=>{let t=La.get(e);if(t!==void 0)return t;let n=Ra.get(e)?.()??Ia(e);return Object.isFrozen(e)&&La.set(e,n),n},Ba=[],Va=(e,t)=>e.get(t)??Ba,Ha=(e,t)=>Va(za(e),t),Ua=e=>e.trim()===``||e.trim()===`about:blank`,Wa=e=>typeof e==`string`&&e.startsWith(`enhance-pending-image:`),Ga=e=>Wa(e.assetId)||e.opacity!==1||e.fit===`crop`&&e.transform!==void 0||(e.rotation??0)!==0||e.fit===`tile`&&(e.tileScale??1)!==1,Ka=e=>`--canvas-image-paint-${va(Aa(ya(JSON.stringify([e.assetId,e.opacity,e.rotation??0,e.fit===`tile`?e.tileScale??1:1,e.fit===`crop`?e.transform:void 0]))))}`,qa=e=>`--canvas-text-paints-${va(Aa(ya(JSON.stringify(e.filter(e=>e.visible),(e,t)=>e===`id`?void 0:t))))}`,Ja=(e,t=1)=>`${E(e.color,t)} ${String(e.position*100)}%`,Ya=e=>encodeURI(e).replaceAll(`"`,`%22`),Xa=e=>`url("${Ya(e)}")`,Za=e=>{switch(e.kind){case`solid`:{let t=E(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=>Ja(t,e.opacity)).join(`, `)})`:`url("data:image/svg+xml,${encodeURIComponent(Zr({...e,transform:e.transform}))}")`;case`radial-gradient`:{if(e.transform!==void 0)return`url("data:image/svg+xml,${encodeURIComponent(ni(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=>Ja(t,e.opacity)).join(`, `)})`}case`angular-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Pn(e))}")`;case`diamond-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Ir(e))}")`;case`image`:return Ua(e.assetId)?`none`:Ga(e)?`var(${Ka(e)}, none)`:Xa(e.assetId)}},Qa=(e,t)=>t>=1?0:e/(1-t)*100,$a=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(Qa(e.x,t))}% ${String(Qa(e.y,n))}%`,"background-size":`${String(100/t)}% ${String(100/n)}%`}},eo=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`?$a(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`}},to=e=>{if(e.length===0)return{};let t=e.toReversed().map(e=>eo(e));return Object.fromEntries([`background-size`,`background-position`,`background-repeat`,`background-origin`].map(e=>[e,t.map(t=>t[e]).join(`, `)]))},no=e=>e.kind===`solid`&&e.visible?E(e.color,e.opacity):void 0,ro=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,io=e=>ro(e)?void 0:no(e),ao=e=>{let t=e.filter(e=>e.visible),[n]=t;return n===void 0||t.length!==1?`transparent`:io(n)??`transparent`},oo=e=>({"background-image":e.toReversed().map(e=>Za(e)).join(`, `),...to(e)}),so=e=>{let t=e.filter(e=>e.visible);if(t.length===0||t.some(e=>ro(e)))return{background:`none`};let[n]=t,r=n===void 0?void 0:io(n);return r!==void 0&&t.length===1?{background:r,"background-image":`none`}:{"background-color":`transparent`,...oo(t)}},co=e=>{let t=e.filter(e=>e.visible),[n]=t;return t.length===1&&n?.kind===`solid`?{color:E(n.color,n.opacity)}:t.length===0?{color:`transparent`}:{color:`transparent`,...t.length>1?{"background-image":`var(${qa(t)}, none)`,"background-size":`100% 100%`,"background-position":`center`,"background-repeat":`no-repeat`}:oo(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`}},lo=new Set(e.keyof().options.filter(e=>/^(?:border|outline)(?:-|$)/u.test(e)&&!e.includes(`radius`))),uo=(e,t)=>{let n=t.toLowerCase();return lo.has(n)&&(n===e||n.startsWith(`${e}-`))},fo=[`top`,`right`,`bottom`,`left`],po=[`solid`,`dashed`,`dotted`],mo=[`width`,`style`,`color`],ho=(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},go=(e,t)=>{let n=x(t);if(/^(?:border(?:-(?:top|right|bottom|left))?|outline)$/u.test(e)){let t=n.find(e=>ho(e)!==void 0),r=n.find(e=>/^(?:none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/u.test(e)),i=n.find(e=>L(`probe`,e)!==null);if(t===void 0||r===void 0||i===void 0||n.length!==mo.length)return null;let a=e===`border`?fo.map(e=>`border-${e}`):[e];return Object.fromEntries(a.flatMap(e=>mo.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>fo.length)return null;let[t=``,r=t,i=t,a=r]=n;return Object.fromEntries(fo.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},_o=(e,t)=>e.additionalStyles?.declarations.filter(({property:n,value:r,enabled:i})=>uo(t,n)&&(!i||r.trim()!==``||e.appearance?.[t]===void 0))??[],vo=(e,t)=>{let n=_o(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(!uo(t,e))continue;let r=go(e.toLowerCase(),Tt(e,n).trim());if(r===null||String(n).includes(`!`))return null;Object.assign(a,r)}return a},yo=e=>{let t=vo(e,`border`);if(t===null)return{kind:`custom`};if(e.appearance?.border!==void 0&&_o(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=fo.map(n=>({width:ho(t[`border-${n}-width`]??`0`),authoredStyle:t[`border-${n}-style`],authoredColor:t[`border-${n}-color`],style:po.find(e=>e===t[`border-${n}-style`]),paint:L(`${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]}}},bo=e=>{let t=vo(e,`outline`);if(t===null)return{kind:`custom`};if(e.appearance?.outline!==void 0&&_o(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=ho(t[`outline-width`]),r=ho(t[`outline-offset`]??`0`,-1/0),i=po.find(e=>e===t[`outline-style`]),a=L(`${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]}}},xo=Object.freeze({top:0,right:0,bottom:0,left:0}),B=e=>e.alignment!==void 0&&e.alignment!==`inside`||e.layoutInclusion===`none`||e.layoutInclusion===`visible`&&(!e.visible||e.paints.every(e=>!e.visible))?xo:e.width,So=e=>{let t=e.visible?ao(e.paints):`transparent`,n=B(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}},Co=e=>{if(!e.visible)return{"outline-style":`none`};let t=ao(e.paints);return{"outline-style":e.style,"outline-width":e.width,"outline-offset":e.offset,"outline-color":t}},wo=e=>({...e.border!==void 0&&So(e.border),...e.outline!==void 0&&Co(e.outline)}),To=e=>{if(e.geometry?.kind===`boolean`||(e.appearance?.radius?.smoothing??0)<=0)return!1;let t=yo(e);return t.kind===`custom`||t.kind===`native`&&t.value.style!==`solid`},Eo=(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 Do(n);let r=Kn(n,t),i=Do(r);if((n.smoothing??0)<=0)return i;if(To(e))return{};let a=`path("${qn(n,t)}") border-box`,o=yo(e);if(o.kind!==`native`||Object.values(B(o.value)).every(e=>e===0))return{...i,"border-shape":a};let{top:s,right:c,bottom:l,left:u}=B(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`}},Do=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}),Oo=new Set([we,re]),ko=e=>e.visible&&e.kind===`blur`&&e.progression!==void 0,Ao=e=>e.geometry===void 0&&Oo.has(e.component)?(e.appearance?.backdropFilters??[]).find(e=>ko(e))??null:null,jo=(e,t)=>{let n=Ao(e);return n===null?t:t.filter(e=>e!==n)},Mo=new Set([we,Nt,re,o]),No=new Set([we,Nt,re]),V=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,Po=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),Fo=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`},Io=e=>{if(e.component!==`rectangle`||e.geometry!==void 0||Fo(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=>!Po(e))},Lo=e=>e.geometry===void 0&&Mo.has(e.component)&&(e.component!==`image`||(typeof e.props?.src!=`string`||e.props.src===``)&&e.appearance?.fills!==void 0),Ro=e=>e?.visible===!0?e.paints.filter(e=>e.visible):[],zo=e=>V(e)||e.kind===`image`&&(e.filters?.some(e=>e.visible)??!1),Bo=e=>{if(!Lo(e))return[];let t=(e.appearance?.fills??[]).filter(e=>e.visible);return t.some(e=>zo(e))||t.length>0&&Ao(e)!==null?t:[]},Vo=e=>e.style===`solid`||e.dashOrigin===`css`&&e.dashPattern===void 0&&e.dashCap===void 0,Ho=e=>{let t=Ro(e);return t.length>0&&((e.alignment??`inside`)!==`inside`||!Vo(e)||t.length>1||t.some(e=>e.kind!==`solid`))},Uo=(e,t)=>{let n=e.appearance?.border;if(n===void 0||e.geometry!==void 0||!No.has(e.component))return[];let r=Ro(n);return r.some(e=>V(e))?r.map(e=>({kind:`border`,paints:[e]})):n.layoutInclusion===`none`||n.layoutInclusion===`visible`||Ho(n)||t&&r.length>0?[{kind:`border`,paints:r}]:[]},Wo=e=>{let[t,...n]=Ro(e.appearance?.outline);return(e.appearance?.radius?.smoothing??0)>0&&n.length===0&&t?.kind===`solid`&&!V(t)},Go=e=>{let t=e.appearance?.outline;if(t===void 0||e.geometry!==void 0||!No.has(e.component)||t.width<=0||Wo(e))return[];let n=Ro(t);return n.some(e=>V(e))?n.map(e=>({kind:`outline`,paints:[e]})):n.length>1||t.style!==`solid`||n.some(e=>e.kind!==`solid`)?[{kind:`outline`,paints:n}]:[]},H=e=>{let t=Bo(e),n=Lo(e)&&!Io(e)?(e.appearance?.shadows??[]).filter(e=>e.visible):[],r=n.filter(e=>e.kind===`outer`&&V(e)),i=n.filter(e=>e.kind===`inner`&&(t.length>0||V(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,...Uo(e,t.length>0),...Go(e)],hasPaintElements:a.length>0}},Ko=e=>e.elements.flatMap(e=>e.kind===`fill`?[e.paint]:[]),qo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.shadow]:[]),Jo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.paints]:[]),Yo=(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`},Xo={top:0,right:0,bottom:0,left:0},Zo={inside:0,center:.5,outside:1},Qo=[[`topLeft`,`top-left`,`left`,`top`],[`topRight`,`top-right`,`right`,`top`],[`bottomRight`,`bottom-right`,`right`,`bottom`],[`bottomLeft`,`bottom-left`,`left`,`bottom`]],$o=e=>Jo(H(e),`border`).length>0,es=(e,t=e.box)=>{if(!$o(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=B(r);if((i.smoothing??0)<=0||Object.values(a).every(e=>e===0))return n;let o=qn(i,t),s=qn(i,t,[-a.left,-a.top]);return{...n,"border-shape":`path("${o}") border-box path("${s}") padding-box`}},ts=(e,t)=>{let n=e.appearance?.radius;return n===void 0?{"border-radius":`inherit`}:Object.fromEntries(Qo.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`]}))},ns=1e3,U=e=>String(Math.round(e*ns)/ns),rs=(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${U(n)} ${U(r)}`:`A${U(e)} ${U(t)} 0 0 1 ${U(n)} ${U(r)}`;return[`M${U(i[0])} 0`,`H${U(e-a[0])}`,c(a,e,a[1]),`V${U(t-o[1])}`,c(o,e-o[0],t),`H${U(s[0])}`,c(s,0,t-s[1]),`V${U(i[1])}`,c(i,i[0],0),`Z`].join(``)},is=e=>{if(e.stroke.style===`solid`)return{};let t=Yo(e.stroke.style,e.widest,e.stroke),n=`<svg xmlns="http://www.w3.org/2000/svg" width="${U(e.width)}" height="${U(e.height)}"><path d="${rs(e.width,e.height,e.corners)}" fill="none" stroke="#000" stroke-width="${U(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`}},as=(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 is({width:n.width+r.left+r.right,height:n.height+r.top+r.bottom,corners:{topLeft:a(Qo[0]),topRight:a(Qo[1]),bottomRight:a(Qo[2]),bottomLeft:a(Qo[3])},widest:Math.max(...Object.values(t.width)),stroke:t})},os=(e,t=e.box,n)=>{let r=e.appearance?.border,[i]=Jo(H(e),`border`);if(r===void 0||i===void 0)return null;let a=n??i,o=B(r),s=Zo[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`&&Vo(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`}:ts(e,c),...wo({...l,border:{...l.border,paints:[...a]}}),...!d&&{"border-color":`transparent`,...oo(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&&Eo({...e,styles:{},additionalStyles:void 0,appearance:l},t),...!d&&as(e,r,t,s===0?Xo:c)}},ss=(e,t)=>{if(Io(e))return[];let n=H(e),r=[...qo(n,`outer-shadow`),...qo(n,`inner-shadow`)];return r.length===0?t:t.filter(e=>!r.includes(e))},cs=e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${E(e.color)}`,ls=e=>`${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${E(e.color)}`,us=(e,t)=>{let n=ss(e,t).filter(e=>e.visible);if(e.component===`text`){let e=n.filter(e=>e.kind===`outer`&&e.spread===0).map(e=>ls(e)).join(`, `);return{"box-shadow":`none`,"text-shadow":e===``?`none`:e}}let r=n.map(e=>cs(e)).join(`, `);return{"box-shadow":r===``?`none`:r}},ds=(e,t)=>{let n=e.appearance?.border,r=n===void 0?{top:0,right:0,bottom:0,left:0}:B(n);return{position:`absolute`,top:-r.top,right:-r.right,bottom:-r.bottom,left:-r.left,"border-radius":`inherit`,"pointer-events":`none`,"box-shadow":cs(t),"mix-blend-mode":t.blendMode??`normal`}},fs=(e,t)=>{let n=t.map((n,r)=>{let[i=``,a,...o]=x(n),s=na(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)},ps=(e,t)=>{let n=/^(linear|radial)-gradient\((.*)\)$/su.exec(t);if(n===null)return null;let r=[...x(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=>x(e).length>1);if(s.some(Boolean)&&!s.every(Boolean))return null;let c=fs(e,r);if(c===null)return null;let l={id:e,visible:!0,opacity:1,stops:c},u=ot.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},ms=(e,t,n,r)=>{let i=x(e[t]??r,`,`);return i[n%i.length]??r},hs=(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=ms(n,`background-position`,r,`0% 0%`),s=ms(n,`background-size`,r,`auto`),c=ms(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}},gs=(e,t)=>{let n=t.background,i=t[`background-color`]??n,a=i===void 0||i===`none`?null:L(`${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=x(o,`,`).map((n,i)=>{let a=`${e}-fill-${String(i)}`,o=ps(a,n),s=ms(t,`background-size`,i,`auto`);if(o!==null&&![`auto`,`auto auto`,`100% 100%`].includes(s))return null;let c=o??hs(a,n,t,i),l=r.safeParse(ms(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()]},_s=[[`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]],vs=new Set([`color`,`-webkit-text-fill-color`]),ys=(e,t)=>{let n=new Set;for(let r of t){let t=r.toLowerCase(),i=e.component===`text`;i&&vs.has(t)&&n.add(`fills`);for(let[e,r]of _s)r.test(t)&&(!i||e!==`fills`)&&n.add(e)}return[...n].filter(t=>e.appearance?.[t]!==void 0)},bs=new Set([`background`,`background-color`,`background-image`]),xs=new Set([`background-position`,`background-size`,`background-repeat`,`background-origin`,`background-blend-mode`]),Ss=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(pt(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},Cs=e=>{let t=Ss(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:bs};if(Object.entries(t).some(([e,t])=>!bs.has(e)&&!xs.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=gs(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(bs);for(let e of xs)i.add(e);return{kind:`native`,fills:r,owned:i}},ws=e=>({...Ko(H(e)).length>0&&{background:`none`},...Ao(e)!==null&&{isolation:`isolate`}}),Ts=e=>({position:`absolute`,inset:0,...oo([e]),...e.kind===`image`&&e.filters!==void 0&&{filter:zr(e.filters)},...e.blendMode!==void 0&&e.blendMode!==`normal`&&{"mix-blend-mode":e.blendMode}}),Es=[[`topLeft`,`top-left`],[`topRight`,`top-right`],[`bottomRight`,`bottom-right`],[`bottomLeft`,`bottom-left`]],Ds=e=>Jo(H(e),`outline`).length>0,Os=e=>Ds(e)?{"outline-style":`none`}:{},ks=(e,t,n)=>{let r=e.appearance?.radius;if(r===void 0)return{};let i=t.offset+t.width,a=Yo(t.style,t.width,t),o=sr(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`}},As=(e,t=e.box,n)=>{let r=e.appearance?.outline,[i]=Jo(H(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}:B(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(Es.map(([e,t])=>[`border-${t}-radius`,d(e)])),...oo(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&&ks(e,r,t),...t!==void 0&&(o?.smoothing??0)<=0&&is({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})}},js=e=>{if(g(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`)},Ms=(e,t)=>{let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)?Math.min(1,Math.max(0,n)):t},Ns=e=>ct.find(t=>t===e)??`normal`,Ps=(e,t)=>{let n=Number(String(e??``).replace(`px`,``));return Number.isFinite(n)?Math.max(t,n):0},Fs=e=>Ps(e,0),Is=(e,t)=>e===0?t:e,Ls=e=>{let[t=0,n=t,r=t,i=n]=String(e[`border-radius`]??`0`).split(/\s+/u).map(e=>Fs(e));return{topLeft:Is(Fs(e[`border-top-left-radius`]),t),topRight:Is(Fs(e[`border-top-right-radius`]),n),bottomRight:Is(Fs(e[`border-bottom-right-radius`]),r),bottomLeft:Is(Fs(e[`border-bottom-left-radius`]),i)}},W=e=>{let t=$r(),n=yo(e),r=bo(e),i=L(`${e.id}-fill`,String(e.styles[e.component===`text`?`color`:`background`]??``)),a=e.component===`text`?null:Cs(e);return{...t,opacity:e.appearance?.opacity??Ms(e.styles.opacity,1),blendMode:e.appearance?.blendMode??Ns(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??Ls(e.styles),...e.appearance?.retainedBorder!==void 0&&{retainedBorder:e.appearance.retainedBorder},shadows:e.appearance?.shadows??[],filters:e.appearance?.filters??[],backdropFilters:e.appearance?.backdropFilters??[]}},Rs=e=>{let t=e.appearance?.fills;return e.component===`text`&&js(e)?{...t!==void 0&&{color:co(t).color??`transparent`},"background-image":`none`}:t===void 0?{}:e.component===`text`?co(t):so(t)},zs=e=>{let t=e.appearance,n={...Rs(e),...ws(e)};return(t?.opacity??Ms(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,Do(t.radius),Eo(e)),Object.assign(n,wo(t),es(e),Os(e)),t.filters!==void 0&&(n.filter=zr(t.filters)),t.shadows!==void 0&&Object.assign(n,us(e,t.shadows)),t.backdropFilters!==void 0&&(n[`backdrop-filter`]=zr(jo(e,t.backdropFilters))),n)},Bs=e=>{let t=W(e).radius;return t.topLeft===0&&t.topRight===0&&t.bottomRight===0&&t.bottomLeft===0},Vs=e=>{let t=W(e);return yo(e).kind!==`native`&&bo(e).kind!==`native`&&t.shadows.every(e=>!e.visible)&&t.filters.every(e=>!e.visible)&&t.backdropFilters.every(e=>!e.visible)},Hs=e=>e!==void 0&&e.geometry===void 0&&(e.component===`image`||e.component===`rectangle`&&Bs(e))&&Vs(e),Us=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},Ws=(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},Gs=(e,t)=>{let n=Ws(e,t);if(n===void 0)return null;let r=Ha(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=>Hs(e)&&Ys(e,i)!==null)?r:null},Ks=(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}},qs=(e,t)=>{let n=Za(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:Ks(e.fit===`fit`?`fit`:`cover`,t,r)}},Js=(e,t)=>{let n=e.props?.src;if(typeof n!=`string`||n===``)return[];let r=Xa(n),i=e.props?.fit;if(i!==`cover`&&i!==`contain`)return[{image:r,box:t}];let a=Us(e);return a===void 0?null:[{image:r,box:Ks(i===`cover`?`cover`:`fit`,t,a)}]},Ys=(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 Js(e,n);let{opacity:r}=W(e),i=[],a=W(e).fills.filter(e=>e.visible).toReversed();for(let e of a)if(e.kind===`image`){let t=qs(e,n);if(t===null)return null;i.push(t)}else i.push({image:Za({...e,opacity:e.opacity*r}),box:n});return i},Xs=(e,t)=>t.geometry?.kind===`mask`?e.nodes[t.geometry.maskId]:void 0,Zs={a:1,b:0,c:0,d:1,e:0,f:0},Qs=(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}),$s=e=>{let{fills:t,opacity:n}=W(e);return(1-t.filter(e=>e.visible).reduce((e,t)=>e*(1-t.opacity*(t.kind===`solid`?t.color.alpha:1)),1))*n},ec=(e,t,n)=>{let[r,i,a,o,s,c]=e.matrix,l=Qs(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}},tc=(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:Mr(t);if(s!==null&&typeof s!=`string`&&n.push(ec(s,i,a*$s(t))),!o&&t.component!==`frame`)return;let c=ur(t);if(c===null)return;let l=Qs(i,c),u=a*W(t).opacity;for(let n of Ha(e.relationships,t.id)){let t=e.nodes[n];t!==void 0&&r(t,l,u)}};return r(t,Zs,1),n},nc=e=>{let t=2166136261;for(let n of e)t=Math.imul(t^(n.codePointAt(0)??0),16777619);return(t>>>0).toString(16)},rc=(e,t,n)=>{if(Gs(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]}},ic=(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=jr(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=jr(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??Xs(e,t);if(a?.component===`text`&&a.visible!==!1)return rc(e,a,i);let o=a===void 0||a.visible===!1?null:tc(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:Mr(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]}},ac=(e,t,n)=>{let r=ic(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(`%`,`_`)}-${nc(JSON.stringify([i,a,c,s]))}`,path:i,fillRule:a,transform:c,matrix:o,...s!==void 0&&{shapes:s}}},oc=(e,t)=>{let n=Ot(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}}},sc=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),cc=(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=_e.safeParse({id:o,property:t,value:String(i),enabled:!0});if(!s.success)throw new y(`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=Tn(t.additionalStyles,a);return o===null?null:{op:`patchAdditionalStyles`,nodeId:t.id,additionalStyles:o}},lc=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...dt(t,r,e),...dt(n,r,e)],o=gt(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}},uc=(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 dt(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},dc=(t,n,r)=>{let i=uc(t,n,r),a=cc(n,i),o=Object.fromEntries(Object.entries(i).filter(([t,n])=>e.safeParse({[t]:n}).success)),s={...n,styles:{...n.styles},...a!==null&&{additionalStyles:wn(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=lc(t,n,s,r),l=oc(n,i),u=ys(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]]},fc=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=sc(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},pc=(e,t)=>{let n=[...fc(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new y(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return dc(e,r,n)});if(n.length===0)throw new y(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},mc=(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=Ke(e.typography,{clear:[...Ot(new Set([...Object.keys(t.styles),...r]))]});return G({...e,styles:n},`typography`,i??`default`)},hc=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),gc=e=>hc.has(e.op),G=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},_c=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new y(`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 mc(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 G(e,`typography`,Ke(e.typography,t.typography)??`default`);case`setTypography`:return G(e,`typography`,t.typography);case`setLayout`:return G(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=wn(e.additionalStyles,t.additionalStyles);return G(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return G(e,`additionalStyles`,t.additionalStyles)}},vc=(e,t)=>{if(!gc(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new y(`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=P(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:_c(n,t)}}},yc=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}}}},bc=(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 pc(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Wi(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=Zi(t.scene,[yc(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},xc=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=bc(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=vc(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:N(r.scene,e)}))}},K=e=>{throw new y(`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.`)},Sc=(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`?K([`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]},Cc=e=>e.op===`insertNode`?[e.node.id]:e.op===`insertText`||e.op===`insertPrototype`?[e.nodeId]:e.op===`insertConvertedSubtree`?Object.keys(e.nodes):[],wc=(e,t)=>{let r=t.destination;if(r.kind===`adjacent`)return K([`adjacent conversion`]);let i=r.kind===`replace`?e.relationships[r.targetNodeId]?.parentId:r.targetNodeId;if(i===void 0)return K([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?K([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:``}}}},Tc=e=>({component:e.op===`insertText`?`text`:`prototype`,props:{...e.op===`insertPrototype`&&e.canvasPageId!==void 0&&{canvasPageId:e.canvasPageId}}}),Ec=(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]:Tc(t)},relationships:{[t.nodeId]:{parentId:t.parentId,sortKey:``}}};if(t.op===`insertConvertedSubtree`)return wc(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:{}}},Dc=(e,t,n,r)=>{let i=Cc(r),a=e.nodeIds.length===0&&(i.length>0||r.op===`move`||r.op===`setParentage`),o=[...Sc(r,t).filter(e=>!a||e!==`root`),...i.filter(e=>t.nodes[e]!==void 0)].filter(e=>!n.has(e));return o.length>0&&K(o),i},Oc=(e,t,r)=>{if(!lt(e))return;let i=new Set(_(e,t)),a=at(e,t);if(!a.ok)return K(e.nodeIds);let o={nodes:{...t.nodes},relationships:{...t.relationships}};for(let t of r){let r=Dc(e,o,i,t),s=Ec(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&&K(c);for(let e of r)i.add(e);if(t.op!==`remove`)continue;let l=at({...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)}},kc=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]}},Ac=(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]:kc(e),jc=(e,t)=>{let n=new Set(e.edits.flatMap(e=>kc(e)));for(let e of n)P(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[],...e.pageId!==void 0&&{pageId:e.pageId}};for(let n of e.edits)b(r,t,Ac(n,t))},Mc=e=>({execute:async t=>{let n=await Pi({remote:e},t.canvasId,t.baseVersion);jc(t,n);let r=xc(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);Oc({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=Ne.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:15,baseVersion:t.baseVersion,operations:r.operations});if(!i.success)throw new y(`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 M(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}}}}),Nc=(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},q=(e,t,n,r=48e3)=>{if(t>e.length)throw new y(`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}},Pc=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}))]:[],Fc=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,Ic=(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:Fc(e),failure:e.failure,details:q(Pc(e),t.offset,t.limit),warnings:e.state===`succeeded`?[`This receipt does not verify visual fidelity. Render the committed root to inspect it.`]:[]}),Lc=e=>new y(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),Rc=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),zc=e=>{let t=e.failure;return new y(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})},Bc=async(e,t)=>{let n=St.safeParse(await e.query(`canvas.render.getImport`,{jobId:t}));if(!n.success)throw Lc(`conversion status`);if(n.data.job.id!==t)throw Lc(`conversion identity`);return n.data.job},Vc=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 Rc(250),i=await Bc(e,i.id)}if(i.state!==`succeeded`)throw zc(i);return i},Hc=(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},Uc=(e,t)=>{let n=t.request;if(e.canvasId!==n.canvasId||e.requestedVersion!==n.expectedVersion||!Hc(e,t))throw Lc(`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 Lc(`conversion source`);if(e.state===`succeeded`&&(e.result.canvasId!==n.canvasId||n.revisionPolicy===`strict`&&e.result.previousVersion!==n.expectedVersion))throw Lc(`conversion commitment`)},Wc=async(e,t)=>{let n=et.safeParse(await e.mutate(`canvas.render.importSource`,t.request));if(!n.success)throw Lc(`conversion creation`);Uc(n.data.job,t);let r=await Vc(e,n.data.job,t.waitMs);return Uc(r,t),r},Gc=async(e,t)=>{let n=At.parse(t),r=i(n.canvasRef);return Ic(await Wc(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})},Kc=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof y?{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.`]}),qc=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 Kc(e,t,n.result.version)}},Jc=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??``}})},Yc=(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}),Xc=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.`]}),Zc=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}}}}),Qc=(e,t)=>({execute:async n=>{let r=await Ti(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await Wc(e,Zc(n));if(n.responseMode===`bounded`)return Ic(i,{offset:0,limit:40});if(i.state!==`succeeded`)return Xc(i);if(n.review===`none`)return Yc(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await qc(t,n,i),o=[];try{o=await Jc(e,i)}catch{o=[]}return{...Yc(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),$c=async(e,t)=>{let n=i(t.canvas),r=Ve.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),a=Ct.parse(r.document);lt(n)&&_(n,a),t.nodeId!==void 0&&b(n,a,[t.nodeId]);let o=at(t.nodeId===void 0?n:{...n,nodeIds:[t.nodeId]},a);if(!o.ok)throw new y(`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.`]}},el=(e,t,n)=>{try{Wt(e,t,{flag:n?`w`:`wx`,mode:384}),zt(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new y(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.`)}},tl=e=>({write:t=>{if(t.outputPath!==null){let e=w.resolve(t.outputPath);return el(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=w.join(e,`sensitive`);Ut(n,{recursive:!0,mode:448}),zt(n,448);let r=w.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return el(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),nl=async(e,t)=>{try{return{value:await e.query(`canvas.render.preparation.get`,{jobId:t})}}catch(e){if(e instanceof y&&![`INTERNAL`,`RATE_LIMITED`].includes(e.code))throw e;return null}},rl=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 qt(Math.min(250,n));let a=await nl(e,t.id);if(a===null)return i;if(i=fe.parse(a.value).job,i.id!==t.id)throw new y(`INTERNAL`,`Preparation identity changed.`,`Retry the original request.`)}return i},il=async(e,t,n)=>{let r=ae.parse(await e.mutate(`canvas.render.preparation.create`,t)),i=await rl(e,r.job,n);if(i.canvasId!==t.canvasId||i.requestedVersion!==t.expectedVersion||!Jt(i.scope,t.scope)||!Jt(i.request,t.request))throw new y(`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 y(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);return i},al=`Repeat canvas_capture with identical arguments and clientToken, or follow operation_status. An unfinished step is not proof that nothing was saved.`,ol=e=>e===`queued`||e===`running`?`pending`:`not_confirmed`,sl=(e,t)=>({operation:t.operation,state:t.state,requestedVersion:e.input.baseVersion,source:e.input.source,attachment:t.frame===void 0||t.frame===null?ol(t.state):`committed`,result:t.result,frame:t.frame??null,failure:t.failure,warningCount:1,warnings:[t.warning]}),cl=e=>({kind:`canvas-mutation`,canvasId:e.canvasId,mutationId:e.clientToken,fingerprint:e.fingerprint}),ll=(e,t,n,r)=>sl(e,{operation:cl(e),state:`succeeded`,result:n,failure:null,frame:{nodeId:r,version:t.version},warning:`The capture is saved as an editable frame. Render the frame at its version to inspect it.`}),ul=e=>({kind:`recording`,recordingId:e.recordingId,atMs:e.atMs}),dl=(e,t,n)=>{let r=Object.fromEntries(Object.entries(e.nodes).map(([r,i])=>{let a={...i.props,capturedResource:{screenId:t.screenId}};if(r!==e.rootNodeId)return[r,{...i,props:a}];let o=i.props?.conversion;return[r,{...i,...i.box!==void 0&&{box:{...i.box,x:t.box.x,y:t.box.y}},props:{...a,conversion:{...typeof o==`object`&&o,provenance:ul(n)}}}]}));return{...e,destination:{kind:`insert-children`,targetNodeId:`root`,...t.pageId!==void 0&&{pageId:t.pageId}},nodes:r}},fl=(e,t)=>new y(t instanceof y?t.code:`INTERNAL`,t instanceof y?t.message:`The captured frame could not be confirmed.`,al,{...t instanceof y&&t.fields,outcome:`not_confirmed`,operation:JSON.stringify(cl(e))}),pl=async(e,t,n)=>{let r=Ne.parse({canvasId:t.canvasId,mutationId:t.clientToken,documentFormatVersion:15,baseVersion:t.input.baseVersion,operations:[n],requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});try{return v.parse(await M(e).execute(r))}catch(e){throw fl(t,e)}},ml=async(e,t,n,r)=>{let[i]=n.result.operations;if(n.result.operations.length!==1||i?.op!==`insertConvertedSubtree`)throw new y(`INTERNAL`,`The compiled capture is not one editable frame.`,`Capture the moment again with a new clientToken.`);let a=await pl(e,t,dl(i,r,t.input.source));if(a.canvasId!==t.canvasId||a.mutationId!==t.clientToken||a.version!==t.input.baseVersion+1||!a.insertedNodeIds.includes(i.rootNodeId))throw fl(t,null);return ll(t,a,r,i.rootNodeId)},hl=[`canvas.render.get`,`canvas.render.snapshot`],gl=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),_l=e=>new y(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}),vl=async(e,t)=>{let n=ut.safeParse(await e.query(hl[0],{jobId:t}));if(!n.success)throw new y(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},yl=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 y(`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 gl();let d=await vl(e,o.id);if(d.id!==t.id)throw bl();Sl(d,n),o=d}return o},bl=()=>new y(`INTERNAL`,`The snapshot response does not match the requested source or revision.`,`Run enhance doctor and report the capture job ID.`),xl=(e,t)=>t.context?.request.placement.kind===`editable-below-source`?e.screenNodeId===null&&e.version===t.context.expectedVersion:e.screenNodeId===`scr_${t.recordingId}_${String(t.atMs)}`&&(t.context===void 0||e.version===t.context.expectedVersion+1),Sl=(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 bl();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||!xl(n,t))throw bl()},Cl=async(e,t,n)=>{let r=bt.safeParse(await e.mutate(hl[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs,...n.context!==void 0&&{context:n.context}}));if(!r.success)throw new y(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");return Sl(r.data.job,n),yl(e,r.data.job,n,t)},wl=async(e,t,n)=>{let r=await Cl(e,t,n);if(r.state!==`succeeded`||r.result.snapshot===void 0)throw _l(r);let i={...r,result:{...r.result,snapshot:r.result.snapshot}},a=i.result.snapshot,{screenNodeId:o}=a;if(o===null)throw bl();return{jobId:i.id,canvasId:i.canvasId,...a,warnings:i.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${i.canvasId} --node-id ${o}`,`enhance canvas render --canvas ${i.canvasId} --node-id ${o} --expected-version ${String(a.version)}`]}},Tl=(e,t)=>({execute:async n=>wl(e,t,n)}),El=[`canvas.mutation.get`],Dl=async(e,t,n,r)=>{let i=await il(e,{canvasId:t.canvasId,expectedVersion:t.input.baseVersion,request:{kind:`compile-screens`,sources:[{screenId:n.screenId,captureId:n.screenId,label:`Captured page`}]},scope:{nodeIds:[]}},r);return i.state===`succeeded`?ml(e,t,i,n):sl(t,{operation:{kind:`canvas-preparation`,canvasId:t.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:t.fingerprint},state:i.state,result:n,failure:i.failure,warning:i.state===`queued`||i.state===`running`?`The page is stored and still being made editable. ${al}`:`The page could not be made editable, and nothing was added to the canvas. Capture the moment again with a new clientToken.`})},Ol=async(e,t,n,r)=>Cl(e,()=>null,{canvasId:t.canvasId,recordingId:t.input.source.recordingId,atMs:t.input.source.atMs,retryClientToken:t.clientToken,timeoutMs:t.input.waitMs,bounded:!0,context:{expectedVersion:t.input.baseVersion,request:{previewJobId:t.input.previewJobId,scope:{pageId:n,nodeIds:[...r]},placement:{kind:`editable-below-source`}}}}),kl=async(e,t,n)=>{let r=ee.parse(t),a=i(r.canvasRef),o={input:r,canvasId:a.canvasId,clientToken:n,fingerprint:s({operation:`canvas.capture/2`,reference:a,baseVersion:r.baseVersion,source:r.source,previewJobId:r.previewJobId})},c=ue.parse(await e.query(El[0],{canvasId:o.canvasId,mutationId:n,fingerprint:o.fingerprint}));if(c.state===`committed`)return ll(o,c.result,null,c.result.insertedNodeIds[0]??``);let l=Date.now(),u=await Ol(e,o,a.pageId,a.nodeIds),d=u.state===`succeeded`?u.result.snapshot:void 0;return d===void 0?sl(o,{operation:{kind:`canvas-render`,canvasId:u.canvasId,jobId:u.id},state:u.state,result:null,failure:u.failure,warning:u.state===`queued`||u.state===`running`?`The moment is still being stored. ${al}`:`The moment could not be stored, and nothing was added to the canvas.`}):Dl(e,o,d,Math.max(0,r.waitMs-(Date.now()-l)))},Al=[`canvas.asset.reserve`,`canvas.asset.complete`,`canvas.document.get`],jl=(e,t)=>new y(e instanceof y?e.code:`INTERNAL`,e instanceof y?e.message:`The asset import did not return a confirmed result.`,e instanceof y?e.remediation:`Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.`,{...e instanceof y&&e.fields,operation:JSON.stringify(t),outcome:`not_confirmed`}),Ml=(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 y(`INTERNAL`,`The returned asset does not match this import intent.`,`Check the API and CLI versions. Do not insert an unverified resource.`)},Nl=(e,t)=>({execute:async n=>{let r=i(n.canvasRef);if(lt(r)){let t=Ve.parse(await e.query(Al[2],{canvasId:r.canvasId}));_(r,Ct.parse(t.document))}let{body:a,...o}=await t.read(),s=qe.parse({...o,canvasId:r.canvasId,clientToken:n.clientToken}),c={kind:`canvas-asset`,canvasId:r.canvasId,clientToken:n.clientToken};try{let t=kt.parse(await e.mutate(Al[0],s));Ml(t,s),t.upload!==null&&await e.upload({...t.upload,body:a});let i=jt.parse(await e.mutate(Al[1],{canvasId:r.canvasId,clientToken:n.clientToken}));if(Ml(i,s),i.assetId!==t.assetId||i.path!==t.path)throw new y(`INTERNAL`,`The completed asset identity changed.`,`Read operation_status and do not place an unconfirmed resource.`);return ve.parse({operation:c,resource:i,placement:`not_requested`})}catch(e){throw jl(e,c)}}}),Pl=15e3,Fl=async e=>new Promise(t=>setTimeout(t,e)),Il=new Set([`ready`,`failed`,`abandoned`]),Ll=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`],Rl=e=>new y(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,`Check the existing deployment status before retrying with the same publication token.`),zl=async(e,t,n,r)=>{let i=Ae.safeParse(await e.mutate(Ll[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 Rl(`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=ze.safeParse(await e.mutate(Ll[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId}));if(!n.success||n.data.deploymentId!==i.data.deploymentId)throw Rl(`artifact submission`)}return i.data},Bl=async(e,t,n,r)=>{let i=ne.safeParse(await e.query(Ll[0],{}));if(!i.success)throw Rl(`capabilities`);let a=await t.package({entryPath:n.entryPath,limits:i.data.limits});try{return await zl(e,n,a,r)}finally{await a.dispose()}},Vl=async(e,t,n)=>{let r=new AbortController,i=Promise.withResolvers(),a=setTimeout(()=>{r.abort(),i.reject(new y(`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(Ll[3],t,{signal:r.signal}),i.promise]),a=de.safeParse(n);if(!a.success||a.data.deploymentId!==t.deploymentId)throw Rl(`status`);return a.data}finally{clearTimeout(a)}},Hl=async(e,t,n)=>{let r=performance.now()+n,i=50,a=await Vl(e,t,n>0?Math.min(Pl,n):Pl);for(;!Il.has(a.state);){let n=r-performance.now();if(n<=0)return a;await Fl(Math.min(i,n)),i=Math.min(i*2,1e3);let o=r-performance.now();if(o<=0)return a;try{a=await Vl(e,t,Math.min(Pl,o))}catch(e){if(e instanceof y&&e.fields?.reason===`STATUS_TIMEOUT`)return a;throw e}}return a},Ul=[`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`],Wl=e=>{let t=e.failure,n=Ul.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.`}}},Gl=e=>e.unavailableFiles?.map(e=>`Unavailable published file: ${e.path} (${e.code}).`)??[],Kl=[`prototype.getArtifactCapabilities`,`prototype.attach`],ql=new Set([`BAD_REQUEST`,`FORBIDDEN`,`UNAUTHORIZED`,`NOT_FOUND`]),Jl=async e=>{let t=ne.safeParse(await e.query(Kl[0],{}));if(!t.success||t.data.attachmentProtocolVersion!==1)throw new y(`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.`)},Yl=e=>e instanceof y?{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.`},Xl=async(e,t,n)=>{let r=i(t.canvasRef),a=ie.safeParse(await e.mutate(Kl[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}},Zl=async(e,t,n,r)=>{try{let i=await Xl(e,t,r);return{...n,attachmentStatus:i.attachment.outcome,attachment:i,nextAction:`inspect_result`}}catch(e){let t=Yl(e),r=t.code===`CONFLICT`,i=ql.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.`]}}},Ql=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:Gl(r)};if(r.state===`failed`){let{nextAction:e,failure:t}=Wl(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`?Zl(e,t,i,r):i},$l=(e,t)=>({execute:async n=>{let r=i(n.canvasRef);await Jl(e);let a=n.source.kind===`deployment`?n.source.deploymentId:null;try{if(n.source.kind===`build`&&(a=(await Bl(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 Ql(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:Yl(e),nextAction:e instanceof y&&(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.`]}}}}),eu=[`prototype.attach`],tu=e=>new y(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),nu=e=>{if(e.state===`failed`){let t=Wl(e);throw new y(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 y(`NOT_FOUND`,`Prototype deployment ${e.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);if(e.state!==`ready`)throw new y(`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})},ru=async(e,t,n)=>{let r={deploymentId:null};try{let i=await Bl(e,t,n,e=>{r.deploymentId=e}),a=await Hl(e,{canvasId:n.canvasId,deploymentId:i.deploymentId},3e5);nu(a);let o=ie.safeParse(await e.mutate(eu[0],{canvasId:n.canvasId,deploymentId:i.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw tu(`attachment`);return{...o.data,fileCount:a.fileCount,totalBytes:a.totalBytes,alreadyExists:i.alreadyExists,warnings:Gl(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 y&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||r.deploymentId===null?e:new st(e instanceof y?e.message:`Prototype deployment ${r.deploymentId} has no confirmed completion.`,`${e instanceof y?`${e.remediation} `:``}Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`,{code:e instanceof y?e.code:`INTERNAL`,fields:{...e instanceof y&&e.fields,canvasId:n.canvasId,deploymentId:r.deploymentId,clientToken:n.clientToken}})}},iu=(e,t)=>({execute:async n=>ru(e,t,n)}),au=(e,t)=>{if(e.id!==t.jobId||e.canvasId!==t.canvasId)throw new y(`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.`]}},ou=async(e,t)=>{let{job:n}=fe.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.jobId}));return au(n,t)},su=(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:[]}},cu=async(e,t,n)=>{if(n.kind!==`canvas-render`||n.state!==`succeeded`)return n;try{let{job:r}=ut.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 di(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.`]}}},lu=[`canvas.mutation.get`,`canvas.render.get`,`canvas.render.getImport`,`prototype.getPublishStatus`,`canvas.asset.get`],uu=(e,t)=>{if(e!==t)throw new y(`NOT_FOUND`,`The operation does not belong to this canvas.`,`Use the operation reference returned by the original action.`)},du=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`}))],fu=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,a=ue.parse(await e.query(lu[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:su(a.result,n.fingerprint),affected:q(du(a.result),r,i)}},pu=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,{job:a}=ut.parse(await e.query(lu[1],{jobId:n.jobId}));uu(a.canvasId,n.canvasId);let o=a.result===null?null:mu(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:q(hu(a),r,i),failure:a.failure,pixelsDelivered:!1,warnings:[`Status reports stored render evidence. It does not deliver or inspect the image.`]}},mu=e=>{let{warnings:t,timings:n,...r}=e;return{...r,warningCount:t.length,timingCount:n.length}},hu=e=>e.result===null?[]:[...e.result.warnings.map(e=>({kind:`warning`,warning:e})),...e.result.timings.map(e=>({kind:`timing`,timing:e}))],gu=async(e,t)=>{let n=jt.parse(await e.query(lu[4],{canvasId:t.canvasId,clientToken:t.clientToken}));if(uu(n.canvasId,t.canvasId),n.clientToken!==t.clientToken)throw new y(`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`}},_u=async(e,t)=>{let{operation:n,offset:r,limit:i}=t;switch(n.kind){case`canvas-asset`:return q([],r,i),gu(e,n);case`canvas-mutation`:return fu(e,{...t,operation:n});case`canvas-preparation`:{let r=await fu(e,{...t,operation:{kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}});return r.kind===`canvas-mutation`&&r.state===`committed`?r:ou(e,n)}case`canvas-render`:return pu(e,{...t,operation:n});case`canvas-conversion`:{let{job:t}=St.parse(await e.query(lu[2],{jobId:n.jobId}));return uu(t.canvasId,n.canvasId),Ic(t,{offset:r,limit:i})}case`prototype-deployment`:return q([],r,i),{kind:`prototype-deployment`,operation:n,publication:de.parse(await e.query(lu[3],{canvasId:n.canvasId,deploymentId:n.deploymentId})),attachment:`not_checked`,warnings:[`Publication readiness does not establish canvas attachment or successful interactive verification.`]}}},vu=(e,t)=>({execute:async n=>{let r=await _u(e,n);return t!==void 0&&n.includeImage?cu(e,t,r):r}}),yu=[`transcript.get`],bu=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),xu=e=>({execute:async t=>{let n=he.safeParse(await e.query(yu[0],t));if(!n.success)throw new y(`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:bu(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Su={".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`},Cu=()=>new y(`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.`),wu=async e=>{let t=Su[w.extname(e).toLowerCase()];if(t===void 0)throw Cu();let n=await $t(e,Bt.O_RDONLY|Bt.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size===0)throw Cu();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 y(`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:T(`sha256`).update(a).digest(`hex`)}}finally{await n.close()}},Tu=e=>({read:async()=>{try{return await wu(e)}catch(e){throw e instanceof y?e:new y(`BAD_REQUEST`,`The selected asset file cannot be read.`,`Choose an existing readable image or font file on this computer.`)}}}),Eu=[`canvas.list`,`organisation.list`],Du=async(e,t)=>{let[n,r]=await Promise.all([e.query(Eu[0],{collection:t.collection,...t.title!==void 0&&{title:t.title},scope:`all`,deleted:!1,hasUnresolved:!1}),t.includeDestinations?e.query(Eu[1],{}):{items:[],truncated:!1}]),i=be.parse(n),a=$e.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}}},Ou=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},ku=e=>({execute:async t=>{let{items:n,sourceTruncated:r}=await Du(e,t),{cursor:i,...a}=t,o=s(a),c=s({items:n,sourceTruncated:r}),l=i===void 0?null:De(i,rt);if(l!==null&&l.queryDigest!==o)throw new y(`BAD_REQUEST`,`This cursor belongs to another canvas search.`,`Restart discovery with the requested query.`);if(l!==null&&l.snapshotDigest!==c)throw new y(`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 y(`BAD_REQUEST`,`The discovery cursor is out of range.`,`Restart discovery.`);let d=Ou(n.slice(u,u+t.limit)),f=u+d.length,p=f<n.length,h=r.canvases||r.destinations;return{items:d,returnedCount:d.length,totalAvailable:n.length,complete:!p&&!h,sourceTruncated:r,nextCursor:p?m({protocol:`enhance-canvas-find/1`,queryDigest:o,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.`]:[]}}}),Au=async(e,t)=>{try{return v.parse(await M(e).execute(t))}catch(e){throw new y(e instanceof y?e.code:`INTERNAL`,e instanceof y?e.message:`The canvas commit could not be confirmed.`,`Read operation_status or repeat the original action with identical arguments and clientToken.`,{...e instanceof y&&e.fields,outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:t.canvasId,mutationId:t.mutationId,fingerprint:t.requestContext?.fingerprint})})}},ju=async(e,t,n,r)=>{if(n.result.loadedVersion!==t.baseVersion)throw new y(`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=Ne.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 Au(e,i);if(a.canvasId!==n.canvasId||a.mutationId!==t.clientToken||a.previousVersion!==t.baseVersion||a.version!==t.baseVersion+1||t.request.kind===`duplicate`&&!Jt(a.copiedNodeIds,n.result.idMap))throw new y(`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 su(a,r)},Mu=e=>({execute:async t=>{let n=i(t.canvasRef),r={...n.pageId!==void 0&&{pageId:n.pageId},nodeIds:[...n.nodeIds]},a=s({operation:`canvas.prepare/1`,reference:n,baseVersion:t.baseVersion,request:t.request}),o=ue.parse(await e.query(`canvas.mutation.get`,{canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:a}));if(o.state===`committed`)return su(o.result,a);let c=await il(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`?ju(e,t,c,a):au(c,l)}}),Nu=/^[MLHVCSQTAZ]$/iu,Pu=/[MLHVCSQTAZ]|[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/giu,Fu={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},Iu=e=>{let t=e.match(Pu)??[];if(t.join(``)!==e.replaceAll(/[\s,]/gu,``))return null;let n=[],r=``,i=0;for(;i<t.length;){let e=t[i]??``;if(Nu.test(e))r=e,i+=1;else if(r===``||r.toUpperCase()===`Z`)return null;let a=Fu[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},Lu=([e,t,n,r,i,a],{x:o,y:s})=>({x:e*o+n*s+i,y:t*o+r*s+a}),Ru=e=>`${String(e.x)} ${String(e.y)}`,zu=Math.PI/2,Bu=Math.PI*2,Vu=(e,t,n,r)=>Math.atan2(e*r-t*n,e*n+t*r),Hu=(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,te=(o===s?-1:1)*Math.sqrt(Math.max(0,(g*g*_*_-ee)/ee)),[v,ne]=[te*g*m/_,-te*_*p/g],[re,ie,ae,oe]=[(p-v)/g,(m-ne)/_,(-p-v)/g,(-m-ne)/_],se=Vu(re,ie,ae,oe);return s===0&&se>0&&(se-=Bu),s===1&&se<0&&(se+=Bu),{ellipse:[l*g,u*g,-u*_,l*_,l*v-u*ne+(e.x+n.x)/2,u*v+l*ne+(e.y+n.y)/2],start:Vu(1,0,re,ie),turn:se}},Uu=(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}=Hu(e,t,n),c=Math.ceil(Math.abs(s)/zu-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(Lu(a,d(t,u)),Lu(a,d(r,-u)),e===c-1?n:Lu(a,d(r,0)))}return f},Wu=(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=Uu(a,e.values,r),s=[];for(let e=0;e<i.length;e+=3)s.push(`C${i.slice(e,e+3).map(e=>Ru(Lu(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${Ru(Lu(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=>Ru(Lu(n,e))).join(` `)}`,pen:{current:l,start:r===`M`?l:t.start}}},Gu=(e,t)=>{let n=Iu(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=Wu(e,i,t);r.push(n.data),i=n.pen}return r.join(``)},Ku=(e,t)=>{let n=e.geometry;if(n?.kind!==`mask`||n.mode===`outline`||t?.box===void 0||t.component===`text`)return{};let r=W(t).opacity,i=W(t).fills.filter(e=>e.visible).toReversed().map(e=>Za({...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`)}},qu=(e,t)=>{let n=t.geometry?.kind===`mask`?ac(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=Gu(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}")`}},Ju=new Set([`data-enhance-id`,`data-enhance-locked`,`data-enhance-name`,`data-enhance-opaque`,`style`]),J=e=>{throw new y(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},Y=e=>{let t=ln(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,cn(e.value))}),Object.fromEntries(n)},Yu=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.`)),Xu=e=>{let t=un(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)||Ur(e.tagName));let t=e.childNodes.filter(e=>`tagName`in e);for(let e of t)e.attrs=e.attrs.filter(e=>Gr(e.name,e.value)),n.push(e)}return t},Zu=new Set([...Ju,`viewBox`,`preserveAspectRatio`]),Qu=(e,t)=>{let[n,...r]=Yu(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}},$u=e=>{let t=e.tagName===`svg`?Zu:Ju;return Object.fromEntries(e.attrs.map(e=>!t.has(e.name)||e.namespace!==void 0?J(`Unsupported attribute: ${e.name}.`):[e.name,e.value]))},ed=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??``)}},td=e=>{let t=[],n=[];for(let r of Yu(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]},nd=(e,t)=>Yu(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:rd(e,t),styles:Y(i)}}),rd=(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(``),id=e=>{let t=Xu(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=$u(e),i=ed(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:Qu(e,t.viewBox??``),text:``,children:[]};let a=e.tagName===`span`&&e.childNodes.some(e=>`tagName`in e),[o,s]=e.tagName===`span`?[[],[]]:td(e);return{...i,tag:e.tagName,...a&&{runs:nd(e,i.id)},...o.length>0&&{paints:o},text:!a&&e.tagName===`span`?rd(e,i.id):``,children:s.map(e=>r(e))}},i=Yu(t.childNodes),a=i[0];return a===void 0||i.length!==1?J(`An editable update must contain exactly its original root.`):r(a)},ad=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},od={fill:`100% 100%`,cover:`cover`,contain:`contain`,"scale-down":`contain`,none:`auto`},sd={"100% 100%":`fill`,cover:`cover`,contain:`contain`,auto:`none`},cd=/^background(?:-.+)?$/u,ld=/^url\((?:"([^"]*)"|'([^']*)'|([^"'()\s]*))\)$/u,ud=e=>{if(e.component!==`image`)return;let t=e.props?.src;return typeof t==`string`&&t!==``?t:void 0},dd=e=>{let t=ud(e);if(t===void 0)return{};let n=e.props?.fit,r=e.props?.position;return{"background-image":`url(${JSON.stringify(t)})`,"background-size":od[typeof n==`string`?n:`fill`]??`100% 100%`,"background-position":typeof r==`string`?r:`50% 50%`,"background-repeat":`no-repeat`}},fd=(e,t)=>ud(e)!==void 0&&cd.test(t),pd=(e,t,n)=>{if(ud(e)===void 0)return[];let r=[...new Set([...Object.keys(t),...Object.keys(n)])].filter(e=>cd.test(e)&&t[e]!==n[e]);if(r.length===0)return[];if(r.some(e=>![`background-image`,`background-size`,`background-position`].includes(e)))return ad(`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=ld.exec(n[`background-image`]??``),a=i?.[1]??i?.[2]??i?.[3],o=sd[n[`background-size`]??``],s=n[`background-position`];return a===void 0||a===``||o===void 0||s===void 0?ad(`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 y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},md={border:/^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u,outline:/^outline(?:-.+)?$/u,paint:/^$/u},hd=e=>Object.fromEntries(Object.entries(Y(e)).toSorted(([e],[t])=>e.localeCompare(t))),gd=e=>hd(Object.entries(e).flatMap(([e,t])=>{let n=Tt(e,t);return e.startsWith(`--`)||n.includes(`var(--canvas`)||n.includes(`url(#`)?[]:[`${e}:${n}`]}).join(`;`)),_d=e=>{let t=H(e),n=n=>qo(t,n).map(t=>({owner:`paint`,paintId:t.id,styles:gd(ds(e,t))})),r=os(e),i=As(e);return[...n(`outer-shadow`),...Ko(t).map(e=>({owner:`paint`,paintId:e.id,styles:gd(Ts(e))})),...n(`inner-shadow`),...r===null?[]:[{owner:`border`,styles:gd(r)}],...i===null?[]:[{owner:`outline`,styles:gd(i)}]]},vd=(e,t)=>e.some(e=>md[e.owner].test(t)),yd=e=>ct.find(t=>t===(e??`normal`))??X(`Unsupported mix-blend-mode: ${e??``}.`),bd=/stroke-(?:dasharray|linecap)="[^"]*"/gu,xd=e=>{let t=/^url\(["']?data:image\/svg\+xml,(.*?)["']?\)$/u.exec(e??``)?.[1];return t===void 0?void 0:decodeURIComponent(t)},Sd=(e,t,n)=>{let r=xd(t),i=xd(n);if(i===void 0||r?.replaceAll(bd,``)!==i.replaceAll(bd,``))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}},Cd=(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=yd(r);return n.paints.map(e=>e===a?{...e,blendMode:o}:e)},wd=(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:yd(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)}}]:[]]},Td=(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`)?Cd(e,s,c,n.styles[`mix-blend-mode`]):c.paints,u=o.includes(`mask-image`)?Sd(e,i.styles[`mask-image`],n.styles[`mask-image`]):{};return[{op:`setAppearance`,nodeId:e.id,appearance:{[s]:{...c,paints:l,...u}}}]}),...wd(e,a)]},Ed=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Dd=e=>e.kind===`text`||e.kind===`span`&&e.children.every(e=>e.kind===`text`),Od=e=>ke([e]),kd=e=>e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`),Ad=e=>e.replaceAll(/-([a-z])/gu,(e,t)=>t.toUpperCase()),jd=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,n])=>{let r=Ad(e);return p.has(r)?[r,n]:Ed(`Run ${String(t+1)} cannot hold ${e}; set it on the text layer.`)})),Md=e=>{if(e.kind!==`span`)return{};let[t,...n]=(e.fills??[]).filter(e=>e.visible),r=t===void 0||n.length>0?void 0:no(t),i=[...Object.entries(e.styles).map(([e,t])=>{let n=kd(e);return`${n}:${Tt(n,t)}`}),...r===void 0?[]:[`color:${r}`]];return Object.fromEntries(Object.entries(Y(i.join(`;`))).toSorted(([e],[t])=>e.localeCompare(t)))},Nd=e=>{let t=Dt(e);return t.length===0||t.some(e=>!Dd(e))?null:t.map(e=>({text:Od(e),styles:Md(e)}))},Pd=e=>Dt(e).some(e=>!Dd(e)),Fd=(e,t,n,r)=>{if(`mix-blend-mode`in r.styles)return Ed(`Text paints have no blend of their own. Set mix-blend-mode on the text layer.`);let{color:i,...a}=r.styles,o=jd(a,t),s=i===void 0?void 0:L(`${e.id}-run-${String(t)}`,i);if(i!==void 0&&s===null)return Ed(`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&&Md(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}]}},Id=(e,t,n)=>{if(t.length!==n.length)return Ed(`Keep each run span of ${e.id}; change a run's words or CSS in place.`);let r=Dt(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:Fd(e,i,r,o)});if(i.every((e,t)=>e===r[t]))return[];let a={...e.props,richText:i,text:ke(i)};return[{op:`editText`,nodeId:e.id,change:Te(e,{...e,props:a})}]},Ld=new Set([`path`,`polygon`,`boolean`]),Rd=e=>Ld.has(e.geometry?.kind??``),zd=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},Bd=e=>{let t=jr(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`:no(n)??`none`,viewBox:[r,i,a,o].map(String).join(` `)}},Vd=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Hd=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}:Vd(`Invalid viewBox: ${e}.`)},Ud=(e,t,n)=>n.d.trim()===``?Vd(`The path of ${t.id} is empty.`):[{op:`setGeometry`,nodeId:t.id,geometry:{kind:`path`,path:n.d,fillRule:n.fillRule,viewBox:Hd(n.viewBox)}},...t.geometry?.kind===`boolean`?N(e,t.id).map(e=>({op:`remove`,nodeId:e})):[]],Wd=(e,t)=>{let n=(e.appearance?.fills??[]).find(e=>e.visible),r=n?.kind===`solid`?n.id:`${e.id}-fill`,i=t===`none`?null:L(r,t);return i===null&&t!==`none`?Vd(`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}}]}}},Gd=(e,t,n,r)=>[...n.d===r.d&&n.fillRule===r.fillRule&&n.viewBox===r.viewBox?[]:Ud(e,t,r),...n.fill===r.fill?[]:[Wd(t,r.fill)]],Kd=new Set([`root`,`frame`,`group`,`rectangle`,`image`,`text`]),qd={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.`},Jd=/^(?:mask(?:-.+)?|clip-path)$/u,Yd=`This layer kind has no editable HTML form yet; edit it in the editor.`,Xd=(e,t,n)=>{let r=qd[t.component];return r===void 0?qu(e,t)===null?`This mask's shape cannot be read; edit it in the editor.`:t.component===`text`&&(n>0||Pd(t))?`Text with nested layers or nested formatting keeps its formatting in the editor.`:Rd(t)?zd(t)??(Bd(t)===null?Yd:null):Kd.has(t.component)&&(t.geometry===void 0||t.geometry.kind===`mask`)?null:Yd:r},Zd=(e,t)=>{let n={...zs(t),...Ku(t,Xs(e,t)),...qu(e,t)},r=pt(t),i=Object.entries(n).flatMap(([e,n])=>{let r=Tt(e,n);return e.startsWith(`--`)||r.includes(`var(--canvas`)||r.includes(`url(#`)||ys(t,[e]).length===0&&!Jd.test(e)?[]:[[e,r]]});return{...Object.fromEntries(i),...dd(t),...Object.fromEntries(Object.entries(r).map(([e,t])=>[e,Tt(e,t)]))}},Qd=e=>{throw new y(`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;`),$d=e=>Rd(e)?Bd(e):null,ef=/^background(?:-.+)?$/u,tf=e=>`<path d="${Z(e.d)}" fill-rule="${e.fillRule}" fill="${Z(e.fill)}"></path>`,nf=e=>{let t=Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`);return t===``?``:` style="${Z(t)}"`},rf=e=>`<div data-enhance-paint="${Z(e.paintId??e.owner)}"${nf(e.styles)}></div>`,af=(e,t)=>`<span data-enhance-run="${String(t)}"${nf(e.styles)}>${Z(e.text)}</span>`,of=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">${tf(e.path)}</svg>`;let r=(e.runs??[]).map((e,t)=>af(e,t)).join(``),i=(e.paints??[]).map(e=>rf(e)).join(``);return`<${e.tag} ${n}>${Z(e.text)}${r}${i}${e.children.map(e=>of(e)).join(``)}</${e.tag}>`},sf=(e,t)=>{let n=new Set,r=[],i={},a=Fi(e),o=t=>{if(n.has(t))return Qd(`The document contains repeated node identity.`);n.add(t);let s=P(e,t),c=a.get(t)??[],l=Xd(e,s,c.length),u=l!==null;u&&(r.push(s.id),i[s.id]=l);let d=u?null:$d(s),f=u||s.component!==`text`?null:Nd(s),p=u||d!==null?[]:_d(s),m=u?{}:Y(Object.entries(Zd(e,s)).filter(([e])=>d===null||!ef.test(e)).filter(([e])=>!vd(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:F(e,t),styles:m,...f!==null&&{runs:f},...p.length>0&&{paints:p},text:f!==null||u||s.component!==`text`?``:se(s)??``,children:u||d!==null?[]:c.map(e=>o(e))}},s=o(t);return{projectionVersion:2,root:s,html:of(s),opaqueNodeIds:r,sealedReasons:i}},cf=(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=at(t,n);if(r.ok)return r.rootNodeIds;throw _(t,n),new y(`NOT_FOUND`,`The linked page is unavailable.`,`Copy a current page link.`)},lf=(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 y(`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 y(`BAD_REQUEST`,`Outline roots repeat.`,`Choose each root once.`)},uf=(e,t,n,r)=>{let i=[],a=new Set,o=Fi(e),s=(t,c)=>{if(a.has(t))return;a.add(t);let l=P(e,t),u=o.get(t)??[],d=F(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},df=(e,t,n)=>{if(e===void 0)return 0;let r=De(e,xt);if(r.canvasId!==t.reference.canvasId||r.queryDigest!==n)throw new y(`BAD_REQUEST`,`This cursor belongs to another outline query.`,`Restart the outline read with the requested scope.`);if(r.version!==t.version)throw new y(`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},ff=(e,t)=>{let{reference:n,scene:r,version:i,isCurrent:a}=t,o=cf(e,n,r);b(n,r,o),lf(r,o);let c=s({reference:n,roots:e.rootNodeIds??null,depth:e.depth,limit:e.limit}),l=df(e.cursor,t,c),u=uf(r,o,e.depth,a);if(l>u.length)throw new y(`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,p=u.some(e=>e.childrenOmitted);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[...o]},view:`outline`,complete:f===u.length&&!p,returnedCount:d.length,total:u.length,nodes:d,omittedDescendants:p,nextCursor:f<u.length?m({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.`]}},pf=e=>{let t=l(e);if(t!==null)return{storage:`canvas-image`,reference:e,ownerId:t.canvasId,assetId:t.assetId};let n=Ee(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}},mf=(e,t)=>typeof e[t]==`string`?e[t]:null,hf=(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:s(r),...pf(r),delivery:`not_checked`,metadata:i};return n.set(s(a),a),r};Yr(r,e=>i(`image`,e,null)),Re(r.props,(e,t)=>i(`font`,e,{family:mf(t,`family`),style:mf(t,`style`),weight:mf(t,`weight`)}))}return Array.from(n,([,e])=>e)},gf=(e,t,n)=>{if(e.cursor===void 0)return 0;let r=De(e.cursor,mt);if(r.canvasId!==t.reference.canvasId||r.digest!==n)throw new y(`BAD_REQUEST`,`The resource cursor belongs to another query.`,`Restart this scoped resource read.`);if(r.version!==t.version)throw new y(`CONFLICT`,`The canvas changed between resource pages.`,`Restart the read at the current revision.`);return r.offset},_f=(e,t)=>{let n=at(t.reference,t.scene);if(!n.ok)throw new y(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link; do not broaden the request.`);let r=s({reference:t.reference,limit:e.limit}),i=gf(e,t,r),a=hf(t,n.nodeIds);if(i>a.length)throw new y(`BAD_REQUEST`,`The resource cursor is out of range.`,`Restart the scoped resource read.`);let o=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:m({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(o([])));return o(q(a,i,e.limit,c).entries)},vf=(e,t,n)=>{if(e.state!==`ready`){if(t.cursor!==void 0)throw new y(`CONFLICT`,`The transcript changed during pagination.`,`Restart the read.`);return e}let{cursor:r,...i}=t,a=s({scope:n,range:i,transcript:e}),o=r===void 0?null:De(r,nt);if(o!==null&&o.digest!==a)throw new y(`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=o?.offset??0;if(l>c.length)throw new y(`BAD_REQUEST`,`Transcript cursor offset is out of range.`,`Restart the read.`);let u=q(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?m({protocol:`enhance-canvas-transcript/1`,digest:a,offset:d}):null}},yf=[`recording.get`,`prototype.getPublishStatus`,`transcript.get`],bf=e=>{let t=Oe.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}},xf=e=>{let t=h.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)}},Sf=async(e,t)=>{let{node:n,canvasId:r}=t;if(n.component===`recording`){let t=ge.parse(n.props),i=C.uuid().parse(t.recordingId),a=Pt.parse(await e.query(yf[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=f.parse(n.props),i=de.parse(await e.query(yf[1],{canvasId:r,deploymentId:t.deploymentId}));if(i.prototypeId!==t.prototypeId)throw new y(`CONFLICT`,`Prototype identity does not match its deployment.`,`Read the node again.`);return{kind:`prototype`,...t,state:i.state,fileCount:i.fileCount}}return bf(t)??xf(n)},Cf=e=>({execute:async t=>{let n=await Sf(e,t),r=t.input.transcript,i=`recordingId`in n?n.recordingId:null;if(r!==void 0&&i===null)throw new y(`BAD_REQUEST`,`This object has no recording transcript source.`,`Choose a recording or a capture with recording provenance.`);let a=r===void 0?null:vf(he.parse(await e.query(yf[2],{canvasId:t.canvasId,recordingId:C.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.`]]}}}),wf=[`canvas.document.get`],Tf=e=>{throw new y(`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`})},Ef=(e,t)=>{let{reference:n,scene:r,version:i}=t;if(!t.isCurrent)throw new y(`BAD_REQUEST`,`This document format cannot produce an editable snapshot.`,`Open it in the current editor before editing.`);b(n,r,[e.rootNodeId]);let a=sf(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:Et({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.`]:[]}},Df=e=>({execute:async t=>{let n=i(t.canvasRef),r=Ve.parse(await e.query(wf[0],{canvasId:n.canvasId}));if(t.expectedVersion!==void 0&&t.expectedVersion!==r.version)return Tf(r.version);let a=Ze.safeParse(r.document),o=a.success?a.data:Ct.parse(r.document);return t.view===`resources`?_f(t,{reference:n,scene:o,version:r.version,isCurrent:a.success}):t.view===`outline`?ff(t,{reference:n,scene:o,version:r.version,isCurrent:a.success}):t.view===`source`?(b(n,o,[t.nodeId]),Cf(e).execute({canvasId:n.canvasId,version:r.version,node:P(o,t.nodeId),screens:r.screens,input:t})):Ef(t,{reference:n,scene:o,version:r.version,isCurrent:a.success})}}),Of=[`canvas.mutation.get`],kf=e=>({execute:async t=>{let n=t.reference.canvasId,r=ue.parse(await e.query(Of[0],{canvasId:n,mutationId:t.clientToken,fingerprint:t.fingerprint}));if(r.state===`committed`)return su(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(Oc(t.reference,i,a),a.length===0)return{outcome:`no_op`,canvasId:n,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let o=Ne.safeParse({canvasId:n,documentFormatVersion:15,mutationId:t.clientToken,baseVersion:t.baseVersion,operations:a,requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});if(!o.success)throw new y(`BAD_REQUEST`,`The planned edit exceeds the canonical canvas contract.`,o.error.issues[0]?.message??`Reduce the edit scope.`,{outcome:`not_committed`});return su(v.parse(await M(e).execute(o.data)),t.fingerprint)}}),Af=(e,t)=>{let n=Fi(e),r=new Set(t),i=new Set,a=t=>{if(i.has(t))return;if(i.add(t),P(e,t),F(e,t))throw new y(`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 y(`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}))},jf=e=>({execute:async({clientToken:t,...n})=>{let r=i(n.canvasRef);return kf(e).execute({reference:r,baseVersion:n.baseVersion,clientToken:t,fingerprint:s({operation:`canvas.remove/1`,...n,reference:r}),plan:e=>Af(e,n.rootNodeIds)})}}),Mf=(e,t,n,r)=>{let i=e.parents.get(t),a=e.children.get(n)??[];if(i===n&&a.indexOf(t)===r)return;if(F(e.document,t)||F(e.document,n))throw new y(`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})},Nf=(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([...Fi(r)].map(([e,t])=>[e,[...t]])),moves:[]},a=e=>{for(let[t,n]of e.children.entries())Mf(i,n.id,e.id,t),a(n)};return a(t),i.moves.length===0?[]:Zi(r,i.moves).operations},Pf=e=>{throw new y(`BAD_REQUEST`,e,`Read the current subtree and reduce or correct the edit. No canvas changes were committed.`)},Ff=(e,t,n)=>{if(Object.keys(t.idMap).length!==n.fragments.length)return Pf(`Native compilation returned unexpected fragment identities.`);if(t.operations.length!==n.fragments.length)return Pf(`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 Pf(`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 Pf(`New HTML identity ${e} already exists.`);let a=N(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:Lt(o,null)}})}return r},If=(e,t)=>({...e,id:Object.hasOwn(t,e.id)?t[e.id]??e.id:e.id,children:e.children.map(e=>If(e,t))}),Lf={operations:[],idMap:{},rootNodeIds:[]},Rf=(e,t,n=Lf)=>{let r=Ff(e,n,t),i=If(t.root,n.idMap);return[...t.operations,...n.operations,...Nf(r,i,t.removed)]},zf=e=>e.attrs.some(e=>e.name===`data-enhance-paint`),Bf=e=>e.attrs.find(e=>e.name===`data-enhance-id`)?.value,Vf=e=>{throw new y(`BAD_REQUEST`,e,`Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.`)},Hf=e=>e.flatMap(e=>`tagName`in e?[e,...Hf(e.childNodes)]:[]),Uf=e=>{let t=Xu(e),n=Hf(t.childNodes),r=new Set(n.map(e=>Bf(e))),i=[],a=(e,t)=>{let n=Bf(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&&!zf(e)?a(e,n):e)};if(t===void 0)return Vf(`The submitted HTML must retain its original root identity.`);if([e,...Hf(e.childNodes)].some(e=>e.attrs.some(e=>[`data-enhance-id`,`data-enhance-opaque`].includes(e.name))))return Vf(`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:fn(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:id(dn(t)),fragments:i}},Q=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Wf=e=>{let t=new Map,n=e=>{t.set(e.id,e);for(let t of e.children)n(t)};return n(e),t},Gf=(e,t)=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n),Kf=(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},qf=(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=>!fd(t,e)).map(e=>[e,r.styles[e]??null]));return[...t.geometry?.kind===`mask`&&Object.keys(a).some(e=>Jd.test(e))?[{op:`setGeometry`,nodeId:t.id,geometry:`default`}]:[],...pd(t,n.styles,r.styles),...Object.keys(a).length===0?[]:pc(e,[{nodeIds:[t.id],styles:a}])]},Jf=(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=!Gf(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:Te(a,{...a,props:c(a,n.text)})}),o.push(...Td(a,t.paints??[],n.paints??[])),(t.runs!==void 0||n.runs!==void 0)&&o.push(...Id(a,t.runs??[],n.runs??[])),t.path!==void 0&&n.path!==void 0&&o.push(...Gd(e,a,t.path,n.path)),r&&o.push(...qf(e,a,t,n)),o},Yf=(e,t,n,r)=>{let i=sf(e,t).root,a=Uf(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=Wf(i),l=Wf(o),u=Kf(c,l,r,t),d=new Set([...u,...r.flatMap(t=>[...Li(e,t)])]);for(let t of d)if(F(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(...Jf(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}},Xf=(e,t,n)=>{let r=d(e.snapshotToken,t);b(t,n,[r.rootNodeId]);let i=sf(n,r.rootNodeId);if(Et({reference:t,version:r.version,rootNodeId:r.rootNodeId,html:i.html})!==e.snapshotToken)throw new y(`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 Yf(n,r.rootNodeId,e.html,e.removeNodeIds)},Zf=async(e,t,n)=>{let r=Xf(t,n.reference,n.scene);if(r.fragments.length===0)return Rf(n.scene,r);let i=await il(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`?Rf(n.scene,r,i.result):au(i,{kind:`canvas-preparation`,canvasId:n.reference.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:n.fingerprint})},Qf=e=>({execute:async t=>{let n=Qe.parse(t),r=i(n.canvasRef),a=d(n.snapshotToken,r),o=s({operation:`canvas.updateHtml/1`,snapshotToken:n.snapshotToken,html:n.html,removeNodeIds:n.removeNodeIds});return kf(e).execute({reference:r,baseVersion:a.version,clientToken:n.clientToken,fingerprint:o,plan:async t=>Zf(e,n,{reference:r,scene:t,fingerprint:o,version:a.version})})}}),$f=(e,t,n)=>({"canvas.arrange":async()=>{let{changes:r,...i}=Ce.parse(t);return Mu(e).execute({...i,clientToken:n,request:{kind:`arrange`,changes:r}})},"canvas.duplicateNodes":async()=>{let{nodeIds:r,destination:i,...o}=a.parse(t);return Mu(e).execute({...o,clientToken:n,request:{kind:`duplicate`,nodeIds:r,destination:i}})},"canvas.find":async()=>ku(e).execute(Ue.parse(t)),"canvas.remove":async()=>jf(e).execute({...We.parse(t),clientToken:n}),"canvas.read":async()=>{let n=te.safeParse(t);return n.success?$c(e,n.data):Df(e).execute(Ye.parse(t))},"canvas.updateHtml":async()=>Qf(e).execute({...wt.parse(t),clientToken:n})}),ep=(e,t)=>{let n=i(e.canvasRef),r=n.nodeIds;if(e.target.kind===`content`&&r.length>1)throw new y(`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}},tp=(e,t)=>{let n=tt.shape.operation.safeParse({kind:`canvas-render`,canvasId:t.input.canvasId,jobId:e instanceof y?e.fields?.jobId:void 0}),r=vt.extract([`failed`,`cancelled`,`expired`]).safeParse(e instanceof y?e.fields?.renderState:void 0);return{...n.success&&{operation:n.data},state:r.success?r.data:`not_confirmed`,error:e instanceof y?{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.`}}},np=(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:ep({...e,...i},a)}}),rp=async(e,t)=>{try{let n=await e.execute({...t.input,maxOutputPixels:t.maxOutputPixels}),r=it.safeParse(n);if(!r.success)return tt.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 y(`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 tp(e,t)}},ip=e=>({execute:async(t,n)=>{let r=xe.parse(t),i=np(r,n),a=[],o=0;for(let t of i){let n=await rp(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.`]}}}),ap=e=>xi(e.remote,tl(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),op=async(e,t,n)=>{let r=xe.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=ap(e);return ip({execute:async t=>(e.mutationKey.select(t.retryClientToken,!1),i.execute(t))}).execute(r.data,t)}let i=yt.safeParse(t);if(i.success)return ap(e).execute(ep(i.data,n));let a=le.parse(t);return ap(e).execute({...a,retryClientToken:n})},sp=e=>({render:ap(e),execute:async(t,n)=>op(e,t,n)}),cp=new Date(`1980-01-01T00:00:00.000Z`),lp=33188,up=(e,t)=>new y(`BAD_REQUEST`,e,t),dp=(e,t)=>{let n=T(`sha256`),r=0;return new hn({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`))}}})},fp=e=>{let t=_t.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 up(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,je,{mtime:cp,mode:lp,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},pp=(e,t,n)=>{let{source:r,content:i}=t,a={mtime:cp,mode:lp,compress:i===null,forceDosTimestamp:!0};if(i===null){e.addReadStreamLazy(r.path,{...a,size:r.bytes},t=>{let i=Vt(r.absolutePath),a=dp(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:T(`sha256`).update(i).digest(`hex`)})},mp=(e,t,n)=>{let r=[];for(let i of t)i!==null&&(pp(e,i,n),r.push(i.source));return r},hp=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 en(e.absolutePath):null;if(t===null&&await Yt(e.absolutePath,Bt.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(...mp(e,a,n))}return r},gp=async e=>{let t=new _n,n=T(`sha256`),r=new hn({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=gn(t.outputStream,r,Ht(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=fp({zip:t,completed:i,...e,files:s}))},l=e=>{i.set(e.path,e),c()};try{s=await hp(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 an(e.artifactPath);if(u.size>e.limits.artifactBytes)throw up(`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}},_p={".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`},vp=e=>_p[w.extname(e).toLowerCase()]??`application/octet-stream`,yp=async e=>{try{return await an(e)}catch{return null}},bp=e=>Buffer.byteLength(e,`utf8`),$=(e,t)=>new y(`BAD_REQUEST`,e,t),xp=(e,t)=>{if(!ce.safeParse(e).success)throw $(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(bp(e)>t.pathBytes)throw $(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},Sp=async(e,t,n,r)=>{let{limits:i,unavailable:a}=r,o=await tn(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=w.join(t,n.name),c=await yp(o);if(c?.isDirectory()===!0){try{u.push(...await Sp(e,o,s,r))}catch{a()}continue}if(c?.isFile()!==!0){a();continue}let l=w.relative(e,o).split(w.sep).join(`/`).normalize(`NFC`);xp(l,i),u.push({absolutePath:o,path:l,bytes:Number(c.size),contentType:vp(o)})}return u},Cp=(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=Pe(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.`)},wp=(e,t)=>{try{pn.mark(`enhance.prototype.packaging`,{detail:{fileCount:e,unavailableFileCount:t}})}catch{}},Tp=async e=>{let t=w.resolve(e.directory),n=await yp(t);if(n===null)throw new y(`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(w.sep).join(`/`).normalize(`NFC`);xp(r,e.limits);let i=0,a=await Sp(t,t,new Set,{limits:e.limits,unavailable:()=>{i+=1}});Cp(a,r,e.limits);let o=await Qt(w.join(It(),`enhance-prototype-artifact-`)),s=w.join(o,`artifact.zip`);try{let t=await gp({artifactPath:s,files:a,entryPath:r,limits:e.limits});return i+=t.unavailableFileCount,wp(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:()=>Vt(s),dispose:async()=>rn(o,{recursive:!0})}}catch(e){throw await rn(o,{recursive:!0}),e}},Ep=e=>({package:async t=>{if(e===void 0)throw $(`No build directory was selected.`,`Select a build before publishing.`);return Tp({...t,directory:e})}}),Dp=async(e,t)=>{let n=Me.parse(t);return M(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Op=async(e,t)=>{let n=ht.parse(t);return Qc(e.remote,sp(e).render).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},kp=async(e,t,n)=>{let r=Mt.parse(t),a=i(r.canvasRef);return Qc(e.remote,sp(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})},Ap=async(e,t)=>{let n=oe.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},jp=async(e,t,n)=>{let r=Le.parse(t);return iu(e.remote,Ep(r.directory)).execute({...r,clientToken:n})},Mp=async(e,t,n)=>{let r=Fe.parse(t);return Tl(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Np=async(e,t)=>{let n=Be.parse(t);return xu(e.remote).execute(n)},Pp=async(e,t)=>{let n=u.parse(t),r=i(n.canvas);return Mc(e.remote).execute({...r,baseVersion:n.baseVersion,edits:n.edits,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Fp=async(e,n)=>vu(e.remote,tl(e.configDirectory)).execute(t.parse(n)),Ip=async(e,t,n,r)=>{let i={...$f(e.remote,n,r),"canvas.importAsset":async()=>{let t=pe.parse(n);return Nl(e.remote,Tu(t.source.path)).execute({canvasRef:t.canvasRef,clientToken:r})},"operation.status":async()=>Fp(e,n),"canvas.edit":async()=>Pp(e,n),"canvas.apply":async()=>Dp(e,n),"canvas.render":async()=>sp(e).execute(n,r),"canvas.writeHtml":async()=>Op(e,n),"canvas.insertHtml":async()=>kp(e,n,r),"canvas.capture":async()=>kl(e.remote,n,r),"canvas.makeEditable":async()=>Gc(e.remote,n),"comment.attention":async()=>Ap(e,n),"prototype.publishCanvas":async()=>{let t=Ge.parse(n);return $l(e.remote,Ep(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()=>jp(e,n,r),"recording.snapshot":async()=>Mp(e,n,r),"transcript.read":async()=>Np(e,n)}[t];if(i===void 0)throw TypeError(`${t} has no composite execution`);return i()},Lp=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??Kt();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Ip(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),Rp=`/callback`,zp=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),Bp=e=>{let t=S.platform===`darwin`?{executable:`open`,arguments:[e]}:S.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=bn(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Vp=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==Rp){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)},Hp=e=>{let t=zp(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},Up=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=xn((n,r)=>{Vp({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)}${Rp}`,a=Hp({...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&&Bp(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},Wp=e=>({authorize:async t=>{try{let n=Gt(32).toString(`base64url`),r=T(`sha256`).update(n).digest(`base64url`),i=Gt(32).toString(`base64url`),a=await Up({...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 y(`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.`)}}}),Gp={apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`},Kp=e=>URL.canParse(e)?new URL(e).href.replace(/\/+$/u,``):e,qp=(e,t,n,r)=>{let i=URL.canParse(e)?new URL(e).origin:null,a=w.resolve(t),o=Gp;if(i===new URL(o.apiUrl).origin&&a===w.resolve(n,`.config`,r.configDirectoryName)||i===new URL(r.apiUrl).origin&&a===w.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.`)},Jp=e=>e===void 0||e===``?void 0:e,Yp=(e,t,n)=>{let r=Jp(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Jp(e.ENHANCE3_API_URL),a=w.join(t,`.config`,n.configDirectoryName),o=Jp(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&Kp(i)!==Kp(n.apiUrl))throw TypeError(`Enhance development cannot use this API. Use the bundled development endpoint.`);if(o!==void 0&&w.resolve(o)!==w.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}else qp(i??n.apiUrl,o??a,t,n);return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}},Xp=()=>Yp(S.env,Ft(),Gp),Zp=()=>{let e=C.enum([`legacy`,`canvas`]).default(`legacy`).parse(S.env.ENHANCE_MCP_PROFILE),t=C.enum([`true`,`false`]).default(`false`).parse(S.env.ENHANCE_MCP_READ_ONLY)===`true`;if(t&&e!==`canvas`)throw Error(`ENHANCE_MCP_READ_ONLY requires the canvas profile.`);return{...Xp(),profile:e,isReadOnly:t,workflowsDirectory:S.env.ENHANCE_WORKFLOWS_DIR}},Qp=C.object({token:C.string().startsWith(`enh_`)}),$p=e=>{let t=w.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await en(t,`utf8`));return Qp.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Zt(e,{recursive:!0,mode:448}),await Xt(e,448);let r=w.join(e,`credentials.${String(S.pid)}.tmp`);await sn(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await nn(r,t),await Xt(t,384)},remove:async()=>{try{return await on(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},em={path:`direct_cli`},tm=C.object({access_token:C.string().min(1)}),nm=C.object({code:C.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),rm=`Check network access and proxy settings for this API, then run enhance doctor again.`,im=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,am=e=>{let t=nm.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?am(e.cause):e instanceof Error?e.name:`Network request failed`},om=(e,t)=>new y(`INTERNAL`,`${im(e)} answered HTTP ${String(t)}.`,rm),sm=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new y(`INTERNAL`,`Could not reach ${im(e)}: ${am(t)}.`,rm)}},cm=async(e,t)=>{let n=await sm(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw om(e,n.status);return n},lm=(e,t,n=null,r=em)=>vn({links:[yn({url:`${e}/trpc`,fetch:async(e,t)=>cm(e,{...t,signal:t?.signal??null}),headers:{[ye]:JSON.stringify(r),...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),um=async e=>{try{return await e()}catch(e){throw Xe(e)}},dm=async e=>{let t=await fetch(e);if(!t.ok)throw new y(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())},fm=async e=>{let t=await sm(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new y(`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 y(`INTERNAL`,`${im(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,rm);return t.json()},pm=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await sm(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw om(e,n.status);return n.json()},mm=async e=>{let t=await sm(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 y(`INTERNAL`,`${im(e.issuer)} token exchange answered HTTP ${String(t.status)}`,rm);return tm.parse(await t.json()).access_token},hm=async e=>{try{let t=await sm(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:om(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${im(e)}.`}}},gm=async e=>{let t=!(e.body instanceof Uint8Array),n=t?mn.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 y(`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 y(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},_m=(e,t,n,r=em)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>fm(i),oauthMetadata:pm,exchangeOauthCode:mm,query:async(e,n,a)=>um(async()=>lm(i,await t.read(),null,r).query(e,n,a)),queryWithToken:async(e,t,n)=>um(async()=>lm(i,n,null,r).query(e,t)),mutate:async(e,a)=>um(async()=>lm(i,await t.read(),n.current(e,a),r).mutation(e,a)),mutateWithToken:async(e,t,n)=>um(async()=>lm(i,n,null,r).mutation(e,t)),download:dm,upload:gm,health:async()=>hm(i)}},vm=e=>Array.isArray(e)?e.map(e=>vm(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,vm(t)])),ym=(e,t,n)=>T(`sha256`).update(`${e}\0${t}\0${JSON.stringify(vm(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),bm=()=>{let e=Kt(),t=!1;return{current:(n,r)=>t?ym(e,n,r):e,select:(n,r)=>{e=n??Kt(),t=r}}};export{Ir as C,Sn as E,zr as S,E as T,Ti as _,Zp as a,ni as b,tl as c,q as d,Nc as f,M as g,Pi as h,Xp as i,$c as l,Oc as m,_m as n,Wp as o,Mc as p,$p as r,Lp as s,bm as t,Qc as u,xi as v,Pn as w,Zr as x,ai as y};
2
+ import{$n as e,A as t,An as n,Ar as r,At as i,B as a,Bn as o,C as s,Cn as c,Cr as l,Ct as u,D as d,Dn as f,Dr as p,E as m,En as h,Er as g,Et as _,F as ee,G as te,Gn as v,Gt as ne,Hn as re,Ht as ie,In as ae,J as oe,Jn as se,Jt as ce,K as le,Kn as ue,Kt as de,Ln as fe,M as pe,Mn as me,Mt as y,Nt as he,On as ge,Or as _e,P as ve,Pn as ye,Pr as be,Q as xe,Qt as Se,R as Ce,Rn as we,Sn as Te,Sr as Ee,T as De,Tn as Oe,Tr as ke,Tt as b,Ut as Ae,Vt as je,W as Me,Wn as Ne,Wt as Pe,X as Fe,Xt as Ie,Y as Le,Yn as Re,Yt as ze,Z as Be,Zn as Ve,Zt as He,_r as x,_t as Ue,at as We,b as Ge,bn as Ke,br as qe,cr as Je,ct as Ye,d as Xe,dr as Ze,dt as Qe,en as $e,er as et,et as tt,ft as nt,gt as rt,it,jn as at,jr as ot,jt as st,kr as ct,kt as lt,lr as ut,mr as dt,or as ft,pr as pt,pt as mt,q as ht,qn as gt,qt as _t,rr as vt,rt as yt,sr as bt,st as xt,tr as St,ur as Ct,ut as wt,vr as Tt,w as Et,wr as Dt,xn as Ot,xr as kt,xt as At,yr as jt,yt as Mt,zn as Nt,zt as Pt}from"./cli-output-identity.lib-Dnk4Pkxd.mjs";import S from"node:process";import{z as C}from"zod";import{homedir as Ft,tmpdir as It}from"node:os";import{generateKeyBetween as Lt,generateNKeysBetween as Rt}from"fractional-indexing";import{chmodSync as zt,constants as Bt,createReadStream as Vt,createWriteStream as Ht,mkdirSync as Ut,writeFileSync as Wt}from"node:fs";import w from"node:path";import{createHash as T,randomBytes as Gt,randomUUID as Kt}from"node:crypto";import{setTimeout as qt}from"node:timers/promises";import{isDeepStrictEqual as Jt}from"node:util";import{access as Yt,chmod as Xt,mkdir as Zt,mkdtemp as Qt,open as $t,readFile as en,realpath as tn,rename as nn,rm as rn,stat as an,unlink as on,writeFile as sn}from"node:fs/promises";import{generate as cn,parse as ln}from"css-tree";import{parseFragment as un,serialize as dn,serializeOuter as fn}from"parse5";import{performance as pn}from"node:perf_hooks";import{Readable as mn,Transform as hn}from"node:stream";import{pipeline as gn}from"node:stream/promises";import{ZipFile as _n}from"yazl";import{createTRPCUntypedClient as vn,httpLink as yn}from"@trpc/client";import{spawn as bn}from"node:child_process";import{createServer as xn}from"node:http";const Sn=(e,t)=>e<t?-1:+(e>t),Cn=(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)??[])]},wn=(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:Cn(a,t.order)}},Tn=(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=wn(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}}},En=1e6,Dn=e=>Math.round(e*255*En)/En,E=(e,t=1)=>{let n=e.alpha*t;if(e.space===`srgb`){let t=[e.red,e.green,e.blue].map(e=>String(Dn(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)})`},On={x:0,y:0,width:1,height:1},kn=(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}},An=(e,t=On)=>[{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=kn(e,t);return[n.x,n.y]}),jn=1024,Mn=(e,t,n)=>{let r=e.stops.map(t=>`${n?`rgb(255 255 255 / ${String(t.color.alpha*e.opacity)})`:E({...t.color,alpha:1})} ${String(t.position*360)}deg`);return`conic-gradient(from 90deg at ${String(t)}% ${String(t)}% in srgb, ${r.join(`, `)})`},Nn=(e,t)=>{let n=An(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/jn:e),s=`width:100%;height:100%;background-image:${Mn(e,a,!1)};mask-image:${Mn(e,a,!0)};`;return`<g transform="matrix(${o.map(String).join(` `)})"><foreignObject x="${String(r*jn)}" y="${String(r*jn)}" width="${String(i*jn)}" height="${String(i*jn)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${s}"></div></foreignObject></g>`},Pn=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Nn(e)}</svg>`,Fn=(e,t)=>e===void 0||t===void 0?!1:e.x===t.x&&e.y===t.y,In=e=>{let t=[...e];for(;t.length>1&&Fn(t[0],t.at(-1));)t.pop();for(;t.length>1&&Fn(t[0],t[1]);)t.splice(1,1);return t},Ln=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},Rn=(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},zn=e=>{let t=Ln(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=Rn(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?In(n):null},Bn=Math.PI/2,Vn=1e6,Hn=e=>String(Math.round(e*Vn)/Vn),D=([e,t])=>`${Hn(e)} ${Hn(t)}`,Un=(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}},Wn=(e,t)=>{let{radius:n,reach:r,smoothing:i}=e,a=D(t([r,0]));if(n===0)return`L${a}`;let o=i*Bn/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=D(t([r-2*u,0])),f=D(t([s+l,0])),p=D(t([s,c])),m=D(t([c,s])),h=D(t([0,s+l])),g=D(t([0,r-2*u])),_=D(t([0,r]));return`L${a}C${d} ${f} ${p}${i===1?``:`A${Hn(n)} ${Hn(n)} 0 0 1 ${m}`}C${h} ${g} ${_}`},Gn=(e,t)=>{let{topLeft:n,topRight:r,bottomRight:i,bottomLeft:a,smoothing:o=0}=e;return[Un(n,[r,a],t,o),Un(r,[n,i],t,o),Un(i,[a,r],t,o),Un(a,[i,n],t,o)]},Kn=(e,t)=>{let[n,r,i,a]=Gn(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}},qn=(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]=Gn(e,{width:r,height:i});return[`M${D([n[0],a.reach+n[1]])}`,Wn(a,([e,t])=>[t+n[0],e+n[1]]),Wn(o,([e,t])=>[r-e+n[0],t+n[1]]),Wn(s,([e,t])=>[r-t+n[0],i-e+n[1]]),Wn(c,([e,t])=>[e+n[0],i-t+n[1]]),`Z`].join(``)},Jn=1e5,Yn=.01,Xn=1e-9,O=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],Zn=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Qn=(e,t)=>e[0]*t[1]-e[1]*t[0],k=(e,t)=>[e[0]-t[0],e[1]-t[1]],$n=e=>String(Math.round(e*Jn)/Jn),er=(e,t,n=0)=>{let[r,i,a,o]=e,s=Zn(r,o);if(n>=16||Zn(r,i)+Zn(i,a)+Zn(a,o)-s<=Yn/8){t.push(o);return}let c=O(r,i),l=O(i,a),u=O(a,o),d=O(c,l),f=O(l,u),p=O(d,f);er([r,c,d,p],t,n+1),er([p,f,u,o],t,n+1)},tr=(e,t,n,r)=>{let i=k(t,e),a=Zn(e,t);if(a<Xn)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-Yn/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)])}},nr=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`){er([t,a(),a(),a()],n);return}if(e===`A`){let e=i();r+=4,tr(t,a(),e,n)}};for(;r<t.length;)o(t[r++]??`Z`);return n.filter((e,t)=>Zn(e,n[(t+1)%n.length]??e)>Xn)},rr=(e,t,n)=>{let[r,i]=k(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]]]},ir=(e,t,n,r)=>{let i=k(t,e),a=k(r,n),o=Qn(i,a);if(Math.abs(o)<Xn)return O(t,n);let s=Qn(k(n,e),a)/o;return[e[0]+s*i[0],e[1]+s*i[1]]},ar=(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]=rr(i,a,t),c=k(s,o),l=[];for(let[e,t]of n.entries()){let r=n[(e+1)%n.length]??t,i=Qn(c,k(t,o))>=-1e-9,a=Qn(c,k(r,o))>=-1e-9;i&&l.push(t),i!==a&&l.push(ir(t,r,o,s))}if(n=l,n.length===0)break}return n},or=(e,t)=>{if(t===0)return e;let n=nr(e),r=t<0?ar(n,t):n.map((e,r)=>{let i=n[(r+n.length-1)%n.length]??e,a=n[(r+1)%n.length]??e,o=rr(i,e,t),s=rr(e,a,t);return ir(...o,...s)});return r.length<3?``:r.map((e,t)=>`${t===0?`M`:`L`}${$n(e[0])} ${$n(e[1])}`).join(``)+`Z`},sr=(e,t,n)=>t.width<=0||t.height<=0?``:or(qn(e,t),n),cr=(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*_}},lr=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}},ur=e=>{let t=lr(e);return t===null||e.box===void 0?null:cr(e.box,e.layout??{},t)},A=(e,t,n)=>({x:e.x+t.x*n,y:e.y+t.y*n}),dr=e=>`${String(e.x)} ${String(e.y)}`,fr=(e,t,n)=>({x:(t.x-e.x)/n,y:(t.y-e.y)/n}),pr=(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}})},mr=(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=fr(n,r,a),c=fr(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)}},hr=(e,t,n,r)=>{let i=n*e.cotangent,a=A(e.vertex,t,i*(1+r)),o=A(e.vertex,t,i),s=A(e.vertex,{x:e.before.x+e.after.x,y:e.before.y+e.after.y},n/Math.sin(e.angle)),c=fr(o,s,n),l=(Math.PI-e.angle)*r/2,u=A(A(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=A(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}},gr=(e,t,n)=>{let r=hr(e,e.before,t,n),i=hr(e,e.after,t,n),a=4/3*t*Math.tan((Math.PI-e.angle)*(1-n)/4),o=A(r.end,r.travel,a),s=A(i.end,i.travel,a),c=(e,t,n)=>`C${dr(e)} ${dr(t)} ${dr(n)}`;return dr(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):``)},_r=(e,t,n)=>{let r=e.map((t,n)=>mr(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+dr(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+gr(o,m,h)}).join(``)}Z`},vr=(e,t,n)=>_r(pr(e,t,n),e.cornerRadius,e.cornerSmoothing),yr=new WeakMap,br=new WeakMap,xr=e=>{if(br.has(e))return br.get(e)??null;let t=e.result.path.match(/M[^M]*/gu)??[],n=t.map(e=>{let t=zn(e);return{path:e,vertices:t!==null&&t.length>=3?t:null}}),r=t.length>0&&t.join(``)===e.result.path?n:null;return br.set(e,r),r},Sr=(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=xr(e);return i===null?r:{...r,path:i.map(e=>e.vertices===null?e.path:_r(e.vertices,n.topLeft,n.smoothing??0)).join(``)}},Cr=e=>{if(yr.has(e))return yr.get(e)??null;let t=zn(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 yr.set(e,n),n},wr=(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=Cr(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:_r(a,r,t.smoothing??0),viewBox:{x:0,y:0,width:n.width,height:n.height}}},Tr={topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},Er=[`border-top-left-radius`,`border-top-right-radius`,`border-bottom-right-radius`,`border-bottom-left-radius`],Dr=(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},Or=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]=Er.map(n=>Dr(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}},kr=(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`},Ar=(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:vr(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=Or(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&&Er.every(t=>e.styles[t]===void 0)?kr(n.width,n.height):qn(t&&e.component===`rectangle`&&e.appearance?.radius!==void 0?Tr:{...Tr,...r},n),viewBox:{x:0,y:0,width:n.width,height:n.height}}},jr=e=>{if(e.geometry?.kind===`boolean`&&e.box!==void 0)return e.geometry.result.isEmpty?`This shape has no closed geometry.`:Sr(e.geometry,e.box,e.appearance?.radius);let t=Ar(e,!1);return typeof t!=`string`&&e.geometry?.kind===`path`&&e.component===`rectangle`&&e.appearance?.radius!==void 0&&e.box!==void 0?wr(t,e.appearance.radius,e.box):t},Mr=e=>{let t=jr(e);if(typeof t==`string`)return t;if(e.box===void 0)return`The shape has no settled local box.`;let n=ur(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]}},Nr=.5,Pr=.25,Fr=(e,t=`field`,n)=>{let r=An(e,n),i=Math.max(Nr,...r.map(e=>Math.abs(e-Nr)))+1,a=Nr-i,o=Nr+i,s=[{x:.75,y:.75,points:`.5,.5 ${String(o)},.5 ${String(o)},${String(o)} .5,${String(o)}`},{x:Pr,y:.75,points:`.5,.5 .5,${String(o)} ${String(a)},${String(o)} ${String(a)},.5`},{x:Pr,y:Pr,points:`.5,.5 ${String(a)},.5 ${String(a)},${String(a)} .5,${String(a)}`},{x:.75,y:Pr,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="${E({...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>`},Ir=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Fr(e)}</svg>`,Lr=e=>e.parameter===`radius`?e.value/2:e.value,Rr=e=>{switch(e.kind){case`blur`:return`blur(${String(Lr(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)`}},zr=e=>e.filter(e=>e.visible).map(e=>Rr(e)).join(` `),Br=new Set([`base`,`embed`,`iframe`,`link`,`meta`,`object`,`script`]),Vr=/^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu,Hr=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,Ur=e=>!Br.has(e.toLowerCase()),Wr=e=>!Hr.test(e),Gr=(e,t)=>{let n=e.toLowerCase();return n===`srcdoc`||/^on/iu.test(n)?!1:n===`style`?Wr(t):![`href`,`src`,`action`,`formaction`,`xlink:href`].includes(n)||!Vr.test(t.replaceAll(/[\p{Control}\s]/gu,``))},Kr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),qr=(e,t)=>{if(!Kr(e)||e.kind!==`image`||typeof e.assetId!=`string`)return e;let n=t(e.assetId);return n===e.assetId?e:{...e,assetId:n}},j=(e,t)=>{let n=qr(e,t);if(!Kr(n)||!Kr(n.alternatives))return n;let r=n.alternatives,i=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,qr(n,t)]));return Object.entries(i).every(([e,t])=>r[e]===t)?n:{...n,alternatives:i}},Jr=(e,t)=>Array.isArray(e)?e.map(e=>{if(!Kr(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=>j(e,t))},...Kr(e.stroke)&&{stroke:{...e.stroke,paint:j(e.stroke.paint,t)}},...Array.isArray(e.children)&&{children:Jr(e.children,t)}}}):e,Yr=(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=>j(e,t))},...n.border!==void 0&&{border:{...n.border,paints:n.border.paints.map(e=>j(e,t))}},...n.outline!==void 0&&{outline:{...n.outline,paints:n.outline.paints.map(e=>j(e,t))}}}},...e.typography?.stroke!==void 0&&{typography:{...e.typography,stroke:{...e.typography.stroke,paint:j(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:Jr(e.props.richText,t)}}}}},Xr=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${E({...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>`},Zr=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${Xr(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,Qr=e=>({id:e,visible:!1,opacity:1,kind:`solid`,color:{space:`srgb`,red:0,green:0,blue:0,alpha:0}}),$r=()=>({opacity:1,blendMode:`normal`,fills:[],border:{visible:!1,width:{top:0,right:0,bottom:0,left:0},style:`solid`,paints:[Qr(`empty-border`)]},outline:{visible:!1,width:0,offset:0,style:`solid`,paints:[Qr(`empty-outline`)]},radius:{topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},shadows:[],filters:[],backdropFilters:[]}),ei=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],ti=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${E({...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(${ei(e).map(String).join(` `)})" color-interpolation="sRGB">${r}</radialGradient>`},ni=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${ti(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,ri=/^enh_[\w-]{43}$/,ii=e=>{let t=Ie.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new y(`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}},ai=(e,t,n)=>({loginWithToken:async n=>{if(!ri.test(n))throw new y(`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=ii(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=He.parse(await t.authenticationConfig());if(i.method===`token`)throw new y(`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=Se.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=ii(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 y(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return ii(await n.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),oi=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),si=e=>{if(e.byteLength<24||oi.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)}},ci=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 y(`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 y(`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=Je.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 y(`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=si(r);if(i===null||r.byteLength!==t.result.bytes||i.width!==t.result.width||i.height!==t.result.height)throw new y(`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}}},li=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]},ui=(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:li(e)}),di=async(e,t,n,r)=>{let i=await ci(e,n);return ui(n,t.write({body:i.body,...r}),i.source)},fi=[`canvas.render.create`,`canvas.render.get`],pi=e=>new y(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),mi=e=>{let t=e.failure;if(t===null)return pi(`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 y(n,t.message,r,{jobId:e.id,reason:t.reason,phase:t.phase,renderState:e.state})},hi=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),gi=async(e,t)=>{let n=ut.safeParse(await e.query(fi[1],{jobId:t}));if(!n.success||n.data.job.id!==t)throw pi(`render status`);return n.data.job},_i=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 y(`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 hi(250),a=a.purpose===`inspection`&&a.state===`queued`&&a.attempt>0?await t.resume():await gi(e,a.id)}if(a.state!==`succeeded`)throw mi(a);return a},vi=async(e,t)=>{let n=ft.safeParse(await e.mutate(fi[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 pi(`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 pi(`render identity`);return n.data.job},yi=(e,t)=>{if(t.maxOutputPixels!==void 0&&e.maxOutputPixels!==t.maxOutputPixels)throw new y(`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`})},bi=async(e,t)=>{let n=await vi(e.remote,t);try{yi(n,t);let r=await _i(e.remote,{initial:n,resume:async()=>vi(e.remote,t),deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress,timeoutOutcome:t.timeoutOutcome});return yi(r,t),r.state===`succeeded`?await di(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 y?new y(e.code,e.message,e.remediation,{...e.fields,jobId:n.id,operation:r}):new y(`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})}},xi=(e,t,n,r=()=>null)=>({execute:async i=>bi({remote:e,files:t,now:n,progress:r},i)}),Si={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},Ci=async e=>{try{return await e(),!0}catch{return!1}},wi=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await Ci(async()=>e.mutate(Si.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 Ci(async()=>e.mutate(Si.end,{canvasId:i.canvasId,activityId:n})))}}},Ti=e=>({begin:async t=>{try{let n=me.safeParse(await e.mutate(Si.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?wi(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>Ci(async()=>e.mutate(Si.end,{canvasId:t,activityId:n}))}),Ei=new Set([`insertPrototype`,`insertText`,`setBox`]),Di=e=>Ei.has(e.op),Oi=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,ki=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],Ai=e=>[...new Set(e.operations.flatMap(e=>ki(e)))].slice(0,100),ji=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:Di(e)?e.box==="default"?null:e.box:null,Mi=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}},Ni=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:15}),r=v.safeParse(n);if(!r.success)throw new y(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data},M=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Ni(e,t);let r=await Ti(e).begin({canvasId:t.canvasId,phase:Oi(t),nodeIds:Ai(t),bounds:Mi(t.operations.flatMap(e=>{let t=ji(e);return t===null?[]:[t]}))});try{return await Ni(e,t)}finally{await r?.finish()}}}),Pi=async(e,t,n)=>{let r=Ve.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!r.success)throw new y(`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 y(`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=Ct.safeParse(r.data.document);if(i.success)return i.data;throw new y(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},N=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):Sn(t.sortKey,r.sortKey)).map(([e])=>e),Fi=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},Ii=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),P=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new y(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Li=(e,t)=>{let n=new Set,r=t=>{for(let i of N(e,t))n.add(i),r(i)};return r(t),n},F=(e,t)=>{let n=new Set,r=t;for(;r!==void 0;){if(n.has(r))throw new y(`BAD_REQUEST`,`The canvas contains a parent cycle.`,`Repair the canvas topology before editing.`);if(n.add(r),P(e,r).locked===!0)return!0;r=e.relationships[r]?.parentId}return!1},Ri=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},zi=e=>{let t=0;return n=>(t+=1,`${Ri(e)}_${Ri(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},Bi=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of N(e,t))r(n)};return r(t),n},Vi=(e,t,n)=>Object.fromEntries(Bi(e,t).map(t=>[t,n(P(e,t).label)])),Hi=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=P(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}}},Ui=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=P(t,n.id);if(n.id===`root`)throw new y(`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 y(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let s=n.parentId??o.parentId;if(!Ii(t.nodes[s]))throw new y(`BAD_REQUEST`,`Canvas node ${s} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let c=Vi(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=Bi(t,n.id).map(e=>Hi(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))}}},Wi=(e,t,n)=>{if(t.length===0)throw new y(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let r=zi(n),i=t.map((t,n)=>Ui({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},Gi=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,N(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Ki=(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))}},qi=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new y(`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 y(`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}},Ji=(e,t)=>`parentId`in e?Ki(e,t):qi(e,t),Yi=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new y(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Li(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!Ii(n.document.nodes[t.parentId]))throw new y(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Xi=(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=Lt(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=Rt(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}}},Zi=(e,t)=>{if(t.length===0)throw new y(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=Gi(e),r=[];return{operations:t.flatMap(e=>{let t=Ji(e,n);Yi(e,t,n),r.push({nodeId:e.nodeId,...t});let i=Xi(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)??[]]}))}},I=e=>Math.min(1,Math.max(0,e)),Qi=e=>I(Number(e)/255),$i=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}},ea=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===`%`?I(Number(e)/100):Qi(e??`0`),r=t[7]===void 0?1:I(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}},ta=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:I(Number(t[2])),green:I(Number(t[3])),blue:I(Number(t[4])),alpha:I(t[5]===void 0?1:Number(t[5]))}},na=e=>{let t=e.trim().toLowerCase();return t===`transparent`?{space:`srgb`,red:0,green:0,blue:0,alpha:0}:t.startsWith(`#`)?$i(t):t.startsWith(`rgb`)?ea(t):t.startsWith(`color(`)?ta(t):null},ra=(e,t)=>({id:e,visible:!0,opacity:1,kind:`solid`,color:t}),L=(e,t)=>{let n=na(t);return n===null?null:ra(e,n)},ia=e=>e/2**32|0,aa=e=>e>>>0;function oa(e,t,n,r){let i=ia(n),a=aa(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function sa(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const ca=e=>e?`"${e}" `:``;function la(e,t=``){if(typeof e!=`number`)throw TypeError(ca(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ca(t)+`expected integer >= 0, got `+e);return e}function ua(e,t,n=``){if(sa(e)&&(t===void 0||e.length===t))return e;t!==void 0&&la(t,`length`);let r=sa(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ca(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const da=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)};function fa(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function pa(e,t){ua(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function ma(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ha(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function R(e,t){return e<<32-t|e>>>t}const ga=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,_a=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function va(e){if(ua(e),ga)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=_a[e[n]];return t}function ya(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function ba(e,t,n=`opts`){return da(e,`defaults`),t!==void 0&&da(t,n),Object.assign(e,t)}function xa(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=ba({},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 Sa=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ca(e,t,n){return e&t^~e&n}function wa(e,t,n){return e&t^e&n^t&n}var Ta=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=ha(this.buffer)}update(e){fa(this),ua(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=ha(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){fa(this),pa(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)),oa(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:ha(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 Ea=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Da=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]),z=new Uint32Array(64);var Oa=class extends Ta{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)z[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=z[e-15],n=z[e-2],r=R(t,7)^R(t,18)^t>>>3,i=R(n,17)^R(n,19)^n>>>10;z[e]=i+z[e-7]+r+z[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=R(o,6)^R(o,11)^R(o,25),u=l+t+Ca(o,s,c)+Da[e]+z[e]|0,d=(R(n,2)^R(n,13)^R(n,22))+wa(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(){ma(z)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ma(this.buffer)}},ka=class extends Oa{constructor(){super(32,Ea)}};const Aa=xa(()=>new ka,Sa(1)),ja=new Map,Ma=new Map,Na={depth:0},Pa=(e,t=1)=>{let n=Na.depth>0?Ma:ja;n.set(e,(n.get(e)??0)+t)},Fa=(e,t)=>e.sortKey===t.sortKey?e.childId.localeCompare(t.childId):e.sortKey<t.sortKey?-1:1,Ia=e=>{Pa(`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(Fa).map(e=>e.childId));return n},La=new WeakMap,Ra=new WeakMap,za=e=>{let t=La.get(e);if(t!==void 0)return t;let n=Ra.get(e)?.()??Ia(e);return Object.isFrozen(e)&&La.set(e,n),n},Ba=[],Va=(e,t)=>e.get(t)??Ba,Ha=(e,t)=>Va(za(e),t),Ua=e=>e.trim()===``||e.trim()===`about:blank`,Wa=e=>typeof e==`string`&&e.startsWith(`enhance-pending-image:`),Ga=e=>Wa(e.assetId)||e.opacity!==1||e.fit===`crop`&&e.transform!==void 0||(e.rotation??0)!==0||e.fit===`tile`&&(e.tileScale??1)!==1,Ka=e=>`--canvas-image-paint-${va(Aa(ya(JSON.stringify([e.assetId,e.opacity,e.rotation??0,e.fit===`tile`?e.tileScale??1:1,e.fit===`crop`?e.transform:void 0]))))}`,qa=e=>`--canvas-text-paints-${va(Aa(ya(JSON.stringify(e.filter(e=>e.visible),(e,t)=>e===`id`?void 0:t))))}`,Ja=(e,t=1)=>`${E(e.color,t)} ${String(e.position*100)}%`,Ya=e=>encodeURI(e).replaceAll(`"`,`%22`),Xa=e=>`url("${Ya(e)}")`,Za=e=>{switch(e.kind){case`solid`:{let t=E(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=>Ja(t,e.opacity)).join(`, `)})`:`url("data:image/svg+xml,${encodeURIComponent(Zr({...e,transform:e.transform}))}")`;case`radial-gradient`:{if(e.transform!==void 0)return`url("data:image/svg+xml,${encodeURIComponent(ni(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=>Ja(t,e.opacity)).join(`, `)})`}case`angular-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Pn(e))}")`;case`diamond-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Ir(e))}")`;case`image`:return Ua(e.assetId)?`none`:Ga(e)?`var(${Ka(e)}, none)`:Xa(e.assetId)}},Qa=(e,t)=>t>=1?0:e/(1-t)*100,$a=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(Qa(e.x,t))}% ${String(Qa(e.y,n))}%`,"background-size":`${String(100/t)}% ${String(100/n)}%`}},eo=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`?$a(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`}},to=e=>{if(e.length===0)return{};let t=e.toReversed().map(e=>eo(e));return Object.fromEntries([`background-size`,`background-position`,`background-repeat`,`background-origin`].map(e=>[e,t.map(t=>t[e]).join(`, `)]))},no=e=>e.kind===`solid`&&e.visible?E(e.color,e.opacity):void 0,ro=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,io=e=>ro(e)?void 0:no(e),ao=e=>{let t=e.filter(e=>e.visible),[n]=t;return n===void 0||t.length!==1?`transparent`:io(n)??`transparent`},oo=e=>({"background-image":e.toReversed().map(e=>Za(e)).join(`, `),...to(e)}),so=e=>{let t=e.filter(e=>e.visible);if(t.length===0||t.some(e=>ro(e)))return{background:`none`};let[n]=t,r=n===void 0?void 0:io(n);return r!==void 0&&t.length===1?{background:r,"background-image":`none`}:{"background-color":`transparent`,...oo(t)}},co=e=>{let t=e.filter(e=>e.visible),[n]=t;return t.length===1&&n?.kind===`solid`?{color:E(n.color,n.opacity)}:t.length===0?{color:`transparent`}:{color:`transparent`,...t.length>1?{"background-image":`var(${qa(t)}, none)`,"background-size":`100% 100%`,"background-position":`center`,"background-repeat":`no-repeat`}:oo(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`}},lo=new Set(e.keyof().options.filter(e=>/^(?:border|outline)(?:-|$)/u.test(e)&&!e.includes(`radius`))),uo=(e,t)=>{let n=t.toLowerCase();return lo.has(n)&&(n===e||n.startsWith(`${e}-`))},fo=[`top`,`right`,`bottom`,`left`],po=[`solid`,`dashed`,`dotted`],mo=[`width`,`style`,`color`],ho=(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},go=(e,t)=>{let n=x(t);if(/^(?:border(?:-(?:top|right|bottom|left))?|outline)$/u.test(e)){let t=n.find(e=>ho(e)!==void 0),r=n.find(e=>/^(?:none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/u.test(e)),i=n.find(e=>L(`probe`,e)!==null);if(t===void 0||r===void 0||i===void 0||n.length!==mo.length)return null;let a=e===`border`?fo.map(e=>`border-${e}`):[e];return Object.fromEntries(a.flatMap(e=>mo.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>fo.length)return null;let[t=``,r=t,i=t,a=r]=n;return Object.fromEntries(fo.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},_o=(e,t)=>e.additionalStyles?.declarations.filter(({property:n,value:r,enabled:i})=>uo(t,n)&&(!i||r.trim()!==``||e.appearance?.[t]===void 0))??[],vo=(e,t)=>{let n=_o(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(!uo(t,e))continue;let r=go(e.toLowerCase(),Tt(e,n).trim());if(r===null||String(n).includes(`!`))return null;Object.assign(a,r)}return a},yo=e=>{let t=vo(e,`border`);if(t===null)return{kind:`custom`};if(e.appearance?.border!==void 0&&_o(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=fo.map(n=>({width:ho(t[`border-${n}-width`]??`0`),authoredStyle:t[`border-${n}-style`],authoredColor:t[`border-${n}-color`],style:po.find(e=>e===t[`border-${n}-style`]),paint:L(`${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]}}},bo=e=>{let t=vo(e,`outline`);if(t===null)return{kind:`custom`};if(e.appearance?.outline!==void 0&&_o(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=ho(t[`outline-width`]),r=ho(t[`outline-offset`]??`0`,-1/0),i=po.find(e=>e===t[`outline-style`]),a=L(`${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]}}},xo=Object.freeze({top:0,right:0,bottom:0,left:0}),B=e=>e.alignment!==void 0&&e.alignment!==`inside`||e.layoutInclusion===`none`||e.layoutInclusion===`visible`&&(!e.visible||e.paints.every(e=>!e.visible))?xo:e.width,So=e=>{let t=e.visible?ao(e.paints):`transparent`,n=B(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}},Co=e=>{if(!e.visible)return{"outline-style":`none`};let t=ao(e.paints);return{"outline-style":e.style,"outline-width":e.width,"outline-offset":e.offset,"outline-color":t}},wo=e=>({...e.border!==void 0&&So(e.border),...e.outline!==void 0&&Co(e.outline)}),To=e=>{if(e.geometry?.kind===`boolean`||(e.appearance?.radius?.smoothing??0)<=0)return!1;let t=yo(e);return t.kind===`custom`||t.kind===`native`&&t.value.style!==`solid`},Eo=(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 Do(n);let r=Kn(n,t),i=Do(r);if((n.smoothing??0)<=0)return i;if(To(e))return{};let a=`path("${qn(n,t)}") border-box`,o=yo(e);if(o.kind!==`native`||Object.values(B(o.value)).every(e=>e===0))return{...i,"border-shape":a};let{top:s,right:c,bottom:l,left:u}=B(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`}},Do=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}),Oo=new Set([we,re]),ko=e=>e.visible&&e.kind===`blur`&&e.progression!==void 0,Ao=e=>e.geometry===void 0&&Oo.has(e.component)?(e.appearance?.backdropFilters??[]).find(e=>ko(e))??null:null,jo=(e,t)=>{let n=Ao(e);return n===null?t:t.filter(e=>e!==n)},Mo=new Set([we,Nt,re,o]),No=new Set([we,Nt,re]),V=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,Po=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),Fo=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`},Io=e=>{if(e.component!==`rectangle`||e.geometry!==void 0||Fo(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=>!Po(e))},Lo=e=>e.geometry===void 0&&Mo.has(e.component)&&(e.component!==`image`||(typeof e.props?.src!=`string`||e.props.src===``)&&e.appearance?.fills!==void 0),Ro=e=>e?.visible===!0?e.paints.filter(e=>e.visible):[],zo=e=>V(e)||e.kind===`image`&&(e.filters?.some(e=>e.visible)??!1),Bo=e=>{if(!Lo(e))return[];let t=(e.appearance?.fills??[]).filter(e=>e.visible);return t.some(e=>zo(e))||t.length>0&&Ao(e)!==null?t:[]},Vo=e=>e.style===`solid`||e.dashOrigin===`css`&&e.dashPattern===void 0&&e.dashCap===void 0,Ho=e=>{let t=Ro(e);return t.length>0&&((e.alignment??`inside`)!==`inside`||!Vo(e)||t.length>1||t.some(e=>e.kind!==`solid`))},Uo=(e,t)=>{let n=e.appearance?.border;if(n===void 0||e.geometry!==void 0||!No.has(e.component))return[];let r=Ro(n);return r.some(e=>V(e))?r.map(e=>({kind:`border`,paints:[e]})):n.layoutInclusion===`none`||n.layoutInclusion===`visible`||Ho(n)||t&&r.length>0?[{kind:`border`,paints:r}]:[]},Wo=e=>{let[t,...n]=Ro(e.appearance?.outline);return(e.appearance?.radius?.smoothing??0)>0&&n.length===0&&t?.kind===`solid`&&!V(t)},Go=e=>{let t=e.appearance?.outline;if(t===void 0||e.geometry!==void 0||!No.has(e.component)||t.width<=0||Wo(e))return[];let n=Ro(t);return n.some(e=>V(e))?n.map(e=>({kind:`outline`,paints:[e]})):n.length>1||t.style!==`solid`||n.some(e=>e.kind!==`solid`)?[{kind:`outline`,paints:n}]:[]},H=e=>{let t=Bo(e),n=Lo(e)&&!Io(e)?(e.appearance?.shadows??[]).filter(e=>e.visible):[],r=n.filter(e=>e.kind===`outer`&&V(e)),i=n.filter(e=>e.kind===`inner`&&(t.length>0||V(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,...Uo(e,t.length>0),...Go(e)],hasPaintElements:a.length>0}},Ko=e=>e.elements.flatMap(e=>e.kind===`fill`?[e.paint]:[]),qo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.shadow]:[]),Jo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.paints]:[]),Yo=(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`},Xo={top:0,right:0,bottom:0,left:0},Zo={inside:0,center:.5,outside:1},Qo=[[`topLeft`,`top-left`,`left`,`top`],[`topRight`,`top-right`,`right`,`top`],[`bottomRight`,`bottom-right`,`right`,`bottom`],[`bottomLeft`,`bottom-left`,`left`,`bottom`]],$o=e=>Jo(H(e),`border`).length>0,es=(e,t=e.box)=>{if(!$o(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=B(r);if((i.smoothing??0)<=0||Object.values(a).every(e=>e===0))return n;let o=qn(i,t),s=qn(i,t,[-a.left,-a.top]);return{...n,"border-shape":`path("${o}") border-box path("${s}") padding-box`}},ts=(e,t)=>{let n=e.appearance?.radius;return n===void 0?{"border-radius":`inherit`}:Object.fromEntries(Qo.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`]}))},ns=1e3,U=e=>String(Math.round(e*ns)/ns),rs=(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${U(n)} ${U(r)}`:`A${U(e)} ${U(t)} 0 0 1 ${U(n)} ${U(r)}`;return[`M${U(i[0])} 0`,`H${U(e-a[0])}`,c(a,e,a[1]),`V${U(t-o[1])}`,c(o,e-o[0],t),`H${U(s[0])}`,c(s,0,t-s[1]),`V${U(i[1])}`,c(i,i[0],0),`Z`].join(``)},is=e=>{if(e.stroke.style===`solid`)return{};let t=Yo(e.stroke.style,e.widest,e.stroke),n=`<svg xmlns="http://www.w3.org/2000/svg" width="${U(e.width)}" height="${U(e.height)}"><path d="${rs(e.width,e.height,e.corners)}" fill="none" stroke="#000" stroke-width="${U(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`}},as=(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 is({width:n.width+r.left+r.right,height:n.height+r.top+r.bottom,corners:{topLeft:a(Qo[0]),topRight:a(Qo[1]),bottomRight:a(Qo[2]),bottomLeft:a(Qo[3])},widest:Math.max(...Object.values(t.width)),stroke:t})},os=(e,t=e.box,n)=>{let r=e.appearance?.border,[i]=Jo(H(e),`border`);if(r===void 0||i===void 0)return null;let a=n??i,o=B(r),s=Zo[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`&&Vo(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`}:ts(e,c),...wo({...l,border:{...l.border,paints:[...a]}}),...!d&&{"border-color":`transparent`,...oo(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&&Eo({...e,styles:{},additionalStyles:void 0,appearance:l},t),...!d&&as(e,r,t,s===0?Xo:c)}},ss=(e,t)=>{if(Io(e))return[];let n=H(e),r=[...qo(n,`outer-shadow`),...qo(n,`inner-shadow`)];return r.length===0?t:t.filter(e=>!r.includes(e))},cs=e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${E(e.color)}`,ls=e=>`${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${E(e.color)}`,us=(e,t)=>{let n=ss(e,t).filter(e=>e.visible);if(e.component===`text`){let e=n.filter(e=>e.kind===`outer`&&e.spread===0).map(e=>ls(e)).join(`, `);return{"box-shadow":`none`,"text-shadow":e===``?`none`:e}}let r=n.map(e=>cs(e)).join(`, `);return{"box-shadow":r===``?`none`:r}},ds=(e,t)=>{let n=e.appearance?.border,r=n===void 0?{top:0,right:0,bottom:0,left:0}:B(n);return{position:`absolute`,top:-r.top,right:-r.right,bottom:-r.bottom,left:-r.left,"border-radius":`inherit`,"pointer-events":`none`,"box-shadow":cs(t),"mix-blend-mode":t.blendMode??`normal`}},fs=(e,t)=>{let n=t.map((n,r)=>{let[i=``,a,...o]=x(n),s=na(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)},ps=(e,t)=>{let n=/^(linear|radial)-gradient\((.*)\)$/su.exec(t);if(n===null)return null;let r=[...x(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=>x(e).length>1);if(s.some(Boolean)&&!s.every(Boolean))return null;let c=fs(e,r);if(c===null)return null;let l={id:e,visible:!0,opacity:1,stops:c},u=ot.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},ms=(e,t,n,r)=>{let i=x(e[t]??r,`,`);return i[n%i.length]??r},hs=(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=ms(n,`background-position`,r,`0% 0%`),s=ms(n,`background-size`,r,`auto`),c=ms(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}},gs=(e,t)=>{let n=t.background,i=t[`background-color`]??n,a=i===void 0||i===`none`?null:L(`${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=x(o,`,`).map((n,i)=>{let a=`${e}-fill-${String(i)}`,o=ps(a,n),s=ms(t,`background-size`,i,`auto`);if(o!==null&&![`auto`,`auto auto`,`100% 100%`].includes(s))return null;let c=o??hs(a,n,t,i),l=r.safeParse(ms(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()]},_s=[[`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]],vs=new Set([`color`,`-webkit-text-fill-color`]),ys=(e,t)=>{let n=new Set;for(let r of t){let t=r.toLowerCase(),i=e.component===`text`;i&&vs.has(t)&&n.add(`fills`);for(let[e,r]of _s)r.test(t)&&(!i||e!==`fills`)&&n.add(e)}return[...n].filter(t=>e.appearance?.[t]!==void 0)},bs=new Set([`background`,`background-color`,`background-image`]),xs=new Set([`background-position`,`background-size`,`background-repeat`,`background-origin`,`background-blend-mode`]),Ss=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(pt(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},Cs=e=>{let t=Ss(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:bs};if(Object.entries(t).some(([e,t])=>!bs.has(e)&&!xs.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=gs(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(bs);for(let e of xs)i.add(e);return{kind:`native`,fills:r,owned:i}},ws=e=>({...Ko(H(e)).length>0&&{background:`none`},...Ao(e)!==null&&{isolation:`isolate`}}),Ts=e=>({position:`absolute`,inset:0,...oo([e]),...e.kind===`image`&&e.filters!==void 0&&{filter:zr(e.filters)},...e.blendMode!==void 0&&e.blendMode!==`normal`&&{"mix-blend-mode":e.blendMode}}),Es=[[`topLeft`,`top-left`],[`topRight`,`top-right`],[`bottomRight`,`bottom-right`],[`bottomLeft`,`bottom-left`]],Ds=e=>Jo(H(e),`outline`).length>0,Os=e=>Ds(e)?{"outline-style":`none`}:{},ks=(e,t,n)=>{let r=e.appearance?.radius;if(r===void 0)return{};let i=t.offset+t.width,a=Yo(t.style,t.width,t),o=sr(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`}},As=(e,t=e.box,n)=>{let r=e.appearance?.outline,[i]=Jo(H(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}:B(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(Es.map(([e,t])=>[`border-${t}-radius`,d(e)])),...oo(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&&ks(e,r,t),...t!==void 0&&(o?.smoothing??0)<=0&&is({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})}},js=e=>{if(g(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`)},Ms=(e,t)=>{let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)?Math.min(1,Math.max(0,n)):t},Ns=e=>ct.find(t=>t===e)??`normal`,Ps=(e,t)=>{let n=Number(String(e??``).replace(`px`,``));return Number.isFinite(n)?Math.max(t,n):0},Fs=e=>Ps(e,0),Is=(e,t)=>e===0?t:e,Ls=e=>{let[t=0,n=t,r=t,i=n]=String(e[`border-radius`]??`0`).split(/\s+/u).map(e=>Fs(e));return{topLeft:Is(Fs(e[`border-top-left-radius`]),t),topRight:Is(Fs(e[`border-top-right-radius`]),n),bottomRight:Is(Fs(e[`border-bottom-right-radius`]),r),bottomLeft:Is(Fs(e[`border-bottom-left-radius`]),i)}},W=e=>{let t=$r(),n=yo(e),r=bo(e),i=L(`${e.id}-fill`,String(e.styles[e.component===`text`?`color`:`background`]??``)),a=e.component===`text`?null:Cs(e);return{...t,opacity:e.appearance?.opacity??Ms(e.styles.opacity,1),blendMode:e.appearance?.blendMode??Ns(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??Ls(e.styles),...e.appearance?.retainedBorder!==void 0&&{retainedBorder:e.appearance.retainedBorder},shadows:e.appearance?.shadows??[],filters:e.appearance?.filters??[],backdropFilters:e.appearance?.backdropFilters??[]}},Rs=e=>{let t=e.appearance?.fills;return e.component===`text`&&js(e)?{...t!==void 0&&{color:co(t).color??`transparent`},"background-image":`none`}:t===void 0?{}:e.component===`text`?co(t):so(t)},zs=e=>{let t=e.appearance,n={...Rs(e),...ws(e)};return(t?.opacity??Ms(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,Do(t.radius),Eo(e)),Object.assign(n,wo(t),es(e),Os(e)),t.filters!==void 0&&(n.filter=zr(t.filters)),t.shadows!==void 0&&Object.assign(n,us(e,t.shadows)),t.backdropFilters!==void 0&&(n[`backdrop-filter`]=zr(jo(e,t.backdropFilters))),n)},Bs=e=>{let t=W(e).radius;return t.topLeft===0&&t.topRight===0&&t.bottomRight===0&&t.bottomLeft===0},Vs=e=>{let t=W(e);return yo(e).kind!==`native`&&bo(e).kind!==`native`&&t.shadows.every(e=>!e.visible)&&t.filters.every(e=>!e.visible)&&t.backdropFilters.every(e=>!e.visible)},Hs=e=>e!==void 0&&e.geometry===void 0&&(e.component===`image`||e.component===`rectangle`&&Bs(e))&&Vs(e),Us=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},Ws=(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},Gs=(e,t)=>{let n=Ws(e,t);if(n===void 0)return null;let r=Ha(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=>Hs(e)&&Ys(e,i)!==null)?r:null},Ks=(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}},qs=(e,t)=>{let n=Za(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:Ks(e.fit===`fit`?`fit`:`cover`,t,r)}},Js=(e,t)=>{let n=e.props?.src;if(typeof n!=`string`||n===``)return[];let r=Xa(n),i=e.props?.fit;if(i!==`cover`&&i!==`contain`)return[{image:r,box:t}];let a=Us(e);return a===void 0?null:[{image:r,box:Ks(i===`cover`?`cover`:`fit`,t,a)}]},Ys=(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 Js(e,n);let{opacity:r}=W(e),i=[],a=W(e).fills.filter(e=>e.visible).toReversed();for(let e of a)if(e.kind===`image`){let t=qs(e,n);if(t===null)return null;i.push(t)}else i.push({image:Za({...e,opacity:e.opacity*r}),box:n});return i},Xs=(e,t)=>t.geometry?.kind===`mask`?e.nodes[t.geometry.maskId]:void 0,Zs={a:1,b:0,c:0,d:1,e:0,f:0},Qs=(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}),$s=e=>{let{fills:t,opacity:n}=W(e);return(1-t.filter(e=>e.visible).reduce((e,t)=>e*(1-t.opacity*(t.kind===`solid`?t.color.alpha:1)),1))*n},ec=(e,t,n)=>{let[r,i,a,o,s,c]=e.matrix,l=Qs(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}},tc=(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:Mr(t);if(s!==null&&typeof s!=`string`&&n.push(ec(s,i,a*$s(t))),!o&&t.component!==`frame`)return;let c=ur(t);if(c===null)return;let l=Qs(i,c),u=a*W(t).opacity;for(let n of Ha(e.relationships,t.id)){let t=e.nodes[n];t!==void 0&&r(t,l,u)}};return r(t,Zs,1),n},nc=e=>{let t=2166136261;for(let n of e)t=Math.imul(t^(n.codePointAt(0)??0),16777619);return(t>>>0).toString(16)},rc=(e,t,n)=>{if(Gs(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]}},ic=(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=jr(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=jr(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??Xs(e,t);if(a?.component===`text`&&a.visible!==!1)return rc(e,a,i);let o=a===void 0||a.visible===!1?null:tc(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:Mr(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]}},ac=(e,t,n)=>{let r=ic(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(`%`,`_`)}-${nc(JSON.stringify([i,a,c,s]))}`,path:i,fillRule:a,transform:c,matrix:o,...s!==void 0&&{shapes:s}}},oc=(e,t)=>{let n=Ot(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}}},sc=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),cc=(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=_e.safeParse({id:o,property:t,value:String(i),enabled:!0});if(!s.success)throw new y(`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=Tn(t.additionalStyles,a);return o===null?null:{op:`patchAdditionalStyles`,nodeId:t.id,additionalStyles:o}},lc=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...dt(t,r,e),...dt(n,r,e)],o=gt(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}},uc=(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 dt(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},dc=(t,n,r)=>{let i=uc(t,n,r),a=cc(n,i),o=Object.fromEntries(Object.entries(i).filter(([t,n])=>e.safeParse({[t]:n}).success)),s={...n,styles:{...n.styles},...a!==null&&{additionalStyles:wn(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=lc(t,n,s,r),l=oc(n,i),u=ys(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]]},fc=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=sc(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},pc=(e,t)=>{let n=[...fc(t)].flatMap(([t,n])=>{let r=e.nodes[t];if(r===void 0)throw new y(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return dc(e,r,n)});if(n.length===0)throw new y(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},mc=(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=Ke(e.typography,{clear:[...Ot(new Set([...Object.keys(t.styles),...r]))]});return G({...e,styles:n},`typography`,i??`default`)},hc=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),gc=e=>hc.has(e.op),G=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},_c=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new y(`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 mc(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 G(e,`typography`,Ke(e.typography,t.typography)??`default`);case`setTypography`:return G(e,`typography`,t.typography);case`setLayout`:return G(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=wn(e.additionalStyles,t.additionalStyles);return G(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return G(e,`additionalStyles`,t.additionalStyles)}},vc=(e,t)=>{if(!gc(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new y(`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=P(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:_c(n,t)}}},yc=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}}}},bc=(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 pc(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Wi(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=Zi(t.scene,[yc(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},xc=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=bc(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=vc(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:N(r.scene,e)}))}},K=e=>{throw new y(`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.`)},Sc=(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`?K([`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]},Cc=e=>e.op===`insertNode`?[e.node.id]:e.op===`insertText`||e.op===`insertPrototype`?[e.nodeId]:e.op===`insertConvertedSubtree`?Object.keys(e.nodes):[],wc=(e,t)=>{let r=t.destination;if(r.kind===`adjacent`)return K([`adjacent conversion`]);let i=r.kind===`replace`?e.relationships[r.targetNodeId]?.parentId:r.targetNodeId;if(i===void 0)return K([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?K([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:``}}}},Tc=e=>({component:e.op===`insertText`?`text`:`prototype`,props:{...e.op===`insertPrototype`&&e.canvasPageId!==void 0&&{canvasPageId:e.canvasPageId}}}),Ec=(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]:Tc(t)},relationships:{[t.nodeId]:{parentId:t.parentId,sortKey:``}}};if(t.op===`insertConvertedSubtree`)return wc(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:{}}},Dc=(e,t,n,r)=>{let i=Cc(r),a=e.nodeIds.length===0&&(i.length>0||r.op===`move`||r.op===`setParentage`),o=[...Sc(r,t).filter(e=>!a||e!==`root`),...i.filter(e=>t.nodes[e]!==void 0)].filter(e=>!n.has(e));return o.length>0&&K(o),i},Oc=(e,t,r)=>{if(!lt(e))return;let i=new Set(_(e,t)),a=at(e,t);if(!a.ok)return K(e.nodeIds);let o={nodes:{...t.nodes},relationships:{...t.relationships}};for(let t of r){let r=Dc(e,o,i,t),s=Ec(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&&K(c);for(let e of r)i.add(e);if(t.op!==`remove`)continue;let l=at({...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)}},kc=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]}},Ac=(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]:kc(e),jc=(e,t)=>{let n=new Set(e.edits.flatMap(e=>kc(e)));for(let e of n)P(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[],...e.pageId!==void 0&&{pageId:e.pageId}};for(let n of e.edits)b(r,t,Ac(n,t))},Mc=e=>({execute:async t=>{let n=await Pi({remote:e},t.canvasId,t.baseVersion);jc(t,n);let r=xc(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);Oc({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=Ne.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:15,baseVersion:t.baseVersion,operations:r.operations});if(!i.success)throw new y(`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 M(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}}}}),Nc=(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},q=(e,t,n,r=48e3)=>{if(t>e.length)throw new y(`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}},Pc=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}))]:[],Fc=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,Ic=(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:Fc(e),failure:e.failure,details:q(Pc(e),t.offset,t.limit),warnings:e.state===`succeeded`?[`This receipt does not verify visual fidelity. Render the committed root to inspect it.`]:[]}),Lc=e=>new y(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),Rc=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),zc=e=>{let t=e.failure;return new y(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})},Bc=async(e,t)=>{let n=St.safeParse(await e.query(`canvas.render.getImport`,{jobId:t}));if(!n.success)throw Lc(`conversion status`);if(n.data.job.id!==t)throw Lc(`conversion identity`);return n.data.job},Vc=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 Rc(250),i=await Bc(e,i.id)}if(i.state!==`succeeded`)throw zc(i);return i},Hc=(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},Uc=(e,t)=>{let n=t.request;if(e.canvasId!==n.canvasId||e.requestedVersion!==n.expectedVersion||!Hc(e,t))throw Lc(`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 Lc(`conversion source`);if(e.state===`succeeded`&&(e.result.canvasId!==n.canvasId||n.revisionPolicy===`strict`&&e.result.previousVersion!==n.expectedVersion))throw Lc(`conversion commitment`)},Wc=async(e,t)=>{let n=et.safeParse(await e.mutate(`canvas.render.importSource`,t.request));if(!n.success)throw Lc(`conversion creation`);Uc(n.data.job,t);let r=await Vc(e,n.data.job,t.waitMs);return Uc(r,t),r},Gc=async(e,t)=>{let n=At.parse(t),r=i(n.canvasRef);return Ic(await Wc(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})},Kc=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof y?{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.`]}),qc=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 Kc(e,t,n.result.version)}},Jc=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??``}})},Yc=(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}),Xc=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.`]}),Zc=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}}}}),Qc=(e,t)=>({execute:async n=>{let r=await Ti(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await Wc(e,Zc(n));if(n.responseMode===`bounded`)return Ic(i,{offset:0,limit:40});if(i.state!==`succeeded`)return Xc(i);if(n.review===`none`)return Yc(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await qc(t,n,i),o=[];try{o=await Jc(e,i)}catch{o=[]}return{...Yc(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),$c=async(e,t)=>{let n=i(t.canvas),r=Ve.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),a=Ct.parse(r.document);lt(n)&&_(n,a),t.nodeId!==void 0&&b(n,a,[t.nodeId]);let o=at(t.nodeId===void 0?n:{...n,nodeIds:[t.nodeId]},a);if(!o.ok)throw new y(`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.`]}},el=(e,t,n)=>{try{Wt(e,t,{flag:n?`w`:`wx`,mode:384}),zt(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new y(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.`)}},tl=e=>({write:t=>{if(t.outputPath!==null){let e=w.resolve(t.outputPath);return el(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=w.join(e,`sensitive`);Ut(n,{recursive:!0,mode:448}),zt(n,448);let r=w.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return el(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),nl=async(e,t)=>{try{return{value:await e.query(`canvas.render.preparation.get`,{jobId:t})}}catch(e){if(e instanceof y&&![`INTERNAL`,`RATE_LIMITED`].includes(e.code))throw e;return null}},rl=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 qt(Math.min(250,n));let a=await nl(e,t.id);if(a===null)return i;if(i=fe.parse(a.value).job,i.id!==t.id)throw new y(`INTERNAL`,`Preparation identity changed.`,`Retry the original request.`)}return i},il=async(e,t,n)=>{let r=ae.parse(await e.mutate(`canvas.render.preparation.create`,t)),i=await rl(e,r.job,n);if(i.canvasId!==t.canvasId||i.requestedVersion!==t.expectedVersion||!Jt(i.scope,t.scope)||!Jt(i.request,t.request))throw new y(`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 y(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);return i},al=`Repeat canvas_capture with identical arguments and clientToken, or follow operation_status. An unfinished step is not proof that nothing was saved.`,ol=e=>e===`queued`||e===`running`?`pending`:`not_confirmed`,sl=(e,t)=>({operation:t.operation,state:t.state,requestedVersion:e.input.baseVersion,source:e.input.source,attachment:t.frame===void 0||t.frame===null?ol(t.state):`committed`,result:t.result,frame:t.frame??null,failure:t.failure,warningCount:1,warnings:[t.warning]}),cl=e=>({kind:`canvas-mutation`,canvasId:e.canvasId,mutationId:e.clientToken,fingerprint:e.fingerprint}),ll=(e,t,n,r)=>sl(e,{operation:cl(e),state:`succeeded`,result:n,failure:null,frame:{nodeId:r,version:t.version},warning:`The capture is saved as an editable frame. Render the frame at its version to inspect it.`}),ul=e=>({kind:`recording`,recordingId:e.recordingId,atMs:e.atMs}),dl=(e,t,n)=>{let r=Object.fromEntries(Object.entries(e.nodes).map(([r,i])=>{let a={...i.props,capturedResource:{screenId:t.screenId}};if(r!==e.rootNodeId)return[r,{...i,props:a}];let o=i.props?.conversion;return[r,{...i,...i.box!==void 0&&{box:{...i.box,x:t.box.x,y:t.box.y}},props:{...a,conversion:{...typeof o==`object`&&o,provenance:ul(n)}}}]}));return{...e,destination:{kind:`insert-children`,targetNodeId:`root`,...t.pageId!==void 0&&{pageId:t.pageId}},nodes:r}},fl=(e,t)=>new y(t instanceof y?t.code:`INTERNAL`,t instanceof y?t.message:`The captured frame could not be confirmed.`,al,{...t instanceof y&&t.fields,outcome:`not_confirmed`,operation:JSON.stringify(cl(e))}),pl=async(e,t,n)=>{let r=Ne.parse({canvasId:t.canvasId,mutationId:t.clientToken,documentFormatVersion:15,baseVersion:t.input.baseVersion,operations:[n],requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});try{return v.parse(await M(e).execute(r))}catch(e){throw fl(t,e)}},ml=async(e,t,n,r)=>{let[i]=n.result.operations;if(n.result.operations.length!==1||i?.op!==`insertConvertedSubtree`)throw new y(`INTERNAL`,`The compiled capture is not one editable frame.`,`Capture the moment again with a new clientToken.`);let a=await pl(e,t,dl(i,r,t.input.source));if(a.canvasId!==t.canvasId||a.mutationId!==t.clientToken||a.version!==t.input.baseVersion+1||!a.insertedNodeIds.includes(i.rootNodeId))throw fl(t,null);return ll(t,a,r,i.rootNodeId)},hl=[`canvas.render.get`,`canvas.render.snapshot`],gl=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),_l=e=>new y(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}),vl=async(e,t)=>{let n=ut.safeParse(await e.query(hl[0],{jobId:t}));if(!n.success)throw new y(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},yl=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 y(`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 gl();let d=await vl(e,o.id);if(d.id!==t.id)throw bl();Sl(d,n),o=d}return o},bl=()=>new y(`INTERNAL`,`The snapshot response does not match the requested source or revision.`,`Run enhance doctor and report the capture job ID.`),xl=(e,t)=>t.context?.request.placement.kind===`editable-below-source`?e.screenNodeId===null&&e.version===t.context.expectedVersion:e.screenNodeId===`scr_${t.recordingId}_${String(t.atMs)}`&&(t.context===void 0||e.version===t.context.expectedVersion+1),Sl=(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 bl();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||!xl(n,t))throw bl()},Cl=async(e,t,n)=>{let r=bt.safeParse(await e.mutate(hl[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs,...n.context!==void 0&&{context:n.context}}));if(!r.success)throw new y(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");return Sl(r.data.job,n),yl(e,r.data.job,n,t)},wl=async(e,t,n)=>{let r=await Cl(e,t,n);if(r.state!==`succeeded`||r.result.snapshot===void 0)throw _l(r);let i={...r,result:{...r.result,snapshot:r.result.snapshot}},a=i.result.snapshot,{screenNodeId:o}=a;if(o===null)throw bl();return{jobId:i.id,canvasId:i.canvasId,...a,warnings:i.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${i.canvasId} --node-id ${o}`,`enhance canvas render --canvas ${i.canvasId} --node-id ${o} --expected-version ${String(a.version)}`]}},Tl=(e,t)=>({execute:async n=>wl(e,t,n)}),El=[`canvas.mutation.get`],Dl=async(e,t,n,r)=>{let i=await il(e,{canvasId:t.canvasId,expectedVersion:t.input.baseVersion,request:{kind:`compile-screens`,landing:`editable-frame`,sources:[{screenId:n.screenId,captureId:n.screenId,label:`Captured page`}]},scope:{nodeIds:[]}},r);return i.state===`succeeded`?ml(e,t,i,n):sl(t,{operation:{kind:`canvas-preparation`,canvasId:t.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:t.fingerprint},state:i.state,result:n,failure:i.failure,warning:i.state===`queued`||i.state===`running`?`The page is stored and still being made editable. ${al}`:`The page could not be made editable, and nothing was added to the canvas. Capture the moment again with a new clientToken.`})},Ol=async(e,t,n,r)=>Cl(e,()=>null,{canvasId:t.canvasId,recordingId:t.input.source.recordingId,atMs:t.input.source.atMs,retryClientToken:t.clientToken,timeoutMs:t.input.waitMs,bounded:!0,context:{expectedVersion:t.input.baseVersion,request:{previewJobId:t.input.previewJobId,scope:{pageId:n,nodeIds:[...r]},placement:{kind:`editable-below-source`}}}}),kl=async(e,t,n)=>{let r=ee.parse(t),a=i(r.canvasRef),o={input:r,canvasId:a.canvasId,clientToken:n,fingerprint:s({operation:`canvas.capture/2`,reference:a,baseVersion:r.baseVersion,source:r.source,previewJobId:r.previewJobId})},c=ue.parse(await e.query(El[0],{canvasId:o.canvasId,mutationId:n,fingerprint:o.fingerprint}));if(c.state===`committed`)return ll(o,c.result,null,c.result.insertedNodeIds[0]??``);let l=Date.now(),u=await Ol(e,o,a.pageId,a.nodeIds),d=u.state===`succeeded`?u.result.snapshot:void 0;return d===void 0?sl(o,{operation:{kind:`canvas-render`,canvasId:u.canvasId,jobId:u.id},state:u.state,result:null,failure:u.failure,warning:u.state===`queued`||u.state===`running`?`The moment is still being stored. ${al}`:`The moment could not be stored, and nothing was added to the canvas.`}):Dl(e,o,d,Math.max(0,r.waitMs-(Date.now()-l)))},Al=[`canvas.asset.reserve`,`canvas.asset.complete`,`canvas.document.get`],jl=(e,t)=>new y(e instanceof y?e.code:`INTERNAL`,e instanceof y?e.message:`The asset import did not return a confirmed result.`,e instanceof y?e.remediation:`Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.`,{...e instanceof y&&e.fields,operation:JSON.stringify(t),outcome:`not_confirmed`}),Ml=(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 y(`INTERNAL`,`The returned asset does not match this import intent.`,`Check the API and CLI versions. Do not insert an unverified resource.`)},Nl=(e,t)=>({execute:async n=>{let r=i(n.canvasRef);if(lt(r)){let t=Ve.parse(await e.query(Al[2],{canvasId:r.canvasId}));_(r,Ct.parse(t.document))}let{body:a,...o}=await t.read(),s=qe.parse({...o,canvasId:r.canvasId,clientToken:n.clientToken}),c={kind:`canvas-asset`,canvasId:r.canvasId,clientToken:n.clientToken};try{let t=kt.parse(await e.mutate(Al[0],s));Ml(t,s),t.upload!==null&&await e.upload({...t.upload,body:a});let i=jt.parse(await e.mutate(Al[1],{canvasId:r.canvasId,clientToken:n.clientToken}));if(Ml(i,s),i.assetId!==t.assetId||i.path!==t.path)throw new y(`INTERNAL`,`The completed asset identity changed.`,`Read operation_status and do not place an unconfirmed resource.`);return ve.parse({operation:c,resource:i,placement:`not_requested`})}catch(e){throw jl(e,c)}}}),Pl=15e3,Fl=async e=>new Promise(t=>setTimeout(t,e)),Il=new Set([`ready`,`failed`,`abandoned`]),Ll=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`],Rl=e=>new y(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,`Check the existing deployment status before retrying with the same publication token.`),zl=async(e,t,n,r)=>{let i=Ae.safeParse(await e.mutate(Ll[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 Rl(`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=ze.safeParse(await e.mutate(Ll[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId}));if(!n.success||n.data.deploymentId!==i.data.deploymentId)throw Rl(`artifact submission`)}return i.data},Bl=async(e,t,n,r)=>{let i=ne.safeParse(await e.query(Ll[0],{}));if(!i.success)throw Rl(`capabilities`);let a=await t.package({entryPath:n.entryPath,limits:i.data.limits});try{return await zl(e,n,a,r)}finally{await a.dispose()}},Vl=async(e,t,n)=>{let r=new AbortController,i=Promise.withResolvers(),a=setTimeout(()=>{r.abort(),i.reject(new y(`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(Ll[3],t,{signal:r.signal}),i.promise]),a=de.safeParse(n);if(!a.success||a.data.deploymentId!==t.deploymentId)throw Rl(`status`);return a.data}finally{clearTimeout(a)}},Hl=async(e,t,n)=>{let r=performance.now()+n,i=50,a=await Vl(e,t,n>0?Math.min(Pl,n):Pl);for(;!Il.has(a.state);){let n=r-performance.now();if(n<=0)return a;await Fl(Math.min(i,n)),i=Math.min(i*2,1e3);let o=r-performance.now();if(o<=0)return a;try{a=await Vl(e,t,Math.min(Pl,o))}catch(e){if(e instanceof y&&e.fields?.reason===`STATUS_TIMEOUT`)return a;throw e}}return a},Ul=[`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`],Wl=e=>{let t=e.failure,n=Ul.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.`}}},Gl=e=>e.unavailableFiles?.map(e=>`Unavailable published file: ${e.path} (${e.code}).`)??[],Kl=[`prototype.getArtifactCapabilities`,`prototype.attach`],ql=new Set([`BAD_REQUEST`,`FORBIDDEN`,`UNAUTHORIZED`,`NOT_FOUND`]),Jl=async e=>{let t=ne.safeParse(await e.query(Kl[0],{}));if(!t.success||t.data.attachmentProtocolVersion!==1)throw new y(`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.`)},Yl=e=>e instanceof y?{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.`},Xl=async(e,t,n)=>{let r=i(t.canvasRef),a=ie.safeParse(await e.mutate(Kl[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}},Zl=async(e,t,n,r)=>{try{let i=await Xl(e,t,r);return{...n,attachmentStatus:i.attachment.outcome,attachment:i,nextAction:`inspect_result`}}catch(e){let t=Yl(e),r=t.code===`CONFLICT`,i=ql.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.`]}}},Ql=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:Gl(r)};if(r.state===`failed`){let{nextAction:e,failure:t}=Wl(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`?Zl(e,t,i,r):i},$l=(e,t)=>({execute:async n=>{let r=i(n.canvasRef);await Jl(e);let a=n.source.kind===`deployment`?n.source.deploymentId:null;try{if(n.source.kind===`build`&&(a=(await Bl(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 Ql(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:Yl(e),nextAction:e instanceof y&&(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.`]}}}}),eu=[`prototype.attach`],tu=e=>new y(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),nu=e=>{if(e.state===`failed`){let t=Wl(e);throw new y(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 y(`NOT_FOUND`,`Prototype deployment ${e.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);if(e.state!==`ready`)throw new y(`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})},ru=async(e,t,n)=>{let r={deploymentId:null};try{let i=await Bl(e,t,n,e=>{r.deploymentId=e}),a=await Hl(e,{canvasId:n.canvasId,deploymentId:i.deploymentId},3e5);nu(a);let o=ie.safeParse(await e.mutate(eu[0],{canvasId:n.canvasId,deploymentId:i.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw tu(`attachment`);return{...o.data,fileCount:a.fileCount,totalBytes:a.totalBytes,alreadyExists:i.alreadyExists,warnings:Gl(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 y&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||r.deploymentId===null?e:new st(e instanceof y?e.message:`Prototype deployment ${r.deploymentId} has no confirmed completion.`,`${e instanceof y?`${e.remediation} `:``}Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`,{code:e instanceof y?e.code:`INTERNAL`,fields:{...e instanceof y&&e.fields,canvasId:n.canvasId,deploymentId:r.deploymentId,clientToken:n.clientToken}})}},iu=(e,t)=>({execute:async n=>ru(e,t,n)}),au=(e,t)=>{if(e.id!==t.jobId||e.canvasId!==t.canvasId)throw new y(`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.`]}},ou=async(e,t)=>{let{job:n}=fe.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.jobId}));return au(n,t)},su=(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:[]}},cu=async(e,t,n)=>{if(n.kind!==`canvas-render`||n.state!==`succeeded`)return n;try{let{job:r}=ut.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 di(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.`]}}},lu=[`canvas.mutation.get`,`canvas.render.get`,`canvas.render.getImport`,`prototype.getPublishStatus`,`canvas.asset.get`],uu=(e,t)=>{if(e!==t)throw new y(`NOT_FOUND`,`The operation does not belong to this canvas.`,`Use the operation reference returned by the original action.`)},du=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`}))],fu=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,a=ue.parse(await e.query(lu[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:su(a.result,n.fingerprint),affected:q(du(a.result),r,i)}},pu=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,{job:a}=ut.parse(await e.query(lu[1],{jobId:n.jobId}));uu(a.canvasId,n.canvasId);let o=a.result===null?null:mu(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:q(hu(a),r,i),failure:a.failure,pixelsDelivered:!1,warnings:[`Status reports stored render evidence. It does not deliver or inspect the image.`]}},mu=e=>{let{warnings:t,timings:n,...r}=e;return{...r,warningCount:t.length,timingCount:n.length}},hu=e=>e.result===null?[]:[...e.result.warnings.map(e=>({kind:`warning`,warning:e})),...e.result.timings.map(e=>({kind:`timing`,timing:e}))],gu=async(e,t)=>{let n=jt.parse(await e.query(lu[4],{canvasId:t.canvasId,clientToken:t.clientToken}));if(uu(n.canvasId,t.canvasId),n.clientToken!==t.clientToken)throw new y(`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`}},_u=async(e,t)=>{let{operation:n,offset:r,limit:i}=t;switch(n.kind){case`canvas-asset`:return q([],r,i),gu(e,n);case`canvas-mutation`:return fu(e,{...t,operation:n});case`canvas-preparation`:{let r=await fu(e,{...t,operation:{kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}});return r.kind===`canvas-mutation`&&r.state===`committed`?r:ou(e,n)}case`canvas-render`:return pu(e,{...t,operation:n});case`canvas-conversion`:{let{job:t}=St.parse(await e.query(lu[2],{jobId:n.jobId}));return uu(t.canvasId,n.canvasId),Ic(t,{offset:r,limit:i})}case`prototype-deployment`:return q([],r,i),{kind:`prototype-deployment`,operation:n,publication:de.parse(await e.query(lu[3],{canvasId:n.canvasId,deploymentId:n.deploymentId})),attachment:`not_checked`,warnings:[`Publication readiness does not establish canvas attachment or successful interactive verification.`]}}},vu=(e,t)=>({execute:async n=>{let r=await _u(e,n);return t!==void 0&&n.includeImage?cu(e,t,r):r}}),yu=[`transcript.get`],bu=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),xu=e=>({execute:async t=>{let n=he.safeParse(await e.query(yu[0],t));if(!n.success)throw new y(`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:bu(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Su={".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`},Cu=()=>new y(`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.`),wu=async e=>{let t=Su[w.extname(e).toLowerCase()];if(t===void 0)throw Cu();let n=await $t(e,Bt.O_RDONLY|Bt.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size===0)throw Cu();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 y(`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:T(`sha256`).update(a).digest(`hex`)}}finally{await n.close()}},Tu=e=>({read:async()=>{try{return await wu(e)}catch(e){throw e instanceof y?e:new y(`BAD_REQUEST`,`The selected asset file cannot be read.`,`Choose an existing readable image or font file on this computer.`)}}}),Eu=[`canvas.list`,`organisation.list`],Du=async(e,t)=>{let[n,r]=await Promise.all([e.query(Eu[0],{collection:t.collection,...t.title!==void 0&&{title:t.title},scope:`all`,deleted:!1,hasUnresolved:!1}),t.includeDestinations?e.query(Eu[1],{}):{items:[],truncated:!1}]),i=be.parse(n),a=$e.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}}},Ou=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},ku=e=>({execute:async t=>{let{items:n,sourceTruncated:r}=await Du(e,t),{cursor:i,...a}=t,o=s(a),c=s({items:n,sourceTruncated:r}),l=i===void 0?null:De(i,rt);if(l!==null&&l.queryDigest!==o)throw new y(`BAD_REQUEST`,`This cursor belongs to another canvas search.`,`Restart discovery with the requested query.`);if(l!==null&&l.snapshotDigest!==c)throw new y(`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 y(`BAD_REQUEST`,`The discovery cursor is out of range.`,`Restart discovery.`);let d=Ou(n.slice(u,u+t.limit)),f=u+d.length,p=f<n.length,h=r.canvases||r.destinations;return{items:d,returnedCount:d.length,totalAvailable:n.length,complete:!p&&!h,sourceTruncated:r,nextCursor:p?m({protocol:`enhance-canvas-find/1`,queryDigest:o,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.`]:[]}}}),Au=async(e,t)=>{try{return v.parse(await M(e).execute(t))}catch(e){throw new y(e instanceof y?e.code:`INTERNAL`,e instanceof y?e.message:`The canvas commit could not be confirmed.`,`Read operation_status or repeat the original action with identical arguments and clientToken.`,{...e instanceof y&&e.fields,outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:t.canvasId,mutationId:t.mutationId,fingerprint:t.requestContext?.fingerprint})})}},ju=async(e,t,n,r)=>{if(n.result.loadedVersion!==t.baseVersion)throw new y(`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=Ne.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 Au(e,i);if(a.canvasId!==n.canvasId||a.mutationId!==t.clientToken||a.previousVersion!==t.baseVersion||a.version!==t.baseVersion+1||t.request.kind===`duplicate`&&!Jt(a.copiedNodeIds,n.result.idMap))throw new y(`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 su(a,r)},Mu=e=>({execute:async t=>{let n=i(t.canvasRef),r={...n.pageId!==void 0&&{pageId:n.pageId},nodeIds:[...n.nodeIds]},a=s({operation:`canvas.prepare/1`,reference:n,baseVersion:t.baseVersion,request:t.request}),o=ue.parse(await e.query(`canvas.mutation.get`,{canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:a}));if(o.state===`committed`)return su(o.result,a);let c=await il(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`?ju(e,t,c,a):au(c,l)}}),Nu=/^[MLHVCSQTAZ]$/iu,Pu=/[MLHVCSQTAZ]|[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/giu,Fu={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},Iu=e=>{let t=e.match(Pu)??[];if(t.join(``)!==e.replaceAll(/[\s,]/gu,``))return null;let n=[],r=``,i=0;for(;i<t.length;){let e=t[i]??``;if(Nu.test(e))r=e,i+=1;else if(r===``||r.toUpperCase()===`Z`)return null;let a=Fu[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},Lu=([e,t,n,r,i,a],{x:o,y:s})=>({x:e*o+n*s+i,y:t*o+r*s+a}),Ru=e=>`${String(e.x)} ${String(e.y)}`,zu=Math.PI/2,Bu=Math.PI*2,Vu=(e,t,n,r)=>Math.atan2(e*r-t*n,e*n+t*r),Hu=(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,te=(o===s?-1:1)*Math.sqrt(Math.max(0,(g*g*_*_-ee)/ee)),[v,ne]=[te*g*m/_,-te*_*p/g],[re,ie,ae,oe]=[(p-v)/g,(m-ne)/_,(-p-v)/g,(-m-ne)/_],se=Vu(re,ie,ae,oe);return s===0&&se>0&&(se-=Bu),s===1&&se<0&&(se+=Bu),{ellipse:[l*g,u*g,-u*_,l*_,l*v-u*ne+(e.x+n.x)/2,u*v+l*ne+(e.y+n.y)/2],start:Vu(1,0,re,ie),turn:se}},Uu=(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}=Hu(e,t,n),c=Math.ceil(Math.abs(s)/zu-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(Lu(a,d(t,u)),Lu(a,d(r,-u)),e===c-1?n:Lu(a,d(r,0)))}return f},Wu=(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=Uu(a,e.values,r),s=[];for(let e=0;e<i.length;e+=3)s.push(`C${i.slice(e,e+3).map(e=>Ru(Lu(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${Ru(Lu(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=>Ru(Lu(n,e))).join(` `)}`,pen:{current:l,start:r===`M`?l:t.start}}},Gu=(e,t)=>{let n=Iu(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=Wu(e,i,t);r.push(n.data),i=n.pen}return r.join(``)},Ku=(e,t)=>{let n=e.geometry;if(n?.kind!==`mask`||n.mode===`outline`||t?.box===void 0||t.component===`text`)return{};let r=W(t).opacity,i=W(t).fills.filter(e=>e.visible).toReversed().map(e=>Za({...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`)}},qu=(e,t)=>{let n=t.geometry?.kind===`mask`?ac(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=Gu(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}")`}},Ju=new Set([`data-enhance-id`,`data-enhance-locked`,`data-enhance-name`,`data-enhance-opaque`,`style`]),J=e=>{throw new y(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},Y=e=>{let t=ln(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,cn(e.value))}),Object.fromEntries(n)},Yu=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.`)),Xu=e=>{let t=un(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)||Ur(e.tagName));let t=e.childNodes.filter(e=>`tagName`in e);for(let e of t)e.attrs=e.attrs.filter(e=>Gr(e.name,e.value)),n.push(e)}return t},Zu=new Set([...Ju,`viewBox`,`preserveAspectRatio`]),Qu=(e,t)=>{let[n,...r]=Yu(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}},$u=e=>{let t=e.tagName===`svg`?Zu:Ju;return Object.fromEntries(e.attrs.map(e=>!t.has(e.name)||e.namespace!==void 0?J(`Unsupported attribute: ${e.name}.`):[e.name,e.value]))},ed=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??``)}},td=e=>{let t=[],n=[];for(let r of Yu(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]},nd=(e,t)=>Yu(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:rd(e,t),styles:Y(i)}}),rd=(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(``),id=e=>{let t=Xu(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=$u(e),i=ed(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:Qu(e,t.viewBox??``),text:``,children:[]};let a=e.tagName===`span`&&e.childNodes.some(e=>`tagName`in e),[o,s]=e.tagName===`span`?[[],[]]:td(e);return{...i,tag:e.tagName,...a&&{runs:nd(e,i.id)},...o.length>0&&{paints:o},text:!a&&e.tagName===`span`?rd(e,i.id):``,children:s.map(e=>r(e))}},i=Yu(t.childNodes),a=i[0];return a===void 0||i.length!==1?J(`An editable update must contain exactly its original root.`):r(a)},ad=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},od={fill:`100% 100%`,cover:`cover`,contain:`contain`,"scale-down":`contain`,none:`auto`},sd={"100% 100%":`fill`,cover:`cover`,contain:`contain`,auto:`none`},cd=/^background(?:-.+)?$/u,ld=/^url\((?:"([^"]*)"|'([^']*)'|([^"'()\s]*))\)$/u,ud=e=>{if(e.component!==`image`)return;let t=e.props?.src;return typeof t==`string`&&t!==``?t:void 0},dd=e=>{let t=ud(e);if(t===void 0)return{};let n=e.props?.fit,r=e.props?.position;return{"background-image":`url(${JSON.stringify(t)})`,"background-size":od[typeof n==`string`?n:`fill`]??`100% 100%`,"background-position":typeof r==`string`?r:`50% 50%`,"background-repeat":`no-repeat`}},fd=(e,t)=>ud(e)!==void 0&&cd.test(t),pd=(e,t,n)=>{if(ud(e)===void 0)return[];let r=[...new Set([...Object.keys(t),...Object.keys(n)])].filter(e=>cd.test(e)&&t[e]!==n[e]);if(r.length===0)return[];if(r.some(e=>![`background-image`,`background-size`,`background-position`].includes(e)))return ad(`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=ld.exec(n[`background-image`]??``),a=i?.[1]??i?.[2]??i?.[3],o=sd[n[`background-size`]??``],s=n[`background-position`];return a===void 0||a===``||o===void 0||s===void 0?ad(`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 y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},md={border:/^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u,outline:/^outline(?:-.+)?$/u,paint:/^$/u},hd=e=>Object.fromEntries(Object.entries(Y(e)).toSorted(([e],[t])=>e.localeCompare(t))),gd=e=>hd(Object.entries(e).flatMap(([e,t])=>{let n=Tt(e,t);return e.startsWith(`--`)||n.includes(`var(--canvas`)||n.includes(`url(#`)?[]:[`${e}:${n}`]}).join(`;`)),_d=e=>{let t=H(e),n=n=>qo(t,n).map(t=>({owner:`paint`,paintId:t.id,styles:gd(ds(e,t))})),r=os(e),i=As(e);return[...n(`outer-shadow`),...Ko(t).map(e=>({owner:`paint`,paintId:e.id,styles:gd(Ts(e))})),...n(`inner-shadow`),...r===null?[]:[{owner:`border`,styles:gd(r)}],...i===null?[]:[{owner:`outline`,styles:gd(i)}]]},vd=(e,t)=>e.some(e=>md[e.owner].test(t)),yd=e=>ct.find(t=>t===(e??`normal`))??X(`Unsupported mix-blend-mode: ${e??``}.`),bd=/stroke-(?:dasharray|linecap)="[^"]*"/gu,xd=e=>{let t=/^url\(["']?data:image\/svg\+xml,(.*?)["']?\)$/u.exec(e??``)?.[1];return t===void 0?void 0:decodeURIComponent(t)},Sd=(e,t,n)=>{let r=xd(t),i=xd(n);if(i===void 0||r?.replaceAll(bd,``)!==i.replaceAll(bd,``))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}},Cd=(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=yd(r);return n.paints.map(e=>e===a?{...e,blendMode:o}:e)},wd=(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:yd(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)}}]:[]]},Td=(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`)?Cd(e,s,c,n.styles[`mix-blend-mode`]):c.paints,u=o.includes(`mask-image`)?Sd(e,i.styles[`mask-image`],n.styles[`mask-image`]):{};return[{op:`setAppearance`,nodeId:e.id,appearance:{[s]:{...c,paints:l,...u}}}]}),...wd(e,a)]},Ed=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Dd=e=>e.kind===`text`||e.kind===`span`&&e.children.every(e=>e.kind===`text`),Od=e=>ke([e]),kd=e=>e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`),Ad=e=>e.replaceAll(/-([a-z])/gu,(e,t)=>t.toUpperCase()),jd=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,n])=>{let r=Ad(e);return p.has(r)?[r,n]:Ed(`Run ${String(t+1)} cannot hold ${e}; set it on the text layer.`)})),Md=e=>{if(e.kind!==`span`)return{};let[t,...n]=(e.fills??[]).filter(e=>e.visible),r=t===void 0||n.length>0?void 0:no(t),i=[...Object.entries(e.styles).map(([e,t])=>{let n=kd(e);return`${n}:${Tt(n,t)}`}),...r===void 0?[]:[`color:${r}`]];return Object.fromEntries(Object.entries(Y(i.join(`;`))).toSorted(([e],[t])=>e.localeCompare(t)))},Nd=e=>{let t=Dt(e);return t.length===0||t.some(e=>!Dd(e))?null:t.map(e=>({text:Od(e),styles:Md(e)}))},Pd=e=>Dt(e).some(e=>!Dd(e)),Fd=(e,t,n,r)=>{if(`mix-blend-mode`in r.styles)return Ed(`Text paints have no blend of their own. Set mix-blend-mode on the text layer.`);let{color:i,...a}=r.styles,o=jd(a,t),s=i===void 0?void 0:L(`${e.id}-run-${String(t)}`,i);if(i!==void 0&&s===null)return Ed(`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&&Md(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}]}},Id=(e,t,n)=>{if(t.length!==n.length)return Ed(`Keep each run span of ${e.id}; change a run's words or CSS in place.`);let r=Dt(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:Fd(e,i,r,o)});if(i.every((e,t)=>e===r[t]))return[];let a={...e.props,richText:i,text:ke(i)};return[{op:`editText`,nodeId:e.id,change:Te(e,{...e,props:a})}]},Ld=new Set([`path`,`polygon`,`boolean`]),Rd=e=>Ld.has(e.geometry?.kind??``),zd=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},Bd=e=>{let t=jr(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`:no(n)??`none`,viewBox:[r,i,a,o].map(String).join(` `)}},Vd=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Hd=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}:Vd(`Invalid viewBox: ${e}.`)},Ud=(e,t,n)=>n.d.trim()===``?Vd(`The path of ${t.id} is empty.`):[{op:`setGeometry`,nodeId:t.id,geometry:{kind:`path`,path:n.d,fillRule:n.fillRule,viewBox:Hd(n.viewBox)}},...t.geometry?.kind===`boolean`?N(e,t.id).map(e=>({op:`remove`,nodeId:e})):[]],Wd=(e,t)=>{let n=(e.appearance?.fills??[]).find(e=>e.visible),r=n?.kind===`solid`?n.id:`${e.id}-fill`,i=t===`none`?null:L(r,t);return i===null&&t!==`none`?Vd(`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}}]}}},Gd=(e,t,n,r)=>[...n.d===r.d&&n.fillRule===r.fillRule&&n.viewBox===r.viewBox?[]:Ud(e,t,r),...n.fill===r.fill?[]:[Wd(t,r.fill)]],Kd=new Set([`root`,`frame`,`group`,`rectangle`,`image`,`text`]),qd={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.`},Jd=/^(?:mask(?:-.+)?|clip-path)$/u,Yd=`This layer kind has no editable HTML form yet; edit it in the editor.`,Xd=(e,t,n)=>{let r=qd[t.component];return r===void 0?qu(e,t)===null?`This mask's shape cannot be read; edit it in the editor.`:t.component===`text`&&(n>0||Pd(t))?`Text with nested layers or nested formatting keeps its formatting in the editor.`:Rd(t)?zd(t)??(Bd(t)===null?Yd:null):Kd.has(t.component)&&(t.geometry===void 0||t.geometry.kind===`mask`)?null:Yd:r},Zd=(e,t)=>{let n={...zs(t),...Ku(t,Xs(e,t)),...qu(e,t)},r=pt(t),i=Object.entries(n).flatMap(([e,n])=>{let r=Tt(e,n);return e.startsWith(`--`)||r.includes(`var(--canvas`)||r.includes(`url(#`)||ys(t,[e]).length===0&&!Jd.test(e)?[]:[[e,r]]});return{...Object.fromEntries(i),...dd(t),...Object.fromEntries(Object.entries(r).map(([e,t])=>[e,Tt(e,t)]))}},Qd=e=>{throw new y(`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;`),$d=e=>Rd(e)?Bd(e):null,ef=/^background(?:-.+)?$/u,tf=e=>`<path d="${Z(e.d)}" fill-rule="${e.fillRule}" fill="${Z(e.fill)}"></path>`,nf=e=>{let t=Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`);return t===``?``:` style="${Z(t)}"`},rf=e=>`<div data-enhance-paint="${Z(e.paintId??e.owner)}"${nf(e.styles)}></div>`,af=(e,t)=>`<span data-enhance-run="${String(t)}"${nf(e.styles)}>${Z(e.text)}</span>`,of=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">${tf(e.path)}</svg>`;let r=(e.runs??[]).map((e,t)=>af(e,t)).join(``),i=(e.paints??[]).map(e=>rf(e)).join(``);return`<${e.tag} ${n}>${Z(e.text)}${r}${i}${e.children.map(e=>of(e)).join(``)}</${e.tag}>`},sf=(e,t)=>{let n=new Set,r=[],i={},a=Fi(e),o=t=>{if(n.has(t))return Qd(`The document contains repeated node identity.`);n.add(t);let s=P(e,t),c=a.get(t)??[],l=Xd(e,s,c.length),u=l!==null;u&&(r.push(s.id),i[s.id]=l);let d=u?null:$d(s),f=u||s.component!==`text`?null:Nd(s),p=u||d!==null?[]:_d(s),m=u?{}:Y(Object.entries(Zd(e,s)).filter(([e])=>d===null||!ef.test(e)).filter(([e])=>!vd(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:F(e,t),styles:m,...f!==null&&{runs:f},...p.length>0&&{paints:p},text:f!==null||u||s.component!==`text`?``:se(s)??``,children:u||d!==null?[]:c.map(e=>o(e))}},s=o(t);return{projectionVersion:2,root:s,html:of(s),opaqueNodeIds:r,sealedReasons:i}},cf=(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=at(t,n);if(r.ok)return r.rootNodeIds;throw _(t,n),new y(`NOT_FOUND`,`The linked page is unavailable.`,`Copy a current page link.`)},lf=(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 y(`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 y(`BAD_REQUEST`,`Outline roots repeat.`,`Choose each root once.`)},uf=(e,t,n,r)=>{let i=[],a=new Set,o=Fi(e),s=(t,c)=>{if(a.has(t))return;a.add(t);let l=P(e,t),u=o.get(t)??[],d=F(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},df=(e,t,n)=>{if(e===void 0)return 0;let r=De(e,xt);if(r.canvasId!==t.reference.canvasId||r.queryDigest!==n)throw new y(`BAD_REQUEST`,`This cursor belongs to another outline query.`,`Restart the outline read with the requested scope.`);if(r.version!==t.version)throw new y(`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},ff=(e,t)=>{let{reference:n,scene:r,version:i,isCurrent:a}=t,o=cf(e,n,r);b(n,r,o),lf(r,o);let c=s({reference:n,roots:e.rootNodeIds??null,depth:e.depth,limit:e.limit}),l=df(e.cursor,t,c),u=uf(r,o,e.depth,a);if(l>u.length)throw new y(`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,p=u.some(e=>e.childrenOmitted);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[...o]},view:`outline`,complete:f===u.length&&!p,returnedCount:d.length,total:u.length,nodes:d,omittedDescendants:p,nextCursor:f<u.length?m({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.`]}},pf=e=>{let t=l(e);if(t!==null)return{storage:`canvas-image`,reference:e,ownerId:t.canvasId,assetId:t.assetId};let n=Ee(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}},mf=(e,t)=>typeof e[t]==`string`?e[t]:null,hf=(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:s(r),...pf(r),delivery:`not_checked`,metadata:i};return n.set(s(a),a),r};Yr(r,e=>i(`image`,e,null)),Re(r.props,(e,t)=>i(`font`,e,{family:mf(t,`family`),style:mf(t,`style`),weight:mf(t,`weight`)}))}return Array.from(n,([,e])=>e)},gf=(e,t,n)=>{if(e.cursor===void 0)return 0;let r=De(e.cursor,mt);if(r.canvasId!==t.reference.canvasId||r.digest!==n)throw new y(`BAD_REQUEST`,`The resource cursor belongs to another query.`,`Restart this scoped resource read.`);if(r.version!==t.version)throw new y(`CONFLICT`,`The canvas changed between resource pages.`,`Restart the read at the current revision.`);return r.offset},_f=(e,t)=>{let n=at(t.reference,t.scene);if(!n.ok)throw new y(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link; do not broaden the request.`);let r=s({reference:t.reference,limit:e.limit}),i=gf(e,t,r),a=hf(t,n.nodeIds);if(i>a.length)throw new y(`BAD_REQUEST`,`The resource cursor is out of range.`,`Restart the scoped resource read.`);let o=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:m({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(o([])));return o(q(a,i,e.limit,c).entries)},vf=(e,t,n)=>{if(e.state!==`ready`){if(t.cursor!==void 0)throw new y(`CONFLICT`,`The transcript changed during pagination.`,`Restart the read.`);return e}let{cursor:r,...i}=t,a=s({scope:n,range:i,transcript:e}),o=r===void 0?null:De(r,nt);if(o!==null&&o.digest!==a)throw new y(`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=o?.offset??0;if(l>c.length)throw new y(`BAD_REQUEST`,`Transcript cursor offset is out of range.`,`Restart the read.`);let u=q(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?m({protocol:`enhance-canvas-transcript/1`,digest:a,offset:d}):null}},yf=[`recording.get`,`prototype.getPublishStatus`,`transcript.get`],bf=e=>{let t=Oe.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}},xf=e=>{let t=h.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)}},Sf=async(e,t)=>{let{node:n,canvasId:r}=t;if(n.component===`recording`){let t=ge.parse(n.props),i=C.uuid().parse(t.recordingId),a=Pt.parse(await e.query(yf[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=f.parse(n.props),i=de.parse(await e.query(yf[1],{canvasId:r,deploymentId:t.deploymentId}));if(i.prototypeId!==t.prototypeId)throw new y(`CONFLICT`,`Prototype identity does not match its deployment.`,`Read the node again.`);return{kind:`prototype`,...t,state:i.state,fileCount:i.fileCount}}return bf(t)??xf(n)},Cf=e=>({execute:async t=>{let n=await Sf(e,t),r=t.input.transcript,i=`recordingId`in n?n.recordingId:null;if(r!==void 0&&i===null)throw new y(`BAD_REQUEST`,`This object has no recording transcript source.`,`Choose a recording or a capture with recording provenance.`);let a=r===void 0?null:vf(he.parse(await e.query(yf[2],{canvasId:t.canvasId,recordingId:C.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.`]]}}}),wf=[`canvas.document.get`],Tf=e=>{throw new y(`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`})},Ef=(e,t)=>{let{reference:n,scene:r,version:i}=t;if(!t.isCurrent)throw new y(`BAD_REQUEST`,`This document format cannot produce an editable snapshot.`,`Open it in the current editor before editing.`);b(n,r,[e.rootNodeId]);let a=sf(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:Et({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.`]:[]}},Df=e=>({execute:async t=>{let n=i(t.canvasRef),r=Ve.parse(await e.query(wf[0],{canvasId:n.canvasId}));if(t.expectedVersion!==void 0&&t.expectedVersion!==r.version)return Tf(r.version);let a=Ze.safeParse(r.document),o=a.success?a.data:Ct.parse(r.document);return t.view===`resources`?_f(t,{reference:n,scene:o,version:r.version,isCurrent:a.success}):t.view===`outline`?ff(t,{reference:n,scene:o,version:r.version,isCurrent:a.success}):t.view===`source`?(b(n,o,[t.nodeId]),Cf(e).execute({canvasId:n.canvasId,version:r.version,node:P(o,t.nodeId),screens:r.screens,input:t})):Ef(t,{reference:n,scene:o,version:r.version,isCurrent:a.success})}}),Of=[`canvas.mutation.get`],kf=e=>({execute:async t=>{let n=t.reference.canvasId,r=ue.parse(await e.query(Of[0],{canvasId:n,mutationId:t.clientToken,fingerprint:t.fingerprint}));if(r.state===`committed`)return su(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(Oc(t.reference,i,a),a.length===0)return{outcome:`no_op`,canvasId:n,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let o=Ne.safeParse({canvasId:n,documentFormatVersion:15,mutationId:t.clientToken,baseVersion:t.baseVersion,operations:a,requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});if(!o.success)throw new y(`BAD_REQUEST`,`The planned edit exceeds the canonical canvas contract.`,o.error.issues[0]?.message??`Reduce the edit scope.`,{outcome:`not_committed`});return su(v.parse(await M(e).execute(o.data)),t.fingerprint)}}),Af=(e,t)=>{let n=Fi(e),r=new Set(t),i=new Set,a=t=>{if(i.has(t))return;if(i.add(t),P(e,t),F(e,t))throw new y(`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 y(`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}))},jf=e=>({execute:async({clientToken:t,...n})=>{let r=i(n.canvasRef);return kf(e).execute({reference:r,baseVersion:n.baseVersion,clientToken:t,fingerprint:s({operation:`canvas.remove/1`,...n,reference:r}),plan:e=>Af(e,n.rootNodeIds)})}}),Mf=(e,t,n,r)=>{let i=e.parents.get(t),a=e.children.get(n)??[];if(i===n&&a.indexOf(t)===r)return;if(F(e.document,t)||F(e.document,n))throw new y(`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})},Nf=(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([...Fi(r)].map(([e,t])=>[e,[...t]])),moves:[]},a=e=>{for(let[t,n]of e.children.entries())Mf(i,n.id,e.id,t),a(n)};return a(t),i.moves.length===0?[]:Zi(r,i.moves).operations},Pf=e=>{throw new y(`BAD_REQUEST`,e,`Read the current subtree and reduce or correct the edit. No canvas changes were committed.`)},Ff=(e,t,n)=>{if(Object.keys(t.idMap).length!==n.fragments.length)return Pf(`Native compilation returned unexpected fragment identities.`);if(t.operations.length!==n.fragments.length)return Pf(`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 Pf(`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 Pf(`New HTML identity ${e} already exists.`);let a=N(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:Lt(o,null)}})}return r},If=(e,t)=>({...e,id:Object.hasOwn(t,e.id)?t[e.id]??e.id:e.id,children:e.children.map(e=>If(e,t))}),Lf={operations:[],idMap:{},rootNodeIds:[]},Rf=(e,t,n=Lf)=>{let r=Ff(e,n,t),i=If(t.root,n.idMap);return[...t.operations,...n.operations,...Nf(r,i,t.removed)]},zf=e=>e.attrs.some(e=>e.name===`data-enhance-paint`),Bf=e=>e.attrs.find(e=>e.name===`data-enhance-id`)?.value,Vf=e=>{throw new y(`BAD_REQUEST`,e,`Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.`)},Hf=e=>e.flatMap(e=>`tagName`in e?[e,...Hf(e.childNodes)]:[]),Uf=e=>{let t=Xu(e),n=Hf(t.childNodes),r=new Set(n.map(e=>Bf(e))),i=[],a=(e,t)=>{let n=Bf(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&&!zf(e)?a(e,n):e)};if(t===void 0)return Vf(`The submitted HTML must retain its original root identity.`);if([e,...Hf(e.childNodes)].some(e=>e.attrs.some(e=>[`data-enhance-id`,`data-enhance-opaque`].includes(e.name))))return Vf(`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:fn(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:id(dn(t)),fragments:i}},Q=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Wf=e=>{let t=new Map,n=e=>{t.set(e.id,e);for(let t of e.children)n(t)};return n(e),t},Gf=(e,t)=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n),Kf=(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},qf=(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=>!fd(t,e)).map(e=>[e,r.styles[e]??null]));return[...t.geometry?.kind===`mask`&&Object.keys(a).some(e=>Jd.test(e))?[{op:`setGeometry`,nodeId:t.id,geometry:`default`}]:[],...pd(t,n.styles,r.styles),...Object.keys(a).length===0?[]:pc(e,[{nodeIds:[t.id],styles:a}])]},Jf=(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=!Gf(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:Te(a,{...a,props:c(a,n.text)})}),o.push(...Td(a,t.paints??[],n.paints??[])),(t.runs!==void 0||n.runs!==void 0)&&o.push(...Id(a,t.runs??[],n.runs??[])),t.path!==void 0&&n.path!==void 0&&o.push(...Gd(e,a,t.path,n.path)),r&&o.push(...qf(e,a,t,n)),o},Yf=(e,t,n,r)=>{let i=sf(e,t).root,a=Uf(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=Wf(i),l=Wf(o),u=Kf(c,l,r,t),d=new Set([...u,...r.flatMap(t=>[...Li(e,t)])]);for(let t of d)if(F(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(...Jf(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}},Xf=(e,t,n)=>{let r=d(e.snapshotToken,t);b(t,n,[r.rootNodeId]);let i=sf(n,r.rootNodeId);if(Et({reference:t,version:r.version,rootNodeId:r.rootNodeId,html:i.html})!==e.snapshotToken)throw new y(`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 Yf(n,r.rootNodeId,e.html,e.removeNodeIds)},Zf=async(e,t,n)=>{let r=Xf(t,n.reference,n.scene);if(r.fragments.length===0)return Rf(n.scene,r);let i=await il(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`?Rf(n.scene,r,i.result):au(i,{kind:`canvas-preparation`,canvasId:n.reference.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:n.fingerprint})},Qf=e=>({execute:async t=>{let n=Qe.parse(t),r=i(n.canvasRef),a=d(n.snapshotToken,r),o=s({operation:`canvas.updateHtml/1`,snapshotToken:n.snapshotToken,html:n.html,removeNodeIds:n.removeNodeIds});return kf(e).execute({reference:r,baseVersion:a.version,clientToken:n.clientToken,fingerprint:o,plan:async t=>Zf(e,n,{reference:r,scene:t,fingerprint:o,version:a.version})})}}),$f=(e,t,n)=>({"canvas.arrange":async()=>{let{changes:r,...i}=Ce.parse(t);return Mu(e).execute({...i,clientToken:n,request:{kind:`arrange`,changes:r}})},"canvas.duplicateNodes":async()=>{let{nodeIds:r,destination:i,...o}=a.parse(t);return Mu(e).execute({...o,clientToken:n,request:{kind:`duplicate`,nodeIds:r,destination:i}})},"canvas.find":async()=>ku(e).execute(Ue.parse(t)),"canvas.remove":async()=>jf(e).execute({...We.parse(t),clientToken:n}),"canvas.read":async()=>{let n=te.safeParse(t);return n.success?$c(e,n.data):Df(e).execute(Ye.parse(t))},"canvas.updateHtml":async()=>Qf(e).execute({...wt.parse(t),clientToken:n})}),ep=(e,t)=>{let n=i(e.canvasRef),r=n.nodeIds;if(e.target.kind===`content`&&r.length>1)throw new y(`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}},tp=(e,t)=>{let n=tt.shape.operation.safeParse({kind:`canvas-render`,canvasId:t.input.canvasId,jobId:e instanceof y?e.fields?.jobId:void 0}),r=vt.extract([`failed`,`cancelled`,`expired`]).safeParse(e instanceof y?e.fields?.renderState:void 0);return{...n.success&&{operation:n.data},state:r.success?r.data:`not_confirmed`,error:e instanceof y?{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.`}}},np=(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:ep({...e,...i},a)}}),rp=async(e,t)=>{try{let n=await e.execute({...t.input,maxOutputPixels:t.maxOutputPixels}),r=it.safeParse(n);if(!r.success)return tt.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 y(`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 tp(e,t)}},ip=e=>({execute:async(t,n)=>{let r=xe.parse(t),i=np(r,n),a=[],o=0;for(let t of i){let n=await rp(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.`]}}}),ap=e=>xi(e.remote,tl(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),op=async(e,t,n)=>{let r=xe.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=ap(e);return ip({execute:async t=>(e.mutationKey.select(t.retryClientToken,!1),i.execute(t))}).execute(r.data,t)}let i=yt.safeParse(t);if(i.success)return ap(e).execute(ep(i.data,n));let a=le.parse(t);return ap(e).execute({...a,retryClientToken:n})},sp=e=>({render:ap(e),execute:async(t,n)=>op(e,t,n)}),cp=new Date(`1980-01-01T00:00:00.000Z`),lp=33188,up=(e,t)=>new y(`BAD_REQUEST`,e,t),dp=(e,t)=>{let n=T(`sha256`),r=0;return new hn({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`))}}})},fp=e=>{let t=_t.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 up(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,je,{mtime:cp,mode:lp,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},pp=(e,t,n)=>{let{source:r,content:i}=t,a={mtime:cp,mode:lp,compress:i===null,forceDosTimestamp:!0};if(i===null){e.addReadStreamLazy(r.path,{...a,size:r.bytes},t=>{let i=Vt(r.absolutePath),a=dp(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:T(`sha256`).update(i).digest(`hex`)})},mp=(e,t,n)=>{let r=[];for(let i of t)i!==null&&(pp(e,i,n),r.push(i.source));return r},hp=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 en(e.absolutePath):null;if(t===null&&await Yt(e.absolutePath,Bt.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(...mp(e,a,n))}return r},gp=async e=>{let t=new _n,n=T(`sha256`),r=new hn({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=gn(t.outputStream,r,Ht(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=fp({zip:t,completed:i,...e,files:s}))},l=e=>{i.set(e.path,e),c()};try{s=await hp(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 an(e.artifactPath);if(u.size>e.limits.artifactBytes)throw up(`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}},_p={".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`},vp=e=>_p[w.extname(e).toLowerCase()]??`application/octet-stream`,yp=async e=>{try{return await an(e)}catch{return null}},bp=e=>Buffer.byteLength(e,`utf8`),$=(e,t)=>new y(`BAD_REQUEST`,e,t),xp=(e,t)=>{if(!ce.safeParse(e).success)throw $(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(bp(e)>t.pathBytes)throw $(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},Sp=async(e,t,n,r)=>{let{limits:i,unavailable:a}=r,o=await tn(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=w.join(t,n.name),c=await yp(o);if(c?.isDirectory()===!0){try{u.push(...await Sp(e,o,s,r))}catch{a()}continue}if(c?.isFile()!==!0){a();continue}let l=w.relative(e,o).split(w.sep).join(`/`).normalize(`NFC`);xp(l,i),u.push({absolutePath:o,path:l,bytes:Number(c.size),contentType:vp(o)})}return u},Cp=(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=Pe(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.`)},wp=(e,t)=>{try{pn.mark(`enhance.prototype.packaging`,{detail:{fileCount:e,unavailableFileCount:t}})}catch{}},Tp=async e=>{let t=w.resolve(e.directory),n=await yp(t);if(n===null)throw new y(`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(w.sep).join(`/`).normalize(`NFC`);xp(r,e.limits);let i=0,a=await Sp(t,t,new Set,{limits:e.limits,unavailable:()=>{i+=1}});Cp(a,r,e.limits);let o=await Qt(w.join(It(),`enhance-prototype-artifact-`)),s=w.join(o,`artifact.zip`);try{let t=await gp({artifactPath:s,files:a,entryPath:r,limits:e.limits});return i+=t.unavailableFileCount,wp(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:()=>Vt(s),dispose:async()=>rn(o,{recursive:!0})}}catch(e){throw await rn(o,{recursive:!0}),e}},Ep=e=>({package:async t=>{if(e===void 0)throw $(`No build directory was selected.`,`Select a build before publishing.`);return Tp({...t,directory:e})}}),Dp=async(e,t)=>{let n=Me.parse(t);return M(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Op=async(e,t)=>{let n=ht.parse(t);return Qc(e.remote,sp(e).render).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},kp=async(e,t,n)=>{let r=Mt.parse(t),a=i(r.canvasRef);return Qc(e.remote,sp(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})},Ap=async(e,t)=>{let n=oe.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},jp=async(e,t,n)=>{let r=Le.parse(t);return iu(e.remote,Ep(r.directory)).execute({...r,clientToken:n})},Mp=async(e,t,n)=>{let r=Fe.parse(t);return Tl(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Np=async(e,t)=>{let n=Be.parse(t);return xu(e.remote).execute(n)},Pp=async(e,t)=>{let n=u.parse(t),r=i(n.canvas);return Mc(e.remote).execute({...r,baseVersion:n.baseVersion,edits:n.edits,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Fp=async(e,n)=>vu(e.remote,tl(e.configDirectory)).execute(t.parse(n)),Ip=async(e,t,n,r)=>{let i={...$f(e.remote,n,r),"canvas.importAsset":async()=>{let t=pe.parse(n);return Nl(e.remote,Tu(t.source.path)).execute({canvasRef:t.canvasRef,clientToken:r})},"operation.status":async()=>Fp(e,n),"canvas.edit":async()=>Pp(e,n),"canvas.apply":async()=>Dp(e,n),"canvas.render":async()=>sp(e).execute(n,r),"canvas.writeHtml":async()=>Op(e,n),"canvas.insertHtml":async()=>kp(e,n,r),"canvas.capture":async()=>kl(e.remote,n,r),"canvas.makeEditable":async()=>Gc(e.remote,n),"comment.attention":async()=>Ap(e,n),"prototype.publishCanvas":async()=>{let t=Ge.parse(n);return $l(e.remote,Ep(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()=>jp(e,n,r),"recording.snapshot":async()=>Mp(e,n,r),"transcript.read":async()=>Np(e,n)}[t];if(i===void 0)throw TypeError(`${t} has no composite execution`);return i()},Lp=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??Kt();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Ip(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),Rp=`/callback`,zp=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),Bp=e=>{let t=S.platform===`darwin`?{executable:`open`,arguments:[e]}:S.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=bn(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Vp=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==Rp){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)},Hp=e=>{let t=zp(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},Up=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=xn((n,r)=>{Vp({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)}${Rp}`,a=Hp({...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&&Bp(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},Wp=e=>({authorize:async t=>{try{let n=Gt(32).toString(`base64url`),r=T(`sha256`).update(n).digest(`base64url`),i=Gt(32).toString(`base64url`),a=await Up({...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 y(`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.`)}}}),Gp={apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`},Kp=e=>URL.canParse(e)?new URL(e).href.replace(/\/+$/u,``):e,qp=(e,t,n,r)=>{let i=URL.canParse(e)?new URL(e).origin:null,a=w.resolve(t),o=Gp;if(i===new URL(o.apiUrl).origin&&a===w.resolve(n,`.config`,r.configDirectoryName)||i===new URL(r.apiUrl).origin&&a===w.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.`)},Jp=e=>e===void 0||e===``?void 0:e,Yp=(e,t,n)=>{let r=Jp(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Jp(e.ENHANCE3_API_URL),a=w.join(t,`.config`,n.configDirectoryName),o=Jp(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&Kp(i)!==Kp(n.apiUrl))throw TypeError(`Enhance development cannot use this API. Use the bundled development endpoint.`);if(o!==void 0&&w.resolve(o)!==w.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}else qp(i??n.apiUrl,o??a,t,n);return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}},Xp=()=>Yp(S.env,Ft(),Gp),Zp=()=>{let e=C.enum([`legacy`,`canvas`]).default(`legacy`).parse(S.env.ENHANCE_MCP_PROFILE),t=C.enum([`true`,`false`]).default(`false`).parse(S.env.ENHANCE_MCP_READ_ONLY)===`true`;if(t&&e!==`canvas`)throw Error(`ENHANCE_MCP_READ_ONLY requires the canvas profile.`);return{...Xp(),profile:e,isReadOnly:t,workflowsDirectory:S.env.ENHANCE_WORKFLOWS_DIR}},Qp=C.object({token:C.string().startsWith(`enh_`)}),$p=e=>{let t=w.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await en(t,`utf8`));return Qp.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Zt(e,{recursive:!0,mode:448}),await Xt(e,448);let r=w.join(e,`credentials.${String(S.pid)}.tmp`);await sn(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await nn(r,t),await Xt(t,384)},remove:async()=>{try{return await on(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},em={path:`direct_cli`},tm=C.object({access_token:C.string().min(1)}),nm=C.object({code:C.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),rm=`Check network access and proxy settings for this API, then run enhance doctor again.`,im=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,am=e=>{let t=nm.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?am(e.cause):e instanceof Error?e.name:`Network request failed`},om=(e,t)=>new y(`INTERNAL`,`${im(e)} answered HTTP ${String(t)}.`,rm),sm=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new y(`INTERNAL`,`Could not reach ${im(e)}: ${am(t)}.`,rm)}},cm=async(e,t)=>{let n=await sm(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw om(e,n.status);return n},lm=(e,t,n=null,r=em)=>vn({links:[yn({url:`${e}/trpc`,fetch:async(e,t)=>cm(e,{...t,signal:t?.signal??null}),headers:{[ye]:JSON.stringify(r),...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),um=async e=>{try{return await e()}catch(e){throw Xe(e)}},dm=async e=>{let t=await fetch(e);if(!t.ok)throw new y(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())},fm=async e=>{let t=await sm(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new y(`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 y(`INTERNAL`,`${im(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,rm);return t.json()},pm=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await sm(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw om(e,n.status);return n.json()},mm=async e=>{let t=await sm(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 y(`INTERNAL`,`${im(e.issuer)} token exchange answered HTTP ${String(t.status)}`,rm);return tm.parse(await t.json()).access_token},hm=async e=>{try{let t=await sm(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:om(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${im(e)}.`}}},gm=async e=>{let t=!(e.body instanceof Uint8Array),n=t?mn.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 y(`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 y(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return a.replaceAll(`"`,``)},_m=(e,t,n,r=em)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>fm(i),oauthMetadata:pm,exchangeOauthCode:mm,query:async(e,n,a)=>um(async()=>lm(i,await t.read(),null,r).query(e,n,a)),queryWithToken:async(e,t,n)=>um(async()=>lm(i,n,null,r).query(e,t)),mutate:async(e,a)=>um(async()=>lm(i,await t.read(),n.current(e,a),r).mutation(e,a)),mutateWithToken:async(e,t,n)=>um(async()=>lm(i,n,null,r).mutation(e,t)),download:dm,upload:gm,health:async()=>hm(i)}},vm=e=>Array.isArray(e)?e.map(e=>vm(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,vm(t)])),ym=(e,t,n)=>T(`sha256`).update(`${e}\0${t}\0${JSON.stringify(vm(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),bm=()=>{let e=Kt(),t=!1;return{current:(n,r)=>t?ym(e,n,r):e,select:(n,r)=>{e=n??Kt(),t=r}}};export{Ir as C,Sn as E,zr as S,E as T,Ti as _,Zp as a,ni as b,tl as c,q as d,Nc as f,M as g,Pi as h,Xp as i,$c as l,Oc as m,_m as n,Wp as o,Mc as p,$p as r,Lp as s,bm as t,Qc as u,xi as v,Pn as w,Zr as x,ai as y};