@enhance-eng/enhance-dev 0.1.41-dev.sha-e57eae05dcd7 → 0.1.41-dev.sha-548ac35f52fa

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.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{$ as e,$n as t,$t as n,A as r,Ar as i,Bn as a,Br as o,C as s,Cr as c,D as l,Dn as u,Dr as d,E as f,En as p,Er as m,Et as h,F as g,Fn as _,Fr as ee,Ft as te,Gn as v,Hn as ne,In as re,Ir as ie,It as y,J as ae,Jn as b,Jt as oe,Kn as se,Kt as ce,Lr as le,Lt as ue,M as de,Mn as fe,Mr as pe,Mt as me,Nn as he,Nr as ge,Nt as x,On as _e,Or as ve,Ot as ye,P as be,Pn as xe,Pr as Se,Pt as Ce,Q as we,Qt as Te,R as Ee,Rn as De,Rr as Oe,Rt as ke,Sr as Ae,St as je,T as Me,Tn as Ne,U as Pe,Ur as Fe,V as Ie,Wn as Le,Wt as Re,X as ze,Xn as Be,Xt as Ve,Y as He,Yt as Ue,Z as We,Zn as Ge,Zt as Ke,_r as qe,an as Je,b as Ye,br as Xe,bt as Ze,cr as Qe,ct as $e,d as et,dt as tt,en as nt,er as rt,et as it,fr as at,gr as ot,gt as st,hr as ct,ht as lt,ir as ut,jn as dt,jr as ft,kn as pt,kr as mt,kt as ht,lr as gt,mt as _t,nn as vt,nr as yt,or as bt,ot as xt,pt as St,q as Ct,qn as wt,qt as Tt,rn as Et,rr as Dt,rt as Ot,st as kt,tn as At,tr as jt,tt as Mt,ur as Nt,ut as Pt,vr as Ft,w as It,wt as Lt,yr as Rt,yt as zt,zn as Bt,zr as Vt}from"./cli-output-identity.lib-CjRqgKQ4.mjs";import S from"node:process";import{z as C}from"zod";import{homedir as Ht,tmpdir as Ut}from"node:os";import{generateKeyBetween as Wt,generateNKeysBetween as Gt}from"fractional-indexing";import{chmodSync as Kt,constants as qt,createReadStream as Jt,createWriteStream as Yt,mkdirSync as Xt,openAsBlob as Zt,writeFileSync as Qt}from"node:fs";import w from"node:path";import{createHash as T,randomBytes as $t,randomUUID as en}from"node:crypto";import{setTimeout as tn}from"node:timers/promises";import{isDeepStrictEqual as nn}from"node:util";import{access as rn,chmod as an,mkdir as on,mkdtemp as sn,open as cn,readFile as ln,realpath as un,rename as dn,rm as fn,stat as pn,unlink as mn,writeFile as hn}from"node:fs/promises";import{generate as gn,parse as _n}from"css-tree";import{parseFragment as vn,serialize as yn,serializeOuter as bn}from"parse5";import{performance as xn}from"node:perf_hooks";import{Transform as Sn}from"node:stream";import{pipeline as Cn}from"node:stream/promises";import{ZipFile as wn}from"yazl";import{createTRPCUntypedClient as Tn,httpLink as En}from"@trpc/client";import{spawn as Dn}from"node:child_process";import{createServer as On}from"node:http";const kn=(e,t)=>e<t?-1:+(e>t),An=(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)??[])]},jn=(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:An(a,t.order)}},Mn=(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=jn(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}}},Nn=1e6,Pn=e=>Math.round(e*255*Nn)/Nn,E=(e,t=1)=>{let n=e.alpha*t;if(e.space===`srgb`){let t=[e.red,e.green,e.blue].map(e=>String(Pn(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)})`},Fn={x:0,y:0,width:1,height:1},In=(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}},Ln=(e,t=Fn)=>[{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=In(e,t);return[n.x,n.y]}),Rn=1024,zn=(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(`, `)})`},Bn=(e,t)=>{let n=Ln(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/Rn:e),s=`width:100%;height:100%;background-image:${zn(e,a,!1)};mask-image:${zn(e,a,!0)};`;return`<g transform="matrix(${o.map(String).join(` `)})"><foreignObject x="${String(r*Rn)}" y="${String(r*Rn)}" width="${String(i*Rn)}" height="${String(i*Rn)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${s}"></div></foreignObject></g>`},Vn=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Bn(e)}</svg>`,Hn=(e,t)=>e===void 0||t===void 0?!1:e.x===t.x&&e.y===t.y,Un=e=>{let t=[...e];for(;t.length>1&&Hn(t[0],t.at(-1));)t.pop();for(;t.length>1&&Hn(t[0],t[1]);)t.splice(1,1);return t},Wn=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},Gn=(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},Kn=e=>{let t=Wn(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=Gn(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?Un(n):null},qn=Math.PI/2,Jn=1e6,Yn=e=>String(Math.round(e*Jn)/Jn),D=([e,t])=>`${Yn(e)} ${Yn(t)}`,Xn=(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}},Zn=(e,t)=>{let{radius:n,reach:r,smoothing:i}=e,a=D(t([r,0]));if(n===0)return`L${a}`;let o=i*qn/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${Yn(n)} ${Yn(n)} 0 0 1 ${m}`}C${h} ${g} ${_}`},Qn=(e,t)=>{let{topLeft:n,topRight:r,bottomRight:i,bottomLeft:a,smoothing:o=0}=e;return[Xn(n,[r,a],t,o),Xn(r,[n,i],t,o),Xn(i,[a,r],t,o),Xn(a,[i,n],t,o)]},$n=(e,t)=>{let[n,r,i,a]=Qn(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}},er=(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]=Qn(e,{width:r,height:i});return[`M${D([n[0],a.reach+n[1]])}`,Zn(a,([e,t])=>[t+n[0],e+n[1]]),Zn(o,([e,t])=>[r-e+n[0],t+n[1]]),Zn(s,([e,t])=>[r-t+n[0],i-e+n[1]]),Zn(c,([e,t])=>[e+n[0],i-t+n[1]]),`Z`].join(``)},tr=1e5,nr=.01,rr=1e-9,O=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],ir=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1]),ar=(e,t)=>e[0]*t[1]-e[1]*t[0],k=(e,t)=>[e[0]-t[0],e[1]-t[1]],or=e=>String(Math.round(e*tr)/tr),sr=(e,t,n=0)=>{let[r,i,a,o]=e,s=ir(r,o);if(n>=16||ir(r,i)+ir(i,a)+ir(a,o)-s<=nr/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);sr([r,c,d,p],t,n+1),sr([p,f,u,o],t,n+1)},cr=(e,t,n,r)=>{let i=k(t,e),a=ir(e,t);if(a<rr)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-nr/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)])}},lr=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`){sr([t,a(),a(),a()],n);return}if(e===`A`){let e=i();r+=4,cr(t,a(),e,n)}};for(;r<t.length;)o(t[r++]??`Z`);return n.filter((e,t)=>ir(e,n[(t+1)%n.length]??e)>rr)},ur=(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]]]},dr=(e,t,n,r)=>{let i=k(t,e),a=k(r,n),o=ar(i,a);if(Math.abs(o)<rr)return O(t,n);let s=ar(k(n,e),a)/o;return[e[0]+s*i[0],e[1]+s*i[1]]},fr=(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]=ur(i,a,t),c=k(s,o),l=[];for(let[e,t]of n.entries()){let r=n[(e+1)%n.length]??t,i=ar(c,k(t,o))>=-1e-9,a=ar(c,k(r,o))>=-1e-9;i&&l.push(t),i!==a&&l.push(dr(t,r,o,s))}if(n=l,n.length===0)break}return n},pr=(e,t)=>{if(t===0)return e;let n=lr(e),r=t<0?fr(n,t):n.map((e,r)=>{let i=n[(r+n.length-1)%n.length]??e,a=n[(r+1)%n.length]??e,o=ur(i,e,t),s=ur(e,a,t);return dr(...o,...s)});return r.length<3?``:r.map((e,t)=>`${t===0?`M`:`L`}${or(e[0])} ${or(e[1])}`).join(``)+`Z`},mr=(e,t,n)=>t.width<=0||t.height<=0?``:pr(er(e,t),n),hr=(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*_}},gr=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}},_r=e=>{let t=gr(e);return t===null||e.box===void 0?null:hr(e.box,e.layout??{},t)},A=(e,t,n)=>({x:e.x+t.x*n,y:e.y+t.y*n}),vr=e=>`${String(e.x)} ${String(e.y)}`,yr=(e,t,n)=>({x:(t.x-e.x)/n,y:(t.y-e.y)/n}),br=(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}})},xr=(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=yr(n,r,a),c=yr(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)}},Sr=(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=yr(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}},Cr=(e,t,n)=>{let r=Sr(e,e.before,t,n),i=Sr(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${vr(e)} ${vr(t)} ${vr(n)}`;return vr(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):``)},wr=(e,t,n)=>{let r=e.map((t,n)=>xr(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+vr(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+Cr(o,m,h)}).join(``)}Z`},Tr=(e,t,n)=>wr(br(e,t,n),e.cornerRadius,e.cornerSmoothing),Er=new WeakMap,Dr=new WeakMap,Or=e=>{if(Dr.has(e))return Dr.get(e)??null;let t=e.result.path.match(/M[^M]*/gu)??[],n=t.map(e=>{let t=Kn(e);return{path:e,vertices:t!==null&&t.length>=3?t:null}}),r=t.length>0&&t.join(``)===e.result.path?n:null;return Dr.set(e,r),r},kr=(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=Or(e);return i===null?r:{...r,path:i.map(e=>e.vertices===null?e.path:wr(e.vertices,n.topLeft,n.smoothing??0)).join(``)}},Ar=e=>{if(Er.has(e))return Er.get(e)??null;let t=Kn(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 Er.set(e,n),n},jr=(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=Ar(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:wr(a,r,t.smoothing??0),viewBox:{x:0,y:0,width:n.width,height:n.height}}},Mr={topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},Nr=[`border-top-left-radius`,`border-top-right-radius`,`border-bottom-right-radius`,`border-bottom-left-radius`],Pr=(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},Fr=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]=Nr.map(n=>Pr(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}},Ir=(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`},Lr=(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:Tr(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=Fr(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&&Nr.every(t=>e.styles[t]===void 0)?Ir(n.width,n.height):er(t&&e.component===`rectangle`&&e.appearance?.radius!==void 0?Mr:{...Mr,...r},n),viewBox:{x:0,y:0,width:n.width,height:n.height}}},Rr=e=>{if(e.geometry?.kind===`boolean`&&e.box!==void 0)return e.geometry.result.isEmpty?`This shape has no closed geometry.`:kr(e.geometry,e.box,e.appearance?.radius);let t=Lr(e,!1);return typeof t!=`string`&&e.geometry?.kind===`path`&&e.component===`rectangle`&&e.appearance?.radius!==void 0&&e.box!==void 0?jr(t,e.appearance.radius,e.box):t},zr=e=>{let t=Rr(e);if(typeof t==`string`)return t;if(e.box===void 0)return`The shape has no settled local box.`;let n=_r(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]}},Br=.5,Vr=.25,Hr=(e,t=`field`,n)=>{let r=Ln(e,n),i=Math.max(Br,...r.map(e=>Math.abs(e-Br)))+1,a=Br-i,o=Br+i,s=[{x:.75,y:.75,points:`.5,.5 ${String(o)},.5 ${String(o)},${String(o)} .5,${String(o)}`},{x:Vr,y:.75,points:`.5,.5 .5,${String(o)} ${String(a)},${String(o)} ${String(a)},.5`},{x:Vr,y:Vr,points:`.5,.5 ${String(a)},.5 ${String(a)},${String(a)} .5,${String(a)}`},{x:.75,y:Vr,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>`},Ur=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Hr(e)}</svg>`,Wr=e=>e.parameter===`radius`?e.value/2:e.value,Gr=e=>{switch(e.kind){case`blur`:return`blur(${String(Wr(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)`}},Kr=e=>e.filter(e=>e.visible).map(e=>Gr(e)).join(` `),qr=new Set([`base`,`embed`,`iframe`,`link`,`meta`,`object`,`script`]),Jr=/^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu,Yr=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,Xr=e=>!qr.has(e.toLowerCase()),Zr=e=>!Yr.test(e),Qr=(e,t)=>{let n=e.toLowerCase();return n===`srcdoc`||/^on/iu.test(n)?!1:n===`style`?Zr(t):![`href`,`src`,`action`,`formaction`,`xlink:href`].includes(n)||!Jr.test(t.replaceAll(/[\p{Control}\s]/gu,``))},$r=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ei=(e,t)=>{if(!$r(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=ei(e,t);if(!$r(n)||!$r(n.alternatives))return n;let r=n.alternatives,i=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,ei(n,t)]));return Object.entries(i).every(([e,t])=>r[e]===t)?n:{...n,alternatives:i}},ti=(e,t)=>Array.isArray(e)?e.map(e=>{if(!$r(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))},...$r(e.stroke)&&{stroke:{...e.stroke,paint:j(e.stroke.paint,t)}},...Array.isArray(e.children)&&{children:ti(e.children,t)}}}):e,ni=(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:ti(e.props.richText,t)}}}}},ri=(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>`},ii=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${ri(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,ai=e=>({id:e,visible:!1,opacity:1,kind:`solid`,color:{space:`srgb`,red:0,green:0,blue:0,alpha:0}}),oi=()=>({opacity:1,blendMode:`normal`,fills:[],border:{visible:!1,width:{top:0,right:0,bottom:0,left:0},style:`solid`,paints:[ai(`empty-border`)]},outline:{visible:!1,width:0,offset:0,style:`solid`,paints:[ai(`empty-outline`)]},radius:{topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},shadows:[],filters:[],backdropFilters:[]}),si=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],ci=(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(${si(e).map(String).join(` `)})" color-interpolation="sRGB">${r}</radialGradient>`},li=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${ci(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,ui=/^enh_[\w-]{43}$/,di=e=>{let t=At.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}},fi=(e,t,n)=>({loginWithToken:async n=>{if(!ui.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=di(await t.queryWithToken(`person.me`,{},n));return await e.write(n),r},loginWithBrowser:async r=>{let i=vt.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=Et.parse(await t.mutateWithToken(`person.createAgentToken`,{label:r.label,expiresAt:null},a)),s=di(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 di(await n.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),pi=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),mi=e=>{if(e.byteLength<24||pi.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)}},hi=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=qe.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!n.success||n.data.jobId!==t.id||n.data.download.bytes!==t.result.bytes)throw new 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=mi(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}}},gi=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]},_i=(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:gi(e)}),vi=async(e,t,n,r)=>{let i=await hi(e,n);return _i(n,t.write({body:i.body,...r}),i.source)},yi=[`canvas.render.create`,`canvas.render.get`],bi=e=>new y(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),xi=e=>{let t=e.failure;if(t===null)return bi(`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})},Si=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Ci=async(e,t)=>{let n=Ft.safeParse(await e.query(yi[1],{jobId:t}));if(!n.success||n.data.job.id!==t)throw bi(`render status`);return n.data.job},wi=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 Si(250),a=a.purpose===`inspection`&&a.state===`queued`&&a.attempt>0?await t.resume():await Ci(e,a.id)}if(a.state!==`succeeded`)throw xi(a);return a},Ti=async(e,t)=>{let n=ct.safeParse(await e.mutate(yi[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 bi(`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 bi(`render identity`);return n.data.job},Ei=(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`})},Di=async(e,t)=>{let n=await Ti(e.remote,t);try{Ei(n,t);let r=await wi(e.remote,{initial:n,resume:async()=>Ti(e.remote,t),deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress,timeoutOutcome:t.timeoutOutcome});return Ei(r,t),r.state===`succeeded`?await vi(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})}},Oi=(e,t,n,r=()=>null)=>({execute:async i=>Di({remote:e,files:t,now:n,progress:r},i)}),ki={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},Ai=async e=>{try{return await e(),!0}catch{return!1}},ji=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await Ai(async()=>e.mutate(ki.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 Ai(async()=>e.mutate(ki.end,{canvasId:i.canvasId,activityId:n})))}}},Mi=e=>({begin:async t=>{try{let n=a.safeParse(await e.mutate(ki.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?ji(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>Ai(async()=>e.mutate(ki.end,{canvasId:t,activityId:n}))}),Ni=new Set([`insertPrototype`,`insertText`,`setBox`]),Pi=e=>Ni.has(e.op),Fi=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,Ii=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],Li=e=>[...new Set(e.operations.flatMap(e=>Ii(e)))].slice(0,100),Ri=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:Pi(e)?e.box==="default"?null:e.box:null,zi=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}},Bi=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:15}),r=rt.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 Bi(e,t);let r=await Mi(e).begin({canvasId:t.canvasId,phase:Fi(t),nodeIds:Li(t),bounds:zi(t.operations.flatMap(e=>{let t=Ri(e);return t===null?[]:[t]}))});try{return await Bi(e,t)}finally{await r?.finish()}}}),Vi=async(e,t,n)=>{let r=bt.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.`);return Ce(r.data.document)},Hi=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):kn(t.sortKey,r.sortKey)).map(([e])=>e),Ui=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},Wi=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),N=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new y(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Gi=(e,t)=>{let n=new Set,r=t=>{for(let i of Hi(e,t))n.add(i),r(i)};return r(t),n},P=(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),N(e,r).locked===!0)return!0;r=e.relationships[r]?.parentId}return!1},Ki=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},qi=e=>{let t=0;return n=>(t+=1,`${Ki(e)}_${Ki(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},Ji=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of Hi(e,t))r(n)};return r(t),n},Yi=(e,t,n)=>Object.fromEntries(Ji(e,t).map(t=>[t,n(N(e,t).label)])),Xi=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=N(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Zi=e=>{let{document:t,input:n,inputIndex:r,nextId:i}=e,a=N(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(!Wi(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=Yi(t,n.id,i),l={document:t,rootId:n.id,parentId:s,inputIndex:r,sourceSortKey:o.sortKey,map:c},u=Ji(t,n.id).map(e=>Xi(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))}}},Qi=(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=qi(n),i=t.map((t,n)=>Zi({document:e,input:t,inputIndex:n,nextId:r}));return{operations:i.flatMap(e=>e.operations),duplicatedNodes:i.map(e=>e.summary)}},$i=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,Hi(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),ea=(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))}},ta=(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}},na=(e,t)=>`parentId`in e?ea(e,t):ta(e,t),ra=(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(Gi(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!Wi(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.`)},ia=(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=Wt(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=Gt(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}}},aa=(e,t)=>{if(t.length===0)throw new y(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=$i(e),r=[];return{operations:t.flatMap(e=>{let t=na(e,n);ra(e,t,n),r.push({nodeId:e.nodeId,...t});let i=ia(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)??[]]}))}},F=e=>Math.min(1,Math.max(0,e)),oa=e=>F(Number(e)/255),sa=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}},ca=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===`%`?F(Number(e)/100):oa(e??`0`),r=t[7]===void 0?1:F(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}},la=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:F(Number(t[2])),green:F(Number(t[3])),blue:F(Number(t[4])),alpha:F(t[5]===void 0?1:Number(t[5]))}},ua=e=>{let t=e.trim().toLowerCase();return t===`transparent`?{space:`srgb`,red:0,green:0,blue:0,alpha:0}:t.startsWith(`#`)?sa(t):t.startsWith(`rgb`)?ca(t):t.startsWith(`color(`)?la(t):null},da=(e,t)=>({id:e,visible:!0,opacity:1,kind:`solid`,color:t}),I=(e,t)=>{let n=ua(t);return n===null?null:da(e,n)},fa=e=>e/2**32|0,pa=e=>e>>>0;function ma(e,t,n,r){let i=fa(n),a=pa(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function ha(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const ga=e=>e?`"${e}" `:``;function _a(e,t=``){if(typeof e!=`number`)throw TypeError(ga(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ga(t)+`expected integer >= 0, got `+e);return e}function va(e,t,n=``){if(ha(e)&&(t===void 0||e.length===t))return e;t!==void 0&&_a(t,`length`);let r=ha(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ga(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const ya=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)};function ba(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function xa(e,t){va(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function Sa(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ca(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function L(e,t){return e<<32-t|e>>>t}const wa=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Ta=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Ea(e){if(va(e),wa)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Ta[e[n]];return t}function Da(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function Oa(e,t,n=`opts`){return ya(e,`defaults`),t!==void 0&&ya(t,n),Object.assign(e,t)}function ka(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=Oa({},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 Aa=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function ja(e,t,n){return e&t^~e&n}function Ma(e,t,n){return e&t^e&n^t&n}var Na=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=Ca(this.buffer)}update(e){ba(this),va(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=Ca(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){ba(this),xa(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)),ma(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:Ca(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 Pa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Fa=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]),R=new Uint32Array(64);var Ia=class extends Na{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)R[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=R[e-15],n=R[e-2],r=L(t,7)^L(t,18)^t>>>3,i=L(n,17)^L(n,19)^n>>>10;R[e]=i+R[e-7]+r+R[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=L(o,6)^L(o,11)^L(o,25),u=l+t+ja(o,s,c)+Fa[e]+R[e]|0,d=(L(n,2)^L(n,13)^L(n,22))+Ma(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(){Sa(R)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Sa(this.buffer)}},La=class extends Ia{constructor(){super(32,Pa)}};const Ra=ka(()=>new La,Aa(1)),za=new Map,Ba=new Map,Va={depth:0},Ha=(e,t=1)=>{let n=Va.depth>0?Ba:za;n.set(e,(n.get(e)??0)+t)},Ua=(e,t)=>e.sortKey===t.sortKey?e.childId.localeCompare(t.childId):e.sortKey<t.sortKey?-1:1,Wa=e=>{Ha(`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(Ua).map(e=>e.childId));return n},Ga=new WeakMap,Ka=new WeakMap,qa=e=>{let t=Ga.get(e);if(t!==void 0)return t;let n=Ka.get(e)?.()??Wa(e);return Object.isFrozen(e)&&Ga.set(e,n),n},Ja=[],Ya=(e,t)=>e.get(t)??Ja,Xa=(e,t)=>Ya(qa(e),t),Za=e=>e.trim()===``||e.trim()===`about:blank`,Qa=e=>typeof e==`string`&&e.startsWith(`enhance-pending-image:`),$a=e=>Qa(e.assetId)||e.opacity!==1||e.fit===`crop`&&e.transform!==void 0||(e.rotation??0)!==0||e.fit===`tile`&&(e.tileScale??1)!==1,eo=e=>`--canvas-image-paint-${Ea(Ra(Da(JSON.stringify([e.assetId,e.opacity,e.rotation??0,e.fit===`tile`?e.tileScale??1:1,e.fit===`crop`?e.transform:void 0]))))}`,to=e=>`--canvas-text-paints-${Ea(Ra(Da(JSON.stringify(e.filter(e=>e.visible),(e,t)=>e===`id`?void 0:t))))}`,no=(e,t=1)=>`${E(e.color,t)} ${String(e.position*100)}%`,ro=e=>encodeURI(e).replaceAll(`"`,`%22`),io=e=>`url("${ro(e)}")`,ao=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=>no(t,e.opacity)).join(`, `)})`:`url("data:image/svg+xml,${encodeURIComponent(ii({...e,transform:e.transform}))}")`;case`radial-gradient`:{if(e.transform!==void 0)return`url("data:image/svg+xml,${encodeURIComponent(li(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=>no(t,e.opacity)).join(`, `)})`}case`angular-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Vn(e))}")`;case`diamond-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Ur(e))}")`;case`image`:return Za(e.assetId)?`none`:$a(e)?`var(${eo(e)}, none)`:io(e.assetId)}},oo=(e,t)=>t>=1?0:e/(1-t)*100,so=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(oo(e.x,t))}% ${String(oo(e.y,n))}%`,"background-size":`${String(100/t)}% ${String(100/n)}%`}},co=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`?so(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`}},lo=e=>{if(e.length===0)return{};let t=e.toReversed().map(e=>co(e));return Object.fromEntries([`background-size`,`background-position`,`background-repeat`,`background-origin`].map(e=>[e,t.map(t=>t[e]).join(`, `)]))},uo=e=>e.kind===`solid`&&e.visible?E(e.color,e.opacity):void 0,fo=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,po=e=>fo(e)?void 0:uo(e),mo=e=>{let t=e.filter(e=>e.visible),[n]=t;return n===void 0||t.length!==1?`transparent`:po(n)??`transparent`},ho=e=>({"background-image":e.toReversed().map(e=>ao(e)).join(`, `),...lo(e)}),go=e=>{let t=e.filter(e=>e.visible);if(t.length===0||t.some(e=>fo(e)))return{background:`none`};let[n]=t,r=n===void 0?void 0:po(n);return r!==void 0&&t.length===1?{background:r,"background-image":`none`}:{"background-color":`transparent`,...ho(t)}},_o=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(${to(t)}, none)`,"background-size":`100% 100%`,"background-position":`center`,"background-repeat":`no-repeat`}:ho(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`}},vo=new Set(Qe.keyof().options.filter(e=>/^(?:border|outline)(?:-|$)/u.test(e)&&!e.includes(`radius`))),yo=(e,t)=>{let n=t.toLowerCase();return vo.has(n)&&(n===e||n.startsWith(`${e}-`))},bo=[`top`,`right`,`bottom`,`left`],xo=[`solid`,`dashed`,`dotted`],So=[`width`,`style`,`color`],Co=(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},wo=(e,t)=>{let n=m(t);if(/^(?:border(?:-(?:top|right|bottom|left))?|outline)$/u.test(e)){let t=n.find(e=>Co(e)!==void 0),r=n.find(e=>/^(?:none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/u.test(e)),i=n.find(e=>I(`probe`,e)!==null);if(t===void 0||r===void 0||i===void 0||n.length!==So.length)return null;let a=e===`border`?bo.map(e=>`border-${e}`):[e];return Object.fromEntries(a.flatMap(e=>So.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>bo.length)return null;let[t=``,r=t,i=t,a=r]=n;return Object.fromEntries(bo.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},To=(e,t)=>e.additionalStyles?.declarations.filter(({property:n,value:r,enabled:i})=>yo(t,n)&&(!i||r.trim()!==``||e.appearance?.[t]===void 0))??[],Eo=(e,t)=>{let n=To(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(!yo(t,e))continue;let r=wo(e.toLowerCase(),d(e,n).trim());if(r===null||String(n).includes(`!`))return null;Object.assign(a,r)}return a},Do=e=>{let t=Eo(e,`border`);if(t===null)return{kind:`custom`};if(e.appearance?.border!==void 0&&To(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=bo.map(n=>({width:Co(t[`border-${n}-width`]??`0`),authoredStyle:t[`border-${n}-style`],authoredColor:t[`border-${n}-color`],style:xo.find(e=>e===t[`border-${n}-style`]),paint:I(`${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]}}},Oo=e=>{let t=Eo(e,`outline`);if(t===null)return{kind:`custom`};if(e.appearance?.outline!==void 0&&To(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=Co(t[`outline-width`]),r=Co(t[`outline-offset`]??`0`,-1/0),i=xo.find(e=>e===t[`outline-style`]),a=I(`${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]}}},ko=Object.freeze({top:0,right:0,bottom:0,left:0}),z=e=>e.alignment!==void 0&&e.alignment!==`inside`||e.layoutInclusion===`none`||e.layoutInclusion===`visible`&&(!e.visible||e.paints.every(e=>!e.visible))?ko:e.width,Ao=e=>{let t=e.visible?mo(e.paints):`transparent`,n=z(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}},jo=e=>{if(!e.visible)return{"outline-style":`none`};let t=mo(e.paints);return{"outline-style":e.style,"outline-width":e.width,"outline-offset":e.offset,"outline-color":t}},Mo=e=>({...e.border!==void 0&&Ao(e.border),...e.outline!==void 0&&jo(e.outline)}),No=e=>{if(e.geometry?.kind===`boolean`||(e.appearance?.radius?.smoothing??0)<=0)return!1;let t=Do(e);return t.kind===`custom`||t.kind===`native`&&t.value.style!==`solid`},Po=(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 Fo(n);let r=$n(n,t),i=Fo(r);if((n.smoothing??0)<=0)return i;if(No(e))return{};let a=`path("${er(n,t)}") border-box`,o=Do(e);if(o.kind!==`native`||Object.values(z(o.value)).every(e=>e===0))return{...i,"border-shape":a};let{top:s,right:c,bottom:l,left:u}=z(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`}},Fo=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}),Io=new Set([se,Be]),Lo=e=>e.visible&&e.kind===`blur`&&e.progression!==void 0,Ro=e=>e.geometry===void 0&&Io.has(e.component)?(e.appearance?.backdropFilters??[]).find(e=>Lo(e))??null:null,zo=(e,t)=>{let n=Ro(e);return n===null?t:t.filter(e=>e!==n)},Bo=new Set([se,wt,Be,b]),Vo=new Set([se,wt,Be]),B=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,Ho=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),Uo=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`},Wo=e=>{if(e.component!==`rectangle`||e.geometry!==void 0||Uo(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=>!Ho(e))},Go=e=>e.geometry===void 0&&Bo.has(e.component)&&(e.component!==`image`||(typeof e.props?.src!=`string`||e.props.src===``)&&e.appearance?.fills!==void 0),Ko=e=>e?.visible===!0?e.paints.filter(e=>e.visible):[],qo=e=>B(e)||e.kind===`image`&&(e.filters?.some(e=>e.visible)??!1),Jo=e=>{if(!Go(e))return[];let t=(e.appearance?.fills??[]).filter(e=>e.visible);return t.some(e=>qo(e))||t.length>0&&Ro(e)!==null?t:[]},Yo=e=>e.style===`solid`||e.dashOrigin===`css`&&e.dashPattern===void 0&&e.dashCap===void 0,Xo=e=>{let t=Ko(e);return t.length>0&&((e.alignment??`inside`)!==`inside`||!Yo(e)||t.length>1||t.some(e=>e.kind!==`solid`))},Zo=(e,t)=>{let n=e.appearance?.border;if(n===void 0||e.geometry!==void 0||!Vo.has(e.component))return[];let r=Ko(n);return r.some(e=>B(e))?r.map(e=>({kind:`border`,paints:[e]})):n.layoutInclusion===`none`||n.layoutInclusion===`visible`||Xo(n)||t&&r.length>0?[{kind:`border`,paints:r}]:[]},Qo=e=>{let[t,...n]=Ko(e.appearance?.outline);return(e.appearance?.radius?.smoothing??0)>0&&n.length===0&&t?.kind===`solid`&&!B(t)},$o=e=>{let t=e.appearance?.outline;if(t===void 0||e.geometry!==void 0||!Vo.has(e.component)||t.width<=0||Qo(e))return[];let n=Ko(t);return n.some(e=>B(e))?n.map(e=>({kind:`outline`,paints:[e]})):n.length>1||t.style!==`solid`||n.some(e=>e.kind!==`solid`)?[{kind:`outline`,paints:n}]:[]},V=e=>{let t=Jo(e),n=Go(e)&&!Wo(e)?(e.appearance?.shadows??[]).filter(e=>e.visible):[],r=n.filter(e=>e.kind===`outer`&&B(e)),i=n.filter(e=>e.kind===`inner`&&(t.length>0||B(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,...Zo(e,t.length>0),...$o(e)],hasPaintElements:a.length>0}},es=e=>e.elements.flatMap(e=>e.kind===`fill`?[e.paint]:[]),ts=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.shadow]:[]),ns=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.paints]:[]),rs=(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`},is={top:0,right:0,bottom:0,left:0},as={inside:0,center:.5,outside:1},os=[[`topLeft`,`top-left`,`left`,`top`],[`topRight`,`top-right`,`right`,`top`],[`bottomRight`,`bottom-right`,`right`,`bottom`],[`bottomLeft`,`bottom-left`,`left`,`bottom`]],ss=e=>ns(V(e),`border`).length>0,cs=(e,t=e.box)=>{if(!ss(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=z(r);if((i.smoothing??0)<=0||Object.values(a).every(e=>e===0))return n;let o=er(i,t),s=er(i,t,[-a.left,-a.top]);return{...n,"border-shape":`path("${o}") border-box path("${s}") padding-box`}},ls=(e,t)=>{let n=e.appearance?.radius;return n===void 0?{"border-radius":`inherit`}:Object.fromEntries(os.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`]}))},us=1e3,H=e=>String(Math.round(e*us)/us),ds=(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${H(n)} ${H(r)}`:`A${H(e)} ${H(t)} 0 0 1 ${H(n)} ${H(r)}`;return[`M${H(i[0])} 0`,`H${H(e-a[0])}`,c(a,e,a[1]),`V${H(t-o[1])}`,c(o,e-o[0],t),`H${H(s[0])}`,c(s,0,t-s[1]),`V${H(i[1])}`,c(i,i[0],0),`Z`].join(``)},fs=e=>{if(e.stroke.style===`solid`)return{};let t=rs(e.stroke.style,e.widest,e.stroke),n=`<svg xmlns="http://www.w3.org/2000/svg" width="${H(e.width)}" height="${H(e.height)}"><path d="${ds(e.width,e.height,e.corners)}" fill="none" stroke="#000" stroke-width="${H(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`}},ps=(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 fs({width:n.width+r.left+r.right,height:n.height+r.top+r.bottom,corners:{topLeft:a(os[0]),topRight:a(os[1]),bottomRight:a(os[2]),bottomLeft:a(os[3])},widest:Math.max(...Object.values(t.width)),stroke:t})},ms=(e,t=e.box,n)=>{let r=e.appearance?.border,[i]=ns(V(e),`border`);if(r===void 0||i===void 0)return null;let a=n??i,o=z(r),s=as[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`&&Yo(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`}:ls(e,c),...Mo({...l,border:{...l.border,paints:[...a]}}),...!d&&{"border-color":`transparent`,...ho(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&&Po({...e,styles:{},additionalStyles:void 0,appearance:l},t),...!d&&ps(e,r,t,s===0?is:c)}},hs=(e,t)=>{if(Wo(e))return[];let n=V(e),r=[...ts(n,`outer-shadow`),...ts(n,`inner-shadow`)];return r.length===0?t:t.filter(e=>!r.includes(e))},gs=e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${E(e.color)}`,_s=e=>`${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${E(e.color)}`,vs=(e,t)=>{let n=hs(e,t).filter(e=>e.visible);if(e.component===`text`){let e=n.filter(e=>e.kind===`outer`&&e.spread===0).map(e=>_s(e)).join(`, `);return{"box-shadow":`none`,"text-shadow":e===``?`none`:e}}let r=n.map(e=>gs(e)).join(`, `);return{"box-shadow":r===``?`none`:r}},ys=(e,t)=>{let n=e.appearance?.border,r=n===void 0?{top:0,right:0,bottom:0,left:0}:z(n);return{position:`absolute`,top:-r.top,right:-r.right,bottom:-r.bottom,left:-r.left,"border-radius":`inherit`,"pointer-events":`none`,"box-shadow":gs(t),"mix-blend-mode":t.blendMode??`normal`}},bs=(e,t)=>{let n=t.map((n,r)=>{let[i=``,a,...o]=m(n),s=ua(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)},xs=(e,t)=>{let n=/^(linear|radial)-gradient\((.*)\)$/su.exec(t);if(n===null)return null;let r=[...m(n[2]??``,`,`)],i=r[0]??``,a=/^(-?(?:\d+(?:\.\d*)?|\.\d+))deg$/u.exec(i),s=/^ellipse ([\d.]+)% ([\d.]+)% at (-?[\d.]+)% (-?[\d.]+)%$/u.exec(i);if(a!==null&&n[1]!==`linear`||s!==null&&n[1]!==`radial`)return null;(a!==null||s!==null)&&r.shift();let c=r.map(e=>m(e).length>1);if(c.some(Boolean)&&!c.every(Boolean))return null;let l=bs(e,r);if(l===null)return null;let u={id:e,visible:!0,opacity:1,stops:l},d=o.safeParse(n[1]===`linear`?{...u,kind:`linear-gradient`,angle:Number(a?.[1]??180)}:s===null?null:{...u,kind:`radial-gradient`,radius:{x:Number(s[1])/100,y:Number(s[2])/100},center:{x:Number(s[3])/100,y:Number(s[4])/100}});if(!d.success)return null;let f=d.data,p=`stops`in f?f.stops[0]:void 0;return p!==void 0&&f.kind===`linear-gradient`&&f.stops.every(e=>JSON.stringify(e.color)===JSON.stringify(p.color))?{id:e,kind:`solid`,visible:!0,opacity:1,color:p.color}:f},Ss=(e,t,n,r)=>{let i=m(e[t]??r,`,`);return i[n%i.length]??r},Cs=(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=Ss(n,`background-position`,r,`0% 0%`),s=Ss(n,`background-size`,r,`auto`),c=Ss(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}},ws=(e,t)=>{let n=t.background,r=t[`background-color`]??n,i=r===void 0||r===`none`?null:I(`${e}-background`,r);if(r!==void 0&&r!==`none`&&i===null)return null;let a=t[`background-image`];if(a===void 0||a===`none`)return i===null?[]:[i];let o=m(a,`,`).map((n,r)=>{let i=`${e}-fill-${String(r)}`,a=xs(i,n),o=Ss(t,`background-size`,r,`auto`);if(a!==null&&![`auto`,`auto auto`,`100% 100%`].includes(o))return null;let s=a??Cs(i,n,t,r),c=Vt.safeParse(Ss(t,`background-blend-mode`,r,`normal`));return s===null||!c.success?null:{...s,blendMode:c.data}});return o.includes(null)?null:[...i===null?[]:[i],...o.filter(e=>e!==null).toReversed()]},Ts=[[`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]],Es=new Set([`color`,`-webkit-text-fill-color`]),Ds=(e,t)=>{let n=new Set;for(let r of t){let t=r.toLowerCase(),i=e.component===`text`;i&&Es.has(t)&&n.add(`fills`);for(let[e,r]of Ts)r.test(t)&&(!i||e!==`fills`)&&n.add(e)}return[...n].filter(t=>e.appearance?.[t]!==void 0)},Os=new Set([`background`,`background-color`,`background-image`]),ks=new Set([`background-position`,`background-size`,`background-repeat`,`background-origin`,`background-blend-mode`]),As=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(Ae(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},js=e=>{let t=As(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:Os};if(Object.entries(t).some(([e,t])=>!Os.has(e)&&!ks.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=ws(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(Os);for(let e of ks)i.add(e);return{kind:`native`,fills:r,owned:i}},Ms=e=>({...es(V(e)).length>0&&{background:`none`},...Ro(e)!==null&&{isolation:`isolate`}}),Ns=e=>({position:`absolute`,inset:0,...ho([e]),...e.kind===`image`&&e.filters!==void 0&&{filter:Kr(e.filters)},...e.blendMode!==void 0&&e.blendMode!==`normal`&&{"mix-blend-mode":e.blendMode}}),Ps=[[`topLeft`,`top-left`],[`topRight`,`top-right`],[`bottomRight`,`bottom-right`],[`bottomLeft`,`bottom-left`]],Fs=e=>ns(V(e),`outline`).length>0,Is=e=>Fs(e)?{"outline-style":`none`}:{},Ls=(e,t,n)=>{let r=e.appearance?.radius;if(r===void 0)return{};let i=t.offset+t.width,a=rs(t.style,t.width,t),o=mr(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`}},Rs=(e,t=e.box,n)=>{let r=e.appearance?.outline,[i]=ns(V(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}:z(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(Ps.map(([e,t])=>[`border-${t}-radius`,d(e)])),...ho(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&&Ls(e,r,t),...t!==void 0&&(o?.smoothing??0)<=0&&fs({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})}},zs=e=>{if(ee(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`)},Bs=(e,t)=>{let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)?Math.min(1,Math.max(0,n)):t},Vs=e=>Oe.find(t=>t===e)??`normal`,Hs=(e,t)=>{let n=Number(String(e??``).replace(`px`,``));return Number.isFinite(n)?Math.max(t,n):0},Us=e=>Hs(e,0),Ws=(e,t)=>e===0?t:e,Gs=e=>{let[t=0,n=t,r=t,i=n]=String(e[`border-radius`]??`0`).split(/\s+/u).map(e=>Us(e));return{topLeft:Ws(Us(e[`border-top-left-radius`]),t),topRight:Ws(Us(e[`border-top-right-radius`]),n),bottomRight:Ws(Us(e[`border-bottom-right-radius`]),r),bottomLeft:Ws(Us(e[`border-bottom-left-radius`]),i)}},U=e=>{let t=oi(),n=Do(e),r=Oo(e),i=I(`${e.id}-fill`,String(e.styles[e.component===`text`?`color`:`background`]??``)),a=e.component===`text`?null:js(e);return{...t,opacity:e.appearance?.opacity??Bs(e.styles.opacity,1),blendMode:e.appearance?.blendMode??Vs(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??Gs(e.styles),...e.appearance?.retainedBorder!==void 0&&{retainedBorder:e.appearance.retainedBorder},shadows:e.appearance?.shadows??[],filters:e.appearance?.filters??[],backdropFilters:e.appearance?.backdropFilters??[]}},Ks=e=>{let t=e.appearance?.fills;return e.component===`text`&&zs(e)?{...t!==void 0&&{color:_o(t).color??`transparent`},"background-image":`none`}:t===void 0?{}:e.component===`text`?_o(t):go(t)},qs=e=>{let t=e.appearance,n={...Ks(e),...Ms(e)};return(t?.opacity??Bs(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,Fo(t.radius),Po(e)),Object.assign(n,Mo(t),cs(e),Is(e)),t.filters!==void 0&&(n.filter=Kr(t.filters)),t.shadows!==void 0&&Object.assign(n,vs(e,t.shadows)),t.backdropFilters!==void 0&&(n[`backdrop-filter`]=Kr(zo(e,t.backdropFilters))),n)},Js=e=>{let t=U(e).radius;return t.topLeft===0&&t.topRight===0&&t.bottomRight===0&&t.bottomLeft===0},Ys=e=>{let t=U(e);return Do(e).kind!==`native`&&Oo(e).kind!==`native`&&t.shadows.every(e=>!e.visible)&&t.filters.every(e=>!e.visible)&&t.backdropFilters.every(e=>!e.visible)},Xs=e=>e!==void 0&&e.geometry===void 0&&(e.component===`image`||e.component===`rectangle`&&Js(e))&&Ys(e),Zs=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},Qs=(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},$s=(e,t)=>{let n=Qs(e,t);if(n===void 0)return null;let r=Xa(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=>Xs(e)&&rc(e,i)!==null)?r:null},ec=(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}},tc=(e,t)=>{let n=ao(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:ec(e.fit===`fit`?`fit`:`cover`,t,r)}},nc=(e,t)=>{let n=e.props?.src;if(typeof n!=`string`||n===``)return[];let r=io(n),i=e.props?.fit;if(i!==`cover`&&i!==`contain`)return[{image:r,box:t}];let a=Zs(e);return a===void 0?null:[{image:r,box:ec(i===`cover`?`cover`:`fit`,t,a)}]},rc=(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 nc(e,n);let{opacity:r}=U(e),i=[],a=U(e).fills.filter(e=>e.visible).toReversed();for(let e of a)if(e.kind===`image`){let t=tc(e,n);if(t===null)return null;i.push(t)}else i.push({image:ao({...e,opacity:e.opacity*r}),box:n});return i},ic=(e,t)=>t.geometry?.kind===`mask`?e.nodes[t.geometry.maskId]:void 0,ac={a:1,b:0,c:0,d:1,e:0,f:0},oc=(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}),sc=e=>{let{fills:t,opacity:n}=U(e);return(1-t.filter(e=>e.visible).reduce((e,t)=>e*(1-t.opacity*(t.kind===`solid`?t.color.alpha:1)),1))*n},cc=(e,t,n)=>{let[r,i,a,o,s,c]=e.matrix,l=oc(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}},lc=(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:zr(t);if(s!==null&&typeof s!=`string`&&n.push(cc(s,i,a*sc(t))),!o&&t.component!==`frame`)return;let c=_r(t);if(c===null)return;let l=oc(i,c),u=a*U(t).opacity;for(let n of Xa(e.relationships,t.id)){let t=e.nodes[n];t!==void 0&&r(t,l,u)}};return r(t,ac,1),n},uc=e=>{let t=2166136261;for(let n of e)t=Math.imul(t^(n.codePointAt(0)??0),16777619);return(t>>>0).toString(16)},dc=(e,t,n)=>{if($s(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]}},fc=(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=Rr(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=Rr(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??ic(e,t);if(a?.component===`text`&&a.visible!==!1)return dc(e,a,i);let o=a===void 0||a.visible===!1?null:lc(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:zr(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]}},pc=(e,t,n)=>{let r=fc(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(`%`,`_`)}-${uc(JSON.stringify([i,a,c,s]))}`,path:i,fillRule:a,transform:c,matrix:o,...s!==void 0&&{shapes:s}}},mc=(e,t)=>{let n=u(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}}},hc=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),gc=(e,t)=>{let n=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.id,e]));for(let[e,r]of Object.entries(t)){let t=Array.from(n,([,e])=>e).filter(t=>(e.startsWith(`--`)?t.property:t.property.toLowerCase())===e);for(let e of t)n.delete(e.id);if(r===null||Qe.safeParse({[e]:r}).success)continue;let i=t[0]?.id??`css-${e}`.slice(0,190),a=i;for(let e=1;n.has(a);e+=1)a=`${i}-${String(e)}`;let o=le.safeParse({id:a,property:e,value:String(r),enabled:!0});if(!o.success)throw new y(`BAD_REQUEST`,`Style ${e} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);n.set(a,o.data)}let r=n.values().toArray(),i=r.length===0&&e.additionalStyles===void 0?void 0:{declarations:r},a=Mn(e.additionalStyles,i);return a===null?null:{op:`patchAdditionalStyles`,nodeId:e.id,additionalStyles:a}},_c=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...c(t,r,e),...c(n,r,e)],o=yt(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}},vc=(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 c(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},yc=(e,t,n)=>{let r=vc(e,t,n),i=gc(t,r),a=Object.fromEntries(Object.entries(r).filter(([e,t])=>Qe.safeParse({[e]:t}).success)),o={...t,styles:{...t.styles},...i!==null&&{additionalStyles:jn(t.additionalStyles,i.additionalStyles)??void 0}};for(let[e,t]of Object.entries(a))t===null?Reflect.deleteProperty(o.styles,e):o.styles[e]=t;let s=_c(e,t,o,n),c=mc(t,r),l=Ds(t,Object.keys(r)),u=l.length>0?[{op:`setAppearance`,nodeId:t.id,appearance:{clear:[...l]}}]:[];return[...Object.keys(a).length>0?[{op:`setStyles`,nodeId:t.id,styles:Qe.parse(a)}]:[],...u,...c===null?[]:[c],...s===null?[]:[s],...i===null?[]:[i]]},bc=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=hc(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},xc=(e,t)=>{let n=[...bc(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 yc(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},Sc=(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=p(e.typography,{clear:[...u(new Set([...Object.keys(t.styles),...r]))]});return W({...e,styles:n},`typography`,i??`default`)},Cc=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),wc=e=>Cc.has(e.op),W=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},Tc=(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 Sc(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 W(e,`typography`,p(e.typography,t.typography)??`default`);case`setTypography`:return W(e,`typography`,t.typography);case`setLayout`:return W(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=jn(e.additionalStyles,t.additionalStyles);return W(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return W(e,`additionalStyles`,t.additionalStyles)}},Ec=(e,t)=>{if(!wc(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=N(e,t.nodeId);return t.op===`setParentage`?{...e,relationships:{...e.relationships,[n.id]:t.parentage}}:{...e,nodes:{...e.nodes,[n.id]:Tc(n,t)}}},Dc=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}}}},Oc=(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 xc(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Qi(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=aa(t.scene,[Dc(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},kc=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=Oc(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=Ec(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:Hi(r.scene,e)}))}},G=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.`)},Ac=(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`?G([`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]},jc=e=>e.op===`insertNode`?[e.node.id]:e.op===`insertText`||e.op===`insertPrototype`?[e.nodeId]:e.op===`insertConvertedSubtree`?Object.keys(e.nodes):[],Mc=(e,t)=>{let n=t.destination;if(n.kind===`adjacent`)return G([`adjacent conversion`]);let r=n.kind===`replace`?e.relationships[n.targetNodeId]?.parentId:n.targetNodeId;if(r===void 0)return G([n.targetNodeId]);let i=n.kind===`insert-children`&&n.targetNodeId===`root`?n.pageId??`canvas-page-default`:De(e,n.targetNodeId),a=t.nodes[t.rootNodeId];return a===void 0?G([t.rootNodeId]):{nodes:{...t.nodes,[t.rootNodeId]:{...a,...r===`root`&&i!==null&&{props:{...a.props,canvasPageId:i}}}},relationships:{...t.relationships,[t.rootNodeId]:{parentId:r,sortKey:``}}}},Nc=e=>({component:e.op===`insertText`?`text`:`prototype`,props:{...e.op===`insertPrototype`&&e.canvasPageId!==void 0&&{canvasPageId:e.canvasPageId}}}),Pc=(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]:Nc(t)},relationships:{[t.nodeId]:{parentId:t.parentId,sortKey:``}}};if(t.op===`insertConvertedSubtree`)return Mc(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:{}}},Fc=(e,t,n,r)=>{let i=jc(r),a=e.nodeIds.length===0&&(i.length>0||r.op===`move`||r.op===`setParentage`),o=[...Ac(r,t).filter(e=>!a||e!==`root`),...i.filter(e=>t.nodes[e]!==void 0)].filter(e=>!n.has(e));return o.length>0&&G(o),i},Ic=(e,t,n)=>{if(!me(e))return;let r=new Set(ht(e,t)),i=Bt(e,t);if(!i.ok)return G(e.nodeIds);let a={nodes:{...t.nodes},relationships:{...t.relationships}};for(let t of n){let n=Fc(e,a,r,t),o=Pc(a,t);Object.assign(a.nodes,o.nodes),Object.assign(a.relationships,o.relationships);let s=[...Object.keys(o.nodes),...Object.keys(o.relationships)].filter(e=>a.nodes[e]?.component===`page`||De(a,e)!==i.pageId);s.length>0&&G(s);for(let e of n)r.add(e);if(t.op!==`remove`)continue;let c=Bt({...e,nodeIds:[t.nodeId]},a);if(c.ok)for(let e of c.nodeIds)r.delete(e),Reflect.deleteProperty(a.nodes,e),Reflect.deleteProperty(a.relationships,e)}},Lc=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]}},Rc=(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]:Lc(e),zc=(e,t)=>{let n=new Set(e.edits.flatMap(e=>Lc(e)));for(let e of n)N(t,e);let r={canvasId:e.canvasId,nodeIds:e.nodeIds??[],...e.pageId!==void 0&&{pageId:e.pageId}};for(let n of e.edits)ye(r,t,Rc(n,t))},Bc=e=>({execute:async n=>{let r=await Vi({remote:e},n.canvasId,n.baseVersion);zc(n,r);let i=kc(r,n.edits,n.idPrefix??`copy_${n.mutationId.replaceAll(`-`,``)}`);Ic({canvasId:n.canvasId,nodeIds:n.nodeIds??[],...n.pageId!==void 0&&{pageId:n.pageId}},r,i.operations.filter(e=>`nodeId`in e&&r.nodes[e.nodeId]!==void 0));let a=t.safeParse({canvasId:n.canvasId,mutationId:n.mutationId,documentFormatVersion:15,baseVersion:n.baseVersion,operations:i.operations});if(!a.success)throw new y(`BAD_REQUEST`,`The edit contains an invalid canvas operation.`,a.error.issues[0]?.message??`Check the edit’s node references and values.`);let o=rt.parse(await M(e).execute(a.data));return{...o,next:[`Reuse version ${String(o.version)} as baseVersion for the next edit; no extra read is required.`,`Render the affected screen at version ${String(o.version)} when ready for visual review.`],...i.duplicatedNodes.length>0&&{duplicatedNodes:i.duplicatedNodes},...i.moves.length>0&&{moves:i.moves,affectedParents:i.affectedParents}}}}),Vc=(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},K=(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}},Hc=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}))]:[],Uc=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,Wc=(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:Uc(e),failure:e.failure,details:K(Hc(e),t.offset,t.limit),warnings:e.state===`succeeded`?[`This receipt does not verify visual fidelity. Render the committed root to inspect it.`]:[]}),q=e=>new y(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),Gc=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Kc=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})},qc=async(e,t)=>{let n=Nt.safeParse(await e.query(`canvas.render.getImport`,{jobId:t}));if(!n.success)throw q(`conversion status`);if(n.data.job.id!==t)throw q(`conversion identity`);return n.data.job},Jc=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 Gc(250),i=await qc(e,i.id)}if(i.state!==`succeeded`)throw Kc(i);return i},Yc=(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},Xc=(e,t)=>{let n=t.request;if(e.canvasId!==n.canvasId||e.requestedVersion!==n.expectedVersion||!Yc(e,t))throw q(`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 q(`conversion source`);if(e.state===`succeeded`&&(e.result.canvasId!==n.canvasId||n.revisionPolicy===`strict`&&e.result.previousVersion!==n.expectedVersion))throw q(`conversion commitment`)},Zc=async(e,t)=>{let n=gt.safeParse(await e.mutate(`canvas.render.importSource`,t.request));if(!n.success)throw q(`conversion creation`);Xc(n.data.job,t);let r=await Jc(e,n.data.job,t.waitMs);return Xc(r,t),r},Qc=async(e,t)=>{let n=Lt.parse(t),r=x(n.canvasRef);return Wc(await Zc(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})},$c=(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.`]}),el=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 $c(e,t,n.result.version)}},tl=async(e,t)=>{let n=await Vi({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??``}})},nl=(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}),rl=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.`]}),il=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}}}}),al=(e,t)=>({execute:async n=>{let r=await Mi(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await Zc(e,il(n));if(n.responseMode===`bounded`)return Wc(i,{offset:0,limit:40});if(i.state!==`succeeded`)return rl(i);if(n.review===`none`)return nl(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await el(t,n,i),o=[];try{o=await tl(e,i)}catch{o=[]}return{...nl(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),ol=async(e,t)=>{let n=x(t.canvas),r=bt.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),i=Ce(r.document);me(n)&&ht(n,i),t.nodeId!==void 0&&ye(n,i,[t.nodeId]);let a=Bt(t.nodeId===void 0?n:{...n,nodeIds:[t.nodeId]},i);if(!a.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 o=Object.groupBy(Object.entries(i.relationships),([,e])=>e.parentId),s=Object.values(i.nodes).filter(e=>a.nodeIds.has(e.id)).map(e=>({...e,kind:e.component,parentId:i.relationships[e.id]?.parentId??null,children:(o[e.id]??[]).map(([e])=>e)}));return{canvasId:n.canvasId,version:r.version,pageId:a.pageId,source:n.nodeIds.length>0?`selection-link`:n.pageId===void 0?`canvas-link`:`page-link`,selectedNodeIds:n.nodeIds,rootNodeIds:a.rootNodeIds,nodeCount:s.length,nodes:s,next:[`Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants.`]}},sl=(e,t,n)=>{try{Qt(e,t,{flag:n?`w`:`wx`,mode:384}),Kt(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.`)}},cl=e=>({write:t=>{if(t.outputPath!==null){let e=w.resolve(t.outputPath);return sl(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=w.join(e,`sensitive`);Xt(n,{recursive:!0,mode:448}),Kt(n,448);let r=w.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return sl(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),ll=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}},ul=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 tn(Math.min(250,n));let a=await ll(e,t.id);if(a===null)return i;if(i=v.parse(a.value).job,i.id!==t.id)throw new y(`INTERNAL`,`Preparation identity changed.`,`Retry the original request.`)}return i},dl=async(e,t,n)=>{let r=Le.parse(await e.mutate(`canvas.render.preparation.create`,t)),i=await ul(e,r.job,n);if(i.canvasId!==t.canvasId||i.requestedVersion!==t.expectedVersion||!nn(i.scope,t.scope)||!nn(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},fl=`Repeat canvas_capture with identical arguments and clientToken, or follow operation_status. An unfinished step is not proof that nothing was saved.`,pl=e=>({kind:`canvas-mutation`,canvasId:e.canvasId,mutationId:e.clientToken,fingerprint:e.fingerprint}),ml=e=>e===`queued`||e===`running`?`pending`:`not_confirmed`,hl=(e,t)=>({operation:t.operation,state:t.state,requestedVersion:e.input.baseVersion,source:e.input.source,attachment:t.frame===void 0||t.frame===null?ml(t.state):`committed`,result:t.result,frame:t.frame??null,failure:t.failure,warningCount:1,warnings:[t.warning]}),gl=(e,t,n,r)=>hl(e,{operation:pl({...e,baseVersion:e.input.baseVersion}),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.`}),_l=e=>({kind:`recording`,recordingId:e.recordingId,atMs:e.atMs}),vl=(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.x,y:t.y}},props:n===void 0?a:{...a,conversion:{...typeof o==`object`&&o,provenance:n}}}]}));return{...e,destination:{kind:`insert-children`,targetNodeId:`root`,...t.pageId!==void 0&&{pageId:t.pageId}},nodes:r}},yl=(e,t)=>new y(t instanceof y?t.code:`INTERNAL`,t instanceof y?t.message:`The captured frame could not be confirmed.`,fl,{...t instanceof y&&t.fields,outcome:`not_confirmed`,operation:JSON.stringify(pl(e))}),bl=e=>{let[t]=e.result.operations;if(e.result.operations.length!==1||t?.op!==`insertConvertedSubtree`)throw new y(`INTERNAL`,`The compiled capture is not one editable frame.`,`Capture the page again with a new clientToken.`);return t},xl=async(e,t,n)=>{try{return rt.parse(await M(e).execute(n))}catch(e){throw ue(e)?e:yl(t,e)}},Sl=async(e,n,r,i=`strict`)=>{let a=r.op===`insertNode`?r.node.id:r.rootNodeId,o=t.parse({canvasId:n.canvasId,mutationId:n.clientToken,documentFormatVersion:15,baseVersion:n.baseVersion,operations:[r],requestContext:{fingerprint:n.fingerprint,revisionPolicy:i}}),s=await xl(e,n,o);if(s.canvasId!==n.canvasId||s.mutationId!==n.clientToken||(i===`strict`?s.version!==n.baseVersion+1:s.version<=n.baseVersion)||![...s.insertedNodeIds,...s.changedNodeIds].includes(a))throw yl(n,null);return s},Cl=async(e,t,n,r)=>{let i=bl(n),a=await Sl(e,{...t,baseVersion:t.input.baseVersion},vl(i,{screenId:r.screenId,x:r.box.x,y:r.box.y,pageId:r.pageId},_l(t.input.source)));return gl(t,a,r,i.rootNodeId)},wl=[`canvas.render.get`,`canvas.render.snapshot`],Tl=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),El=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}),Dl=async(e,t)=>{let n=Ft.safeParse(await e.query(wl[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},Ol=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 Tl();let d=await Dl(e,o.id);if(d.id!==t.id)throw kl();jl(d,n),o=d}return o},kl=()=>new y(`INTERNAL`,`The snapshot response does not match the requested source or revision.`,`Run enhance doctor and report the capture job ID.`),Al=(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),jl=(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 kl();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||!Al(n,t))throw kl()},Ml=async(e,t,n)=>{let r=ot.safeParse(await e.mutate(wl[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 jl(r.data.job,n),Ol(e,r.data.job,n,t)},Nl=async(e,t,n)=>{let r=await Ml(e,t,n);if(r.state!==`succeeded`||r.result.snapshot===void 0)throw El(r);let i={...r,result:{...r.result,snapshot:r.result.snapshot}},a=i.result.snapshot,{screenNodeId:o}=a;if(o===null)throw kl();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)}`]}},Pl=(e,t)=>({execute:async n=>Nl(e,t,n)}),Fl=[`canvas.mutation.get`],Il=async(e,t,n,r)=>{let i=await dl(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`?Cl(e,t,i,n):hl(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. ${fl}`:`The page could not be made editable, and nothing was added to the canvas. Capture the moment again with a new clientToken.`})},Ll=async(e,t,n,r)=>Ml(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`}}}}),Rl=async(e,t,n)=>{let r=Ee.parse(t),i=x(r.canvasRef),a={input:r,canvasId:i.canvasId,clientToken:n,fingerprint:s({operation:`canvas.capture/2`,reference:i,baseVersion:r.baseVersion,source:r.source,previewJobId:r.previewJobId})},o=jt.parse(await e.query(Fl[0],{canvasId:a.canvasId,mutationId:n,fingerprint:a.fingerprint}));if(o.state===`committed`)return gl(a,o.result,null,o.result.insertedNodeIds[0]??``);let c=Date.now(),l=await Ll(e,a,i.pageId,i.nodeIds),u=l.state===`succeeded`?l.result.snapshot:void 0;return u===void 0?hl(a,{operation:{kind:`canvas-render`,canvasId:l.canvasId,jobId:l.id},state:l.state,result:null,failure:l.failure,warning:l.state===`queued`||l.state===`running`?`The moment is still being stored. ${fl}`:`The moment could not be stored, and nothing was added to the canvas.`}):Il(e,a,u,Math.max(0,r.waitMs-(Date.now()-c)))},zl=`Captured page`,Bl=(e,t)=>({step:e,snippet:t.snippet??null,picture:t.picture??null,passExpiresAt:t.passExpiresAt??null,operation:t.operation??null,frame:t.frame??null,failure:t.failure??null,warningCount:1,warnings:[t.warning]}),Vl=(e,t)=>T(`sha256`).update(`${e}:${t}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-4$3-8$4-$5`),Hl=e=>`capture_${e.replaceAll(`-`,``)}`,Ul=(e,t,n)=>({canvasId:e.canvasId,clientToken:t===`picture`?e.clientToken:Vl(e.clientToken,t),baseVersion:n,fingerprint:s({operation:`canvas.capturePage/${t}`,reference:e.reference,baseVersion:e.baseVersion,captureId:e.captureId,at:e.at})}),Wl=e=>({kind:`canvas-mutation`,canvasId:e.canvasId,mutationId:e.clientToken,fingerprint:e.fingerprint}),Gl=(e,t,n)=>Bl(`placed`,{operation:Wl(e),picture:n,frame:t,warning:`The picture has become an editable frame in place. Render the frame at its version to inspect it, and use its box to place the next capture beside it.`}),Kl=async(e,t)=>{let n=jt.parse(await e.query(`canvas.mutation.get`,{canvasId:t.canvasId,mutationId:t.clientToken,fingerprint:t.fingerprint}));return n.state===`committed`?n.result.version:null},ql=e=>{let t=`a0`;for(let n of Object.values(e.relationships))n.parentId===`root`&&n.sortKey>t&&(t=n.sortKey);return`${t}~capture`},Jl=async(e,t)=>{let n=Ul(t,`picture`,t.baseVersion),r=await Kl(e,n);if(r!==null)return r;let i=await Vi({remote:e},t.canvasId,t.baseVersion),a=i.nodes[Hl(t.captureId)];return a===void 0?(await Sl(e,n,{op:`insertNode`,node:{id:Hl(t.captureId),label:zl,component:Ge,styles:{},box:{...t.at,...t.size},props:{...t.pageId!==void 0&&{canvasPageId:t.pageId},capture:{screenId:t.captureId,viewport:t.size,atMs:0,landing:dt}}},parentage:{parentId:`root`,sortKey:ql(i)}})).version:Yl(a)?await Xl(e,t,dt,`retry`)??t.baseVersion:t.baseVersion},Yl=e=>{let t=e.props?.capture,n=re.safeParse(typeof t==`object`&&t?Reflect.get(t,`landing`):void 0);return e.component===`screen`&&n.success&&n.data.state===`failed`},Xl=async(e,n,r,i)=>{let a=Hl(n.captureId),o=bt.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),s=Rt.safeParse(o.document),c=s.success?s.data.nodes[a]:void 0;if(c?.component!==`screen`)return null;let l=c.props?.capture,u=Ul(n,i,o.version);return(await xl(e,u,t.parse({canvasId:n.canvasId,mutationId:u.clientToken,documentFormatVersion:15,baseVersion:o.version,operations:[{op:`setProps`,nodeId:a,props:{...c.props,capture:{...typeof l==`object`&&l,landing:r}}}],requestContext:{fingerprint:u.fingerprint,revisionPolicy:`rebase`}}))).version},Zl=async(e,t,n,r)=>{let i=Hl(t.captureId),a=vl(r,{screenId:t.captureId,x:t.at.x,y:t.at.y,pageId:t.pageId}),o=e=>e===r.rootNodeId?i:e;try{return(await Sl(e,n,{...a,destination:{kind:`replace`,targetNodeId:i,onlyPicture:!0},rootNodeId:i,nodes:Object.fromEntries(Object.entries(a.nodes).map(([e,t])=>[o(e),{...t,id:o(e)}])),relationships:Object.fromEntries(Object.entries(a.relationships).map(([e,t])=>[o(e),{...t,parentId:o(t.parentId)}]))},`rebase`)).version}catch(n){let r=bt.parse(await e.query(`canvas.document.get`,{canvasId:t.canvasId})),a=Rt.safeParse(r.document),o=a.success?a.data.nodes[i]:void 0;if(o!==void 0&&o.component!==`screen`)return r.version;throw n}},Ql=[`capturePass.create`],$l=(e,t)=>{let n=`The capture script did not load from ${new URL(e.scriptUrl).origin}. If this page has a Content Security Policy, run this snippet from Playwright in a context created with bypassCSP: true.`;return[`(async () => {`,` if (globalThis.__enhance_capture__ === undefined)`,` await new Promise((loaded, failed) => {`,` const script = document.createElement('script');`,` script.src = ${JSON.stringify(e.scriptUrl)};`,` script.onload = loaded;`,` script.onerror = () => failed(new Error(${JSON.stringify(n)}));`,` document.head.append(script);`,` });`,` return globalThis.__enhance_capture__.captureToEnhance({`,` apiUrl: ${JSON.stringify(e.apiUrl)},`,` pass: ${JSON.stringify(e.pass)},`,` extent: ${JSON.stringify(t)},`,` });`,`})()`].join(`
3
+ `)},eu=async(e,t,n)=>{let r=Ne.parse(await e.mutate(Ql[0],{canvasId:t}));return Bl(`run-snippet`,{snippet:$l(r,n),passExpiresAt:r.expiresAt,warning:`Run snippet in the page you opened, with Playwright's page.evaluate or your browser's JavaScript tool. It answers with captureId; call canvas_capture_page again with that captureId, at and baseVersion. The pass works for 15 minutes and for any number of pages.`})},tu=async(e,t,n,r)=>{let{picture:i,save:a}=n,o=[`queued`,`running`].includes(r.state);return o||await Xl(e,t,{state:`failed`,reason:(r.failure?.message??`The page could not be made editable.`).slice(0,200)},`failed`),Bl(o?`converting`:`failed`,{picture:i,operation:{kind:`canvas-preparation`,canvasId:t.canvasId,jobId:r.id,mutationId:a.clientToken,fingerprint:a.fingerprint},failure:r.failure,warning:o?`The picture is on the canvas and is being made editable. ${fl}`:`The picture is on the canvas, marked as not editable with the reason. Repeat the call with a new clientToken to try again.`})},nu=async(e,t)=>{let n=await Jl(e,t),r={nodeId:Hl(t.captureId),version:n},i=Ul(t,`frame`,n),a=await Kl(e,i);if(a!==null)return Gl(i,{nodeId:r.nodeId,version:a,box:null},r);let o=await dl(e,{canvasId:t.canvasId,expectedVersion:n,request:{kind:`compile-screens`,landing:`editable-frame`,sources:[{screenId:t.captureId,captureId:t.captureId,label:zl}]},scope:{nodeIds:[]}},t.waitMs);if(o.state!==`succeeded`)return tu(e,t,{picture:r,save:i},o);let s=bl(o),c=await Zl(e,t,i,s),l=s.nodes[s.rootNodeId];return Gl(i,{nodeId:r.nodeId,version:c,box:{...t.at,width:l?.box?.width??0,height:l?.box?.height??0}},r)},ru=async(e,t,n)=>{let r=g.parse(t),i=x(r.canvasRef);if(r.captureId===void 0)return eu(e,i.canvasId,r.extent);if(r.at===void 0||r.size===void 0||r.baseVersion===void 0)throw new y(`BAD_REQUEST`,`A placement needs x and y in at, the size the snippet answered, and the baseVersion you read.`,`Call canvas_capture_page again with captureId, at: { x, y }, size: { width, height } and baseVersion.`);return nu(e,{canvasId:i.canvasId,clientToken:n,reference:i,baseVersion:r.baseVersion,captureId:r.captureId,at:r.at,size:r.size,pageId:i.pageId,waitMs:r.waitMs})},iu=[`canvas.asset.reserve`,`canvas.asset.complete`,`canvas.document.get`],au=(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`}),ou=(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.`)},su=(e,t)=>({execute:async n=>{let r=x(n.canvasRef);me(r)&&ht(r,Ce(bt.parse(await e.query(iu[2],{canvasId:r.canvasId})).document));let{body:a,...o}=await t.read(),s=mt.parse({...o,canvasId:r.canvasId,clientToken:n.clientToken}),c={kind:`canvas-asset`,canvasId:r.canvasId,clientToken:n.clientToken};try{let t=i.parse(await e.mutate(iu[0],s));ou(t,s),t.upload!==null&&await e.upload({...t.upload,body:a});let o=ve.parse(await e.mutate(iu[1],{canvasId:r.canvasId,clientToken:n.clientToken}));if(ou(o,s),o.assetId!==t.assetId||o.path!==t.path)throw new y(`INTERNAL`,`The completed asset identity changed.`,`Read operation_status and do not place an unconfirmed resource.`);return be.parse({operation:c,resource:o,placement:`not_requested`})}catch(e){throw au(e,c)}}}),cu=15e3,lu=async e=>new Promise(t=>setTimeout(t,e)),uu=new Set([`ready`,`failed`,`abandoned`]),du=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`],fu=e=>new y(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,`Check the existing deployment status before retrying with the same publication token.`),pu=async(e,t,n,r)=>{let i=oe.safeParse(await e.mutate(du[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 fu(`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:await n.open()}),i.data.state===`uploading`||i.data.state===`queued`){let n=nt.safeParse(await e.mutate(du[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId}));if(!n.success||n.data.deploymentId!==i.data.deploymentId)throw fu(`artifact submission`)}return i.data},mu=async(e,t,n,r)=>{let i=Ve.safeParse(await e.query(du[0],{}));if(!i.success)throw fu(`capabilities`);let a=await t.package({entryPath:n.entryPath,limits:i.data.limits});try{return await pu(e,n,a,r)}finally{await a.dispose()}},hu=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(du[3],t,{signal:r.signal}),i.promise]),a=Ke.safeParse(n);if(!a.success||a.data.deploymentId!==t.deploymentId)throw fu(`status`);return a.data}finally{clearTimeout(a)}},gu=async(e,t,n)=>{let r=performance.now()+n,i=50,a=await hu(e,t,n>0?Math.min(cu,n):cu);for(;!uu.has(a.state);){let n=r-performance.now();if(n<=0)return a;await lu(Math.min(i,n)),i=Math.min(i*2,1e3);let o=r-performance.now();if(o<=0)return a;try{a=await hu(e,t,Math.min(cu,o))}catch(e){if(e instanceof y&&e.fields?.reason===`STATUS_TIMEOUT`)return a;throw e}}return a},_u=[`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`],vu=e=>{let t=e.failure,n=_u.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.`}}},yu=e=>e.unavailableFiles?.map(e=>`Unavailable published file: ${e.path} (${e.code}).`)??[],bu=[`prototype.getArtifactCapabilities`,`prototype.attach`],xu=new Set([`BAD_REQUEST`,`FORBIDDEN`,`UNAUTHORIZED`,`NOT_FOUND`]),Su=async e=>{let t=Ve.safeParse(await e.query(bu[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.`)},Cu=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.`},wu=async(e,t,n)=>{let r=x(t.canvasRef),i=Tt.safeParse(await e.mutate(bu[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(!i.success)throw Error(`Invalid prototype attachment response`);let a=i.data,o=a.attachment;if(o===void 0||a.canvasId!==r.canvasId||a.deploymentId!==n.deploymentId||a.prototypeId!==n.prototypeId||a.nodeId!==n.nodeId||a.version!==o.version||o.outcome===`committed`&&(o.mutationId!==t.clientToken||o.version!==o.previousVersion+1)||o.outcome===`no_op`&&o.version!==t.baseVersion)throw Error(`Unconfirmed prototype attachment receipt`);return{...a,attachment:o}},Tu=async(e,t,n,r)=>{try{let i=await wu(e,t,r);return{...n,attachmentStatus:i.attachment.outcome,attachment:i,nextAction:`inspect_result`}}catch(e){let t=Cu(e),r=t.code===`CONFLICT`,i=xu.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.`]}}},Eu=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:yu(r)};if(r.state===`failed`){let{nextAction:e,failure:t}=vu(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`?Tu(e,t,i,r):i},Du=(e,t)=>({execute:async n=>{let r=x(n.canvasRef);await Su(e);let i=n.source.kind===`deployment`?n.source.deploymentId:null;try{if(n.source.kind===`build`&&(i=(await mu(e,t,{...n.source,canvasId:r.canvasId,...r.pageId!==void 0&&{canvasPageId:r.pageId},clientToken:n.clientToken},e=>{i=e})).deploymentId),i===null)throw Error(`Publication has no deployment`);let a=await gu(e,{canvasId:r.canvasId,deploymentId:i},n.waitMs);return await Eu(e,n,r.canvasId,a)}catch(e){if(i===null)throw e;return{operation:{kind:`prototype-deployment`,canvasId:r.canvasId,deploymentId:i},deploymentStatus:`unknown`,publication:null,attachmentStatus:`not_attempted`,attachment:null,failure:Cu(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.`]}}}}),Ou=[`prototype.attach`],ku=e=>new y(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),Au=e=>{if(e.state===`failed`){let t=vu(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})},ju=async(e,t,n)=>{let r={deploymentId:null};try{let i=await mu(e,t,n,e=>{r.deploymentId=e}),a=await gu(e,{canvasId:n.canvasId,deploymentId:i.deploymentId},3e5);Au(a);let o=Tt.safeParse(await e.mutate(Ou[0],{canvasId:n.canvasId,deploymentId:i.deploymentId,baseVersion:n.baseVersion}));if(!o.success)throw ku(`attachment`);return{...o.data,fileCount:a.fileCount,totalBytes:a.totalBytes,alreadyExists:i.alreadyExists,warnings:yu(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 te(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}})}},Mu=(e,t)=>({execute:async n=>ju(e,t,n)}),Nu=(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.`]}},Pu=async(e,t)=>{let{job:n}=v.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.jobId}));return Nu(n,t)},Fu=(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:[]}},Iu=async(e,t,n)=>{if(n.kind!==`canvas-render`||n.state!==`succeeded`)return n;try{let{job:r}=Ft.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 vi(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`],Ru=(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.`)},zu=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`}))],Bu=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,a=jt.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:Fu(a.result,n.fingerprint),affected:K(zu(a.result),r,i)}},Vu=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,{job:a}=Ft.parse(await e.query(Lu[1],{jobId:n.jobId}));Ru(a.canvasId,n.canvasId);let o=a.result===null?null:Hu(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:K(Uu(a),r,i),failure:a.failure,pixelsDelivered:!1,warnings:[`Status reports stored render evidence. It does not deliver or inspect the image.`]}},Hu=e=>{let{warnings:t,timings:n,...r}=e;return{...r,warningCount:t.length,timingCount:n.length}},Uu=e=>e.result===null?[]:[...e.result.warnings.map(e=>({kind:`warning`,warning:e})),...e.result.timings.map(e=>({kind:`timing`,timing:e}))],Wu=async(e,t)=>{let n=ve.parse(await e.query(Lu[4],{canvasId:t.canvasId,clientToken:t.clientToken}));if(Ru(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`}},Gu=async(e,t)=>{let{operation:n,offset:r,limit:i}=t;switch(n.kind){case`canvas-asset`:return K([],r,i),Wu(e,n);case`canvas-mutation`:return Bu(e,{...t,operation:n});case`canvas-preparation`:{let r=await Bu(e,{...t,operation:{kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:n.mutationId,fingerprint:n.fingerprint}});return r.kind===`canvas-mutation`&&r.state===`committed`?r:Pu(e,n)}case`canvas-render`:return Vu(e,{...t,operation:n});case`canvas-conversion`:{let{job:t}=Nt.parse(await e.query(Lu[2],{jobId:n.jobId}));return Ru(t.canvasId,n.canvasId),Wc(t,{offset:r,limit:i})}case`prototype-deployment`:return K([],r,i),{kind:`prototype-deployment`,operation:n,publication:Ke.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.`]}}},Ku=(e,t)=>({execute:async n=>{let r=await Gu(e,n);return t!==void 0&&n.includeImage?Iu(e,t,r):r}}),qu=[`transcript.get`],Ju=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),Yu=e=>({execute:async t=>{let n=ke.safeParse(await e.query(qu[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:Ju(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Xu={".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`},Zu=()=>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.`),Qu=async e=>{let t=Xu[w.extname(e).toLowerCase()];if(t===void 0)throw Zu();let n=await cn(e,qt.O_RDONLY|qt.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size===0)throw Zu();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()}},$u=e=>({read:async()=>{try{return await Qu(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.`)}}}),ed=[`canvas.list`,`organisation.list`],td=async(e,t)=>{let[n,r]=await Promise.all([e.query(ed[0],{collection:t.collection,...t.title!==void 0&&{title:t.title},scope:`all`,deleted:!1,hasUnresolved:!1}),t.includeDestinations?e.query(ed[1],{}):{items:[],truncated:!1}]),i=Fe.parse(n),a=Je.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}}},nd=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},rd=e=>({execute:async t=>{let{items:n,sourceTruncated:r}=await td(e,t),{cursor:i,...a}=t,o=s(a),c=s({items:n,sourceTruncated:r}),l=i===void 0?null:Me(i,zt);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=nd(n.slice(u,u+t.limit)),p=u+d.length,m=p<n.length,h=r.canvases||r.destinations;return{items:d,returnedCount:d.length,totalAvailable:n.length,complete:!m&&!h,sourceTruncated:r,nextCursor:m?f({protocol:`enhance-canvas-find/1`,queryDigest:o,snapshotDigest:c,offset:p}):null,warnings:h?[`The source collection reached its existing limit. Refine the title or team; these results are not a complete inventory.`]:[]}}}),id=async(e,t)=>{try{return rt.parse(await M(e).execute(t))}catch(e){throw ue(e)?e: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})})}},ad=async(e,n,r,i)=>{if(r.result.loadedVersion!==n.baseVersion)throw new y(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);if(r.result.operations.length===0)return{outcome:`no_op`,canvasId:r.canvasId,version:n.baseVersion,verification:{rendered:!1},warnings:[]};let a=t.parse({canvasId:r.canvasId,mutationId:n.clientToken,documentFormatVersion:15,baseVersion:n.baseVersion,operations:r.result.operations,requestContext:{fingerprint:i,revisionPolicy:`strict`,...n.request.kind===`duplicate`&&{copiedNodeIds:r.result.idMap}}}),o=await id(e,a);if(o.canvasId!==r.canvasId||o.mutationId!==n.clientToken||o.previousVersion!==n.baseVersion||o.version!==n.baseVersion+1||n.request.kind===`duplicate`&&!nn(o.copiedNodeIds,r.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:r.canvasId,mutationId:n.clientToken,fingerprint:i})});return Fu(o,i)},od=e=>({execute:async t=>{let n=x(t.canvasRef),r={...n.pageId!==void 0&&{pageId:n.pageId},nodeIds:[...n.nodeIds]},i=s({operation:`canvas.prepare/1`,reference:n,baseVersion:t.baseVersion,request:t.request}),a=jt.parse(await e.query(`canvas.mutation.get`,{canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:i}));if(a.state===`committed`)return Fu(a.result,i);let o=await dl(e,{canvasId:n.canvasId,expectedVersion:t.baseVersion,request:t.request,scope:r},t.waitMs),c={kind:`canvas-preparation`,canvasId:n.canvasId,jobId:o.id,mutationId:t.clientToken,fingerprint:i};return o.state===`succeeded`?ad(e,t,o,i):Nu(o,c)}}),sd=/^[MLHVCSQTAZ]$/iu,cd=/[MLHVCSQTAZ]|[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/giu,ld={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},ud=e=>{let t=e.match(cd)??[];if(t.join(``)!==e.replaceAll(/[\s,]/gu,``))return null;let n=[],r=``,i=0;for(;i<t.length;){let e=t[i]??``;if(sd.test(e))r=e,i+=1;else if(r===``||r.toUpperCase()===`Z`)return null;let a=ld[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},dd=([e,t,n,r,i,a],{x:o,y:s})=>({x:e*o+n*s+i,y:t*o+r*s+a}),fd=e=>`${String(e.x)} ${String(e.y)}`,pd=Math.PI/2,md=Math.PI*2,hd=(e,t,n,r)=>Math.atan2(e*r-t*n,e*n+t*r),gd=(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,y,ae]=[(p-v)/g,(m-ne)/_,(-p-v)/g,(-m-ne)/_],b=hd(re,ie,y,ae);return s===0&&b>0&&(b-=md),s===1&&b<0&&(b+=md),{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:hd(1,0,re,ie),turn:b}},_d=(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}=gd(e,t,n),c=Math.ceil(Math.abs(s)/pd-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(dd(a,d(t,u)),dd(a,d(r,-u)),e===c-1?n:dd(a,d(r,0)))}return f},vd=(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=_d(a,e.values,r),s=[];for(let e=0;e<i.length;e+=3)s.push(`C${i.slice(e,e+3).map(e=>fd(dd(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${fd(dd(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=>fd(dd(n,e))).join(` `)}`,pen:{current:l,start:r===`M`?l:t.start}}},yd=(e,t)=>{let n=ud(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=vd(e,i,t);r.push(n.data),i=n.pen}return r.join(``)},bd=(e,t)=>{let n=e.geometry;if(n?.kind!==`mask`||n.mode===`outline`||t?.box===void 0||t.component===`text`)return{};let r=U(t).opacity,i=U(t).fills.filter(e=>e.visible).toReversed().map(e=>ao({...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`)}},xd=(e,t)=>{let n=t.geometry?.kind===`mask`?pc(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=yd(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}")`}},Sd=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=_n(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,gn(e.value))}),Object.fromEntries(n)},Cd=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.`)),wd=e=>{let t=vn(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)||Xr(e.tagName));let t=e.childNodes.filter(e=>`tagName`in e);for(let e of t)e.attrs=e.attrs.filter(e=>Qr(e.name,e.value)),n.push(e)}return t},Td=new Set([...Sd,`viewBox`,`preserveAspectRatio`]),Ed=(e,t)=>{let[n,...r]=Cd(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}},Dd=e=>{let t=e.tagName===`svg`?Td:Sd;return Object.fromEntries(e.attrs.map(e=>!t.has(e.name)||e.namespace!==void 0?J(`Unsupported attribute: ${e.name}.`):[e.name,e.value]))},Od=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??``)}},kd=e=>{let t=[],n=[];for(let r of Cd(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]},Ad=(e,t)=>Cd(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:jd(e,t),styles:Y(i)}}),jd=(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(``),Md=e=>{let t=wd(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=Dd(e),i=Od(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:Ed(e,t.viewBox??``),text:``,children:[]};let a=e.tagName===`span`&&e.childNodes.some(e=>`tagName`in e),[o,s]=e.tagName===`span`?[[],[]]:kd(e);return{...i,tag:e.tagName,...a&&{runs:Ad(e,i.id)},...o.length>0&&{paints:o},text:!a&&e.tagName===`span`?jd(e,i.id):``,children:s.map(e=>r(e))}},i=Cd(t.childNodes),a=i[0];return a===void 0||i.length!==1?J(`An editable update must contain exactly its original root.`):r(a)},Nd=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Pd={fill:`100% 100%`,cover:`cover`,contain:`contain`,"scale-down":`contain`,none:`auto`},Fd={"100% 100%":`fill`,cover:`cover`,contain:`contain`,auto:`none`},Id=/^background(?:-.+)?$/u,Ld=/^url\((?:"([^"]*)"|'([^']*)'|([^"'()\s]*))\)$/u,Rd=e=>{if(e.component!==`image`)return;let t=e.props?.src;return typeof t==`string`&&t!==``?t:void 0},zd=e=>{let t=Rd(e);if(t===void 0)return{};let n=e.props?.fit,r=e.props?.position;return{"background-image":`url(${JSON.stringify(t)})`,"background-size":Pd[typeof n==`string`?n:`fill`]??`100% 100%`,"background-position":typeof r==`string`?r:`50% 50%`,"background-repeat":`no-repeat`}},Bd=(e,t)=>Rd(e)!==void 0&&Id.test(t),Vd=(e,t,n)=>{if(Rd(e)===void 0)return[];let r=[...new Set([...Object.keys(t),...Object.keys(n)])].filter(e=>Id.test(e)&&t[e]!==n[e]);if(r.length===0)return[];if(r.some(e=>![`background-image`,`background-size`,`background-position`].includes(e)))return Nd(`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=Fd[n[`background-size`]??``],s=n[`background-position`];return a===void 0||a===``||o===void 0||s===void 0?Nd(`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.`)},Hd={border:/^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u,outline:/^outline(?:-.+)?$/u,paint:/^$/u},Ud=e=>Object.fromEntries(Object.entries(Y(e)).toSorted(([e],[t])=>e.localeCompare(t))),Wd=e=>Ud(Object.entries(e).flatMap(([e,t])=>{let n=d(e,t);return e.startsWith(`--`)||n.includes(`var(--canvas`)||n.includes(`url(#`)?[]:[`${e}:${n}`]}).join(`;`)),Gd=e=>{let t=V(e),n=n=>ts(t,n).map(t=>({owner:`paint`,paintId:t.id,styles:Wd(ys(e,t))})),r=ms(e),i=Rs(e);return[...n(`outer-shadow`),...es(t).map(e=>({owner:`paint`,paintId:e.id,styles:Wd(Ns(e))})),...n(`inner-shadow`),...r===null?[]:[{owner:`border`,styles:Wd(r)}],...i===null?[]:[{owner:`outline`,styles:Wd(i)}]]},Kd=(e,t)=>e.some(e=>Hd[e.owner].test(t)),qd=e=>Oe.find(t=>t===(e??`normal`))??X(`Unsupported mix-blend-mode: ${e??``}.`),Jd=/stroke-(?:dasharray|linecap)="[^"]*"/gu,Yd=e=>{let t=/^url\(["']?data:image\/svg\+xml,(.*?)["']?\)$/u.exec(e??``)?.[1];return t===void 0?void 0:decodeURIComponent(t)},Xd=(e,t,n)=>{let r=Yd(t),i=Yd(n);if(i===void 0||r?.replaceAll(Jd,``)!==i.replaceAll(Jd,``))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}},Zd=(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=qd(r);return n.paints.map(e=>e===a?{...e,blendMode:o}:e)},Qd=(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:qd(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)}}]:[]]},$d=(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`)?Zd(e,s,c,n.styles[`mix-blend-mode`]):c.paints,u=o.includes(`mask-image`)?Xd(e,i.styles[`mask-image`],n.styles[`mask-image`]):{};return[{op:`setAppearance`,nodeId:e.id,appearance:{[s]:{...c,paints:l,...u}}}]}),...Qd(e,a)]},ef=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},tf=e=>e.kind===`text`||e.kind===`span`&&e.children.every(e=>e.kind===`text`),nf=e=>Se([e]),rf=e=>e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`),af=e=>e.replaceAll(/-([a-z])/gu,(e,t)=>t.toUpperCase()),of=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,n])=>{let r=af(e);return ie.has(r)?[r,n]:ef(`Run ${String(t+1)} cannot hold ${e}; set it on the text layer.`)})),sf=e=>{if(e.kind!==`span`)return{};let[t,...n]=(e.fills??[]).filter(e=>e.visible),r=t===void 0||n.length>0?void 0:uo(t),i=[...Object.entries(e.styles).map(([e,t])=>{let n=rf(e);return`${n}:${d(n,t)}`}),...r===void 0?[]:[`color:${r}`]];return Object.fromEntries(Object.entries(Y(i.join(`;`))).toSorted(([e],[t])=>e.localeCompare(t)))},cf=e=>{let t=ge(e);return t.length===0||t.some(e=>!tf(e))?null:t.map(e=>({text:nf(e),styles:sf(e)}))},lf=e=>ge(e).some(e=>!tf(e)),uf=(e,t,n,r)=>{if(`mix-blend-mode`in r.styles)return ef(`Text paints have no blend of their own. Set mix-blend-mode on the text layer.`);let{color:i,...a}=r.styles,o=of(a,t),s=i===void 0?void 0:I(`${e.id}-run-${String(t)}`,i);if(i!==void 0&&s===null)return ef(`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&&sf(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}]}},df=(e,t,n)=>{if(t.length!==n.length)return ef(`Keep each run span of ${e.id}; change a run's words or CSS in place.`);let r=ge(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:uf(e,i,r,o)});if(i.every((e,t)=>e===r[t]))return[];let a={...e.props,richText:i,text:Se(i)};return[{op:`editText`,nodeId:e.id,change:_e(e,{...e,props:a})}]},ff=new Set([`path`,`polygon`,`boolean`]),pf=e=>ff.has(e.geometry?.kind??``),mf=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},hf=e=>{let t=Rr(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`:uo(n)??`none`,viewBox:[r,i,a,o].map(String).join(` `)}},gf=e=>{throw new y(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},_f=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}:gf(`Invalid viewBox: ${e}.`)},vf=(e,t,n)=>n.d.trim()===``?gf(`The path of ${t.id} is empty.`):[{op:`setGeometry`,nodeId:t.id,geometry:{kind:`path`,path:n.d,fillRule:n.fillRule,viewBox:_f(n.viewBox)}},...t.geometry?.kind===`boolean`?Hi(e,t.id).map(e=>({op:`remove`,nodeId:e})):[]],yf=(e,t)=>{let n=(e.appearance?.fills??[]).find(e=>e.visible),r=n?.kind===`solid`?n.id:`${e.id}-fill`,i=t===`none`?null:I(r,t);return i===null&&t!==`none`?gf(`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}}]}}},bf=(e,t,n,r)=>[...n.d===r.d&&n.fillRule===r.fillRule&&n.viewBox===r.viewBox?[]:vf(e,t,r),...n.fill===r.fill?[]:[yf(t,r.fill)]],xf=new Set([`root`,`frame`,`group`,`rectangle`,`image`,`text`]),Sf={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.`},Cf=/^(?:mask(?:-.+)?|clip-path)$/u,wf=`This layer kind has no editable HTML form yet; edit it in the editor.`,Tf=(e,t,n)=>{let r=Sf[t.component];return r===void 0?xd(e,t)===null?`This mask's shape cannot be read; edit it in the editor.`:t.component===`text`&&(n>0||lf(t))?`Text with nested layers or nested formatting keeps its formatting in the editor.`:pf(t)?mf(t)??(hf(t)===null?wf:null):xf.has(t.component)&&(t.geometry===void 0||t.geometry.kind===`mask`)?null:wf:r},Ef=(e,t)=>{let n={...qs(t),...bd(t,ic(e,t)),...xd(e,t)},r=Ae(t),i=Object.entries(n).flatMap(([e,n])=>{let r=d(e,n);return e.startsWith(`--`)||r.includes(`var(--canvas`)||r.includes(`url(#`)||Ds(t,[e]).length===0&&!Cf.test(e)?[]:[[e,r]]});return{...Object.fromEntries(i),...zd(t),...Object.fromEntries(Object.entries(r).map(([e,t])=>[e,d(e,t)]))}},Df=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;`),Of=e=>pf(e)?hf(e):null,kf=/^background(?:-.+)?$/u,Af=e=>`<path d="${Z(e.d)}" fill-rule="${e.fillRule}" fill="${Z(e.fill)}"></path>`,jf=e=>{let t=Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`);return t===``?``:` style="${Z(t)}"`},Mf=e=>`<div data-enhance-paint="${Z(e.paintId??e.owner)}"${jf(e.styles)}></div>`,Nf=(e,t)=>`<span data-enhance-run="${String(t)}"${jf(e.styles)}>${Z(e.text)}</span>`,Pf=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">${Af(e.path)}</svg>`;let r=(e.runs??[]).map((e,t)=>Nf(e,t)).join(``),i=(e.paints??[]).map(e=>Mf(e)).join(``);return`<${e.tag} ${n}>${Z(e.text)}${r}${i}${e.children.map(e=>Pf(e)).join(``)}</${e.tag}>`},Ff=(e,t)=>{let n=new Set,r=[],i={},a=Ui(e),o=t=>{if(n.has(t))return Df(`The document contains repeated node identity.`);n.add(t);let s=N(e,t),c=a.get(t)??[],l=Tf(e,s,c.length),u=l!==null;u&&(r.push(s.id),i[s.id]=l);let d=u?null:Of(s),f=u||s.component!==`text`?null:cf(s),p=u||d!==null?[]:Gd(s),m=u?{}:Y(Object.entries(Ef(e,s)).filter(([e])=>d===null||!kf.test(e)).filter(([e])=>!Kd(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:P(e,t),styles:m,...f!==null&&{runs:f},...p.length>0&&{paints:p},text:f!==null||u||s.component!==`text`?``:Dt(s)??``,children:u||d!==null?[]:c.map(e=>o(e))}},s=o(t);return{projectionVersion:2,root:s,html:Pf(s),opaqueNodeIds:r,sealedReasons:i}},If=(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=Bt(t,n);if(r.ok)return r.rootNodeIds;throw ht(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.`)},Rf=(e,t,n,r)=>{let i=[],a=new Set,o=Ui(e),s=(t,c)=>{if(a.has(t))return;a.add(t);let l=N(e,t),u=o.get(t)??[],d=P(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},zf=(e,t,n)=>{if(e===void 0)return 0;let r=Me(e,Pt);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},Bf=(e,t)=>{let{reference:n,scene:r,version:i,isCurrent:a}=t,o=If(e,n,r);ye(n,r,o),Lf(r,o);let c=s({reference:n,roots:e.rootNodeIds??null,depth:e.depth,limit:e.limit}),l=zf(e.cursor,t,c),u=Rf(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),p=l+d.length,m=u.some(e=>e.childrenOmitted);return{canvasId:n.canvasId,version:i,scope:{rootNodeIds:[...o]},view:`outline`,complete:p===u.length&&!m,returnedCount:d.length,total:u.length,nodes:d,omittedDescendants:m,nextCursor:p<u.length?f({protocol:`enhance-canvas-outline/1`,canvasId:n.canvasId,version:i,queryDigest:c,offset:p}):null,warnings:a?[]:[`This legacy document is read-only until the normal editor upgrades it.`]}},Vf=e=>{let t=pe(e);if(t!==null)return{storage:`canvas-image`,reference:e,ownerId:t.canvasId,assetId:t.assetId};let n=ft(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}},Hf=(e,t)=>typeof e[t]==`string`?e[t]:null,Uf=(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),...Vf(r),delivery:`not_checked`,metadata:i};return n.set(s(a),a),r};ni(r,e=>i(`image`,e,null)),ut(r.props,(e,t)=>i(`font`,e,{family:Hf(t,`family`),style:Hf(t,`style`),weight:Hf(t,`weight`)}))}return Array.from(n,([,e])=>e)},Wf=(e,t,n)=>{if(e.cursor===void 0)return 0;let r=Me(e.cursor,st);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},Gf=(e,t)=>{let n=Bt(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=Wf(e,t,r),a=Uf(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:f({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(K(a,i,e.limit,c).entries)},Kf=(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:Me(r,lt);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=K(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?f({protocol:`enhance-canvas-transcript/1`,digest:a,offset:d}):null}},qf=[`recording.get`,`prototype.getPublishStatus`,`transcript.get`],Jf=e=>{let t=fe.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}},Yf=e=>{let t=he.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)}},Xf=async(e,t)=>{let{node:n,canvasId:r}=t;if(n.component===`recording`){let t=_.parse(n.props),i=C.uuid().parse(t.recordingId),a=Re.parse(await e.query(qf[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=xe.parse(n.props),i=Ke.parse(await e.query(qf[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 Jf(t)??Yf(n)},Zf=e=>({execute:async t=>{let n=await Xf(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:Kf(ke.parse(await e.query(qf[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.`]]}}}),Qf=[`canvas.document.get`],$f=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`})},ep=(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.`);ye(n,r,[e.rootNodeId]);let a=Ff(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:It({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.`]:[]}},tp=e=>({execute:async t=>{let n=x(t.canvasRef),r=bt.parse(await e.query(Qf[0],{canvasId:n.canvasId}));if(t.expectedVersion!==void 0&&t.expectedVersion!==r.version)return $f(r.version);let i=Ce(r.document),a=Xe.safeParse(r.document);return t.view===`resources`?Gf(t,{reference:n,scene:i,version:r.version,isCurrent:a.success}):t.view===`outline`?Bf(t,{reference:n,scene:i,version:r.version,isCurrent:a.success}):t.view===`source`?(ye(n,i,[t.nodeId]),Zf(e).execute({canvasId:n.canvasId,version:r.version,node:N(i,t.nodeId),screens:r.screens,input:t})):ep(t,{reference:n,scene:i,version:r.version,isCurrent:a.success})}}),np=[`canvas.mutation.get`],rp=e=>({execute:async n=>{let r=n.reference.canvasId,i=jt.parse(await e.query(np[0],{canvasId:r,mutationId:n.clientToken,fingerprint:n.fingerprint}));if(i.state===`committed`)return Fu(i.result,n.fingerprint);let a=await Vi({remote:e},r,n.baseVersion),o=await n.plan(a);if(`outcome`in o)return o;if(Ic(n.reference,a,o),o.length===0)return{outcome:`no_op`,canvasId:r,version:n.baseVersion,verification:{rendered:!1},warnings:[]};let s=t.safeParse({canvasId:r,documentFormatVersion:15,mutationId:n.clientToken,baseVersion:n.baseVersion,operations:o,requestContext:{fingerprint:n.fingerprint,revisionPolicy:`strict`}});if(!s.success)throw new y(`BAD_REQUEST`,`The planned edit exceeds the canonical canvas contract.`,s.error.issues[0]?.message??`Reduce the edit scope.`,{outcome:`not_committed`});return Fu(rt.parse(await M(e).execute(s.data)),n.fingerprint)}}),ip=(e,t)=>{let n=Ui(e),r=new Set(t),i=new Set,a=t=>{if(i.has(t))return;if(i.add(t),N(e,t),P(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}))},ap=e=>({execute:async({clientToken:t,...n})=>{let r=x(n.canvasRef);return rp(e).execute({reference:r,baseVersion:n.baseVersion,clientToken:t,fingerprint:s({operation:`canvas.remove/1`,...n,reference:r}),plan:e=>ip(e,n.rootNodeIds)})}}),op=(e,t,n,r)=>{let i=e.parents.get(t),a=e.children.get(n)??[];if(i===n&&a.indexOf(t)===r)return;if(P(e.document,t)||P(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})},sp=(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([...Ui(r)].map(([e,t])=>[e,[...t]])),moves:[]},a=e=>{for(let[t,n]of e.children.entries())op(i,n.id,e.id,t),a(n)};return a(t),i.moves.length===0?[]:aa(r,i.moves).operations},cp=e=>{throw new y(`BAD_REQUEST`,e,`Read the current subtree and reduce or correct the edit. No canvas changes were committed.`)},lp=(e,t,n)=>{if(Object.keys(t.idMap).length!==n.fragments.length)return cp(`Native compilation returned unexpected fragment identities.`);if(t.operations.length!==n.fragments.length)return cp(`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 cp(`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 cp(`New HTML identity ${e} already exists.`);let a=Hi(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:Wt(o,null)}})}return r},up=(e,t)=>({...e,id:Object.hasOwn(t,e.id)?t[e.id]??e.id:e.id,children:e.children.map(e=>up(e,t))}),dp={operations:[],idMap:{},rootNodeIds:[]},fp=(e,t,n=dp)=>{let r=lp(e,n,t),i=up(t.root,n.idMap);return[...t.operations,...n.operations,...sp(r,i,t.removed)]},pp=e=>e.attrs.some(e=>e.name===`data-enhance-paint`),mp=e=>e.attrs.find(e=>e.name===`data-enhance-id`)?.value,hp=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.`)},gp=e=>e.flatMap(e=>`tagName`in e?[e,...gp(e.childNodes)]:[]),_p=e=>{let t=wd(e),n=gp(t.childNodes),r=new Set(n.map(e=>mp(e))),i=[],a=(e,t)=>{let n=mp(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&&!pp(e)?a(e,n):e)};if(t===void 0)return hp(`The submitted HTML must retain its original root identity.`);if([e,...gp(e.childNodes)].some(e=>e.attrs.some(e=>[`data-enhance-id`,`data-enhance-opaque`].includes(e.name))))return hp(`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:bn(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:Md(yn(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.`)},vp=e=>{let t=new Map,n=e=>{t.set(e.id,e);for(let t of e.children)n(t)};return n(e),t},yp=(e,t)=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n),bp=(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},xp=(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=>!Bd(t,e)).map(e=>[e,r.styles[e]??null]));return[...t.geometry?.kind===`mask`&&Object.keys(a).some(e=>Cf.test(e))?[{op:`setGeometry`,nodeId:t.id,geometry:`default`}]:[],...Vd(t,n.styles,r.styles),...Object.keys(a).length===0?[]:xc(e,[{nodeIds:[t.id],styles:a}])]},Sp=(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=!yp(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:_e(a,{...a,props:pt(a,n.text)})}),o.push(...$d(a,t.paints??[],n.paints??[])),(t.runs!==void 0||n.runs!==void 0)&&o.push(...df(a,t.runs??[],n.runs??[])),t.path!==void 0&&n.path!==void 0&&o.push(...bf(e,a,t.path,n.path)),r&&o.push(...xp(e,a,t,n)),o},Cp=(e,t,n,r)=>{let i=Ff(e,t).root,a=_p(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=vp(i),l=vp(o),u=bp(c,l,r,t),d=new Set([...u,...r.flatMap(t=>[...Gi(e,t)])]);for(let t of d)if(P(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(...Sp(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}},wp=(e,t,n)=>{let r=l(e.snapshotToken,t);ye(t,n,[r.rootNodeId]);let i=Ff(n,r.rootNodeId);if(It({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 Cp(n,r.rootNodeId,e.html,e.removeNodeIds)},Tp=async(e,t,n)=>{let r=wp(t,n.reference,n.scene);if(r.fragments.length===0)return fp(n.scene,r);let i=await dl(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`?fp(n.scene,r,i.result):Nu(i,{kind:`canvas-preparation`,canvasId:n.reference.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:n.fingerprint})},Ep=e=>({execute:async t=>{let n=_t.parse(t),r=x(n.canvasRef),i=l(n.snapshotToken,r),a=s({operation:`canvas.updateHtml/1`,snapshotToken:n.snapshotToken,html:n.html,removeNodeIds:n.removeNodeIds});return rp(e).execute({reference:r,baseVersion:i.version,clientToken:n.clientToken,fingerprint:a,plan:async t=>Tp(e,n,{reference:r,scene:t,fingerprint:a,version:i.version})})}}),Dp=(e,t,n)=>({"canvas.arrange":async()=>{let{changes:r,...i}=Ie.parse(t);return od(e).execute({...i,clientToken:n,request:{kind:`arrange`,changes:r}})},"canvas.duplicateNodes":async()=>{let{nodeIds:r,destination:i,...a}=Pe.parse(t);return od(e).execute({...a,clientToken:n,request:{kind:`duplicate`,nodeIds:r,destination:i}})},"canvas.find":async()=>rd(e).execute(Ze.parse(t)),"canvas.remove":async()=>ap(e).execute({...$e.parse(t),clientToken:n}),"canvas.read":async()=>{let n=ae.safeParse(t);return n.success?ol(e,n.data):tp(e).execute(tt.parse(t))},"canvas.updateHtml":async()=>Ep(e).execute({...St.parse(t),clientToken:n})}),Op=(e,t)=>{let n=x(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 i=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:i,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}},kp=(e,t)=>{let n=Ot.shape.operation.safeParse({kind:`canvas-render`,canvasId:t.input.canvasId,jobId:e instanceof y?e.fields?.jobId:void 0}),r=at.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.`}}},Ap=(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:Op({...e,...i},a)}}),jp=async(e,t)=>{try{let n=await e.execute({...t.input,maxOutputPixels:t.maxOutputPixels}),r=kt.safeParse(n);if(!r.success)return Ot.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 kp(e,t)}},Mp=e=>({execute:async(t,n)=>{let r=Mt.parse(t),i=Ap(r,n),a=[],o=0;for(let t of i){let n=await jp(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.`]}}}),Np=e=>Oi(e.remote,cl(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Pp=async(e,t,n)=>{let r=Mt.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=Np(e);return Mp({execute:async t=>(e.mutationKey.select(t.retryClientToken,!1),i.execute(t))}).execute(r.data,t)}let i=xt.safeParse(t);if(i.success)return Np(e).execute(Op(i.data,n));let a=He.parse(t);return Np(e).execute({...a,retryClientToken:n})},Fp=e=>({render:Np(e),execute:async(t,n)=>Pp(e,t,n)}),Ip=new Date(`1980-01-01T00:00:00.000Z`),Lp=33188,Rp=(e,t)=>new y(`BAD_REQUEST`,e,t),zp=(e,t)=>{let n=T(`sha256`),r=0;return new Sn({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`))}}})},Bp=e=>{let t=Te.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 Rp(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,ce,{mtime:Ip,mode:Lp,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},Vp=(e,t,n)=>{let{source:r,content:i}=t,a={mtime:Ip,mode:Lp,compress:i===null,forceDosTimestamp:!0};if(i===null){e.addReadStreamLazy(r.path,{...a,size:r.bytes},t=>{let i=Jt(r.absolutePath),a=zp(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`)})},Hp=(e,t,n)=>{let r=[];for(let i of t)i!==null&&(Vp(e,i,n),r.push(i.source));return r},Up=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 ln(e.absolutePath):null;if(t===null&&await rn(e.absolutePath,qt.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(...Hp(e,a,n))}return r},Wp=async e=>{let t=new wn,n=T(`sha256`),r=new Sn({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Cn(t.outputStream,r,Yt(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=Bp({zip:t,completed:i,...e,files:s}))},l=e=>{i.set(e.path,e),c()};try{s=await Up(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 pn(e.artifactPath);if(u.size>e.limits.artifactBytes)throw Rp(`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}},Gp={".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`},Kp=e=>Gp[w.extname(e).toLowerCase()]??`application/octet-stream`,qp=async e=>{try{return await pn(e)}catch{return null}},Jp=e=>Buffer.byteLength(e,`utf8`),$=(e,t)=>new y(`BAD_REQUEST`,e,t),Yp=(e,t)=>{if(!n.safeParse(e).success)throw $(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Jp(e)>t.pathBytes)throw $(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},Xp=async(e,t,n,r)=>{let{limits:i,unavailable:a}=r,o=await un(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 qp(o);if(c?.isDirectory()===!0){try{u.push(...await Xp(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`);Yp(l,i),u.push({absolutePath:o,path:l,bytes:Number(c.size),contentType:Kp(o)})}return u},Zp=(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=Ue(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.`)},Qp=(e,t)=>{try{xn.mark(`enhance.prototype.packaging`,{detail:{fileCount:e,unavailableFileCount:t}})}catch{}},$p=async e=>{let t=w.resolve(e.directory),n=await qp(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`);Yp(r,e.limits);let i=0,a=await Xp(t,t,new Set,{limits:e.limits,unavailable:()=>{i+=1}});Zp(a,r,e.limits);let o=await sn(w.join(Ut(),`enhance-prototype-artifact-`)),s=w.join(o,`artifact.zip`);try{let t=await Wp({artifactPath:s,files:a,entryPath:r,limits:e.limits});return i+=t.unavailableFileCount,Qp(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:async()=>Zt(s),dispose:async()=>fn(o,{recursive:!0})}}catch(e){throw await fn(o,{recursive:!0}),e}},em=e=>({package:async t=>{if(e===void 0)throw $(`No build directory was selected.`,`Select a build before publishing.`);return $p({...t,directory:e})}}),tm=async(e,t)=>{let n=Ct.parse(t);return M(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},nm=async(e,t)=>{let n=ze.parse(t);return al(e.remote,Fp(e).render).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},rm=async(e,t,n)=>{let r=je.parse(t),i=x(r.canvasRef);return al(e.remote,Fp(e).render).execute({canvasId:i.canvasId,pageId:i.pageId,selectionNodeIds:i.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})},im=async(e,t)=>{let n=We.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},am=async(e,t,n)=>{let r=we.parse(t);return Mu(e.remote,em(r.directory)).execute({...r,clientToken:n})},om=async(t,n,r)=>{let i=e.parse(n);return Pl(t.remote,t.progress??(()=>null)).execute({...i,retryClientToken:r})},sm=async(e,t)=>{let n=it.parse(t);return Yu(e.remote).execute(n)},cm=async(e,t)=>{let n=h.parse(t),r=x(n.canvas);return Bc(e.remote).execute({...r,baseVersion:n.baseVersion,edits:n.edits,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},lm=async(e,t)=>Ku(e.remote,cl(e.configDirectory)).execute(r.parse(t)),um=async(e,t,n,r)=>{let i={...Dp(e.remote,n,r),"canvas.importAsset":async()=>{let t=de.parse(n);return su(e.remote,$u(t.source.path)).execute({canvasRef:t.canvasRef,clientToken:r})},"operation.status":async()=>lm(e,n),"canvas.edit":async()=>cm(e,n),"canvas.apply":async()=>tm(e,n),"canvas.render":async()=>Fp(e).execute(n,r),"canvas.writeHtml":async()=>nm(e,n),"canvas.insertHtml":async()=>rm(e,n,r),"canvas.capture":async()=>Rl(e.remote,n,r),"canvas.capturePage":async()=>ru(e.remote,n,r),"canvas.makeEditable":async()=>Qc(e.remote,n),"comment.attention":async()=>im(e,n),"prototype.publishCanvas":async()=>{let t=Ye.parse(n);return Du(e.remote,em(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()=>am(e,n,r),"recording.snapshot":async()=>om(e,n,r),"transcript.read":async()=>sm(e,n)}[t];if(i===void 0)throw TypeError(`${t} has no composite execution`);return i()},dm=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??en();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?um(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),fm=`/callback`,pm=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),mm=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=Dn(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},hm=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==fm){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)},gm=e=>{let t=pm(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},_m=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=On((n,r)=>{hm({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)}${fm}`,a=gm({...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&&mm(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},vm=e=>({authorize:async t=>{try{let n=$t(32).toString(`base64url`),r=T(`sha256`).update(n).digest(`base64url`),i=$t(32).toString(`base64url`),a=await _m({...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.`)}}}),ym={apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`},bm=e=>URL.canParse(e)?new URL(e).href.replace(/\/+$/u,``):e,xm=(e,t,n,r)=>{let i=URL.canParse(e)?new URL(e).origin:null,a=w.resolve(t),o=ym;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.`)},Sm=e=>e===void 0||e===``?void 0:e,Cm=(e,t,n)=>{let r=Sm(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Sm(e.ENHANCE3_API_URL),a=w.join(t,`.config`,n.configDirectoryName),o=Sm(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&bm(i)!==bm(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 xm(i??n.apiUrl,o??a,t,n);return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}},wm=()=>Cm(S.env,Ht(),ym),Tm=()=>{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{...wm(),profile:e,isReadOnly:t,workflowsDirectory:S.env.ENHANCE_WORKFLOWS_DIR}},Em=C.object({token:C.string().startsWith(`enh_`)}),Dm=e=>{let t=w.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await ln(t,`utf8`));return Em.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await on(e,{recursive:!0,mode:448}),await an(e,448);let r=w.join(e,`credentials.${String(S.pid)}.tmp`);await hn(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await dn(r,t),await an(t,384)},remove:async()=>{try{return await mn(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},Om={path:`direct_cli`},km=C.object({access_token:C.string().min(1)}),Am=C.object({code:C.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),jm=`Check network access and proxy settings for this API, then run enhance doctor again.`,Mm=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,Nm=e=>{let t=Am.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?Nm(e.cause):e instanceof Error?e.name:`Network request failed`},Pm=(e,t)=>new y(`INTERNAL`,`${Mm(e)} answered HTTP ${String(t)}.`,jm),Fm=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new y(`INTERNAL`,`Could not reach ${Mm(e)}: ${Nm(t)}.`,jm)}},Im=async(e,t)=>{let n=await Fm(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw Pm(e,n.status);return n},Lm=(e,t,n=null,r=Om)=>Tn({links:[En({url:`${e}/trpc`,fetch:async(e,t)=>Im(e,{...t,signal:t?.signal??null}),headers:{[ne]:JSON.stringify(r),...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),Rm=async e=>{try{return await e()}catch(e){throw et(e)}},zm=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())},Bm=async e=>{let t=await Fm(`${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`,`${Mm(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,jm);return t.json()},Vm=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await Fm(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw Pm(e,n.status);return n.json()},Hm=async e=>{let t=await Fm(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`,`${Mm(e.issuer)} token exchange answered HTTP ${String(t.status)}`,jm);return km.parse(await t.json()).access_token},Um=async e=>{try{let t=await Fm(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:Pm(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${Mm(e)}.`}}},Wm=async e=>{let t=await fetch(e.url,{method:`PUT`,headers:e.headers,body:e.body});if(!t.ok)throw new y(`INTERNAL`,`Signed upload answered HTTP ${String(t.status)}.`,`Retry the fixture command with the same source file.`);let n=t.headers.get(`etag`);if(n===null||n===``)throw new y(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return n.replaceAll(`"`,``)},Gm=(e,t,n,r=Om)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>Bm(i),oauthMetadata:Vm,exchangeOauthCode:Hm,query:async(e,n,a)=>Rm(async()=>Lm(i,await t.read(),null,r).query(e,n,a)),queryWithToken:async(e,t,n)=>Rm(async()=>Lm(i,n,null,r).query(e,t)),mutate:async(e,a)=>Rm(async()=>Lm(i,await t.read(),n.current(e,a),r).mutation(e,a)),mutateWithToken:async(e,t,n)=>Rm(async()=>Lm(i,n,null,r).mutation(e,t)),download:zm,upload:Wm,health:async()=>Um(i)}},Km=e=>Array.isArray(e)?e.map(e=>Km(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Km(t)])),qm=(e,t,n)=>T(`sha256`).update(`${e}\0${t}\0${JSON.stringify(Km(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),Jm=()=>{let e=en(),t=!1;return{current:(n,r)=>t?qm(e,n,r):e,select:(n,r)=>{e=n??en(),t=r}}},Ym=()=>{C.config(C.locales.en())};export{Kr as C,kn as D,E,ii as S,Vn as T,M as _,wm as a,fi as b,dm as c,al as d,K as f,Vi as g,Ic as h,Dm as i,cl as l,Bc as m,Jm as n,Tm as o,Vc as p,Gm as r,vm as s,Ym as t,ol as u,Mi as v,Ur as w,li as x,Oi as y};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enhance-eng/enhance-dev",
3
- "version": "0.1.41-dev.sha-e57eae05dcd7",
3
+ "version": "0.1.41-dev.sha-548ac35f52fa",
4
4
  "private": false,
5
5
  "description": "Development command-line interface for Enhance.",
6
6
  "keywords": [