@enhance-eng/enhance-dev 0.1.39-dev.sha-4fbf7fe2d39e → 0.1.40-dev.sha-9311d39dbc6d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli-output-identity.lib-g9z_Jf_h.mjs +25 -0
- package/dist/main.mjs +12 -12
- package/dist/mcp-main.mjs +5 -5
- package/dist/mcp-server.adapter-CjYO9dGd.mjs +4 -0
- package/dist/mcp.mjs +1 -1
- package/dist/mutation-key.adapter-BCqcIraY.mjs +2 -0
- package/package.json +1 -1
- package/dist/cli-output-identity.lib-jpwIAYMc.mjs +0 -25
- package/dist/mcp-server.adapter-Dw31KrKk.mjs +0 -4
- package/dist/mutation-key.adapter-BTr7nKb8.mjs +0 -2
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{At as e,Dt as t,G as n,Jn as r,Nn as i,Ot as a,Tt as o,Z as s,c,cr as l,er as u,f as d,n as f,nr as ee,nt as p,o as te,r as m,t as h,u as g,xt as _}from"./cli-output-identity.lib-jpwIAYMc.mjs";import{z as v}from"zod";import{readFileSync as y}from"node:fs";import b from"node:path";import{createHash as x,randomUUID as S}from"node:crypto";import{readFile as ne,rm as re}from"node:fs/promises";import{StdioServerTransport as ie}from"@modelcontextprotocol/server/stdio";import{CLIENT_INFO_META_KEY as C,McpServer as ae}from"@modelcontextprotocol/server";import{AsyncLocalStorage as oe}from"node:async_hooks";const w=new oe,T=v.object({method:v.literal(`initialize`),params:v.object({clientInfo:v.object({name:v.string(),version:v.string()})})}),se=v.object({[C]:v.object({name:v.string(),version:v.string()}).optional()}),ce=()=>w.getStore(),le=(e,t)=>{let n=se.safeParse(e.mcpReq.envelope),r=n.success?n.data[C]:void 0,a=e.mcpReq.envelope===void 0?void 0:i({path:`local_mcp`,...r!==void 0&&{name:r.name,version:r.version}});return w.run(a,t)},ue=e=>{let t=e??new ie,n={metadata:i({path:`local_mcp`}),isInitialized:!1},r=(e,t)=>{let r=T.safeParse(e);!n.isInitialized&&r.success&&(n.metadata=i({path:`local_mcp`,...r.data.params.clientInfo}),n.isInitialized=!0),a.onmessage?.(e,t)},a={start:async()=>{Object.assign(t,{onmessage:r,onclose:()=>a.onclose?.(),onerror:e=>a.onerror?.(e)}),await t.start()},send:async(e,n)=>t.send(e,n),close:async()=>t.close()};return{transport:a,metadata:()=>n.metadata}},E=()=>({current:ce,run:le,createStdio:ue}),D=async(e,t,n)=>{let r=await ne(t.path),i=S(),a=`enhance://artifact/${i}`;if(n===`embedded`&&t.cleanup===`unlink-after-use`)try{await re(t.path,{force:!0})}catch{}return n===`linked`&&e.registerResource(`artifact-${i}`,a,{title:`Enhance artifact`,mimeType:t.contentType},e=>({contents:[{uri:e.href,mimeType:t.contentType,blob:r.toString(`base64`)}]})),{metadata:p.omit({path:!0,sensitive:!0,cleanup:!0,deleteAfter:!0}).parse(t),artifact:{uri:a,mimeType:t.contentType,bytes:r.byteLength},image:{type:`image`,data:r.toString(`base64`),mimeType:t.contentType}}},de=async(e,t,n)=>{let r=s.safeParse(t);if(!r.success)return null;let i=[],a=r.data.complete,o=[];for(let t of r.data.results){let r=p.safeParse(t.outcome);if(!r.success){o.push({...t,pixelsDelivered:!1});continue}try{let a=await D(e,r.data,n);i.push(a),o.push({...t,outcome:a.metadata,pixelsDelivered:!0,contentIndex:i.length,artifact:a.artifact})}catch{a=!1,o.push({id:t.id,target:t.target,maxOutputPixels:t.maxOutputPixels,pixelsDelivered:!1,outcome:{state:`delivery_unavailable`,...r.data.source!==void 0&&{source:r.data.source},operation:{kind:`canvas-render`,canvasId:r.data.canvasId,jobId:r.data.jobId},requestedVersion:r.data.requestedVersion,loadedVersion:r.data.loadedVersion,next:[`Read operation_status with includeImage true to collect the existing render.`]}})}}return{value:{...r.data,complete:a,results:o},detail:null,attachments:i}},fe=/(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu,O=/[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu,k=e=>JSON.stringify(e),A=(e,t=``)=>typeof e==`string`?O.test(e)||fe.test(t)&&!t.endsWith(`Id`):Array.isArray(e)?e.some(e=>A(e,t)):typeof e!=`object`||!e?!1:Reflect.get(e,`sensitive`)===!0||Object.entries(e).some(([e,t])=>A(t,e)),j=(e,t,n)=>{let r=S(),i=`enhance://result/${r}`,a=Buffer.byteLength(t);if(n===`embedded`){let e={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:k(e)},{type:`resource`,resource:{uri:i,mimeType:`application/json`,text:t}}],structuredContent:e}}e.registerResource(`result-${r}`,i,{title:`Protected Enhance result`,mimeType:`application/json`},e=>({contents:[{uri:e.href,mimeType:`application/json`,text:t}]}));let o={ok:!0,artifact:{uri:i,mimeType:`application/json`,bytes:a}};return{content:[{type:`text`,text:k(o)},{type:`resource_link`,name:`Protected Enhance result`,uri:i,mimeType:`application/json`}],structuredContent:o}},M=t=>new e(`BAD_REQUEST`,`Input validation error.`,`Correct the rejected fields using this tool’s schema, then retry. Describe the exact capability only if its contract is unknown.`,Object.fromEntries(t.issues.map(e=>[e.path.length===0?`input`:e.path.join(`.`),e.message]))),N=async(e,t,n)=>{let r=await de(e,t,n);if(r!==null)return r;let i=p.safeParse(t);if(i.success){let t=await D(e,i.data,n);return{value:t.metadata,detail:null,attachments:[t]}}let a=m(t);if(a===null)return{value:t,detail:null,attachments:[]};let o=a.detail??a.value,s=p.safeParse(o.review);if(!s.success)return{...a,attachments:[]};try{let t=await D(e,s.data,n),r={...o,review:{...t.metadata,artifact:t.artifact}},i=m(r);return{value:i?.value??r,detail:i?.detail??null,attachments:[t]}}catch{let e={...o,review:{state:`unavailable`,mutationCommitted:!0,requestedVersion:o.version,retry:{tool:`canvas_render`,arguments:{canvas:o.canvasId,expectedVersion:o.version,target:s.data.target}}},next:[`Retry the render of the committed version; do not replay the write.`]},t=m(e);return{value:t?.value??e,detail:t?.detail??null,attachments:[]}}},P=(e,t)=>{let n={ok:!0,result:f(e,t)};return{content:[{type:`text`,text:k(n)}],structuredContent:n}},F=(e,t=`enhance`)=>({success:async(e,n,r)=>{let i=f(n,t),a=await N(e,i,r),o=a.attachments,s=o.length===1?o[0]:void 0,c=k(a.value);if(A(a.value)||o.length===0&&a.detail===null&&Buffer.byteLength(c)>2e4)return j(e,c,r);let l=a.detail===null?null:j(e,k(a.detail),r),u={ok:!0,result:a.value,...s!==void 0&&{artifact:s.artifact},...l!==null&&{detail:l.structuredContent.artifact}};return{content:[{type:`text`,text:k(u)},...o.map(e=>e.image),...l?.content.filter(e=>e.type!==`text`)??[]],structuredContent:u}},inline:e=>P(e,t),structured:e=>({structuredContent:e,content:[{type:`text`,text:k(e)}]}),failure:n=>{let r=h(te(n instanceof v.ZodError?M(n):n),t),i={ok:!1,error:r.code===`UNAUTHORIZED`?{...r,remediation:e}:r};return{content:[{type:`text`,text:k(i)}],structuredContent:i,isError:!0}}}),I=v.object({ok:v.literal(!1),error:v.object({code:v.string(),message:v.string(),remediation:v.string(),fields:v.array(v.object({path:v.string(),message:v.string()})).optional()})}),L=v.object({uri:v.string(),mimeType:v.string(),bytes:v.number().int().nonnegative()}),R=v.object({ok:v.literal(!0),artifact:L}),z=v.object({id:v.string(),operation:v.enum([`query`,`mutation`]),effect:v.enum([`read`,`write`,`delete`,`external`]),idempotency:v.enum([`none`,`single`,`composite`]),summary:v.string(),useWhen:v.string(),preconditions:v.array(v.string()),inputSchema:v.unknown(),exampleInput:v.unknown(),output:v.array(v.object({name:v.string(),required:v.boolean(),meaning:v.string()})),result:v.string(),recovery:v.array(v.string()),next:v.array(v.string()),schemaDigest:v.string(),guidanceDigest:v.string(),behaviorDigest:v.string()}),B=z.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),V=v.union([v.object({ok:v.literal(!0),result:v.unknown(),artifact:L.optional(),detail:L.optional()}),R,I]),pe=v.union([v.object({ok:v.literal(!0),result:v.object({matches:v.array(B),totalMatches:v.number().int().nonnegative(),truncated:v.boolean(),bestContract:z.optional(),detailRequired:v.object({capability:v.string()}).optional()})}),I]),me=v.union([v.object({ok:v.literal(!0),result:z}),I]),he=v.object({capability:v.string().min(1).describe(`Exact query id from an available complete contract.`),input:v.record(v.string(),v.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`)}),H=v.object({capability:v.string().min(1).describe(`Exact mutation id from an available complete contract.`),input:v.record(v.string(),v.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`),clientToken:v.uuid().optional().describe(`Stable UUID reused only when retrying this exact mutation input.`)}),ge=E(),U=(e,t)=>({invoke:async n=>e.invoke({...n,clientMetadata:ge.current()??t?.()??i({path:`local_mcp`})})}),W=v.enum([`apply-canvas-design`,`design-on-canvas`,`publish-prototype`,`respond-to-feedback`]),_e=v.object({name:W,description:v.string().min(1),body:v.string().min(1)}),G=`Before designing on a canvas, responding to feedback, publishing a prototype or applying a canvas design, call workflow_guide with the matching workflow and follow its guidance.`,K=(e,t)=>{let n=W.options.map(t=>{let n=y(b.join(e,t,`SKILL.md`),`utf8`),r=/^---\r?\nname: ([^\r\n]+)\r?\ndescription: ([^\r\n]+)\r?\n---\r?\n([\s\S]+)$/u.exec(n),i=_e.parse({name:r?.[1],description:r?.[2],body:r?.[3]});if(i.name!==t)throw Error(`Workflow name does not match its folder: ${t}`);return i});return{instructions:[G,t].filter(Boolean).join(` `),register:e=>{for(let t of n)e.registerPrompt(t.name,{description:t.description},()=>({messages:[{role:`user`,content:{type:`text`,text:t.body}}]}));e.registerTool(`workflow_guide`,{title:`Load an Enhance workflow`,description:G,inputSchema:v.strictObject({workflow:W}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},({workflow:e})=>({content:n.filter(t=>t.name===e).map(e=>({type:`text`,text:e.body}))}))}}},q=E(),J=v.uuid().optional().describe(`Reuse only when retrying this exact mutation.`),ve=n.pick({baseVersion:!0,targetNodeId:!0,html:!0,idPrefix:!0}).extend({canvas:v.string().min(1).describe(`Canvas UUID or complete canvas/page/selection URL. Preserve every supplied page and selection.`),mode:v.enum([`insert-children`,`replace`]).default(`insert-children`),clientToken:J}),ye=_.extend({clientToken:J}),be=v.object({clientToken:J,canvas:v.string().min(1),expectedVersion:v.number().int().positive().describe(`Version returned by the latest successful read or write.`),target:ee.default({kind:`content`}),sourceState:u.nullable().default(null),scale:v.number().positive().default(1)}),Y=async(e,t,n,r=null)=>{let i=e.catalog.find(e=>e.id===t);if(i===void 0)throw TypeError(`Missing canvas capability ${t}`);return e.invocation.invoke({capability:i,arguments:n,clientToken:r})},xe=async(n,i)=>{let s=a(i.canvas),c=n.scope??s;if(c.canvasId!==s.canvasId)throw new e(`FORBIDDEN`,`This turn cannot render another canvas.`,`Render the submitted canvas and selection.`);if(!t(c))return{canvasId:c.canvasId,target:i.target};let u=r.parse(await Y(n,`canvas.document.get`,{canvasId:c.canvasId}));if(u.version!==i.expectedVersion)throw new e(`CONFLICT`,`The canvas changed before rendering.`,`Read the selected subtree and render its current version.`);return{canvasId:c.canvasId,target:o(c,l.parse(u.document),i.target)}},X=async(e,t,n)=>{try{return await t.results.success(e,await n(),t.delivery)}catch(e){return t.results.failure(e)}},Se=(e,t)=>{t.catalog.some(e=>e.id===`canvas.writeHtml`)&&e.registerTool(`canvas_write_html`,{title:`Design editable canvas content`,description:`Create a populated screen or visual group from safe HTML/CSS. For multiple screens, publish the first populated screen before authoring the next, then publish each subsequent screen separately so the user can see and steer progress. Prepare only what that screen needs; do not prepare the whole set before the first write. Returns the committed version and root node without an extra read or render. ${t.readTool===`canvas_read`?`Read canonical IDs and the current version with canvas_read. Keep all writes inside the frozen selection.`:`If starting state is unknown, call capability_query with {"capability":"canvas.read","input":{"canvasId":"<UUID from canvas URL>"}}. When nodeCount is 0, use targetNodeId "root" and the returned version.`} Use flex, padding, gap, concrete inline CSS and layer-name. Give important rows/cards/buttons explicit dimensions; avoid implicit stretch, margins, grid, tables and inline badge backgrounds. Include real content, not an empty shell. Reuse a returned version for subsequent edits; read a targeted subtree only when its ids or structure are unknown. Use canvas_edit for small changes, then canvas_render once at a useful review point. The schema here is executable; no search or describe is required.`,inputSchema:ve,outputSchema:V,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({canvas:n,clientToken:r,...i},o)=>q.run(o,async()=>X(e,t,async()=>{let e=a(n);return Y(t,`canvas.writeHtml`,{...i,canvasId:e.canvasId,...e.pageId!==void 0&&{pageId:e.pageId},...e.nodeIds.length>0&&{selectionNodeIds:e.nodeIds},review:`none`,renderOutputPath:null,overwriteRender:!1,renderScale:1,renderTimeoutMs:12e4},r??null)})))},Ce=(e,t)=>{t.catalog.some(e=>e.id===`canvas.edit`)&&e.registerTool(`canvas_edit`,{title:`Edit existing canvas content`,description:`Apply text, styles, rename, duplicate or move edits together in one atomic mutation. Use ids from the input version and the latest successful read or write version; no intermediate read is required just to advance a version. Keep the complete selection URL. Read only the missing subtree when ids are unknown. Returns a compact committed receipt; render after the requested changes are complete.`,inputSchema:ye,outputSchema:V,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},async({clientToken:n,...r},i)=>q.run(i,async()=>X(e,t,async()=>Y(t,`canvas.edit`,r,n??null))))},we=(e,t)=>{t.catalog.some(e=>e.id===`canvas.render`)&&e.registerTool(`canvas_render`,{title:`Review canvas pixels`,description:`Render the version returned by a successful read or write and inspect its native PNG. Target the affected screen/node; a blank canvas does not need a pre-render. For a selection link use one node inside the selection. Review after a meaningful visual change, and repeat only after further changes or a real discrepancy.`,inputSchema:be,outputSchema:V,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},async(n,r)=>q.run(r,async()=>X(e,t,async()=>Y(t,`canvas.render`,{...await xe(t,n),expectedVersion:n.expectedVersion,sourceState:n.sourceState,scale:n.scale,outputPath:null,overwrite:!1,timeoutMs:12e4},n.clientToken??null))))},Te=e=>({register:t=>{let n=e.tools??[`write`,`edit`,`render`];n.includes(`write`)&&Se(t,e),n.includes(`edit`)&&Ce(t,e),n.includes(`render`)&&we(t,e)}}),Ee=e=>e.replaceAll(/\s+/gu,` `).trim(),De=e=>{let t=`${e.id} [${e.effect}] — `,n=Ee(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},Oe=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>De(e)),r=x(`sha256`).update(n.join(`
|
|
3
|
-
`)).digest(`hex`),i=[`Enhance MCP ${t} — ${String(n.length)} capabilities — sha256:${r}`,...n].join(`
|
|
4
|
-
`);if(Buffer.byteLength(i)>24576)throw RangeError(`the complete capability catalogue exceeds 24 KiB`);return{digest:r,text:i}},ke=(e,t,n=`enhance`)=>{let r=Oe(e,t),i=String(f(r.text,n));return{register:t=>{t.registerTool(`capability_catalogue`,{title:`Scan every Enhance capability`,description:`Return the complete bounded capability inventory when the task is broad, uncertain, or capability_search does not find the right words. Call capability_describe with one exact id before invoking it.`,inputSchema:v.strictObject({}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":e.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":e.length}},()=>({content:[{type:`text`,text:i}]}))}}},Ae=v.object({capability:v.string().min(1).describe(`Exact capability id returned by capability_search or capability_catalogue.`)}),je=(t,n)=>({register:r=>{r.registerTool(`capability_describe`,{title:`Load one Enhance capability contract`,description:`Load the exact input schema, example, preconditions, result guidance, recovery, and next steps for one id returned by capability_search or capability_catalogue.`,inputSchema:Ae,outputSchema:me,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},({capability:r})=>{let i=t.describe(r);return i===null?n.failure(new e(`BAD_REQUEST`,`Unknown shared capability: ${r}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`})):n.inline(i)})}}),Z=E(),Q={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},Me=v.object({query:v.string().trim().min(1).max(200).describe(`Plain-language task, domain, or exact capability id to discover.`),operation:v.enum([`any`,`query`,`mutation`]).default(`any`).describe(`Filter dispatch, not effect. Omit if unknown; render uses mutation.`),limit:v.number().int().min(1).max(10).default(5).describe(`Maximum contracts to return.`)}),$=(t,n,r)=>{let i=t.find(e=>e.id===n);if(i===void 0)throw new e(`BAD_REQUEST`,`Unknown shared capability: ${n}.`,`Call capability_search or capability_catalogue and use an exact id from its results.`,{capability:`No shared capability has this id.`});if(i.operation!==r){let t=i.operation===`query`?`capability_query`:`capability_mutate`;throw new e(`BAD_REQUEST`,`${n} is a ${i.operation}, not a ${r}.`,`Call ${t} with the same capability and input.`,{capability:`Use ${t} for this capability.`})}return i},Ne=(e,t,n,r)=>{e.registerTool(`capability_search`,{title:`Discover Enhance capabilities`,description:`Search the Enhance capability catalogue for a specific likely action. Returns relevant summaries and a complete bestContract when it fits. Invoke from that contract directly; call capability_describe only when detailRequired is returned or a different match is needed.`,inputSchema:Me,outputSchema:pe,annotations:Q,_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":t.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":t.length}},async({query:e,operation:t,limit:i},a)=>Z.run(a,async()=>r.inline(n.search({query:e,operation:t,limit:i}))))},Pe=(e,t,n,r)=>{e.registerTool(`capability_query`,{title:`Run a discovered Enhance query`,description:`Run one read-only capability using an available complete contract. Search or describe only when the contract is missing.`,inputSchema:he,outputSchema:V,annotations:Q,_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a},o)=>Z.run(o,async()=>{try{return await r.results.success(e,await n.invoke({capability:$(t,i,`query`),arguments:a,clientToken:null}),r.delivery)}catch(e){return r.results.failure(e)}}))},Fe=(e,t,n,r)=>{e.registerTool(`capability_mutate`,{title:`Run a discovered Enhance mutation`,description:`Run one state-changing capability using an available complete contract. Respect its preconditions and reuse clientToken only when retrying the identical mutation.`,inputSchema:H,outputSchema:V,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a,clientToken:o},s)=>Z.run(s,async()=>{try{return await r.results.success(e,await n.invoke({capability:$(t,i,`mutation`),arguments:a,clientToken:o??null}),r.delivery)}catch(e){return r.results.failure(e)}}))},Ie=e=>{let t=e.exposures?.includes(`mcp-transport`)===!0?`Transport attachment is not Enhance sign-in, even when the host reports mcp_auth success. Use capability_query with capability auth.status to check the person. If authenticated is false or a read returns UNAUTHORIZED, use capability_mutate with capability auth.login and input {"openBrowser":true}, then show the returned sign-in URL and let the person complete browser sign-in. If their browser restores a canvas or another page, direct them to this exact URL. A waiting_for_browser result is pending, not authenticated. Verify auth.status and a read such as canvas.list before reporting setup complete.`:void 0,n=e.workflowsDirectory===void 0?void 0:K(e.workflowsDirectory,t),r=n?.instructions??t,i=new ae({name:e.name??`enhance-mcp`,version:e.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!0}},...r!==void 0&&{instructions:r}}),a=c(e.catalog??d(),e.exposures??[`shared`]),o=g(a),s=F(e.exposures?.includes(`mcp-transport`)===!0?`Call capability_mutate with capability auth.login and input {"openBrowser":true}. Show the returned sign-in URL, complete browser sign-in, then verify auth.status and a read such as canvas.list.`:`Reconnect this hosted MCP server through your host’s browser OAuth sign-in. Then verify person.me and a read such as canvas.list.`,e.commandName);ke(a,e.version,e.commandName).register(i),Ne(i,a,o,s),je(o,s).register(i);let l={delivery:e.delivery??`linked`,results:s,invocation:U(e.invocation,e.clientMetadata)};return Pe(i,a,l.invocation,l),Fe(i,a,l.invocation,l),Te({catalog:a,...l}).register(i),n?.register(i),i};export{F as a,V as i,K as n,E as o,U as r,Ie as t};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{$n as e,A as t,An as n,At as r,Bn as i,Bt as a,C as o,Cn as s,Cr as c,Ct as l,Dr as u,Dt as d,En as f,Er as p,F as m,Fn as h,G as g,Gn as _,Gt as ee,H as te,Hn as v,Ht as ne,In as re,J as ie,Jn as ae,Jt as oe,K as se,Kn as ce,Kt as le,Ln as ue,Lt as de,M as fe,Mn as pe,Mr as me,N as he,O as ge,On as _e,Or as ve,Ot as y,Pn as ye,Q as be,Qn as xe,Qt as Se,Rn as Ce,S as we,Sr as Te,T as Ee,Tn as De,Tr as Oe,U as ke,Un as Ae,Ut as je,Vt as Me,W as Ne,Wn as Pe,Wt as Fe,X as Ie,Xt as Le,Y as Re,Yt as ze,Zn as Be,_r as Ve,_t as He,ar as Ue,at as We,bn as Ge,br as Ke,cr as qe,ct as Je,dr as Ye,dt as Xe,fr as Ze,gr as Qe,hr as $e,ht as et,ir as tt,jt as nt,kn as rt,kr as it,kt as at,lr as ot,lt as st,mt as ct,nt as lt,or as ut,ot as dt,q as ft,qn as pt,qt as mt,rt as ht,s as gt,sr as _t,tr as vt,tt as yt,ut as bt,v as xt,vn as St,vr as Ct,w as wt,wn as Tt,wr as Et,wt as Dt,x as b,xn as Ot,xr as kt,xt as At,yn as jt,yr as Mt,yt as Nt,z as Pt,zt as Ft}from"./cli-output-identity.lib-jpwIAYMc.mjs";import x from"node:process";import{z as S}from"zod";import{homedir as It,tmpdir as Lt}from"node:os";import{generateKeyBetween as Rt,generateNKeysBetween as zt}from"fractional-indexing";import{chmodSync as Bt,constants as Vt,createReadStream as Ht,createWriteStream as Ut,mkdirSync as Wt,writeFileSync as Gt}from"node:fs";import C from"node:path";import{createHash as w,randomBytes as Kt,randomUUID as qt}from"node:crypto";import{setTimeout as Jt}from"node:timers/promises";import{access as Yt,chmod as Xt,mkdir as Zt,mkdtemp as Qt,open as $t,readFile as en,realpath as tn,rename as nn,rm as rn,stat as an,unlink as on,writeFile as sn}from"node:fs/promises";import{isDeepStrictEqual as cn}from"node:util";import{generate as ln,parse as un}from"css-tree";import{parseFragment as dn,serialize as fn,serializeOuter as pn}from"parse5";import{performance as mn}from"node:perf_hooks";import{Readable as hn,Transform as gn}from"node:stream";import{pipeline as _n}from"node:stream/promises";import{ZipFile as vn}from"yazl";import{createTRPCUntypedClient as yn,httpLink as bn}from"@trpc/client";import{spawn as xn}from"node:child_process";import{createServer as Sn}from"node:http";const Cn=(e,t)=>e<t?-1:+(e>t),wn=(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)??[])]},Tn=(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:wn(a,t.order)}},En=(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=Tn(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}}},Dn=1e6,On=e=>Math.round(e*255*Dn)/Dn,T=(e,t=1)=>{let n=e.alpha*t;if(e.space===`srgb`){let t=[e.red,e.green,e.blue].map(e=>String(On(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)})`},kn={x:0,y:0,width:1,height:1},An=(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}},jn=(e,t=kn)=>[{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=An(e,t);return[n.x,n.y]}),Mn=1024,Nn=(e,t,n)=>{let r=e.stops.map(t=>`${n?`rgb(255 255 255 / ${String(t.color.alpha*e.opacity)})`:T({...t.color,alpha:1})} ${String(t.position*360)}deg`);return`conic-gradient(from 90deg at ${String(t)}% ${String(t)}% in srgb, ${r.join(`, `)})`},Pn=(e,t)=>{let n=jn(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/Mn:e),s=`width:100%;height:100%;background-image:${Nn(e,a,!1)};mask-image:${Nn(e,a,!0)};`;return`<g transform="matrix(${o.map(String).join(` `)})"><foreignObject x="${String(r*Mn)}" y="${String(r*Mn)}" width="${String(i*Mn)}" height="${String(i*Mn)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${s}"></div></foreignObject></g>`},Fn=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Pn(e)}</svg>`,In=(e,t)=>e===void 0||t===void 0?!1:e.x===t.x&&e.y===t.y,Ln=e=>{let t=[...e];for(;t.length>1&&In(t[0],t.at(-1));)t.pop();for(;t.length>1&&In(t[0],t[1]);)t.splice(1,1);return t},Rn=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},zn=(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},Bn=e=>{let t=Rn(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=zn(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?Ln(n):null},Vn=Math.PI/2,Hn=1e6,Un=e=>String(Math.round(e*Hn)/Hn),E=([e,t])=>`${Un(e)} ${Un(t)}`,Wn=(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}},Gn=(e,t)=>{let{radius:n,reach:r,smoothing:i}=e,a=E(t([r,0]));if(n===0)return`L${a}`;let o=i*Vn/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=E(t([r-2*u,0])),f=E(t([s+l,0])),p=E(t([s,c])),m=E(t([c,s])),h=E(t([0,s+l])),g=E(t([0,r-2*u])),_=E(t([0,r]));return`L${a}C${d} ${f} ${p}${i===1?``:`A${Un(n)} ${Un(n)} 0 0 1 ${m}`}C${h} ${g} ${_}`},Kn=(e,t)=>{let{topLeft:n,topRight:r,bottomRight:i,bottomLeft:a,smoothing:o=0}=e;return[Wn(n,[r,a],t,o),Wn(r,[n,i],t,o),Wn(i,[a,r],t,o),Wn(a,[i,n],t,o)]},qn=(e,t)=>{let[n,r,i,a]=Kn(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}},Jn=(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]=Kn(e,{width:r,height:i});return[`M${E([n[0],a.reach+n[1]])}`,Gn(a,([e,t])=>[t+n[0],e+n[1]]),Gn(o,([e,t])=>[r-e+n[0],t+n[1]]),Gn(s,([e,t])=>[r-t+n[0],i-e+n[1]]),Gn(c,([e,t])=>[e+n[0],i-t+n[1]]),`Z`].join(``)},Yn=1e5,Xn=.01,Zn=1e-9,D=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],O=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1]),Qn=(e,t)=>e[0]*t[1]-e[1]*t[0],k=(e,t)=>[e[0]-t[0],e[1]-t[1]],$n=e=>String(Math.round(e*Yn)/Yn),er=(e,t,n=0)=>{let[r,i,a,o]=e,s=O(r,o);if(n>=16||O(r,i)+O(i,a)+O(a,o)-s<=Xn/8){t.push(o);return}let c=D(r,i),l=D(i,a),u=D(a,o),d=D(c,l),f=D(l,u),p=D(d,f);er([r,c,d,p],t,n+1),er([p,f,u,o],t,n+1)},tr=(e,t,n,r)=>{let i=k(t,e),a=O(e,t);if(a<Zn)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-Xn/n)))));for(let e=1;e<=u;e+=1){let t=c+l*e/u;r.push([s[0]+n*Math.cos(t),s[1]+n*Math.sin(t)])}},nr=e=>{let t=e.match(/[MLCAZ]|-?(?:\d*\.)?\d+(?:e[-+]?\d+)?/giu)??[],n=[],r=0,i=()=>Number(t[r++]),a=()=>[i(),i()],o=e=>{let t=n.at(-1)??[0,0];if(e===`M`||e===`L`){n.push(a());return}if(e===`C`){er([t,a(),a(),a()],n);return}if(e===`A`){let e=i();r+=4,tr(t,a(),e,n)}};for(;r<t.length;)o(t[r++]??`Z`);return n.filter((e,t)=>O(e,n[(t+1)%n.length]??e)>Zn)},rr=(e,t,n)=>{let[r,i]=k(t,e),a=Math.hypot(r,i),o=[i*n/a,-r*n/a];return[[e[0]+o[0],e[1]+o[1]],[t[0]+o[0],t[1]+o[1]]]},ir=(e,t,n,r)=>{let i=k(t,e),a=k(r,n),o=Qn(i,a);if(Math.abs(o)<Zn)return D(t,n);let s=Qn(k(n,e),a)/o;return[e[0]+s*i[0],e[1]+s*i[1]]},ar=(e,t)=>{let n=[...e];for(let[r,i]of e.entries()){let a=e[(r+1)%e.length];if(a===void 0)continue;let[o,s]=rr(i,a,t),c=k(s,o),l=[];for(let[e,t]of n.entries()){let r=n[(e+1)%n.length]??t,i=Qn(c,k(t,o))>=-1e-9,a=Qn(c,k(r,o))>=-1e-9;i&&l.push(t),i!==a&&l.push(ir(t,r,o,s))}if(n=l,n.length===0)break}return n},or=(e,t)=>{if(t===0)return e;let n=nr(e),r=t<0?ar(n,t):n.map((e,r)=>{let i=n[(r+n.length-1)%n.length]??e,a=n[(r+1)%n.length]??e,o=rr(i,e,t),s=rr(e,a,t);return ir(...o,...s)});return r.length<3?``:r.map((e,t)=>`${t===0?`M`:`L`}${$n(e[0])} ${$n(e[1])}`).join(``)+`Z`},sr=(e,t,n)=>t.width<=0||t.height<=0?``:or(Jn(e,t),n),cr=(e,t,n)=>{let r=(t.rotation??0)*Math.PI/180,i=Math.cos(r),a=Math.sin(r),o=t.flipHorizontal===!0?-1:1,s=t.flipVertical===!0?-1:1,c=i*o,l=a*o,u=-a*s,d=i*s,f=n===void 0?c:c*n.a+u*n.b,p=n===void 0?l:l*n.a+d*n.b,m=n===void 0?u:c*n.c+u*n.d,h=n===void 0?d:l*n.c+d*n.d,g=e.width/2,_=e.height/2;return{a:f,b:p,c:m,d:h,e:e.x+g-f*g-m*_,f:e.y+_-p*g-h*_}},lr=e=>{let t=e.additionalStyles?.declarations.find(e=>e.enabled&&e.property===`--enhance-group-affine-residual`)?.value;if(t===void 0)return;let n=/^matrix\(([^)]*)\)$/iu.exec(t)?.[1]?.split(`,`).map(e=>Number(e.trim()));if(n?.length!==6||n.some(e=>!Number.isFinite(e)))return null;let[r,i,a,o]=n;return r===void 0||i===void 0||a===void 0||o===void 0?null:{a:r,b:i,c:a,d:o}},ur=e=>{let t=lr(e);return t===null||e.box===void 0?null:cr(e.box,e.layout??{},t)},A=(e,t,n)=>({x:e.x+t.x*n,y:e.y+t.y*n}),dr=e=>`${String(e.x)} ${String(e.y)}`,fr=(e,t,n)=>({x:(t.x-e.x)/n,y:(t.y-e.y)/n}),pr=(e,t,n)=>{let r=e.innerRatio!==void 0,i=e.count,a=e.innerRatio??1,o=r?i*2:i;return Array.from({length:o},(e,r)=>{let i=r%2==0?1:a,s=-Math.PI/2+r*Math.PI*2/o;return{x:t/2+Math.cos(s)*t*i/2,y:n/2+Math.sin(s)*n*i/2}})},mr=(e,t)=>{let n=e[t],r=e[(t+e.length-1)%e.length],i=e[(t+1)%e.length];if(n===void 0||r===void 0||i===void 0)return;let a=Math.hypot(r.x-n.x,r.y-n.y),o=Math.hypot(i.x-n.x,i.y-n.y);if(a===0||o===0)return;let s=fr(n,r,a),c=fr(n,i,o),l=Math.acos(Math.min(1,Math.max(-1,s.x*c.x+s.y*c.y)));if(l!==0&&l!==Math.PI)return{vertex:n,before:s,after:c,previousLength:a,nextLength:o,angle:l,cotangent:1/Math.tan(l/2)}},hr=(e,t,n,r)=>{let i=n*e.cotangent,a=A(e.vertex,t,i*(1+r)),o=A(e.vertex,t,i),s=A(e.vertex,{x:e.before.x+e.after.x,y:e.before.y+e.after.y},n/Math.sin(e.angle)),c=fr(o,s,n),l=(Math.PI-e.angle)*r/2,u=A(A(o,t,-n*Math.sin(l)),c,n*(1-Math.cos(l))),d={x:-t.x*Math.cos(l)+c.x*Math.sin(l),y:-t.y*Math.cos(l)+c.y*Math.sin(l)},f=A(u,d,-n*Math.tan(l/2));return{start:a,first:{x:a.x+(f.x-a.x)*2/3,y:a.y+(f.y-a.y)*2/3},second:f,end:u,travel:d}},gr=(e,t,n)=>{let r=hr(e,e.before,t,n),i=hr(e,e.after,t,n),a=4/3*t*Math.tan((Math.PI-e.angle)*(1-n)/4),o=A(r.end,r.travel,a),s=A(i.end,i.travel,a),c=(e,t,n)=>`C${dr(e)} ${dr(t)} ${dr(n)}`;return dr(r.start)+(n>0?c(r.first,r.second,r.end):``)+c(o,s,i.end)+(n>0?c(i.second,i.first,i.start):``)},_r=(e,t,n)=>{let r=e.map((t,n)=>mr(e,n)),i=e=>typeof t==`number`?t:t[e]??0;return`${e.map((t,a)=>{let o=r[a],s=(a+e.length-1)%e.length,c=(a+1)%e.length,l=r[s],u=r[c],d=i(a),f=a===0?`M`:`L`;if(d===0||o===void 0)return f+dr(t);let p=Math.min(o.previousLength/(o.cotangent+(l?.cotangent??0)*(i(s)/d)),o.nextLength/(o.cotangent+(u?.cotangent??0)*(i(c)/d))),m=Math.min(d,p),h=Math.min(n,Math.max(0,p/m-1));return f+gr(o,m,h)}).join(``)}Z`},vr=(e,t,n)=>_r(pr(e,t,n),e.cornerRadius,e.cornerSmoothing),yr=new WeakMap,br=new WeakMap,xr=e=>{if(br.has(e))return br.get(e)??null;let t=e.result.path.match(/M[^M]*/gu)??[],n=t.map(e=>{let t=Bn(e);return{path:e,vertices:t!==null&&t.length>=3?t:null}}),r=t.length>0&&t.join(``)===e.result.path?n:null;return br.set(e,r),r},Sr=(e,t,n)=>{let r={kind:`path`,path:e.result.path,fillRule:e.result.fillRule,viewBox:{x:0,y:0,width:t.width,height:t.height}};if(n===void 0||n.topLeft===0||[n.topRight,n.bottomLeft,n.bottomRight].some(e=>e!==n.topLeft))return r;let i=xr(e);return i===null?r:{...r,path:i.map(e=>e.vertices===null?e.path:_r(e.vertices,n.topLeft,n.smoothing??0)).join(``)}},Cr=e=>{if(yr.has(e))return yr.get(e)??null;let t=Bn(e.path),n=t?.length===4&&t.every((e,n)=>{let r=t[(n+1)%4],i=t[(n+2)%4];return r!==void 0&&i!==void 0&&(r.x-e.x)*(i.y-r.y)>(r.y-e.y)*(i.x-r.x)})?t:null;return yr.set(e,n),n},wr=(e,t,n)=>{if(n.width<=0||n.height<=0)return e;let r=[t.topLeft,t.topRight,t.bottomRight,t.bottomLeft];if(r.every(e=>e===0)&&e.viewBox.x===0&&e.viewBox.y===0&&n.width===e.viewBox.width&&n.height===e.viewBox.height)return e;let i=Cr(e);if(i===null)return e;let a=i.map(t=>({x:(t.x-e.viewBox.x)*n.width/e.viewBox.width,y:(t.y-e.viewBox.y)*n.height/e.viewBox.height}));return{...e,path:_r(a,r,t.smoothing??0),viewBox:{x:0,y:0,width:n.width,height:n.height}}},Tr={topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},Er=[`border-top-left-radius`,`border-top-right-radius`,`border-bottom-right-radius`,`border-bottom-left-radius`],Dr=(e,t)=>{if(e===void 0)return 0;if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:null;let n=/^\s*(\d+(?:\.\d+)?)(px|%)?\s*$/u.exec(e);if(n===null)return null;let r=Number(n[1]);return n[2]===`%`?t*r/100:r},Or=e=>{if(e.appearance?.radius!==void 0)return e.appearance.radius;if(e.box===void 0)return null;let t=e.styles[`border-radius`],[n,r,i,a]=Er.map(n=>Dr(e.styles[n]??t,Math.min(e.box?.width??0,e.box?.height??0)));return n===null||r===null||i===null||a===null?null:{topLeft:n??0,topRight:r??0,bottomRight:i??0,bottomLeft:a??0}},kr=(e,t)=>{let n=e/2,r=t/2;return`M0 ${String(r)}A${String(n)} ${String(r)} 0 1 0 ${String(e)} ${String(r)}A${String(n)} ${String(r)} 0 1 0 0 ${String(r)}Z`},Ar=(e,t)=>{if(e.geometry?.kind===`path`)return e.geometry;let n=e.box;if(n!==void 0&&e.geometry?.kind===`polygon`&&n.width>0&&n.height>0)return{kind:`path`,path:vr(e.geometry,n.width,n.height),fillRule:`nonzero`,viewBox:{x:0,y:0,width:n.width,height:n.height}};if(n===void 0||![`rectangle`,`frame`].includes(e.component)||n.width<=0||n.height<=0)return`Choose a closed shape or an editable vector path.`;let r=Or(e);return r===null?`This shape uses a corner expression that cannot be edited as a path.`:{kind:`path`,fillRule:`nonzero`,path:e.styles[`border-radius`]===`50%`&&e.appearance?.radius===void 0&&Er.every(t=>e.styles[t]===void 0)?kr(n.width,n.height):Jn(t&&e.component===`rectangle`&&e.appearance?.radius!==void 0?Tr:{...Tr,...r},n),viewBox:{x:0,y:0,width:n.width,height:n.height}}},jr=e=>{if(e.geometry?.kind===`boolean`&&e.box!==void 0)return e.geometry.result.isEmpty?`This shape has no closed geometry.`:Sr(e.geometry,e.box,e.appearance?.radius);let t=Ar(e,!1);return typeof t!=`string`&&e.geometry?.kind===`path`&&e.component===`rectangle`&&e.appearance?.radius!==void 0&&e.box!==void 0?wr(t,e.appearance.radius,e.box):t},Mr=e=>{let t=jr(e);if(typeof t==`string`)return t;if(e.box===void 0)return`The shape has no settled local box.`;let n=ur(e);if(n===null)return`The shape has an invalid affine transform.`;let r=e.box.width/t.viewBox.width,i=e.box.height/t.viewBox.height;return{path:t.path,fillRule:t.fillRule,matrix:[n.a*r,n.b*r,n.c*i,n.d*i,n.e-n.a*r*t.viewBox.x-n.c*i*t.viewBox.y,n.f-n.b*r*t.viewBox.x-n.d*i*t.viewBox.y]}},Nr=.5,Pr=.25,Fr=(e,t=`field`,n)=>{let r=jn(e,n),i=Math.max(Nr,...r.map(e=>Math.abs(e-Nr)))+1,a=Nr-i,o=Nr+i,s=[{x:.75,y:.75,points:`.5,.5 ${String(o)},.5 ${String(o)},${String(o)} .5,${String(o)}`},{x:Pr,y:.75,points:`.5,.5 .5,${String(o)} ${String(a)},${String(o)} ${String(a)},.5`},{x:Pr,y:Pr,points:`.5,.5 ${String(a)},.5 ${String(a)},${String(a)} .5,${String(a)}`},{x:.75,y:Pr,points:`.5,.5 .5,${String(a)} ${String(o)},${String(a)} ${String(o)},.5`}],c=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${T({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``),l=s.map((e,n)=>`<linearGradient id="${t}-${String(n)}" gradientUnits="userSpaceOnUse" x1=".5" y1=".5" x2="${String(e.x)}" y2="${String(e.y)}" color-interpolation="sRGB">${c}</linearGradient>`).join(``),u=s.map((e,n)=>`<polygon points="${e.points}" fill="url(#${t}-${String(n)})" shape-rendering="crispEdges" />`).join(``);return`<defs>${l}</defs><g transform="matrix(${e.transform.map(String).join(` `)})">${u}</g>`},Ir=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${Fr(e)}</svg>`,Lr=e=>e.parameter===`radius`?e.value/2:e.value,Rr=e=>{switch(e.kind){case`blur`:return`blur(${String(Lr(e))}px)`;case`brightness`:case`contrast`:case`saturate`:return`${e.kind}(${String(e.value)})`;case`grayscale`:case`invert`:case`sepia`:return`${e.kind}(${String(e.value*100)}%)`;case`hue-rotate`:return`hue-rotate(${String(e.value)}deg)`}},zr=e=>e.filter(e=>e.visible).map(e=>Rr(e)).join(` `),Br=new Set([`base`,`embed`,`iframe`,`link`,`meta`,`object`,`script`]),Vr=/^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu,Hr=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,Ur=e=>!Br.has(e.toLowerCase()),Wr=e=>!Hr.test(e),Gr=(e,t)=>{let n=e.toLowerCase();return n===`srcdoc`||/^on/iu.test(n)?!1:n===`style`?Wr(t):![`href`,`src`,`action`,`formaction`,`xlink:href`].includes(n)||!Vr.test(t.replaceAll(/[\p{Control}\s]/gu,``))},Kr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),qr=(e,t)=>{if(!Kr(e)||e.kind!==`image`||typeof e.assetId!=`string`)return e;let n=t(e.assetId);return n===e.assetId?e:{...e,assetId:n}},j=(e,t)=>{let n=qr(e,t);if(!Kr(n)||!Kr(n.alternatives))return n;let r=n.alternatives,i=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,qr(n,t)]));return Object.entries(i).every(([e,t])=>r[e]===t)?n:{...n,alternatives:i}},Jr=(e,t)=>Array.isArray(e)?e.map(e=>{if(!Kr(e)||e.kind!==`span`)return e;let n=Array.isArray(e.fills)?e.fills:void 0;return{...e,...n!==void 0&&{fills:n.map(e=>j(e,t))},...Kr(e.stroke)&&{stroke:{...e.stroke,paint:j(e.stroke.paint,t)}},...Array.isArray(e.children)&&{children:Jr(e.children,t)}}}):e,Yr=(e,t)=>{let n=e.appearance,r=e.props?.src;return{...e,...n!==void 0&&{appearance:{...n,...n.fills!==void 0&&{fills:n.fills.map(e=>j(e,t))},...n.border!==void 0&&{border:{...n.border,paints:n.border.paints.map(e=>j(e,t))}},...n.outline!==void 0&&{outline:{...n.outline,paints:n.outline.paints.map(e=>j(e,t))}}}},...e.typography?.stroke!==void 0&&{typography:{...e.typography,stroke:{...e.typography.stroke,paint:j(e.typography.stroke.paint,t)}}},...e.props!==void 0&&{props:{...e.props,...e.component===`image`&&typeof r==`string`&&{src:t(r)},...e.component===`text`&&e.props.richText!==void 0&&{richText:Jr(e.props.richText,t)}}}}},Xr=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${T({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``);return`<linearGradient id="${t}" gradientUnits="${n}" x1="0" y1=".5" x2="1" y2=".5" gradientTransform="matrix(${e.transform.map(String).join(` `)})" color-interpolation="sRGB">${r}</linearGradient>`},Zr=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${Xr(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,Qr=e=>({id:e,visible:!1,opacity:1,kind:`solid`,color:{space:`srgb`,red:0,green:0,blue:0,alpha:0}}),$r=()=>({opacity:1,blendMode:`normal`,fills:[],border:{visible:!1,width:{top:0,right:0,bottom:0,left:0},style:`solid`,paints:[Qr(`empty-border`)]},outline:{visible:!1,width:0,offset:0,style:`solid`,paints:[Qr(`empty-outline`)]},radius:{topLeft:0,topRight:0,bottomRight:0,bottomLeft:0},shadows:[],filters:[],backdropFilters:[]}),ei=e=>e.transform??[e.radius.x*2,0,0,e.radius.y*2,e.center.x-e.radius.x,e.center.y-e.radius.y],ti=(e,t,n=`userSpaceOnUse`)=>{let r=e.stops.map(t=>`<stop offset="${String(t.position)}" stop-color="${T({...t.color,alpha:1})}" stop-opacity="${String(t.color.alpha*e.opacity)}" />`).join(``);return`<radialGradient id="${t}" gradientUnits="${n}" cx=".5" cy=".5" r=".5" gradientTransform="matrix(${ei(e).map(String).join(` `)})" color-interpolation="sRGB">${r}</radialGradient>`},ni=e=>`<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${ti(e,`field`)}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`,ri=/^enh_[\w-]{43}$/,ii=e=>{let t=oe.parse(e);if(t.authentication.kind!==`agent`||t.person===null)throw new r(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:t.person.id,displayName:t.person.displayName,tokenId:t.authentication.tokenId,tokenLabel:t.authentication.tokenLabel,expiresAt:t.authentication.expiresAt}},ai=(e,t,n)=>({loginWithToken:async n=>{if(!ri.test(n))throw new r(`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 i=ii(await t.queryWithToken(`person.me`,{},n));return await e.write(n),i},loginWithBrowser:async i=>{let a=ze.parse(await t.authenticationConfig());if(a.method===`token`)throw new r(`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 o=await n.authorize({issuer:a.issuer,clientId:a.clientId,scope:a.scope,openBrowser:i.openBrowser,onReady:i.onReady,...i.signal!==void 0&&{signal:i.signal}});i.signal?.throwIfAborted();let s=Le.parse(await t.mutateWithToken(`person.createAgentToken`,{label:i.label,expiresAt:null},o)),c=ii(await t.queryWithToken(`person.me`,{},s.token));return i.signal?.throwIfAborted(),await e.write(s.token),c},status:async(n=t)=>{if(await e.read()===null)throw new r(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return ii(await n.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),oi=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),si=e=>{if(e.byteLength<24||oi.some((t,n)=>e[n]!==t))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}},ci=async(e,t)=>{if(t.result.canvasId!==t.canvasId||t.result.requestedVersion!==t.requestedVersion||t.result.loadedVersion!==t.requestedVersion||JSON.stringify(t.result.target)!==JSON.stringify(t.target))throw new r(`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 r(`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=ut.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 r(`INTERNAL`,`The API returned an invalid render download response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");let i=await e.download(n.data.download.url),a=si(i);if(a===null||i.byteLength!==t.result.bytes||a.width!==t.result.width||a.height!==t.result.height)throw new r(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return{body:i,...n.data.source!==void 0&&{source:n.data.source}}},li=e=>{let t=`enhance canvas inspect --canvas ${e.canvasId}`;return e.result.sourceState===void 0?e.target.kind===`node`?[t,`enhance canvas node --canvas ${e.canvasId} --node-id ${e.target.nodeId}`]:[t]:[`Inspect the PNG at path before persisting this moment.`,`enhance recording snapshot --canvas ${e.canvasId} --recording-id ${e.result.sourceState.recordingId} --at-ms ${String(e.result.sourceState.settledAtMs)}`,t]},ui=(e,t,n)=>({...n!==void 0&&{source:n},jobId:e.id,operation:{kind:`canvas-render`,canvasId:e.canvasId,jobId:e.id},canvasId:e.canvasId,requestedVersion:e.requestedVersion,loadedVersion:e.result.loadedVersion,target:e.target,sourceState:e.result.sourceState??null,bounds:e.result.bounds,width:e.result.width,height:e.result.height,scale:e.result.scale,contentType:e.result.contentType,bytes:e.result.bytes,warnings:e.result.warnings,path:t.path,sensitive:!0,cleanup:t.temporary?`unlink-after-use`:`caller-owned`,...t.deleteAfter!==null&&{deleteAfter:t.deleteAfter.toISOString()},next:li(e)}),di=async(e,t,n,r)=>{let i=await ci(e,n);return ui(n,t.write({body:i.body,...r}),i.source)},fi=[`canvas.render.create`,`canvas.render.get`],pi=e=>new r(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),mi=e=>{let t=e.failure;if(t===null)return pi(`render job`);let n=t.reason===`VERSION_CHANGED`?`CONFLICT`:t.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:t.reason===`TARGET_INVALID`||t.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,i=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 r(n,t.message,i,{jobId:e.id,reason:t.reason,phase:t.phase,renderState:e.state})},hi=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),gi=async(e,t)=>{let n=_t.safeParse(await e.query(fi[1],{jobId:t}));if(!n.success||n.data.job.id!==t)throw pi(`render status`);return n.data.job},_i=async(e,t)=>{let n=Date.now(),i=0,a=``,o=t.initial;for(;o.state===`queued`||o.state===`running`;){let s=Date.now(),c=`${o.state}:${o.phase}`;if((c!==a||s-i>=5e3)&&(t.progress({event:`render.progress`,jobId:o.id,state:o.state,phase:o.phase,elapsedMs:s-n,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),i=s,a=c),s>=t.deadline){if(t.timeoutOutcome===`pending`)return o;throw new r(`INTERNAL`,`Render ${o.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:o.id,phase:o.phase})}await hi(250),o=o.purpose===`inspection`&&o.state===`queued`&&o.attempt>0?await t.resume():await gi(e,o.id)}if(o.state!==`succeeded`)throw mi(o);return o},vi=async(e,t)=>{let n=tt.safeParse(await e.mutate(fi[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.scope!==void 0&&{scope:t.scope},...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,...t.maxOutputPixels!==void 0&&{maxOutputPixels:t.maxOutputPixels},format:`png`}));if(!n.success)throw pi(`render creation`);if(n.data.job.canvasId!==t.canvasId||t.expectedVersion!==null&&n.data.job.requestedVersion!==t.expectedVersion||JSON.stringify(n.data.job.target)!==JSON.stringify(t.target)||n.data.job.scale!==t.scale)throw pi(`render identity`);return n.data.job},yi=(e,t)=>{if(t.maxOutputPixels!==void 0&&e.maxOutputPixels!==t.maxOutputPixels)throw new r(`INTERNAL`,`This API does not preserve the requested render pixel budget.`,`Update the API and renderer together before rendering a batch.`,{reason:`RENDER_BUDGET_UNSUPPORTED`})},bi=async(e,t)=>{let n=await vi(e.remote,t);try{yi(n,t);let r=await _i(e.remote,{initial:n,resume:async()=>vi(e.remote,t),deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress,timeoutOutcome:t.timeoutOutcome});return yi(r,t),r.state===`succeeded`?await di(e.remote,e.files,r,{outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()}):{state:r.state,phase:r.phase,canvasId:r.canvasId,requestedVersion:r.requestedVersion,target:r.target,operation:{kind:`canvas-render`,canvasId:r.canvasId,jobId:r.id},pixelsDelivered:!1,next:[`Read operation_status with includeImage true. Do not create another render.`,`If it stays queued with attempt above 0, an attempt failed: repeat this exact request with the same clientToken to retry it.`]}}catch(e){let i=JSON.stringify({kind:`canvas-render`,canvasId:t.canvasId,jobId:n.id});throw e instanceof r?new r(e.code,e.message,e.remediation,{...e.fields,jobId:n.id,operation:i}):new r(`INTERNAL`,`The native render outcome could not be confirmed.`,`Read operation_status or retry with the identical request and clientToken.`,{jobId:n.id,operation:i})}},xi=(e,t,n,r=()=>null)=>({execute:async i=>bi({remote:e,files:t,now:n,progress:r},i)}),Si={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},Ci=async e=>{try{return await e(),!0}catch{return!1}},wi=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await Ci(async()=>e.mutate(Si.renew,{...i,nodeIds:[...i.nodeIds],activityId:n})),o=!1)},c=setInterval(()=>void s(),r);return{activityId:n,update:async e=>{a||(i={...i,...e},await s())},finish:async()=>{a||(a=!0,clearInterval(c),await Ci(async()=>e.mutate(Si.end,{canvasId:i.canvasId,activityId:n})))}}},Ti=e=>({begin:async t=>{try{let r=n.safeParse(await e.mutate(Si.begin,{...t,nodeIds:[...t.nodeIds]}));return r.success?wi(e,t,r.data.activityId,r.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>Ci(async()=>e.mutate(Si.end,{canvasId:t,activityId:n}))}),Ei=new Set([`insertPrototype`,`insertText`,`setBox`]),Di=e=>Ei.has(e.op),Oi=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,ki=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],Ai=e=>[...new Set(e.operations.flatMap(e=>ki(e)))].slice(0,100),ji=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:Di(e)?e.box==="default"?null:e.box:null,Mi=e=>{let t=e[0];if(t===void 0)return null;let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}},Ni=async(e,t)=>{let n=await e.mutate(`canvas.applyOperations`,{...t,documentFormatVersion:13}),i=Ae.safeParse(n);if(!i.success)throw new r(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return i.data},Pi=e=>({execute:async(t,n)=>{if(n?.activity===!1)return Ni(e,t);let r=await Ti(e).begin({canvasId:t.canvasId,phase:Oi(t),nodeIds:Ai(t),bounds:Mi(t.operations.flatMap(e=>{let t=ji(e);return t===null?[]:[t]}))});try{return await Ni(e,t)}finally{await r?.finish()}}}),Fi=async(e,t,n)=>{let i=ae.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:t}));if(!i.success)throw new r(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(i.data.version!==n)throw new r(`CONFLICT`,`Canvas version ${String(i.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(i.data.version)} before submitting a new edit.`);let a=qe.safeParse(i.data.document);if(a.success)return a.data;throw new r(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},M=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):Cn(t.sortKey,r.sortKey)).map(([e])=>e),Ii=e=>{let t=new Map;for(let[n,r]of Object.entries(e.relationships)){let e=t.get(r.parentId)??[];e.push(n),t.set(r.parentId,e)}for(let n of t.values())n.sort((t,n)=>{let r=e.relationships[t]?.sortKey??``,i=e.relationships[n]?.sortKey??``;return r===i?t.localeCompare(n):r.localeCompare(i)});return t},Li=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),N=(e,t)=>{let n=e.nodes[t];if(n!==void 0)return n;throw new r(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use a current stable node id.`)},Ri=(e,t)=>{let n=new Set,r=t=>{for(let i of M(e,t))n.add(i),r(i)};return r(t),n},zi=(e,t)=>{let n=new Set,i=t;for(;i!==void 0;){if(n.has(i))throw new r(`BAD_REQUEST`,`The canvas contains a parent cycle.`,`Repair the canvas topology before editing.`);if(n.add(i),N(e,i).locked===!0)return!0;i=e.relationships[i]?.parentId}return!1},Bi=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},Vi=e=>{let t=0;return n=>(t+=1,`${Bi(e)}_${Bi(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},Hi=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of M(e,t))r(n)};return r(t),n},Ui=(e,t,n)=>Object.fromEntries(Hi(e,t).map(t=>[t,n(N(e,t).label)])),Wi=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=N(n,t),l=s[t];if(l===void 0)throw Error(`Missing duplicate id for ${t}`);let u=n.relationships[t],d=t===r,f=d?i:s[u?.parentId??``];if(f===void 0)throw Error(`Missing duplicate parent for ${t}`);let p=`agent:${String(a+1).padStart(6,`0`)}`;return{op:`insertNode`,node:{...structuredClone(c),id:l},parentage:{parentId:f,sortKey:d?`${o}~agent-copy-${String(a+1).padStart(4,`0`)}`.slice(0,500):u?.sortKey??p}}},Gi=e=>{let{document:t,input:n,inputIndex:i,nextId:a}=e,o=N(t,n.id);if(n.id===`root`)throw new r(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let s=t.relationships[n.id];if(s===void 0)throw new r(`BAD_REQUEST`,`Canvas node ${n.id} is detached.`,`Choose a reachable node from canvas tree.`);let c=n.parentId??s.parentId;if(!Li(t.nodes[c]))throw new r(`BAD_REQUEST`,`Canvas node ${c} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let l=Ui(t,n.id,a),u={document:t,rootId:n.id,parentId:c,inputIndex:i,sourceSortKey:s.sortKey,map:l},d=Hi(t,n.id).map(e=>Wi(u,e)),f=l[n.id];if(f===void 0)throw Error(`Missing duplicate root id for ${n.id}`);return{operations:d,summary:{sourceId:n.id,newId:f,name:o.label,component:o.component,descendantIdMap:Object.fromEntries(Object.entries(l).filter(([e])=>e!==n.id))}}},Ki=(e,t,n)=>{if(t.length===0)throw new r(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let i=Vi(n),a=t.map((t,n)=>Gi({document:e,input:t,inputIndex:n,nextId:i}));return{operations:a.flatMap(e=>e.operations),duplicatedNodes:a.map(e=>e.summary)}},qi=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,M(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Ji=(e,t)=>{let n=(t.children.get(e.parentId)??[]).filter(t=>t!==e.nodeId);return{parentId:e.parentId,index:Math.max(0,Math.min(e.index??n.length,n.length))}},Yi=(e,t)=>{let n=`before`in e?e.before:e.after;if(n===e.nodeId||t.document.nodes[n]===void 0)throw new r(`BAD_REQUEST`,`Sibling ${n} is not a valid move target.`,`Choose another current sibling node.`);let i=t.parentOf.get(n);if(i===void 0)throw new r(`BAD_REQUEST`,`Sibling ${n} is detached.`,`Choose a reachable sibling from canvas tree.`);let a=(t.children.get(i)??[]).filter(t=>t!==e.nodeId).indexOf(n);return{parentId:i,index:`before`in e?a:a+1}},Xi=(e,t)=>`parentId`in e?Ji(e,t):Yi(e,t),Zi=(e,t,n)=>{if(e.nodeId===`root`||n.document.nodes[e.nodeId]===void 0)throw new r(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(Ri(n.document,e.nodeId).has(t.parentId)||t.parentId===e.nodeId||!Li(n.document.nodes[t.parentId]))throw new r(`BAD_REQUEST`,`Canvas node ${t.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},Qi=(e,t,n)=>{let r=n.parentOf.get(e.nodeId);r!==void 0&&(n.children.set(r,(n.children.get(r)??[]).filter(t=>t!==e.nodeId)),n.affected.add(r));let i=[...n.children.get(t.parentId)??[]],a=[],o={...n.document.relationships},s=e=>{let t=i[e];return t===void 0?null:o[t]?.sortKey??null},c=null;try{let e=s(t.index-1),n=s(t.index),r=Rt(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=zt(null,null,n.length).toSorted((e,t)=>e.localeCompare(t));for(let[e,i]of n.entries()){let n=r[e];if(n===void 0)throw Error(`Missing generated move sort key.`);let s={parentId:t.parentId,sortKey:n};o[i]=s,a.push({op:`setParentage`,nodeId:i,parentage:s})}}else{let n={parentId:t.parentId,sortKey:c};o[e.nodeId]=n,a.push({op:`setParentage`,nodeId:e.nodeId,parentage:n})}return i.splice(t.index,0,e.nodeId),n.children.set(t.parentId,i),n.parentOf.set(e.nodeId,t.parentId),n.affected.add(t.parentId),{operations:a,document:{...n.document,relationships:o}}},$i=(e,t)=>{if(t.length===0)throw new r(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let n=qi(e),i=[];return{operations:t.flatMap(e=>{let t=Xi(e,n);Zi(e,t,n),i.push({nodeId:e.nodeId,...t});let r=Qi(e,t,n);return n.document=r.document,r.operations}),moves:i,affectedParents:Array.from(n.affected,e=>({parentId:e,children:[...n.children.get(e)??[]]}))}},P=e=>Math.min(1,Math.max(0,e)),ea=e=>P(Number(e)/255),ta=e=>{let t=e.slice(1);if(![3,4,6,8].includes(t.length)||!/^[\da-f]+$/iu.test(t))return null;let n=t.length<=4?t.replaceAll(/([\da-f])/giu,`$1$1`):t,r=e=>Number.parseInt(n.slice(e,e+2),16)/255;return{space:`srgb`,red:r(0),green:r(2),blue:r(4),alpha:n.length===8?r(6):1}},na=e=>{let t=/^rgba?\(\s*([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*[,/]\s*([\d.]+)(%?))?\s*\)$/iu.exec(e);if(t===null)return null;let n=(e,t)=>t===`%`?P(Number(e)/100):ea(e??`0`),r=t[7]===void 0?1:P(Number(t[7])/(t[8]===`%`?100:1));return{space:`srgb`,red:n(t[1],t[2]),green:n(t[3],t[4]),blue:n(t[5],t[6]),alpha:r}},ra=e=>{let t=/^color\(\s*(srgb|display-p3)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\s*\)$/iu.exec(e);return t===null?null:{space:t[1]===`display-p3`?`display-p3`:`srgb`,red:P(Number(t[2])),green:P(Number(t[3])),blue:P(Number(t[4])),alpha:P(t[5]===void 0?1:Number(t[5]))}},ia=e=>{let t=e.trim().toLowerCase();return t===`transparent`?{space:`srgb`,red:0,green:0,blue:0,alpha:0}:t.startsWith(`#`)?ta(t):t.startsWith(`rgb`)?na(t):t.startsWith(`color(`)?ra(t):null},aa=(e,t)=>({id:e,visible:!0,opacity:1,kind:`solid`,color:t}),F=(e,t)=>{let n=ia(t);return n===null?null:aa(e,n)},oa=e=>e/2**32|0,sa=e=>e>>>0;function ca(e,t,n,r){let i=oa(n),a=sa(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function la(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const ua=e=>e?`"${e}" `:``;function da(e,t=``){if(typeof e!=`number`)throw TypeError(ua(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ua(t)+`expected integer >= 0, got `+e);return e}function fa(e,t,n=``){if(la(e)&&(t===void 0||e.length===t))return e;t!==void 0&&da(t,`length`);let r=la(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ua(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const pa=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)};function ma(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function ha(e,t){fa(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function ga(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _a(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function I(e,t){return e<<32-t|e>>>t}const va=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,ya=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ba(e){if(fa(e),va)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=ya[e[n]];return t}function xa(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function Sa(e,t,n=`opts`){return pa(e,`defaults`),t!==void 0&&pa(t,n),Object.assign(e,t)}function Ca(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=Sa({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}const wa=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ta(e,t,n){return e&t^~e&n}function Ea(e,t,n){return e&t^e&n^t&n}var Da=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=_a(this.buffer)}update(e){ma(this),fa(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=_a(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0;continue}n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){ma(this),ha(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),ca(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:_a(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};const Oa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ka=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),L=new Uint32Array(64);var Aa=class extends Da{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)L[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=L[e-15],n=L[e-2],r=I(t,7)^I(t,18)^t>>>3,i=I(n,17)^I(n,19)^n>>>10;L[e]=i+L[e-7]+r+L[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=I(o,6)^I(o,11)^I(o,25),u=l+t+Ta(o,s,c)+ka[e]+L[e]|0,d=(I(n,2)^I(n,13)^I(n,22))+Ea(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){ga(L)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ga(this.buffer)}},ja=class extends Aa{constructor(){super(32,Oa)}};const Ma=Ca(()=>new ja,wa(1)),Na=(e,t)=>e.sortKey===t.sortKey?e.childId.localeCompare(t.childId):e.sortKey<t.sortKey?-1:1,Pa=e=>{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(Na).map(e=>e.childId));return n},Fa=new WeakMap,Ia=e=>{let t=Fa.get(e);if(t!==void 0)return t;let n=Pa(e);return Object.isFrozen(e)&&Fa.set(e,n),n},La=[],Ra=(e,t)=>e.get(t)??La,za=(e,t)=>Ra(Ia(e),t),Ba=e=>e.trim()===``||e.trim()===`about:blank`,Va=e=>typeof e==`string`&&e.startsWith(`enhance-pending-image:`),Ha=e=>Va(e.assetId)||e.opacity!==1||e.fit===`crop`&&e.transform!==void 0||(e.rotation??0)!==0||e.fit===`tile`&&(e.tileScale??1)!==1,Ua=e=>`--canvas-image-paint-${ba(Ma(xa(JSON.stringify([e.assetId,e.opacity,e.rotation??0,e.fit===`tile`?e.tileScale??1:1,e.fit===`crop`?e.transform:void 0]))))}`,Wa=e=>`--canvas-text-paints-${ba(Ma(xa(JSON.stringify(e.filter(e=>e.visible),(e,t)=>e===`id`?void 0:t))))}`,Ga=(e,t=1)=>`${T(e.color,t)} ${String(e.position*100)}%`,Ka=e=>encodeURI(e).replaceAll(`"`,`%22`),qa=e=>`url("${Ka(e)}")`,Ja=e=>{switch(e.kind){case`solid`:{let t=T(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=>Ga(t,e.opacity)).join(`, `)})`:`url("data:image/svg+xml,${encodeURIComponent(Zr({...e,transform:e.transform}))}")`;case`radial-gradient`:{if(e.transform!==void 0)return`url("data:image/svg+xml,${encodeURIComponent(ni(e))}")`;let t=`${String(e.center.x*100)}% ${String(e.center.y*100)}%`;return`radial-gradient(ellipse ${String(e.radius.x*100)}% ${String(e.radius.y*100)}% at ${t}, ${e.stops.map(t=>Ga(t,e.opacity)).join(`, `)})`}case`angular-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Fn(e))}")`;case`diamond-gradient`:return`url("data:image/svg+xml,${encodeURIComponent(Ir(e))}")`;case`image`:return Ba(e.assetId)?`none`:Ha(e)?`var(${Ua(e)}, none)`:qa(e.assetId)}},Ya=(e,t)=>t>=1?0:e/(1-t)*100,Xa=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(Ya(e.x,t))}% ${String(Ya(e.y,n))}%`,"background-size":`${String(100/t)}% ${String(100/n)}%`}},Za=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`?Xa(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`}},Qa=e=>{if(e.length===0)return{};let t=e.toReversed().map(e=>Za(e));return Object.fromEntries([`background-size`,`background-position`,`background-repeat`,`background-origin`].map(e=>[e,t.map(t=>t[e]).join(`, `)]))},$a=e=>e.kind===`solid`&&e.visible?T(e.color,e.opacity):void 0,eo=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,to=e=>eo(e)?void 0:$a(e),no=e=>{let t=e.filter(e=>e.visible),[n]=t;return n===void 0||t.length!==1?`transparent`:to(n)??`transparent`},ro=e=>({"background-image":e.toReversed().map(e=>Ja(e)).join(`, `),...Qa(e)}),io=e=>{let t=e.filter(e=>e.visible);if(t.length===0||t.some(e=>eo(e)))return{background:`none`};let[n]=t,r=n===void 0?void 0:to(n);return r!==void 0&&t.length===1?{background:r,"background-image":`none`}:{"background-color":`transparent`,...ro(t)}},ao=e=>{let t=e.filter(e=>e.visible),[n]=t;return t.length===1&&n?.kind===`solid`?{color:T(n.color,n.opacity)}:t.length===0?{color:`transparent`}:{color:`transparent`,...t.length>1?{"background-image":`var(${Wa(t)}, none)`,"background-size":`100% 100%`,"background-position":`center`,"background-repeat":`no-repeat`}:ro(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`}},oo=new Set(Be.keyof().options.filter(e=>/^(?:border|outline)(?:-|$)/u.test(e)&&!e.includes(`radius`))),so=(e,t)=>{let n=t.toLowerCase();return oo.has(n)&&(n===e||n.startsWith(`${e}-`))},co=[`top`,`right`,`bottom`,`left`],lo=[`solid`,`dashed`,`dotted`],uo=[`width`,`style`,`color`],fo=(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},po=(e,t)=>{let n=$e(t);if(/^(?:border(?:-(?:top|right|bottom|left))?|outline)$/u.test(e)){let t=n.find(e=>fo(e)!==void 0),r=n.find(e=>/^(?:none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/u.test(e)),i=n.find(e=>F(`probe`,e)!==null);if(t===void 0||r===void 0||i===void 0||n.length!==uo.length)return null;let a=e===`border`?co.map(e=>`border-${e}`):[e];return Object.fromEntries(a.flatMap(e=>uo.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>co.length)return null;let[t=``,r=t,i=t,a=r]=n;return Object.fromEntries(co.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},mo=(e,t)=>e.additionalStyles?.declarations.filter(({property:n,value:r,enabled:i})=>so(t,n)&&(!i||r.trim()!==``||e.appearance?.[t]===void 0))??[],ho=(e,t)=>{let n=mo(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(!so(t,e))continue;let r=po(e.toLowerCase(),Qe(e,n).trim());if(r===null||String(n).includes(`!`))return null;Object.assign(a,r)}return a},go=e=>{let t=ho(e,`border`);if(t===null)return{kind:`custom`};if(e.appearance?.border!==void 0&&mo(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=co.map(n=>({width:fo(t[`border-${n}-width`]??`0`),authoredStyle:t[`border-${n}-style`],authoredColor:t[`border-${n}-color`],style:lo.find(e=>e===t[`border-${n}-style`]),paint:F(`${e.id}-border`,t[`border-${n}-color`]??``)})),r=n.find(e=>e.width!==0)??n[0];if(r?.style===void 0||r.paint===null||n.some(e=>e.width===void 0||e.authoredStyle!==void 0&&e.style===void 0||e.authoredColor!==void 0&&e.paint===null||e.width!==0&&(e.style!==r.style||JSON.stringify(e.paint)!==JSON.stringify(r.paint))||e.width===0&&(e.style!==void 0&&e.style!==r.style||e.paint!==null&&JSON.stringify(e.paint)!==JSON.stringify(r.paint))))return{kind:`custom`};let[i=0,a=0,o=0,s=0]=n.map(e=>e.width);return{kind:`native`,value:{visible:!0,width:{top:i,right:a,bottom:o,left:s},style:r.style,paints:[r.paint]}}},_o=e=>{let t=ho(e,`outline`);if(t===null)return{kind:`custom`};if(e.appearance?.outline!==void 0&&mo(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=fo(t[`outline-width`]),r=fo(t[`outline-offset`]??`0`,-1/0),i=lo.find(e=>e===t[`outline-style`]),a=F(`${e.id}-outline`,t[`outline-color`]??``);return n===void 0||r===void 0||i===void 0||a===null?{kind:`custom`}:{kind:`native`,value:{visible:!0,width:n,offset:r,style:i,paints:[a]}}},vo=Object.freeze({top:0,right:0,bottom:0,left:0}),R=e=>e.alignment!==void 0&&e.alignment!==`inside`||e.layoutInclusion===`none`||e.layoutInclusion===`visible`&&(!e.visible||e.paints.every(e=>!e.visible))?vo:e.width,yo=e=>{let t=e.visible?no(e.paints):`transparent`,n=R(e);return{"border-style":e.style,"border-top-width":n.top,"border-right-width":n.right,"border-bottom-width":n.bottom,"border-left-width":n.left,"border-color":t}},bo=e=>{if(!e.visible)return{"outline-style":`none`};let t=no(e.paints);return{"outline-style":e.style,"outline-width":e.width,"outline-offset":e.offset,"outline-color":t}},xo=e=>({...e.border!==void 0&&yo(e.border),...e.outline!==void 0&&bo(e.outline)}),So=e=>{if(e.geometry?.kind===`boolean`||(e.appearance?.radius?.smoothing??0)<=0)return!1;let t=go(e);return t.kind===`custom`||t.kind===`native`&&t.value.style!==`solid`},Co=(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 wo(n);let r=qn(n,t),i=wo(r);if((n.smoothing??0)<=0)return i;if(So(e))return{};let a=`path("${Jn(n,t)}") border-box`,o=go(e);if(o.kind!==`native`||Object.values(R(o.value)).every(e=>e===0))return{...i,"border-shape":a};let{top:s,right:c,bottom:l,left:u}=R(o.value),d=[r.topLeft,r.topRight,r.bottomRight,r.bottomLeft],f=e=>d.map((t,n)=>`max(0px, ${String(t)}px - ${String(e[n]??0)}px)`).join(` `),p=f([u,c,c,u]),m=f([s,s,l,l]);return{...i,"border-shape":`${a} inset(0 round ${p} / ${m}) padding-box`}},wo=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}),To=new Set([re,i]),Eo=e=>e.visible&&e.kind===`blur`&&e.progression!==void 0,Do=e=>e.geometry===void 0&&To.has(e.component)?(e.appearance?.backdropFilters??[]).find(e=>Eo(e))??null:null,Oo=(e,t)=>{let n=Do(e);return n===null?t:t.filter(e=>e!==n)},ko=new Set([re,ue,i,Ce]),Ao=new Set([re,ue,i]),z=e=>e.visible&&(e.blendMode??`normal`)!==`normal`,jo=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),Mo=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`},No=e=>{if(e.component!==`rectangle`||e.geometry!==void 0||Mo(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=>!jo(e))},Po=e=>e.geometry===void 0&&ko.has(e.component)&&(e.component!==`image`||(typeof e.props?.src!=`string`||e.props.src===``)&&e.appearance?.fills!==void 0),Fo=e=>e?.visible===!0?e.paints.filter(e=>e.visible):[],Io=e=>z(e)||e.kind===`image`&&(e.filters?.some(e=>e.visible)??!1),Lo=e=>{if(!Po(e))return[];let t=(e.appearance?.fills??[]).filter(e=>e.visible);return t.some(e=>Io(e))||t.length>0&&Do(e)!==null?t:[]},Ro=e=>e.style===`solid`||e.dashOrigin===`css`&&e.dashPattern===void 0&&e.dashCap===void 0,zo=e=>{let t=Fo(e);return t.length>0&&((e.alignment??`inside`)!==`inside`||!Ro(e)||t.length>1||t.some(e=>e.kind!==`solid`))},Bo=(e,t)=>{let n=e.appearance?.border;if(n===void 0||e.geometry!==void 0||!Ao.has(e.component))return[];let r=Fo(n);return r.some(e=>z(e))?r.map(e=>({kind:`border`,paints:[e]})):n.layoutInclusion===`none`||n.layoutInclusion===`visible`||zo(n)||t&&r.length>0?[{kind:`border`,paints:r}]:[]},Vo=e=>{let[t,...n]=Fo(e.appearance?.outline);return(e.appearance?.radius?.smoothing??0)>0&&n.length===0&&t?.kind===`solid`&&!z(t)},Ho=e=>{let t=e.appearance?.outline;if(t===void 0||e.geometry!==void 0||!Ao.has(e.component)||t.width<=0||Vo(e))return[];let n=Fo(t);return n.some(e=>z(e))?n.map(e=>({kind:`outline`,paints:[e]})):n.length>1||t.style!==`solid`||n.some(e=>e.kind!==`solid`)?[{kind:`outline`,paints:n}]:[]},B=e=>{let t=Lo(e),n=Po(e)&&!No(e)?(e.appearance?.shadows??[]).filter(e=>e.visible):[],r=n.filter(e=>e.kind===`outer`&&z(e)),i=n.filter(e=>e.kind===`inner`&&(t.length>0||z(e))),a=[...r.map(e=>({kind:`outer-shadow`,shadow:e})),...t.map(e=>({kind:`fill`,paint:e})),...i.map(e=>({kind:`inner-shadow`,shadow:e}))];return{elements:[...a,...Bo(e,t.length>0),...Ho(e)],hasPaintElements:a.length>0}},Uo=e=>e.elements.flatMap(e=>e.kind===`fill`?[e.paint]:[]),Wo=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.shadow]:[]),Go=(e,t)=>e.elements.flatMap(e=>e.kind===t?[e.paints]:[]),Ko=(e,t,n={})=>e===`solid`?{dash:void 0,linecap:`butt`}:n.dashPattern===void 0?e===`dotted`?{dash:`0 ${String(t*2)}`,linecap:`round`}:{dash:`${String(t*3)} ${String(t*2)}`,linecap:`butt`}:{dash:n.dashPattern.map(String).join(` `),linecap:n.dashCap===`round`?`round`:n.dashCap===`square`?`square`:`butt`},qo={top:0,right:0,bottom:0,left:0},Jo={inside:0,center:.5,outside:1},Yo=[[`topLeft`,`top-left`,`left`,`top`],[`topRight`,`top-right`,`right`,`top`],[`bottomRight`,`bottom-right`,`right`,`bottom`],[`bottomLeft`,`bottom-left`,`left`,`bottom`]],Xo=e=>Go(B(e),`border`).length>0,Zo=(e,t=e.box)=>{if(!Xo(e))return{};let n={"border-color":`transparent`},r=e.appearance?.border,i=e.appearance?.radius;if(i===void 0||t===void 0||r?.style!==`solid`||e.geometry?.kind===`path`)return n;let a=R(r);if((i.smoothing??0)<=0||Object.values(a).every(e=>e===0))return n;let o=Jn(i,t),s=Jn(i,t,[-a.left,-a.top]);return{...n,"border-shape":`path("${o}") border-box path("${s}") padding-box`}},Qo=(e,t)=>{let n=e.appearance?.radius;return n===void 0?{"border-radius":`inherit`}:Object.fromEntries(Yo.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`]}))},$o=1e3,V=e=>String(Math.round(e*$o)/$o),es=(e,t,n)=>{let r=([n,r])=>[Math.min(n,e/2),Math.min(r,t/2)],[i,a,o,s]=[r(n.topLeft),r(n.topRight),r(n.bottomRight),r(n.bottomLeft)],c=([e,t],n,r)=>e===0||t===0?`L${V(n)} ${V(r)}`:`A${V(e)} ${V(t)} 0 0 1 ${V(n)} ${V(r)}`;return[`M${V(i[0])} 0`,`H${V(e-a[0])}`,c(a,e,a[1]),`V${V(t-o[1])}`,c(o,e-o[0],t),`H${V(s[0])}`,c(s,0,t-s[1]),`V${V(i[1])}`,c(i,i[0],0),`Z`].join(``)},ts=e=>{if(e.stroke.style===`solid`)return{};let t=Ko(e.stroke.style,e.widest,e.stroke),n=`<svg xmlns="http://www.w3.org/2000/svg" width="${V(e.width)}" height="${V(e.height)}"><path d="${es(e.width,e.height,e.corners)}" fill="none" stroke="#000" stroke-width="${V(e.widest*2)}" stroke-dasharray="${t.dash??`none`}" stroke-linecap="${t.linecap}"/></svg>`;return{"border-style":`solid`,"mask-image":`url("data:image/svg+xml,${encodeURIComponent(n)}")`,"mask-size":`100% 100%`,"mask-repeat":`no-repeat`,"mask-origin":`border-box`}},ns=(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 ts({width:n.width+r.left+r.right,height:n.height+r.top+r.bottom,corners:{topLeft:a(Yo[0]),topRight:a(Yo[1]),bottomRight:a(Yo[2]),bottomLeft:a(Yo[3])},widest:Math.max(...Object.values(t.width)),stroke:t})},rs=(e,t=e.box,n)=>{let r=e.appearance?.border,[i]=Go(B(e),`border`);if(r===void 0||i===void 0)return null;let a=n??i,o=R(r),s=Jo[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`&&Ro(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`}:Qo(e,c),...xo({...l,border:{...l.border,paints:[...a]}}),...!d&&{"border-color":`transparent`,...ro(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&&Co({...e,styles:{},additionalStyles:void 0,appearance:l},t),...!d&&ns(e,r,t,s===0?qo:c)}},is=(e,t)=>{if(No(e))return[];let n=B(e),r=[...Wo(n,`outer-shadow`),...Wo(n,`inner-shadow`)];return r.length===0?t:t.filter(e=>!r.includes(e))},as=e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${T(e.color)}`,os=e=>`${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${T(e.color)}`,ss=(e,t)=>{let n=is(e,t).filter(e=>e.visible);if(e.component===`text`){let e=n.filter(e=>e.kind===`outer`&&e.spread===0).map(e=>os(e)).join(`, `);return{"box-shadow":`none`,"text-shadow":e===``?`none`:e}}let r=n.map(e=>as(e)).join(`, `);return{"box-shadow":r===``?`none`:r}},cs=(e,t)=>{let n=e.appearance?.border,r=n===void 0?{top:0,right:0,bottom:0,left:0}:R(n);return{position:`absolute`,top:-r.top,right:-r.right,bottom:-r.bottom,left:-r.left,"border-radius":`inherit`,"pointer-events":`none`,"box-shadow":as(t),"mix-blend-mode":t.blendMode??`normal`}},ls=(e,t)=>{let n=t.map((n,r)=>{let[i=``,a,...o]=$e(n),s=ia(i),c=a===void 0?r/(t.length-1):/^\d+(?:\.\d+)?%$/u.test(a)?Number(a.slice(0,-1))/100:NaN;return s===null||o.length>0?null:{id:`${e}-stop-${String(r)}`,color:s,position:c}});return n.includes(null)?null:n.filter(e=>e!==null)},us=(e,t)=>{let n=/^(linear|radial)-gradient\((.*)\)$/su.exec(t);if(n===null)return null;let r=[...$e(n[2]??``,`,`)],i=r[0]??``,a=/^(-?(?:\d+(?:\.\d*)?|\.\d+))deg$/u.exec(i),o=/^ellipse ([\d.]+)% ([\d.]+)% at (-?[\d.]+)% (-?[\d.]+)%$/u.exec(i);if(a!==null&&n[1]!==`linear`||o!==null&&n[1]!==`radial`)return null;(a!==null||o!==null)&&r.shift();let s=r.map(e=>$e(e).length>1);if(s.some(Boolean)&&!s.every(Boolean))return null;let c=ls(e,r);if(c===null)return null;let l={id:e,visible:!0,opacity:1,stops:c},u=it.safeParse(n[1]===`linear`?{...l,kind:`linear-gradient`,angle:Number(a?.[1]??180)}:o===null?null:{...l,kind:`radial-gradient`,radius:{x:Number(o[1])/100,y:Number(o[2])/100},center:{x:Number(o[3])/100,y:Number(o[4])/100}});if(!u.success)return null;let d=u.data,f=`stops`in d?d.stops[0]:void 0;return f!==void 0&&d.kind===`linear-gradient`&&d.stops.every(e=>JSON.stringify(e.color)===JSON.stringify(f.color))?{id:e,kind:`solid`,visible:!0,opacity:1,color:f.color}:d},ds=(e,t,n,r)=>{let i=$e(e[t]??r,`,`);return i[n%i.length]??r},fs=(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=ds(n,`background-position`,r,`0% 0%`),s=ds(n,`background-size`,r,`auto`),c=ds(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}},ps=(e,t)=>{let n=t.background,r=t[`background-color`]??n,i=r===void 0||r===`none`?null:F(`${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=$e(a,`,`).map((n,r)=>{let i=`${e}-fill-${String(r)}`,a=us(i,n),o=ds(t,`background-size`,r,`auto`);if(a!==null&&![`auto`,`auto auto`,`100% 100%`].includes(o))return null;let s=a??fs(i,n,t,r),c=ve.safeParse(ds(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()]},ms=[[`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]],hs=new Set([`color`,`-webkit-text-fill-color`]),gs=(e,t)=>{let n=new Set;for(let r of t){let t=r.toLowerCase(),i=e.component===`text`;i&&hs.has(t)&&n.add(`fills`);for(let[e,r]of ms)r.test(t)&&(!i||e!==`fills`)&&n.add(e)}return[...n].filter(t=>e.appearance?.[t]!==void 0)},_s=new Set([`background`,`background-color`,`background-image`]),vs=new Set([`background-position`,`background-size`,`background-repeat`,`background-origin`,`background-blend-mode`]),ys=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(Ye(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},bs=e=>{let t=ys(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:_s};if(Object.entries(t).some(([e,t])=>!_s.has(e)&&!vs.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=ps(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(_s);for(let e of vs)i.add(e);return{kind:`native`,fills:r,owned:i}},xs=e=>({...Uo(B(e)).length>0&&{background:`none`},...Do(e)!==null&&{isolation:`isolate`}}),Ss=e=>({position:`absolute`,inset:0,...ro([e]),...e.kind===`image`&&e.filters!==void 0&&{filter:zr(e.filters)},...e.blendMode!==void 0&&e.blendMode!==`normal`&&{"mix-blend-mode":e.blendMode}}),Cs=[[`topLeft`,`top-left`],[`topRight`,`top-right`],[`bottomRight`,`bottom-right`],[`bottomLeft`,`bottom-left`]],ws=e=>Go(B(e),`outline`).length>0,Ts=e=>ws(e)?{"outline-style":`none`}:{},Es=(e,t,n)=>{let r=e.appearance?.radius;if(r===void 0)return{};let i=t.offset+t.width,a=Ko(t.style,t.width,t),o=sr(r,n,t.offset+t.width/2),s=`<svg xmlns="http://www.w3.org/2000/svg" width="${String(n.width+2*i)}" height="${String(n.height+2*i)}"><path d="${o}" transform="translate(${String(i)} ${String(i)})" fill="none" stroke="#000" stroke-width="${String(t.width)}" stroke-dasharray="${a.dash??`none`}" stroke-linecap="${a.linecap}"/></svg>`;return{"background-clip":`border-box`,"mask-image":`url("data:image/svg+xml,${encodeURIComponent(s)}")`,"mask-size":`100% 100%`,"mask-repeat":`no-repeat`,"mask-origin":`border-box`}},Ds=(e,t=e.box,n)=>{let r=e.appearance?.outline,[i]=Go(B(e),`outline`);if(r===void 0||i===void 0)return null;let a=r.offset+r.width,o=e.appearance?.radius,s=n??i,[c]=s,l=e.appearance?.border,u=l===void 0?{top:0,right:0,bottom:0,left:0}:R(l),d=e=>{let t=o?.[e]??0;return t<=0?0:t+a};return{position:`absolute`,top:-(u.top+a),right:-(u.right+a),bottom:-(u.bottom+a),left:-(u.left+a),"box-sizing":`border-box`,"pointer-events":`none`,"border-style":r.style,"border-width":r.width,"border-color":`transparent`,...Object.fromEntries(Cs.map(([e,t])=>[`border-${t}-radius`,d(e)])),...ro(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&&Es(e,r,t),...t!==void 0&&(o?.smoothing??0)<=0&&ts({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})}},Os=e=>{if(Et(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`)},ks=(e,t)=>{let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)?Math.min(1,Math.max(0,n)):t},As=e=>u.find(t=>t===e)??`normal`,js=(e,t)=>{let n=Number(String(e??``).replace(`px`,``));return Number.isFinite(n)?Math.max(t,n):0},Ms=e=>js(e,0),Ns=(e,t)=>e===0?t:e,Ps=e=>{let[t=0,n=t,r=t,i=n]=String(e[`border-radius`]??`0`).split(/\s+/u).map(e=>Ms(e));return{topLeft:Ns(Ms(e[`border-top-left-radius`]),t),topRight:Ns(Ms(e[`border-top-right-radius`]),n),bottomRight:Ns(Ms(e[`border-bottom-right-radius`]),r),bottomLeft:Ns(Ms(e[`border-bottom-left-radius`]),i)}},H=e=>{let t=$r(),n=go(e),r=_o(e),i=F(`${e.id}-fill`,String(e.styles[e.component===`text`?`color`:`background`]??``)),a=e.component===`text`?null:bs(e);return{...t,opacity:e.appearance?.opacity??ks(e.styles.opacity,1),blendMode:e.appearance?.blendMode??As(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??Ps(e.styles),...e.appearance?.retainedBorder!==void 0&&{retainedBorder:e.appearance.retainedBorder},shadows:e.appearance?.shadows??[],filters:e.appearance?.filters??[],backdropFilters:e.appearance?.backdropFilters??[]}},Fs=e=>{let t=e.appearance?.fills;return e.component===`text`&&Os(e)?{...t!==void 0&&{color:ao(t).color??`transparent`},"background-image":`none`}:t===void 0?{}:e.component===`text`?ao(t):io(t)},Is=e=>{let t=e.appearance,n={...Fs(e),...xs(e)};return(t?.opacity??ks(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,wo(t.radius),Co(e)),Object.assign(n,xo(t),Zo(e),Ts(e)),t.filters!==void 0&&(n.filter=zr(t.filters)),t.shadows!==void 0&&Object.assign(n,ss(e,t.shadows)),t.backdropFilters!==void 0&&(n[`backdrop-filter`]=zr(Oo(e,t.backdropFilters))),n)},Ls=e=>{let t=H(e).radius;return t.topLeft===0&&t.topRight===0&&t.bottomRight===0&&t.bottomLeft===0},Rs=e=>{let t=H(e);return go(e).kind!==`native`&&_o(e).kind!==`native`&&t.shadows.every(e=>!e.visible)&&t.filters.every(e=>!e.visible)&&t.backdropFilters.every(e=>!e.visible)},zs=e=>e!==void 0&&e.geometry===void 0&&(e.component===`image`||e.component===`rectangle`&&Ls(e))&&Rs(e),Bs=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},Vs=(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},Hs=(e,t)=>{let n=Vs(e,t);if(n===void 0)return null;let r=za(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=>zs(e)&&Ks(e,i)!==null)?r:null},Us=(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}},Ws=(e,t)=>{let n=Ja(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:Us(e.fit===`fit`?`fit`:`cover`,t,r)}},Gs=(e,t)=>{let n=e.props?.src;if(typeof n!=`string`||n===``)return[];let r=qa(n),i=e.props?.fit;if(i!==`cover`&&i!==`contain`)return[{image:r,box:t}];let a=Bs(e);return a===void 0?null:[{image:r,box:Us(i===`cover`?`cover`:`fit`,t,a)}]},Ks=(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 Gs(e,n);let{opacity:r}=H(e),i=[],a=H(e).fills.filter(e=>e.visible).toReversed();for(let e of a)if(e.kind===`image`){let t=Ws(e,n);if(t===null)return null;i.push(t)}else i.push({image:Ja({...e,opacity:e.opacity*r}),box:n});return i},qs=(e,t)=>t.geometry?.kind===`mask`?e.nodes[t.geometry.maskId]:void 0,Js={a:1,b:0,c:0,d:1,e:0,f:0},Ys=(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}),Xs=e=>{let{fills:t,opacity:n}=H(e);return(1-t.filter(e=>e.visible).reduce((e,t)=>e*(1-t.opacity*(t.kind===`solid`?t.color.alpha:1)),1))*n},Zs=(e,t,n)=>{let[r,i,a,o,s,c]=e.matrix,l=Ys(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}},Qs=(e,t)=>{if(t.component!==`group`||t.geometry!==void 0)return null;let n=[],r=(t,i,a)=>{if(t.visible===!1)return;let o=t.component===`group`&&t.geometry===void 0,s=o?null:Mr(t);if(s!==null&&typeof s!=`string`&&n.push(Zs(s,i,a*Xs(t))),!o&&t.component!==`frame`)return;let c=ur(t);if(c===null)return;let l=Ys(i,c),u=a*H(t).opacity;for(let n of za(e.relationships,t.id)){let t=e.nodes[n];t!==void 0&&r(t,l,u)}};return r(t,Js,1),n},$s=e=>{let t=2166136261;for(let n of e)t=Math.imul(t^(n.codePointAt(0)??0),16777619);return(t>>>0).toString(16)},ec=(e,t,n)=>{if(Hs(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]}},tc=(e,t,n)=>{let r=t.geometry,i=t.box;if(r===void 0||i===void 0||i.width<=0||i.height<=0)return null;if(r.kind===`path`||r.kind===`polygon`){let e=jr(t);if(typeof e==`string`)return null;let n=e.viewBox;return{path:e.path,fillRule:e.fillRule,matrix:[1/n.width,0,0,1/n.height,-n.x/n.width,-n.y/n.height]}}if(r.kind===`boolean`){let e=jr(t);return{path:typeof e==`string`?``:e.path,fillRule:r.result.fillRule,matrix:[1/i.width,0,0,1/i.height,0,0]}}let a=n??qs(e,t);if(a?.component===`text`&&a.visible!==!1)return ec(e,a,i);let o=a===void 0||a.visible===!1?null:Qs(e,a);if(o!==null)return{path:``,fillRule:`nonzero`,matrix:[1/i.width,0,0,1/i.height,0,0],shapes:o};let s=a===void 0||a.visible===!1?null:Mr(a);if(s===null||typeof s==`string`)return{path:``,fillRule:`nonzero`,matrix:[1,0,0,1,0,0]};let[c,l,u,d,f,p]=s.matrix;return{path:s.path,fillRule:s.fillRule,matrix:[c/i.width,l/i.height,u/i.width,d/i.height,f/i.width,p/i.height]}},nc=(e,t,n)=>{let r=tc(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(`%`,`_`)}-${$s(JSON.stringify([i,a,c,s]))}`,path:i,fillRule:a,transform:c,matrix:o,...s!==void 0&&{shapes:s}}},rc=(e,t)=>{let n=jt(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}}},ic=e=>e.startsWith(`--`)?e:e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),ac=(e,t)=>{let n=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.id,e]));for(let[e,i]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(i===null||Be.safeParse({[e]:i}).success)continue;let a=t[0]?.id??`css-${e}`.slice(0,190),o=a;for(let e=1;n.has(o);e+=1)o=`${a}-${String(e)}`;let s=p.safeParse({id:o,property:e,value:String(i),enabled:!0});if(!s.success)throw new r(`BAD_REQUEST`,`Style ${e} is not safe CSS.`,`Use a valid CSS property without imports, expressions, or executable URLs.`);n.set(o,s.data)}let i=n.values().toArray(),a=i.length===0&&e.additionalStyles===void 0?void 0:{declarations:i},o=En(e.additionalStyles,a);return o===null?null:{op:`patchAdditionalStyles`,nodeId:e.id,additionalStyles:o}},oc=(e,t,n,r)=>{let i=new Set(Object.keys(r)),a=r=>[...Ze(t,r,e),...Ze(n,r,e)],o=_(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}},sc=(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 Ze(t,a,e))(t.styles[n]!==void 0||t.additionalStyles?.declarations.some(e=>e.property===n)===!0)&&(r[n]=null)}return r},cc=(e,t,n)=>{let r=sc(e,t,n),i=ac(t,r),a=Object.fromEntries(Object.entries(r).filter(([e,t])=>Be.safeParse({[e]:t}).success)),o={...t,styles:{...t.styles},...i!==null&&{additionalStyles:Tn(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=oc(e,t,o,n),c=rc(t,r),l=gs(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:Be.parse(a)}]:[],...u,...c===null?[]:[c],...s===null?[]:[s],...i===null?[]:[i]]},lc=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=ic(e);Reflect.deleteProperty(r,n),r[n]=t}t.set(e,r)}return t},uc=(e,t)=>{let n=[...lc(t)].flatMap(([t,n])=>{let i=e.nodes[t];if(i===void 0)throw new r(`NOT_FOUND`,`Canvas node ${t} does not exist.`,`Run canvas tree and use current stable node ids.`);return cc(e,i,n)});if(n.length===0)throw new r(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return n},dc=(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=St(e.typography,{clear:[...jt(new Set([...Object.keys(t.styles),...r]))]});return U({...e,styles:n},`typography`,i??`default`)},fc=new Set([`insertNode`,`setText`,`setLabel`,`setStyles`,`setAppearance`,`setTypography`,`patchTypography`,`setLayout`,`setAdditionalStyles`,`patchAdditionalStyles`,`setParentage`]),pc=e=>fc.has(e.op),U=(e,t,n)=>{let r={...e};return n==="default"?Reflect.deleteProperty(r,t):Reflect.set(r,t,n),r},mc=(e,t)=>{switch(t.op){case`setText`:if(e.component!==`text`)throw new r(`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 dc(e,t);case`setAppearance`:{let n={...e.appearance},r=t.appearance.clear??[];for(let e of r)Reflect.deleteProperty(n,e);let i={...e,appearance:n};return Object.keys(n).length===0&&Reflect.deleteProperty(i,`appearance`),i}case`patchTypography`:return U(e,`typography`,St(e.typography,t.typography)??`default`);case`setTypography`:return U(e,`typography`,t.typography);case`setLayout`:return U(e,`layout`,t.layout);case`patchAdditionalStyles`:{let n=Tn(e.additionalStyles,t.additionalStyles);return U(e,`additionalStyles`,n??`default`)}case`setAdditionalStyles`:return U(e,`additionalStyles`,t.additionalStyles)}},hc=(e,t)=>{if(!pc(t))throw Error(`Unexpected focused edit operation: ${t.op}`);if(t.op===`insertNode`){if(e.nodes[t.node.id]!==void 0)throw new r(`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]:mc(n,t)}}},gc=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}}}},_c=(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 uc(t.scene,[{nodeIds:e.nodeIds,styles:e.styles}]);case`duplicate`:{let i=r===0?n:`${String(r+1)}_${n}`,a=Ki(t.scene,e.nodeIds.map(t=>({id:t,...e.parentId!==void 0&&{parentId:e.parentId}})),i);return t.duplicatedNodes.push(...a.duplicatedNodes),a.operations}case`move`:{let n=$i(t.scene,[gc(e)]);t.moves.push(...n.moves);for(let e of n.affectedParents)t.affectedParents.add(e.parentId);return n.operations}}},vc=(e,t,n)=>{let r={scene:e,operations:[],duplicatedNodes:[],moves:[],affectedParents:new Set},i=0;for(let e of t){let t=_c(e,r,n,i);e.kind===`duplicate`&&(i+=1);for(let e of t)r.scene=hc(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:M(r.scene,e)}))}},W=e=>{throw new r(`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.`)},yc=(e,t)=>{if(e.op===`insertNode`)return[e.parentage.parentId];if(e.op===`insertText`||e.op===`insertPrototype`)return[e.parentId,...e.afterId===void 0?[]:[e.afterId]];if(e.op===`insertConvertedSubtree`)return e.destination.kind===`adjacent`?W([`adjacent conversion`]):[e.destination.targetNodeId];if(e.op===`move`||e.op===`setParentage`){let n=e.op===`move`?e.parentId:e.parentage.parentId;return[e.nodeId,...n===t.relationships[e.nodeId]?.parentId?[]:[n],...e.op===`move`&&e.afterId!==void 0?[e.afterId]:[]]}return[e.nodeId]},bc=e=>e.op===`insertNode`?[e.node.id]:e.op===`insertText`||e.op===`insertPrototype`?[e.nodeId]:e.op===`insertConvertedSubtree`?Object.keys(e.nodes):[],xc=(e,t)=>{let n=t.destination;if(n.kind===`adjacent`)return W([`adjacent conversion`]);let r=n.kind===`replace`?e.relationships[n.targetNodeId]?.parentId:n.targetNodeId;if(r===void 0)return W([n.targetNodeId]);let i=n.kind===`insert-children`&&n.targetNodeId===`root`?n.pageId??`canvas-page-default`:_e(e,n.targetNodeId),a=t.nodes[t.rootNodeId];return a===void 0?W([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:``}}}},Sc=e=>({component:e.op===`insertText`?`text`:`prototype`,props:{...e.op===`insertPrototype`&&e.canvasPageId!==void 0&&{canvasPageId:e.canvasPageId}}}),Cc=(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]:Sc(t)},relationships:{[t.nodeId]:{parentId:t.parentId,sortKey:``}}};if(t.op===`insertConvertedSubtree`)return xc(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:{}}},wc=(e,t,n,r)=>{let i=bc(r),a=e.nodeIds.length===0&&(i.length>0||r.op===`move`||r.op===`setParentage`),o=[...yc(r,t).filter(e=>!a||e!==`root`),...i.filter(e=>t.nodes[e]!==void 0)].filter(e=>!n.has(e));return o.length>0&&W(o),i},Tc=(e,t,n)=>{if(!d(e))return;let r=new Set(Dt(e,t)),i=rt(e,t);if(!i.ok)return W(e.nodeIds);let a={nodes:{...t.nodes},relationships:{...t.relationships}};for(let t of n){let n=wc(e,a,r,t),o=Cc(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`||_e(a,e)!==i.pageId);s.length>0&&W(s);for(let e of n)r.add(e);if(t.op!==`remove`)continue;let c=rt({...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)}},Ec=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]}},Dc=(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]:Ec(e),Oc=(e,t)=>{let n=new Set(e.edits.flatMap(e=>Ec(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)l(r,t,Dc(n,t))},kc=e=>({execute:async t=>{let n=await Fi({remote:e},t.canvasId,t.baseVersion);Oc(t,n);let i=vc(n,t.edits,t.idPrefix??`copy_${t.mutationId.replaceAll(`-`,``)}`);Tc({canvasId:t.canvasId,nodeIds:t.nodeIds??[],...t.pageId!==void 0&&{pageId:t.pageId}},n,i.operations.filter(e=>`nodeId`in e&&n.nodes[e.nodeId]!==void 0));let a=v.safeParse({canvasId:t.canvasId,mutationId:t.mutationId,documentFormatVersion:13,baseVersion:t.baseVersion,operations:i.operations});if(!a.success)throw new r(`BAD_REQUEST`,`The edit contains an invalid canvas operation.`,a.error.issues[0]?.message??`Check the edit’s node references and values.`);let o=Ae.parse(await Pi(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}}}}),Ac=(e,t)=>{let n=e.find(e=>e.id===t);if(n===void 0)throw TypeError(`${t} is missing from the capability catalogue`);return n},G=(e,t,n,i=48e3)=>{if(t>e.length)throw new r(`BAD_REQUEST`,`The result page offset is out of range.`,`Restart pagination at offset 0.`);let a=[],o=2,s=e.slice(t,t+n);for(let e of s){let t=Buffer.byteLength(JSON.stringify(e))+1;if(a.length>0&&o+t>i)break;a.push(e),o+=t}let c=t+a.length;return{entries:a,total:e.length,offset:t,nextOffset:c<e.length?c:null,complete:c===e.length}},jc=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}))]:[],Mc=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,Nc=(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:Mc(e),failure:e.failure,details:G(jc(e),t.offset,t.limit),warnings:e.state===`succeeded`?[`This receipt does not verify visual fidelity. Render the committed root to inspect it.`]:[]}),K=e=>new r(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),Pc=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Fc=e=>{let t=e.failure;return new r(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})},Ic=async(t,n)=>{let r=e.safeParse(await t.query(`canvas.render.getImport`,{jobId:n}));if(!r.success)throw K(`conversion status`);if(r.data.job.id!==n)throw K(`conversion identity`);return r.data.job},Lc=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 Pc(250),i=await Ic(e,i.id)}if(i.state!==`succeeded`)throw Fc(i);return i},Rc=(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},zc=(e,t)=>{let n=t.request;if(e.canvasId!==n.canvasId||e.requestedVersion!==n.expectedVersion||!Rc(e,t))throw K(`conversion destination or revision`);let r=e.source;if(r.kind!==n.source.kind||r.kind===`screen`&&n.source.kind===`screen`&&r.nodeId!==n.source.nodeId||r.kind===`html`&&n.source.kind===`html`&&r.label!==n.source.label)throw K(`conversion source`);if(e.state===`succeeded`&&(e.result.canvasId!==n.canvasId||n.revisionPolicy===`strict`&&e.result.previousVersion!==n.expectedVersion))throw K(`conversion commitment`)},Bc=async(e,t)=>{let n=xe.safeParse(await e.mutate(`canvas.render.importSource`,t.request));if(!n.success)throw K(`conversion creation`);zc(n.data.job,t);let r=await Lc(e,n.data.job,t.waitMs);return zc(r,t),r},Vc=async(e,t)=>{let n=Nt.parse(t),r=y(n.canvasRef);return Nc(await Bc(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})},Hc=(e,t,n)=>({state:`failed`,mutationCommitted:!0,requestedVersion:n,...e instanceof r?{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.`]}),Uc=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 Hc(e,t,n.result.version)}},Wc=async(e,t)=>{let n=await Fi({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??``}})},Gc=(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}),Kc=e=>({state:`pending`,canvasId:e.canvasId,jobId:e.id,phase:e.phase,status:{tool:`capability_query`,arguments:{capability:`canvas.render.getImport`,input:{jobId:e.id}}},next:[`Read the existing import status; do not start another import.`]}),qc=e=>({waitMs:e.renderTimeoutMs,request:{canvasId:e.canvasId,expectedVersion:e.baseVersion,...e.revisionPolicy!==void 0&&{revisionPolicy:e.revisionPolicy},...(e.pageId!==void 0||(e.selectionNodeIds?.length??0)>0)&&{scope:{pageId:e.pageId,nodeIds:[...e.selectionNodeIds??[]]}},source:{kind:`html`,html:e.html,label:`Agent-authored HTML`,...e.idPrefix!==void 0&&{idPrefix:e.idPrefix}},destination:{kind:e.mode,targetNodeId:e.targetNodeId,...e.mode===`insert-children`&&e.pageId!==void 0&&{pageId:e.pageId}}}}),Jc=(e,t)=>({execute:async n=>{let r=await Ti(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await Bc(e,qc(n));if(n.responseMode===`bounded`)return Nc(i,{offset:0,limit:40});if(i.state!==`succeeded`)return Kc(i);if(n.review===`none`)return Gc(n,i);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await Uc(t,n,i),o=[];try{o=await Wc(e,i)}catch{o=[]}return{...Gc(n,i),createdNodes:o,review:a,next:[`Inspect the review PNG before continuing.`]}}finally{await r?.finish()}}}),Yc=async(e,t)=>{let n=y(t.canvas),i=ae.parse(await e.query(`canvas.document.get`,{canvasId:n.canvasId})),a=qe.parse(i.document);d(n)&&Dt(n,a),t.nodeId!==void 0&&l(n,a,[t.nodeId]);let o=rt(t.nodeId===void 0?n:{...n,nodeIds:[t.nodeId]},a);if(!o.ok)throw new r(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link. Do not broaden the request.`);let s=Object.groupBy(Object.entries(a.relationships),([,e])=>e.parentId),c=Object.values(a.nodes).filter(e=>o.nodeIds.has(e.id)).map(e=>({...e,kind:e.component,parentId:a.relationships[e.id]?.parentId??null,children:(s[e.id]??[]).map(([e])=>e)}));return{canvasId:n.canvasId,version:i.version,pageId:o.pageId,source:n.nodeIds.length>0?`selection-link`:n.pageId===void 0?`canvas-link`:`page-link`,selectedNodeIds:n.nodeIds,rootNodeIds:o.rootNodeIds,nodeCount:c.length,nodes:c,next:[`Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants.`]}},Xc=(e,t,n)=>{try{Gt(e,t,{flag:n?`w`:`wx`,mode:384}),Bt(e,384)}catch(t){let n=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new r(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.`)}},Zc=e=>({write:t=>{if(t.outputPath!==null){let e=C.resolve(t.outputPath);return Xc(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=C.join(e,`sensitive`);Wt(n,{recursive:!0,mode:448}),Bt(n,448);let r=C.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return Xc(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),Qc=[`canvas.asset.reserve`,`canvas.asset.complete`,`canvas.document.get`],$c=(e,t)=>new r(e instanceof r?e.code:`INTERNAL`,e instanceof r?e.message:`The asset import did not return a confirmed result.`,e instanceof r?e.remediation:`Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.`,{...e instanceof r&&e.fields,operation:JSON.stringify(t),outcome:`not_confirmed`}),el=(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 r(`INTERNAL`,`The returned asset does not match this import intent.`,`Check the API and CLI versions. Do not insert an unverified resource.`)},tl=(e,t)=>({execute:async n=>{let i=y(n.canvasRef);if(d(i)){let t=ae.parse(await e.query(Qc[2],{canvasId:i.canvasId}));Dt(i,qe.parse(t.document))}let{body:a,...o}=await t.read(),s=Ct.parse({...o,canvasId:i.canvasId,clientToken:n.clientToken}),c={kind:`canvas-asset`,canvasId:i.canvasId,clientToken:n.clientToken};try{let t=Mt.parse(await e.mutate(Qc[0],s));el(t,s),t.upload!==null&&await e.upload({...t.upload,body:a});let o=Ve.parse(await e.mutate(Qc[1],{canvasId:i.canvasId,clientToken:n.clientToken}));if(el(o,s),o.assetId!==t.assetId||o.path!==t.path)throw new r(`INTERNAL`,`The completed asset identity changed.`,`Read operation_status and do not place an unconfirmed resource.`);return fe.parse({operation:c,resource:o,placement:`not_requested`})}catch(e){throw $c(e,c)}}}),nl=15e3,rl=async e=>new Promise(t=>setTimeout(t,e)),il=new Set([`ready`,`failed`,`abandoned`]),al=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`],ol=e=>new r(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,`Check the existing deployment status before retrying with the same publication token.`),sl=async(e,t,n,r)=>{let i=Me.safeParse(await e.mutate(al[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 ol(`artifact creation`);if(r(i.data.deploymentId),i.data.state===`uploading`&&await e.upload({url:i.data.upload.url,headers:i.data.upload.headers,body:n.open()}),i.data.state===`uploading`||i.data.state===`queued`){let n=mt.safeParse(await e.mutate(al[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId}));if(!n.success||n.data.deploymentId!==i.data.deploymentId)throw ol(`artifact submission`)}return i.data},cl=async(e,t,n,r)=>{let i=je.safeParse(await e.query(al[0],{}));if(!i.success)throw ol(`capabilities`);let a=await t.package({entryPath:n.entryPath,limits:i.data.limits});try{return await sl(e,n,a,r)}finally{await a.dispose()}},ll=async(e,t,n)=>{let i=new AbortController,a=Promise.withResolvers(),o=setTimeout(()=>{i.abort(),a.reject(new r(`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(al[3],t,{signal:i.signal}),a.promise]),r=Fe.safeParse(n);if(!r.success||r.data.deploymentId!==t.deploymentId)throw ol(`status`);return r.data}finally{clearTimeout(o)}},ul=async(e,t,n)=>{let i=performance.now()+n,a=50,o=await ll(e,t,n>0?Math.min(nl,n):nl);for(;!il.has(o.state);){let n=i-performance.now();if(n<=0)return o;await rl(Math.min(a,n)),a=Math.min(a*2,1e3);let s=i-performance.now();if(s<=0)return o;try{o=await ll(e,t,Math.min(nl,s))}catch(e){if(e instanceof r&&e.fields?.reason===`STATUS_TIMEOUT`)return o;throw e}}return o},dl=[`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`],fl=e=>{let t=e.failure,n=dl.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.`}}},pl=e=>e.unavailableFiles?.map(e=>`Unavailable published file: ${e.path} (${e.code}).`)??[],ml=[`prototype.getArtifactCapabilities`,`prototype.attach`],hl=new Set([`BAD_REQUEST`,`FORBIDDEN`,`UNAUTHORIZED`,`NOT_FOUND`]),gl=async e=>{let t=je.safeParse(await e.query(ml[0],{}));if(!t.success||t.data.attachmentProtocolVersion!==1)throw new r(`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.`)},_l=e=>e instanceof r?{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.`},vl=async(e,t,n)=>{let r=y(t.canvasRef),i=a.safeParse(await e.mutate(ml[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 o=i.data,s=o.attachment;if(s===void 0||o.canvasId!==r.canvasId||o.deploymentId!==n.deploymentId||o.prototypeId!==n.prototypeId||o.nodeId!==n.nodeId||o.version!==s.version||s.outcome===`committed`&&(s.mutationId!==t.clientToken||s.version!==s.previousVersion+1)||s.outcome===`no_op`&&s.version!==t.baseVersion)throw Error(`Unconfirmed prototype attachment receipt`);return{...o,attachment:s}},yl=async(e,t,n,r)=>{try{let i=await vl(e,t,r);return{...n,attachmentStatus:i.attachment.outcome,attachment:i,nextAction:`inspect_result`}}catch(e){let t=_l(e),r=t.code===`CONFLICT`,i=hl.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.`]}}},bl=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:pl(r)};if(r.state===`failed`){let{nextAction:e,failure:t}=fl(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`?yl(e,t,i,r):i},xl=(e,t)=>({execute:async n=>{let i=y(n.canvasRef);await gl(e);let a=n.source.kind===`deployment`?n.source.deploymentId:null;try{if(n.source.kind===`build`&&(a=(await cl(e,t,{...n.source,canvasId:i.canvasId,...i.pageId!==void 0&&{canvasPageId:i.pageId},clientToken:n.clientToken},e=>{a=e})).deploymentId),a===null)throw Error(`Publication has no deployment`);let r=await ul(e,{canvasId:i.canvasId,deploymentId:a},n.waitMs);return await bl(e,n,i.canvasId,r)}catch(e){if(a===null)throw e;return{operation:{kind:`prototype-deployment`,canvasId:i.canvasId,deploymentId:a},deploymentStatus:`unknown`,publication:null,attachmentStatus:`not_attempted`,attachment:null,failure:_l(e),nextAction:e instanceof r&&(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.`]}}}}),Sl=[`prototype.attach`],Cl=e=>new r(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),wl=e=>{if(e.state===`failed`){let t=fl(e);throw new r(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 r(`NOT_FOUND`,`Prototype deployment ${e.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);if(e.state!==`ready`)throw new r(`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})},Tl=async(e,t,n)=>{let i={deploymentId:null};try{let r=await cl(e,t,n,e=>{i.deploymentId=e}),o=await ul(e,{canvasId:n.canvasId,deploymentId:r.deploymentId},3e5);wl(o);let s=a.safeParse(await e.mutate(Sl[0],{canvasId:n.canvasId,deploymentId:r.deploymentId,baseVersion:n.baseVersion}));if(!s.success)throw Cl(`attachment`);return{...s.data,fileCount:o.fileCount,totalBytes:o.totalBytes,alreadyExists:r.alreadyExists,warnings:pl(o),next:[s.data.canvasUrl??s.data.openUrl,`enhance canvas render --canvas ${n.canvasId} --node-id ${s.data.nodeId} --expected-version ${String(s.data.version)}`]}}catch(e){throw e instanceof r&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||i.deploymentId===null?e:new at(e instanceof r?e.message:`Prototype deployment ${i.deploymentId} has no confirmed completion.`,`${e instanceof r?`${e.remediation} `:``}Retry 'enhance prototype publish' with the same --client-token ${n.clientToken}.`,{code:e instanceof r?e.code:`INTERNAL`,fields:{...e instanceof r&&e.fields,canvasId:n.canvasId,deploymentId:i.deploymentId,clientToken:n.clientToken}})}},El=(e,t)=>({execute:async n=>Tl(e,t,n)}),Dl=(e,t)=>{if(e.id!==t.jobId||e.canvasId!==t.canvasId)throw new r(`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.`]}},Ol=async(e,t)=>{let{job:n}=h.parse(await e.query(`canvas.render.preparation.get`,{jobId:t.jobId}));return Dl(n,t)},kl=(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:[]}},Al=async(e,t,n)=>{if(n.kind!==`canvas-render`||n.state!==`succeeded`)return n;try{let{job:r}=_t.parse(await e.query(`canvas.render.get`,{jobId:n.operation.jobId}));return r.id!==n.operation.jobId||r.canvasId!==n.operation.canvasId||r.state!==`succeeded`?{...n,warnings:[`The stored result is unavailable for image delivery. Read this operation again.`]}:{status:n,localImage:await di(e,t,r,{at:new Date,outputPath:null,overwrite:!1})}}catch{return{...n,warnings:[`The render completed, but its image could not be delivered. Check access and artifact expiry before retrying this operation reference.`]}}},jl=[`canvas.mutation.get`,`canvas.render.get`,`canvas.render.getImport`,`prototype.getPublishStatus`,`canvas.asset.get`],Ml=(e,t)=>{if(e!==t)throw new r(`NOT_FOUND`,`The operation does not belong to this canvas.`,`Use the operation reference returned by the original action.`)},Nl=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`}))],Pl=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,a=Pe.parse(await e.query(jl[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:kl(a.result,n.fingerprint),affected:G(Nl(a.result),r,i)}},Fl=async(e,t)=>{let{operation:n,offset:r,limit:i}=t,{job:a}=_t.parse(await e.query(jl[1],{jobId:n.jobId}));Ml(a.canvasId,n.canvasId);let o=a.result===null?null:Il(a.result);return{kind:`canvas-render`,operation:n,state:a.state,phase:a.phase,requestedVersion:a.requestedVersion,attempt:a.attempt,target:a.target,sourceState:a.sourceState??null,evidence:o,details:G(Ll(a),r,i),failure:a.failure,pixelsDelivered:!1,warnings:[`Status reports stored render evidence. It does not deliver or inspect the image.`]}},Il=e=>{let{warnings:t,timings:n,...r}=e;return{...r,warningCount:t.length,timingCount:n.length}},Ll=e=>e.result===null?[]:[...e.result.warnings.map(e=>({kind:`warning`,warning:e})),...e.result.timings.map(e=>({kind:`timing`,timing:e}))],Rl=async(e,t)=>{let n=Ve.parse(await e.query(jl[4],{canvasId:t.canvasId,clientToken:t.clientToken}));if(Ml(n.canvasId,t.canvasId),n.clientToken!==t.clientToken)throw new r(`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`}},zl=async(t,n)=>{let{operation:r,offset:i,limit:a}=n;switch(r.kind){case`canvas-asset`:return G([],i,a),Rl(t,r);case`canvas-mutation`:return Pl(t,{...n,operation:r});case`canvas-preparation`:{let e=await Pl(t,{...n,operation:{kind:`canvas-mutation`,canvasId:r.canvasId,mutationId:r.mutationId,fingerprint:r.fingerprint}});return e.kind===`canvas-mutation`&&e.state===`committed`?e:Ol(t,r)}case`canvas-render`:return Fl(t,{...n,operation:r});case`canvas-conversion`:{let{job:n}=e.parse(await t.query(jl[2],{jobId:r.jobId}));return Ml(n.canvasId,r.canvasId),Nc(n,{offset:i,limit:a})}case`prototype-deployment`:return G([],i,a),{kind:`prototype-deployment`,operation:r,publication:Fe.parse(await t.query(jl[3],{canvasId:r.canvasId,deploymentId:r.deploymentId})),attachment:`not_checked`,warnings:[`Publication readiness does not establish canvas attachment or successful interactive verification.`]}}},Bl=(e,t)=>({execute:async n=>{let r=await zl(e,n);return t!==void 0&&n.includeImage?Al(e,t,r):r}}),Vl=[`transcript.get`],Hl=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),Ul=e=>({execute:async t=>{let n=nt.safeParse(await e.query(Vl[0],t));if(!n.success)throw new r(`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:Hl(t.canvasId,t.recordingId,n.data.cues.map(e=>e.startMs))}:n.data}}),Wl=[`canvas.render.get`,`canvas.render.snapshot`],Gl=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Kl=e=>new r(e.failure?.reason===`VERSION_CHANGED`?`CONFLICT`:e.failure?.reason===`TARGET_NOT_FOUND`?`NOT_FOUND`:e.failure?.reason===`TARGET_INVALID`||e.failure?.reason===`OUTPUT_TOO_LARGE`?`BAD_REQUEST`:`INTERNAL`,e.failure?.message??`The snapshot job ended without a result.`,`Run 'enhance canvas tree --canvas ${e.canvasId}' and retry the exact snapshot if its recording node still exists.`,{jobId:e.id,phase:e.phase}),ql=async(e,t)=>{let n=_t.safeParse(await e.query(Wl[0],{jobId:t}));if(!n.success)throw new r(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return n.data.job},Jl=async(e,t,n,i)=>{let a=Date.now()+n.timeoutMs,o=Date.now(),s=t,c=0,l=``;for(;s.state===`queued`||s.state===`running`;){let u=Date.now(),d=`${s.state}:${s.phase}`;if((d!==l||u-c>=5e3)&&(i({event:`snapshot.progress`,jobId:s.id,state:s.state,phase:s.phase,elapsedMs:u-o,timeoutMs:n.timeoutMs,retryClientToken:n.retryClientToken}),c=u,l=d),u>=a){if(n.bounded===!0)return s;throw new r(`INTERNAL`,`Snapshot ${s.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${n.retryClientToken} and a larger --timeout-ms.`,{jobId:s.id,phase:s.phase})}await Gl();let f=await ql(e,s.id);if(f.id!==t.id)throw Yl();Xl(f,n),s=f}return s},Yl=()=>new r(`INTERNAL`,`The snapshot response does not match the requested source or revision.`,`Run enhance doctor and report the capture job ID.`),Xl=(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 Yl();if(e.state!==`succeeded`)return;let n=e.result.snapshot,r=e.result.sourceState;if(e.result.canvasId!==t.canvasId||e.result.loadedVersion!==e.requestedVersion||e.result.requestedVersion!==e.requestedVersion||r?.recordingId!==t.recordingId||r.requestedAtMs!==t.atMs||r.settledAtMs!==t.atMs||n?.recordingId!==t.recordingId||n.atMs!==t.atMs||n.screenId!==e.id||n.screenNodeId!==`scr_${t.recordingId}_${String(t.atMs)}`||t.context!==void 0&&n.version!==t.context.expectedVersion+1)throw Yl()},Zl=(e,t)=>({operation:{kind:`canvas-render`,canvasId:e.canvasId,jobId:e.id},state:e.state,requestedVersion:e.requestedVersion,source:{kind:`recording`,recordingId:t.recordingId,atMs:t.atMs},attachment:e.state===`succeeded`?`committed`:e.state===`queued`||e.state===`running`?`pending`:`not_confirmed`,result:e.result?.snapshot??null,failure:e.failure,warningCount:e.result?.warnings.length??0,warnings:[e.state===`succeeded`?`The durable screen is attached. Render the returned node at its committed version to verify placement; use operation_status for source warnings.`:`Follow operation_status for this job. An incomplete job is not proof of attachment or proof that no durable screen was created.`]}),Ql=async(e,t,n)=>{let r=Pt.parse(t),i=y(r.canvasRef);return eu(e,()=>null).execute({canvasId:i.canvasId,recordingId:r.source.recordingId,atMs:r.source.atMs,retryClientToken:n,timeoutMs:r.waitMs,bounded:!0,context:{expectedVersion:r.baseVersion,request:{previewJobId:r.previewJobId,scope:{pageId:i.pageId,nodeIds:[...i.nodeIds]},placement:r.placement}}})},$l=async(e,t,n)=>{let i=Ue.safeParse(await e.mutate(Wl[1],{canvasId:n.canvasId,recordingId:n.recordingId,atMs:n.atMs,...n.context!==void 0&&{context:n.context}}));if(!i.success)throw new r(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");Xl(i.data.job,n);let a=await Jl(e,i.data.job,n,t);if(n.bounded===!0)return Zl(a,n);if(a.state!==`succeeded`||a.result.snapshot===void 0)throw Kl(a);let o={...a,result:{...a.result,snapshot:a.result.snapshot}},s=o.result.snapshot;return{jobId:o.id,canvasId:o.canvasId,...s,warnings:o.result.warnings,retryClientToken:n.retryClientToken,next:[`enhance canvas node --canvas ${o.canvasId} --node-id ${s.screenNodeId}`,`enhance canvas render --canvas ${o.canvasId} --node-id ${s.screenNodeId} --expected-version ${String(s.version)}`]}},eu=(e,t)=>({execute:async n=>$l(e,t,n)}),tu={".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`},nu=()=>new r(`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.`),ru=async e=>{let t=tu[C.extname(e).toLowerCase()];if(t===void 0)throw nu();let n=await $t(e,Vt.O_RDONLY|Vt.O_NONBLOCK);try{let e=await n.stat();if(!e.isFile()||e.size===0)throw nu();let i=Buffer.alloc(e.size+1),a=0;for(;a<i.byteLength;){let e=await n.read(i,a,i.byteLength-a,a);if(e.bytesRead===0)break;a+=e.bytesRead}if(a!==e.size)throw new r(`CONFLICT`,`The selected asset changed while it was being read.`,`Finish writing the file, then retry the unchanged import intent.`);let o=i.subarray(0,a);return{body:o,kind:t.startsWith(`image/`)?`image`:`font`,contentType:t,bytes:a,sha256:w(`sha256`).update(o).digest(`hex`)}}finally{await n.close()}},iu=e=>({read:async()=>{try{return await ru(e)}catch(e){throw e instanceof r?e:new r(`BAD_REQUEST`,`The selected asset file cannot be read.`,`Choose an existing readable image or font file on this computer.`)}}}),au=[`canvas.list`,`organisation.list`],ou=async(e,t)=>{let[n,r]=await Promise.all([e.query(au[0],{collection:t.collection,...t.title!==void 0&&{title:t.title},scope:`all`,deleted:!1,hasUnresolved:!1}),t.includeDestinations?e.query(au[1],{}):{items:[],truncated:!1}]),i=me.parse(n),a=Se.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}}},su=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},cu=e=>({execute:async t=>{let{items:n,sourceTruncated:i}=await ou(e,t),{cursor:a,...s}=t,c=b(s),l=b({items:n,sourceTruncated:i}),u=a===void 0?null:o(a,ct);if(u!==null&&u.queryDigest!==c)throw new r(`BAD_REQUEST`,`This cursor belongs to another canvas search.`,`Restart discovery with the requested query.`);if(u!==null&&u.snapshotDigest!==l)throw new r(`CONFLICT`,`The accessible canvases or destinations changed between pages.`,`Restart discovery so results are not silently skipped or combined across permissions.`);let d=u?.offset??0;if(d>n.length)throw new r(`BAD_REQUEST`,`The discovery cursor is out of range.`,`Restart discovery.`);let f=su(n.slice(d,d+t.limit)),p=d+f.length,m=p<n.length,h=i.canvases||i.destinations;return{items:f,returnedCount:f.length,totalAvailable:n.length,complete:!m&&!h,sourceTruncated:i,nextCursor:m?wt({protocol:`enhance-canvas-find/1`,queryDigest:c,snapshotDigest:l,offset:p}):null,warnings:h?[`The source collection reached its existing limit. Refine the title or team; these results are not a complete inventory.`]:[]}}}),lu=async(e,t)=>{try{return{value:await e.query(`canvas.render.preparation.get`,{jobId:t})}}catch(e){if(e instanceof r&&![`INTERNAL`,`RATE_LIMITED`].includes(e.code))throw e;return null}},uu=async(e,t,n)=>{let i=Date.now()+n,a=t;for(;a.state===`queued`||a.state===`running`;){let n=i-Date.now();if(n<=0)break;await Jt(Math.min(250,n));let o=await lu(e,t.id);if(o===null)return a;if(a=h.parse(o.value).job,a.id!==t.id)throw new r(`INTERNAL`,`Preparation identity changed.`,`Retry the original request.`)}return a},du=async(e,t,n)=>{let i=ye.parse(await e.mutate(`canvas.render.preparation.create`,t)),a=await uu(e,i.job,n);if(a.canvasId!==t.canvasId||a.requestedVersion!==t.expectedVersion||!cn(a.scope,t.scope)||!cn(a.request,t.request))throw new r(`CONFLICT`,`The native preparation does not match this request.`,`Read the canvas and prepare a new intent; do not apply this plan.`);if(a.state===`succeeded`&&a.result.loadedVersion!==t.expectedVersion)throw new r(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);return a},fu=async(e,t)=>{try{return Ae.parse(await Pi(e).execute(t))}catch(e){throw new r(e instanceof r?e.code:`INTERNAL`,e instanceof r?e.message:`The canvas commit could not be confirmed.`,`Read operation_status or repeat the original action with identical arguments and clientToken.`,{...e instanceof r&&e.fields,outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:t.canvasId,mutationId:t.mutationId,fingerprint:t.requestContext?.fingerprint})})}},pu=async(e,t,n,i)=>{if(n.result.loadedVersion!==t.baseVersion)throw new r(`CONFLICT`,`The native preparation measured a different revision.`,`Read the canvas and prepare a new intent.`);if(n.result.operations.length===0)return{outcome:`no_op`,canvasId:n.canvasId,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let a=v.parse({canvasId:n.canvasId,mutationId:t.clientToken,documentFormatVersion:13,baseVersion:t.baseVersion,operations:n.result.operations,requestContext:{fingerprint:i,revisionPolicy:`strict`,...t.request.kind===`duplicate`&&{copiedNodeIds:n.result.idMap}}}),o=await fu(e,a);if(o.canvasId!==n.canvasId||o.mutationId!==t.clientToken||o.previousVersion!==t.baseVersion||o.version!==t.baseVersion+1||t.request.kind===`duplicate`&&!cn(o.copiedNodeIds,n.result.idMap))throw new r(`INTERNAL`,`The canvas commit receipt could not be verified.`,`Check operation_status using the original mutation reference before retrying.`,{outcome:`not_confirmed`,operation:JSON.stringify({kind:`canvas-mutation`,canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:i})});return kl(o,i)},mu=e=>({execute:async t=>{let n=y(t.canvasRef),r={...n.pageId!==void 0&&{pageId:n.pageId},nodeIds:[...n.nodeIds]},i=b({operation:`canvas.prepare/1`,reference:n,baseVersion:t.baseVersion,request:t.request}),a=Pe.parse(await e.query(`canvas.mutation.get`,{canvasId:n.canvasId,mutationId:t.clientToken,fingerprint:i}));if(a.state===`committed`)return kl(a.result,i);let o=await du(e,{canvasId:n.canvasId,expectedVersion:t.baseVersion,request:t.request,scope:r},t.waitMs),s={kind:`canvas-preparation`,canvasId:n.canvasId,jobId:o.id,mutationId:t.clientToken,fingerprint:i};return o.state===`succeeded`?pu(e,t,o,i):Dl(o,s)}}),hu=/^[MLHVCSQTAZ]$/iu,gu=/[MLHVCSQTAZ]|[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/giu,_u={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},vu=e=>{let t=e.match(gu)??[];if(t.join(``)!==e.replaceAll(/[\s,]/gu,``))return null;let n=[],r=``,i=0;for(;i<t.length;){let e=t[i]??``;if(hu.test(e))r=e,i+=1;else if(r===``||r.toUpperCase()===`Z`)return null;let a=_u[r.toUpperCase()]??0,o=t.slice(i,i+a).map(Number);if(o.length!==a||o.some(e=>!Number.isFinite(e)))return null;i+=a,n.push({command:r,values:o}),r.toUpperCase()===`M`&&(r=r===`M`?`L`:`l`)}return n},q=([e,t,n,r,i,a],{x:o,y:s})=>({x:e*o+n*s+i,y:t*o+r*s+a}),yu=e=>`${String(e.x)} ${String(e.y)}`,bu=Math.PI/2,xu=Math.PI*2,Su=(e,t,n,r)=>Math.atan2(e*r-t*n,e*n+t*r),Cu=(e,t,n)=>{let[r=0,i=0,a=0,o=0,s=0]=t,c=a*Math.PI/180,[l,u]=[Math.cos(c),Math.sin(c)],[d,f]=[(e.x-n.x)/2,(e.y-n.y)/2],[p,m]=[l*d+u*f,-u*d+l*f],h=Math.max(1,Math.hypot(p/r,m/i)),[g,_]=[Math.abs(r)*h,Math.abs(i)*h],ee=g*g*m*m+_*_*p*p,te=(o===s?-1:1)*Math.sqrt(Math.max(0,(g*g*_*_-ee)/ee)),[v,ne]=[te*g*m/_,-te*_*p/g],[re,ie,ae,oe]=[(p-v)/g,(m-ne)/_,(-p-v)/g,(-m-ne)/_],se=Su(re,ie,ae,oe);return s===0&&se>0&&(se-=xu),s===1&&se<0&&(se+=xu),{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:Su(1,0,re,ie),turn:se}},wu=(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}=Cu(e,t,n),c=Math.ceil(Math.abs(s)/bu-1e-9),l=s/c,u=4/3*Math.tan(l/4),d=(e,t)=>({x:Math.cos(e)-Math.sin(e)*t,y:Math.sin(e)+Math.cos(e)*t}),f=[];for(let e=0;e<c;e+=1){let[t,r]=[o+l*e,o+l*(e+1)];f.push(q(a,d(t,u)),q(a,d(r,-u)),e===c-1?n:q(a,d(r,0)))}return f},Tu=(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=wu(a,e.values,r),s=[];for(let e=0;e<i.length;e+=3)s.push(`C${i.slice(e,e+3).map(e=>yu(q(n,e))).join(` `)}`);return{data:s.join(``),pen:{...t,current:r}}}if(r===`H`||r===`V`){let e=r===`H`?o(s,i?0:a.y):o(i?0:a.x,s);return{data:`L${yu(q(n,e))}`,pen:{...t,current:e}}}let c=[];for(let t=0;t<e.values.length;t+=2)c.push(o(e.values[t],e.values[t+1]));let l=c.at(-1)??a;return{data:`${r}${c.map(e=>yu(q(n,e))).join(` `)}`,pen:{current:l,start:r===`M`?l:t.start}}},Eu=(e,t)=>{let n=vu(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=Tu(e,i,t);r.push(n.data),i=n.pen}return r.join(``)},Du=(e,t)=>{let n=e.geometry;if(n?.kind!==`mask`||n.mode===`outline`||t?.box===void 0||t.component===`text`)return{};let r=H(t).opacity,i=H(t).fills.filter(e=>e.visible).toReversed().map(e=>Ja({...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`)}},Ou=(e,t)=>{let n=t.geometry?.kind===`mask`?nc(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=Eu(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}")`}},ku=new Set([`data-enhance-id`,`data-enhance-locked`,`data-enhance-name`,`data-enhance-opaque`,`style`]),J=e=>{throw new r(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},Y=e=>{let t=un(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,ln(e.value))}),Object.fromEntries(n)},Au=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.`)),ju=e=>{let t=dn(e,{sourceCodeLocationInfo:!0,onParseError:e=>J(`Invalid HTML at line ${String(e.startLine)}: ${e.code}.`)}),n=[t];for(;n.length>0;){let e=n.pop();if(e===void 0)break;e.childNodes=e.childNodes.filter(e=>!(`tagName`in e)||Ur(e.tagName));let t=e.childNodes.filter(e=>`tagName`in e);for(let e of t)e.attrs=e.attrs.filter(e=>Gr(e.name,e.value)),n.push(e)}return t},Mu=new Set([...ku,`viewBox`,`preserveAspectRatio`]),Nu=(e,t)=>{let[n,...r]=Au(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}},Pu=e=>{let t=e.tagName===`svg`?Mu:ku;return Object.fromEntries(e.attrs.map(e=>!t.has(e.name)||e.namespace!==void 0?J(`Unsupported attribute: ${e.name}.`):[e.name,e.value]))},Fu=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??``)}},Iu=e=>{let t=[],n=[];for(let r of Au(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]},Lu=(e,t)=>Au(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:Ru(e,t),styles:Y(i)}}),Ru=(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(``),zu=e=>{let t=ju(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=Pu(e),i=Fu(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:Nu(e,t.viewBox??``),text:``,children:[]};let a=e.tagName===`span`&&e.childNodes.some(e=>`tagName`in e),[o,s]=e.tagName===`span`?[[],[]]:Iu(e);return{...i,tag:e.tagName,...a&&{runs:Lu(e,i.id)},...o.length>0&&{paints:o},text:!a&&e.tagName===`span`?Ru(e,i.id):``,children:s.map(e=>r(e))}},i=Au(t.childNodes),a=i[0];return a===void 0||i.length!==1?J(`An editable update must contain exactly its original root.`):r(a)},Bu=e=>{throw new r(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Vu={fill:`100% 100%`,cover:`cover`,contain:`contain`,"scale-down":`contain`,none:`auto`},Hu={"100% 100%":`fill`,cover:`cover`,contain:`contain`,auto:`none`},Uu=/^background(?:-.+)?$/u,Wu=/^url\((?:"([^"]*)"|'([^']*)'|([^"'()\s]*))\)$/u,Gu=e=>{if(e.component!==`image`)return;let t=e.props?.src;return typeof t==`string`&&t!==``?t:void 0},Ku=e=>{let t=Gu(e);if(t===void 0)return{};let n=e.props?.fit,r=e.props?.position;return{"background-image":`url(${JSON.stringify(t)})`,"background-size":Vu[typeof n==`string`?n:`fill`]??`100% 100%`,"background-position":typeof r==`string`?r:`50% 50%`,"background-repeat":`no-repeat`}},qu=(e,t)=>Gu(e)!==void 0&&Uu.test(t),Ju=(e,t,n)=>{if(Gu(e)===void 0)return[];let r=[...new Set([...Object.keys(t),...Object.keys(n)])].filter(e=>Uu.test(e)&&t[e]!==n[e]);if(r.length===0)return[];if(r.some(e=>![`background-image`,`background-size`,`background-position`].includes(e)))return Bu(`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=Wu.exec(n[`background-image`]??``),a=i?.[1]??i?.[2]??i?.[3],o=Hu[n[`background-size`]??``],s=n[`background-position`];return a===void 0||a===``||o===void 0||s===void 0?Bu(`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 r(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Yu={border:/^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u,outline:/^outline(?:-.+)?$/u,paint:/^$/u},Xu=e=>Object.fromEntries(Object.entries(Y(e)).toSorted(([e],[t])=>e.localeCompare(t))),Zu=e=>Xu(Object.entries(e).flatMap(([e,t])=>{let n=Qe(e,t);return e.startsWith(`--`)||n.includes(`var(--canvas`)||n.includes(`url(#`)?[]:[`${e}:${n}`]}).join(`;`)),Qu=e=>{let t=B(e),n=n=>Wo(t,n).map(t=>({owner:`paint`,paintId:t.id,styles:Zu(cs(e,t))})),r=rs(e),i=Ds(e);return[...n(`outer-shadow`),...Uo(t).map(e=>({owner:`paint`,paintId:e.id,styles:Zu(Ss(e))})),...n(`inner-shadow`),...r===null?[]:[{owner:`border`,styles:Zu(r)}],...i===null?[]:[{owner:`outline`,styles:Zu(i)}]]},$u=(e,t)=>e.some(e=>Yu[e.owner].test(t)),ed=e=>u.find(t=>t===(e??`normal`))??X(`Unsupported mix-blend-mode: ${e??``}.`),td=/stroke-(?:dasharray|linecap)="[^"]*"/gu,nd=e=>{let t=/^url\(["']?data:image\/svg\+xml,(.*?)["']?\)$/u.exec(e??``)?.[1];return t===void 0?void 0:decodeURIComponent(t)},rd=(e,t,n)=>{let r=nd(t),i=nd(n);if(i===void 0||r?.replaceAll(td,``)!==i.replaceAll(td,``))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}},id=(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=ed(r);return n.paints.map(e=>e===a?{...e,blendMode:o}:e)},ad=(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:ed(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)}}]:[]]},od=(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`)?id(e,s,c,n.styles[`mix-blend-mode`]):c.paints,u=o.includes(`mask-image`)?rd(e,i.styles[`mask-image`],n.styles[`mask-image`]):{};return[{op:`setAppearance`,nodeId:e.id,appearance:{[s]:{...c,paints:l,...u}}}]}),...ad(e,a)]},sd=e=>{throw new r(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},cd=e=>e.kind===`text`||e.kind===`span`&&e.children.every(e=>e.kind===`text`),ld=e=>c([e]),ud=e=>e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`),dd=e=>e.replaceAll(/-([a-z])/gu,(e,t)=>t.toUpperCase()),fd=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,n])=>{let r=dd(e);return Oe.has(r)?[r,n]:sd(`Run ${String(t+1)} cannot hold ${e}; set it on the text layer.`)})),pd=e=>{if(e.kind!==`span`)return{};let[t,...n]=(e.fills??[]).filter(e=>e.visible),r=t===void 0||n.length>0?void 0:$a(t),i=[...Object.entries(e.styles).map(([e,t])=>{let n=ud(e);return`${n}:${Qe(n,t)}`}),...r===void 0?[]:[`color:${r}`]];return Object.fromEntries(Object.entries(Y(i.join(`;`))).toSorted(([e],[t])=>e.localeCompare(t)))},md=e=>{let t=Te(e);return t.length===0||t.some(e=>!cd(e))?null:t.map(e=>({text:ld(e),styles:pd(e)}))},hd=e=>Te(e).some(e=>!cd(e)),gd=(e,t,n,r)=>{if(`mix-blend-mode`in r.styles)return sd(`Text paints have no blend of their own. Set mix-blend-mode on the text layer.`);let{color:i,...a}=r.styles,o=fd(a,t),s=i===void 0?void 0:F(`${e.id}-run-${String(t)}`,i);if(i!==void 0&&s===null)return sd(`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&&pd(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}]}},_d=(e,t,n)=>{if(t.length!==n.length)return sd(`Keep each run span of ${e.id}; change a run's words or CSS in place.`);let r=Te(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:gd(e,i,r,o)});if(i.every((e,t)=>e===r[t]))return[];let a={...e.props,richText:i,text:c(i)};return[{op:`editText`,nodeId:e.id,change:Ge(e,{...e,props:a})}]},vd=new Set([`path`,`polygon`,`boolean`]),yd=e=>vd.has(e.geometry?.kind??``),bd=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},xd=e=>{let t=jr(e);if(typeof t==`string`)return null;let n=(e.appearance?.fills??[]).find(e=>e.visible),{x:r,y:i,width:a,height:o}=t.viewBox;return{d:t.path,fillRule:t.fillRule,fill:n===void 0?`none`:$a(n)??`none`,viewBox:[r,i,a,o].map(String).join(` `)}},Sd=e=>{throw new r(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Cd=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}:Sd(`Invalid viewBox: ${e}.`)},wd=(e,t,n)=>n.d.trim()===``?Sd(`The path of ${t.id} is empty.`):[{op:`setGeometry`,nodeId:t.id,geometry:{kind:`path`,path:n.d,fillRule:n.fillRule,viewBox:Cd(n.viewBox)}},...t.geometry?.kind===`boolean`?M(e,t.id).map(e=>({op:`remove`,nodeId:e})):[]],Td=(e,t)=>{let n=(e.appearance?.fills??[]).find(e=>e.visible),r=n?.kind===`solid`?n.id:`${e.id}-fill`,i=t===`none`?null:F(r,t);return i===null&&t!==`none`?Sd(`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}}]}}},Ed=(e,t,n,r)=>[...n.d===r.d&&n.fillRule===r.fillRule&&n.viewBox===r.viewBox?[]:wd(e,t,r),...n.fill===r.fill?[]:[Td(t,r.fill)]],Dd=new Set([`root`,`frame`,`group`,`rectangle`,`image`,`text`]),Od={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.`},kd=/^(?:mask(?:-.+)?|clip-path)$/u,Ad=`This layer kind has no editable HTML form yet; edit it in the editor.`,jd=(e,t,n)=>{let r=Od[t.component];return r===void 0?Ou(e,t)===null?`This mask's shape cannot be read; edit it in the editor.`:t.component===`text`&&(n>0||hd(t))?`Text with nested layers or nested formatting keeps its formatting in the editor.`:yd(t)?bd(t)??(xd(t)===null?Ad:null):Dd.has(t.component)&&(t.geometry===void 0||t.geometry.kind===`mask`)?null:Ad:r},Md=(e,t)=>{let n={...Is(t),...Du(t,qs(e,t)),...Ou(e,t)},r=Ye(t),i=Object.entries(n).flatMap(([e,n])=>{let r=Qe(e,n);return e.startsWith(`--`)||r.includes(`var(--canvas`)||r.includes(`url(#`)||gs(t,[e]).length===0&&!kd.test(e)?[]:[[e,r]]});return{...Object.fromEntries(i),...Ku(t),...Object.fromEntries(Object.entries(r).map(([e,t])=>[e,Qe(e,t)]))}},Nd=e=>{throw new r(`BAD_REQUEST`,e,`Use a complete current editable read and preserve its identity and opaque markers.`)},Z=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`),Pd=e=>yd(e)?xd(e):null,Fd=/^background(?:-.+)?$/u,Id=e=>`<path d="${Z(e.d)}" fill-rule="${e.fillRule}" fill="${Z(e.fill)}"></path>`,Ld=e=>{let t=Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`;`);return t===``?``:` style="${Z(t)}"`},Rd=e=>`<div data-enhance-paint="${Z(e.paintId??e.owner)}"${Ld(e.styles)}></div>`,zd=(e,t)=>`<span data-enhance-run="${String(t)}"${Ld(e.styles)}>${Z(e.text)}</span>`,Bd=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">${Id(e.path)}</svg>`;let r=(e.runs??[]).map((e,t)=>zd(e,t)).join(``),i=(e.paints??[]).map(e=>Rd(e)).join(``);return`<${e.tag} ${n}>${Z(e.text)}${r}${i}${e.children.map(e=>Bd(e)).join(``)}</${e.tag}>`},Vd=(e,t)=>{let n=new Set,r=[],i={},a=Ii(e),o=t=>{if(n.has(t))return Nd(`The document contains repeated node identity.`);n.add(t);let s=N(e,t),c=a.get(t)??[],l=jd(e,s,c.length),u=l!==null;u&&(r.push(s.id),i[s.id]=l);let d=u?null:Pd(s),f=u||s.component!==`text`?null:md(s),p=u||d!==null?[]:Qu(s),m=u?{}:Y(Object.entries(Md(e,s)).filter(([e])=>d===null||!Fd.test(e)).filter(([e])=>!$u(p,e)).map(([e,t])=>`${e}:${t}`).join(`;`));return{id:s.id,tag:d===null?s.component===`text`?`span`:`div`:`svg`,...d!==null&&{path:d},label:s.label,opaque:u,locked:zi(e,t),styles:m,...f!==null&&{runs:f},...p.length>0&&{paints:p},text:f!==null||u||s.component!==`text`?``:ce(s)??``,children:u||d!==null?[]:c.map(e=>o(e))}},s=o(t);return{projectionVersion:2,root:s,html:Bd(s),opaqueNodeIds:r,sealedReasons:i}},Hd=(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 i=rt(t,n);if(i.ok)return i.rootNodeIds;throw Dt(t,n),new r(`NOT_FOUND`,`The linked page is unavailable.`,`Copy a current page link.`)},Ud=(e,t)=>{let n=new Set(t);for(let i of t){let t=new Set,a=e.relationships[i]?.parentId;for(;a!==void 0;){if(t.has(a)||n.has(a))throw new r(`BAD_REQUEST`,`Outline roots overlap or contain a parent cycle.`,`Choose disjoint roots so each depth and coverage statement has one meaning.`);t.add(a),a=e.relationships[a]?.parentId}}if(n.size!==t.length)throw new r(`BAD_REQUEST`,`Outline roots repeat.`,`Choose each root once.`)},Wd=(e,t,n,r)=>{let i=[],a=new Set,o=Ii(e),s=(t,c)=>{if(a.has(t))return;a.add(t);let l=N(e,t),u=o.get(t)??[],d=zi(e,t);if(i.push({id:t,label:l.label,kind:l.component,parentId:e.relationships[t]?.parentId??null,sortKey:e.relationships[t]?.sortKey??null,depth:c,childCount:u.length,childrenOmitted:c===n&&u.length>0,locked:d,visible:l.visible!==!1,editable:r&&!d&&[`root`,`frame`,`group`,`text`].includes(l.component),bounds:l.box??null}),c<n)for(let e of u)s(e,c+1)};for(let e of t)s(e,0);return i},Gd=(e,t,n)=>{if(e===void 0)return 0;let i=o(e,We);if(i.canvasId!==t.reference.canvasId||i.queryDigest!==n)throw new r(`BAD_REQUEST`,`This cursor belongs to another outline query.`,`Restart the outline read with the requested scope.`);if(i.version!==t.version)throw new r(`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 i.offset},Kd=(e,t)=>{let{reference:n,scene:i,version:a,isCurrent:o}=t,s=Hd(e,n,i);l(n,i,s),Ud(i,s);let c=b({reference:n,roots:e.rootNodeIds??null,depth:e.depth,limit:e.limit}),u=Gd(e.cursor,t,c),d=Wd(i,s,e.depth,o);if(u>d.length)throw new r(`BAD_REQUEST`,`The outline cursor is out of range.`,`Restart the outline read.`);let f=d.slice(u,u+e.limit),p=u+f.length,m=d.some(e=>e.childrenOmitted);return{canvasId:n.canvasId,version:a,scope:{rootNodeIds:[...s]},view:`outline`,complete:p===d.length&&!m,returnedCount:f.length,total:d.length,nodes:f,omittedDescendants:m,nextCursor:p<d.length?wt({protocol:`enhance-canvas-outline/1`,canvasId:n.canvasId,version:a,queryDigest:c,offset:p}):null,warnings:o?[]:[`This legacy document is read-only until the normal editor upgrades it.`]}},qd=e=>{let t=kt(e);if(t!==null)return{storage:`canvas-image`,reference:e,ownerId:t.canvasId,assetId:t.assetId};let n=Ke(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}},Jd=(e,t)=>typeof e[t]==`string`?e[t]:null,Yd=(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:b(r),...qd(r),delivery:`not_checked`,metadata:i};return n.set(b(a),a),r};Yr(r,e=>i(`image`,e,null)),pt(r.props,(e,t)=>i(`font`,e,{family:Jd(t,`family`),style:Jd(t,`style`),weight:Jd(t,`weight`)}))}return Array.from(n,([,e])=>e)},Xd=(e,t,n)=>{if(e.cursor===void 0)return 0;let i=o(e.cursor,Xe);if(i.canvasId!==t.reference.canvasId||i.digest!==n)throw new r(`BAD_REQUEST`,`The resource cursor belongs to another query.`,`Restart this scoped resource read.`);if(i.version!==t.version)throw new r(`CONFLICT`,`The canvas changed between resource pages.`,`Restart the read at the current revision.`);return i.offset},Zd=(e,t)=>{let n=rt(t.reference,t.scene);if(!n.ok)throw new r(`NOT_FOUND`,`The requested canvas scope is unavailable.`,`Copy a current page or selection link; do not broaden the request.`);let i=b({reference:t.reference,limit:e.limit}),a=Xd(e,t,i),o=Yd(t,n.nodeIds);if(a>o.length)throw new r(`BAD_REQUEST`,`The resource cursor is out of range.`,`Restart the scoped resource read.`);let s=e=>{let r=a+e.length;return{view:`resources`,canvasId:t.reference.canvasId,version:t.version,scope:{rootNodeIds:[...n.rootNodeIds]},coverage:`authored-resource-slots`,resources:e,total:o.length,returnedCount:e.length,complete:r===o.length,nextCursor:r===o.length?null:wt({protocol:`enhance-canvas-resources/1`,canvasId:t.reference.canvasId,version:t.version,digest:i,offset:r}),warnings:[`Inventory includes declared image and font resource slots, including hidden and unused declarations. It does not resolve computed font usage or assets inside opaque screens, recordings, prototypes or raw CSS.`,`Resource delivery and availability have not been checked. Protected paths retain product authorization. External URLs and inline bytes are omitted; their digests identify the original source without exposing credentials or blobs.`,`Scoped reads include declarations on selected nodes and descendants only. A font declaration owned by an ancestor requires a separate explicit read of that scope.`]}},c=48e3-Buffer.byteLength(JSON.stringify(s([])));return s(G(o,a,e.limit,c).entries)},Qd=(e,t,n)=>{if(e.state!==`ready`){if(t.cursor!==void 0)throw new r(`CONFLICT`,`The transcript changed during pagination.`,`Restart the read.`);return e}let{cursor:i,...a}=t,s=b({scope:n,range:a,transcript:e}),c=i===void 0?null:o(i,bt);if(c!==null&&c.digest!==s)throw new r(`CONFLICT`,`The transcript cursor no longer matches this source, range or revision.`,`Restart the requested range; do not combine transcript revisions.`);let l=e.cues.filter(e=>e.endMs>=t.startMs&&(t.endMs===void 0||e.startMs<t.endMs)),u=c?.offset??0;if(u>l.length)throw new r(`BAD_REQUEST`,`Transcript cursor offset is out of range.`,`Restart the read.`);let d=G(l,u,t.limit).entries,f=u+d.length;return{state:`ready`,languageCode:e.languageCode,integrity:e.integrity,isRefreshing:e.isRefreshing,requestedRange:{startMs:t.startMs,endMs:t.endMs??null},cues:d,returnedCount:d.length,totalInRange:l.length,omittedOutsideRange:e.cues.length-l.length,complete:f===l.length,nextCursor:f<l.length?wt({protocol:`enhance-canvas-transcript/1`,digest:s,offset:f}):null}},$d=[`recording.get`,`prototype.getPublishStatus`,`transcript.get`],ef=e=>{let t=s.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}},tf=e=>{let t=Tt.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)}},nf=async(e,t)=>{let{node:n,canvasId:i}=t;if(n.component===`recording`){let t=f.parse(n.props),r=S.uuid().parse(t.recordingId),a=de.parse(await e.query($d[0],{canvasId:i,recordingId:r}));return{kind:`recording`,recordingId:r,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=De.parse(n.props),a=Fe.parse(await e.query($d[1],{canvasId:i,deploymentId:t.deploymentId}));if(a.prototypeId!==t.prototypeId)throw new r(`CONFLICT`,`Prototype identity does not match its deployment.`,`Read the node again.`);return{kind:`prototype`,...t,state:a.state,fileCount:a.fileCount}}return ef(t)??tf(n)},rf=e=>({execute:async t=>{let n=await nf(e,t),i=t.input.transcript,a=`recordingId`in n?n.recordingId:null;if(i!==void 0&&a===null)throw new r(`BAD_REQUEST`,`This object has no recording transcript source.`,`Choose a recording or a capture with recording provenance.`);let o=i===void 0?null:Qd(nt.parse(await e.query($d[2],{canvasId:t.canvasId,recordingId:S.uuid().parse(a)})),i,{canvasRef:t.input.canvasRef,nodeId:t.node.id,version:t.version}),s=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:o,complete:!s&&(o===null||o.state===`empty`||o.state===`ready`&&o.complete),pixelsInspected:!1,warnings:[...s?[`The captured source bytes are not currently available.`]:[],...o===null?[]:[`Transcript times describe speech, not verified visual transitions. Render and inspect candidate moments.`]]}}}),af=[`canvas.document.get`],of=e=>{throw new r(`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`})},sf=(e,t)=>{let{reference:n,scene:i,version:a}=t;if(!t.isCurrent)throw new r(`BAD_REQUEST`,`This document format cannot produce an editable snapshot.`,`Open it in the current editor before editing.`);l(n,i,[e.rootNodeId]);let o=Vd(i,e.rootNodeId);return{canvasId:n.canvasId,version:a,scope:{rootNodeIds:[e.rootNodeId]},view:`editable`,complete:!0,projectionVersion:o.projectionVersion,rootNodeId:e.rootNodeId,html:o.html,opaqueNodeIds:[...o.opaqueNodeIds],sealedReasons:{...o.sealedReasons},snapshotToken:we({reference:n,version:a,rootNodeId:e.rootNodeId,html:o.html}),warnings:o.opaqueNodeIds.length>0?[`Preserve opaque placeholders unchanged; their authored content remains in the canvas.`]:[]}},cf=e=>({execute:async t=>{let n=y(t.canvasRef),r=ae.parse(await e.query(af[0],{canvasId:n.canvasId}));if(t.expectedVersion!==void 0&&t.expectedVersion!==r.version)return of(r.version);let i=ot.safeParse(r.document),a=i.success?i.data:qe.parse(r.document);return t.view===`resources`?Zd(t,{reference:n,scene:a,version:r.version,isCurrent:i.success}):t.view===`outline`?Kd(t,{reference:n,scene:a,version:r.version,isCurrent:i.success}):t.view===`source`?(l(n,a,[t.nodeId]),rf(e).execute({canvasId:n.canvasId,version:r.version,node:N(a,t.nodeId),screens:r.screens,input:t})):sf(t,{reference:n,scene:a,version:r.version,isCurrent:i.success})}}),lf=[`canvas.mutation.get`],uf=e=>({execute:async t=>{let n=t.reference.canvasId,i=Pe.parse(await e.query(lf[0],{canvasId:n,mutationId:t.clientToken,fingerprint:t.fingerprint}));if(i.state===`committed`)return kl(i.result,t.fingerprint);let a=await Fi({remote:e},n,t.baseVersion),o=await t.plan(a);if(`outcome`in o)return o;if(Tc(t.reference,a,o),o.length===0)return{outcome:`no_op`,canvasId:n,version:t.baseVersion,verification:{rendered:!1},warnings:[]};let s=v.safeParse({canvasId:n,documentFormatVersion:13,mutationId:t.clientToken,baseVersion:t.baseVersion,operations:o,requestContext:{fingerprint:t.fingerprint,revisionPolicy:`strict`}});if(!s.success)throw new r(`BAD_REQUEST`,`The planned edit exceeds the canonical canvas contract.`,s.error.issues[0]?.message??`Reduce the edit scope.`,{outcome:`not_committed`});return kl(Ae.parse(await Pi(e).execute(s.data)),t.fingerprint)}}),df=(e,t)=>{let n=Ii(e),i=new Set(t),a=new Set,o=t=>{if(a.has(t))return;if(a.add(t),N(e,t),zi(e,t))throw new r(`BAD_REQUEST`,`Removing this subtree would remove locked content: ${t}.`,`Keep the locked subtree, or explicitly unlock it before requesting removal.`);let i=n.get(t)??[];for(let e of i)o(e)};for(let e of i){if(e===`root`)throw new r(`BAD_REQUEST`,`The canvas root cannot be removed.`,`Name its children.`);o(e)}return[...i].filter(t=>{let n=e.relationships[t]?.parentId;for(;n!==void 0;){if(i.has(n))return!1;n=e.relationships[n]?.parentId}return!0}).map(e=>({op:`remove`,nodeId:e}))},ff=e=>({execute:async({clientToken:t,...n})=>{let r=y(n.canvasRef);return uf(e).execute({reference:r,baseVersion:n.baseVersion,clientToken:t,fingerprint:b({operation:`canvas.remove/1`,...n,reference:r}),plan:e=>df(e,n.rootNodeIds)})}}),pf=(e,t,n,i)=>{let a=e.parents.get(t),o=e.children.get(n)??[];if(a===n&&o.indexOf(t)===i)return;if(zi(e.document,t)||zi(e.document,n))throw new r(`BAD_REQUEST`,`Locked node ${t} cannot be rearranged through HTML.`,`Keep locked placeholders in place or unlock them in the editor before editing.`);a!==void 0&&e.children.set(a,(e.children.get(a)??[]).filter(e=>e!==t));let s=e.children.get(n)??[];s.splice(i,0,t),e.children.set(n,s),e.parents.set(t,n),e.moves.push({nodeId:t,parentId:n,index:i})},mf=(e,t,n)=>{let r={...e,nodes:Object.fromEntries(Object.entries(e.nodes).filter(([e])=>!n.has(e))),relationships:Object.fromEntries(Object.entries(e.relationships).filter(([e])=>!n.has(e)))},i={document:r,parents:new Map(Object.entries(r.relationships).map(([e,t])=>[e,t.parentId])),children:new Map([...Ii(r)].map(([e,t])=>[e,[...t]])),moves:[]},a=e=>{for(let[t,n]of e.children.entries())pf(i,n.id,e.id,t),a(n)};return a(t),i.moves.length===0?[]:$i(r,i.moves).operations},hf=e=>{throw new r(`BAD_REQUEST`,e,`Read the current subtree and reduce or correct the edit. No canvas changes were committed.`)},gf=(e,t,n)=>{if(Object.keys(t.idMap).length!==n.fragments.length)return hf(`Native compilation returned unexpected fragment identities.`);if(t.operations.length!==n.fragments.length)return hf(`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 hf(`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 hf(`New HTML identity ${e} already exists.`);let a=M(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:Rt(o,null)}})}return r},_f=(e,t)=>({...e,id:Object.hasOwn(t,e.id)?t[e.id]??e.id:e.id,children:e.children.map(e=>_f(e,t))}),vf={operations:[],idMap:{},rootNodeIds:[]},yf=(e,t,n=vf)=>{let r=gf(e,n,t),i=_f(t.root,n.idMap);return[...t.operations,...n.operations,...mf(r,i,t.removed)]},bf=e=>e.attrs.some(e=>e.name===`data-enhance-paint`),xf=e=>e.attrs.find(e=>e.name===`data-enhance-id`)?.value,Sf=e=>{throw new r(`BAD_REQUEST`,e,`Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.`)},Cf=e=>e.flatMap(e=>`tagName`in e?[e,...Cf(e.childNodes)]:[]),wf=e=>{let t=ju(e),n=Cf(t.childNodes),r=new Set(n.map(e=>xf(e))),i=[],a=(e,t)=>{let n=xf(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&&!bf(e)?a(e,n):e)};if(t===void 0)return Sf(`The submitted HTML must retain its original root identity.`);if([e,...Cf(e.childNodes)].some(e=>e.attrs.some(e=>[`data-enhance-id`,`data-enhance-opaque`].includes(e.name))))return Sf(`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:pn(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:zu(fn(t)),fragments:i}},Q=e=>{throw new r(`BAD_REQUEST`,e,`Read the current editable subtree and apply only the intended change. No changes were committed.`)},Tf=e=>{let t=new Map,n=e=>{t.set(e.id,e);for(let t of e.children)n(t)};return n(e),t},Ef=(e,t)=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n),Df=(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},Of=(e,t,n,r)=>{let i=new Set([...Object.keys(n.styles),...Object.keys(r.styles)]),a=Object.fromEntries([...i].filter(e=>n.styles[e]!==r.styles[e]).filter(e=>!qu(t,e)).map(e=>[e,r.styles[e]??null]));return[...t.geometry?.kind===`mask`&&Object.keys(a).some(e=>kd.test(e))?[{op:`setGeometry`,nodeId:t.id,geometry:`default`}]:[],...Ju(t,n.styles,r.styles),...Object.keys(a).length===0?[]:uc(e,[{nodeIds:[t.id],styles:a}])]},kf=(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=!Ef(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:Ge(a,{...a,props:Ot(a,n.text)})}),o.push(...od(a,t.paints??[],n.paints??[])),(t.runs!==void 0||n.runs!==void 0)&&o.push(..._d(a,t.runs??[],n.runs??[])),t.path!==void 0&&n.path!==void 0&&o.push(...Ed(e,a,t.path,n.path)),r&&o.push(...Of(e,a,t,n)),o},Af=(e,t,n,r)=>{let i=Vd(e,t).root,a=wf(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=Tf(i),l=Tf(o),u=Df(c,l,r,t),d=new Set([...u,...r.flatMap(t=>[...Ri(e,t)])]);for(let t of d)if(zi(e,t))return Q(`Locked node ${t} cannot be removed through HTML.`);let f=r.map(e=>c.get(e)?.opaque===!0?Q(`Use explicit canvas removal for opaque node ${e}.`):{op:`remove`,nodeId:e});for(let[t,n]of l){if(s.has(t))continue;let r=c.get(t);if(r===void 0)return Q(`Unknown or outside-scope identity: ${t}.`);f.push(...kf(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}},jf=(e,t,n)=>{let i=Ee(e.snapshotToken,t);l(t,n,[i.rootNodeId]);let a=Vd(n,i.rootNodeId);if(we({reference:t,version:i.version,rootNodeId:i.rootNodeId,html:a.html})!==e.snapshotToken)throw new r(`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 Af(n,i.rootNodeId,e.html,e.removeNodeIds)},Mf=async(e,t,n)=>{let r=jf(t,n.reference,n.scene);if(r.fragments.length===0)return yf(n.scene,r);let i=await du(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`?yf(n.scene,r,i.result):Dl(i,{kind:`canvas-preparation`,canvasId:n.reference.canvasId,jobId:i.id,mutationId:t.clientToken,fingerprint:n.fingerprint})},Nf=e=>({execute:async t=>{let n=st.parse(t),r=y(n.canvasRef),i=Ee(n.snapshotToken,r),a=b({operation:`canvas.updateHtml/1`,snapshotToken:n.snapshotToken,html:n.html,removeNodeIds:n.removeNodeIds});return uf(e).execute({reference:r,baseVersion:i.version,clientToken:n.clientToken,fingerprint:a,plan:async t=>Mf(e,n,{reference:r,scene:t,fingerprint:a,version:i.version})})}}),Pf=(e,t,n)=>({"canvas.arrange":async()=>{let{changes:r,...i}=he.parse(t);return mu(e).execute({...i,clientToken:n,request:{kind:`arrange`,changes:r}})},"canvas.duplicateNodes":async()=>{let{nodeIds:r,destination:i,...a}=m.parse(t);return mu(e).execute({...a,clientToken:n,request:{kind:`duplicate`,nodeIds:r,destination:i}})},"canvas.find":async()=>cu(e).execute(et.parse(t)),"canvas.remove":async()=>ff(e).execute({...ht.parse(t),clientToken:n}),"canvas.read":async()=>{let n=ke.safeParse(t);return n.success?Yc(e,n.data):cf(e).execute(dt.parse(t))},"canvas.updateHtml":async()=>Nf(e).execute({...Je.parse(t),clientToken:n})}),Ff=(e,t)=>{let n=y(e.canvasRef),i=n.nodeIds;if(e.target.kind===`content`&&i.length>1)throw new r(`BAD_REQUEST`,`Choose an explicit node within this selection.`,`Render the selected screens separately; do not broaden to the whole canvas.`);let a=e.target.kind===`content`?i[0]===void 0?n.pageId===void 0?e.target:{kind:`page`,pageId:n.pageId}:{kind:`node`,nodeId:i[0]}:e.target;return{canvasId:n.canvasId,expectedVersion:e.expectedVersion,target:a,sourceState:e.sourceState,scale:e.scale,scope:{nodeIds:i,...n.pageId!==void 0&&{pageId:n.pageId}},outputPath:null,overwrite:!1,timeoutMs:e.waitMs,timeoutOutcome:`pending`,retryClientToken:t}},If=(e,t)=>{let n=be.shape.operation.safeParse({kind:`canvas-render`,canvasId:t.input.canvasId,jobId:e instanceof r?e.fields?.jobId:void 0}),i=vt.extract([`failed`,`cancelled`,`expired`]).safeParse(e instanceof r?e.fields?.renderState:void 0);return{...n.success&&{operation:n.data},state:i.success?i.data:`not_confirmed`,error:e instanceof r?{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.`}}},Lf=(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:Ff({...e,...i},a)}}),Rf=async(e,t)=>{try{let n=await e.execute({...t.input,maxOutputPixels:t.maxOutputPixels}),i=lt.safeParse(n);if(!i.success)return be.parse(n);let a=i.data.width*i.data.height;if(!Number.isSafeInteger(a)||a<=0||t.maxOutputPixels!==void 0&&a>t.maxOutputPixels)throw new r(`INTERNAL`,`The render exceeded its allocated pixel budget.`,`Update the API and renderer together, then retry.`,{reason:`RENDER_BUDGET_UNSUPPORTED`});return i.data}catch(e){return If(e,t)}},zf=e=>({execute:async(t,n)=>{let r=Ie.parse(t),i=Lf(r,n),a=[],o=0;for(let t of i){let n=await Rf(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.`]}}}),Bf=e=>xi(e.remote,Zc(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Vf=async(e,t,n)=>{let r=Ie.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=Bf(e);return zf({execute:async t=>(e.mutationKey.select(t.retryClientToken,!1),i.execute(t))}).execute(r.data,t)}let i=yt.safeParse(t);if(i.success)return Bf(e).execute(Ff(i.data,n));let a=Ne.parse(t);return Bf(e).execute({...a,retryClientToken:n})},Hf=e=>({render:Bf(e),execute:async(t,n)=>Vf(e,t,n)}),Uf=new Date(`1980-01-01T00:00:00.000Z`),Wf=33188,Gf=(e,t)=>new r(`BAD_REQUEST`,e,t),Kf=(e,t)=>{let n=w(`sha256`),r=0;return new gn({transform:(e,t,i)=>{r+=e.byteLength,n.update(e),i(null,e)},flush:i=>{if(r!==e.bytes){i(Error(`prototype file ${e.path} changed while it was packaged`));return}try{t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}catch(e){i(e instanceof Error?e:Error(`prototype manifest failed`))}}})},qf=e=>{let t=ee.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 Gf(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,Ft,{mtime:Uf,mode:Wf,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},Jf=(e,t,n)=>{let{source:r,content:i}=t,a={mtime:Uf,mode:Wf,compress:i===null,forceDosTimestamp:!0};if(i===null){e.addReadStreamLazy(r.path,{...a,size:r.bytes},t=>{let i=Ht(r.absolutePath),a=Kf(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:w(`sha256`).update(i).digest(`hex`)})},Yf=(e,t,n)=>{let r=[];for(let i of t)i!==null&&(Jf(e,i,n),r.push(i.source));return r},Xf=async(e,t,n)=>{let r=[];for(let i=0;i<t.files.length;i+=32){let a=await Promise.all(t.files.slice(i,i+32).map(async e=>{try{let t=e.bytes<=128?await en(e.absolutePath):null;if(t===null&&await Yt(e.absolutePath,Vt.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(...Yf(e,a,n))}return r},Zf=async e=>{let t=new vn,n=w(`sha256`),r=new gn({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=_n(t.outputStream,r,Ut(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=null,c=()=>{s!==null&&a.manifest===null&&i.size===s.length&&(a.manifest=qf({zip:t,completed:i,...e,files:s}))},l=e=>{i.set(e.path,e),c()};try{s=await Xf(t,e,l),c()}catch(e){r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)),await o}if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let u=await an(e.artifactPath);if(u.size>e.limits.artifactBytes)throw Gf(`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}},Qf={".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`},$f=e=>Qf[C.extname(e).toLowerCase()]??`application/octet-stream`,ep=async e=>{try{return await an(e)}catch{return null}},tp=e=>Buffer.byteLength(e,`utf8`),$=(e,t)=>new r(`BAD_REQUEST`,e,t),np=(e,t)=>{if(!le.safeParse(e).success)throw $(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(tp(e)>t.pathBytes)throw $(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},rp=async(e,t,n,r)=>{let{limits:i,unavailable:a}=r,o=await tn(t);if(n.has(o))return a(),[];let s=new Set(n).add(o),{readdir:c}=await import(`node:fs/promises`),l=await c(t,{withFileTypes:!0}),u=[],d=l.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of d){let o=C.join(t,n.name),c=await ep(o);if(c?.isDirectory()===!0){try{u.push(...await rp(e,o,s,r))}catch{a()}continue}if(c?.isFile()!==!0){a();continue}let l=C.relative(e,o).split(C.sep).join(`/`).normalize(`NFC`);np(l,i),u.push({absolutePath:o,path:l,bytes:Number(c.size),contentType:$f(o)})}return u},ip=(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=ne(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.`)},ap=(e,t)=>{try{mn.mark(`enhance.prototype.packaging`,{detail:{fileCount:e,unavailableFileCount:t}})}catch{}},op=async e=>{let t=C.resolve(e.directory),n=await ep(t);if(n===null)throw new r(`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 i=e.entryPath.split(C.sep).join(`/`).normalize(`NFC`);np(i,e.limits);let a=0,o=await rp(t,t,new Set,{limits:e.limits,unavailable:()=>{a+=1}});ip(o,i,e.limits);let s=await Qt(C.join(Lt(),`enhance-prototype-artifact-`)),c=C.join(s,`artifact.zip`);try{let t=await Zf({artifactPath:c,files:o,entryPath:i,limits:e.limits});return a+=t.unavailableFileCount,ap(t.manifest.files.length,a),{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:()=>Ht(c),dispose:async()=>rn(s,{recursive:!0})}}catch(e){throw await rn(s,{recursive:!0}),e}},sp=e=>({package:async t=>{if(e===void 0)throw $(`No build directory was selected.`,`Select a build before publishing.`);return op({...t,directory:e})}}),cp=async(e,t)=>{let n=te.parse(t);return Pi(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},lp=async(e,t)=>{let n=g.parse(t);return Jc(e.remote,Hf(e).render).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},up=async(e,t,n)=>{let r=He.parse(t),i=y(r.canvasRef);return Jc(e.remote,Hf(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})},dp=async(e,t)=>{let n=se.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},fp=async(e,t,n)=>{let r=ft.parse(t);return El(e.remote,sp(r.directory)).execute({...r,clientToken:n})},pp=async(e,t,n)=>{let r=ie.parse(t);return eu(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},mp=async(e,t)=>{let n=Re.parse(t);return Ul(e.remote).execute(n)},hp=async(e,t)=>{let n=At.parse(t),r=y(n.canvas);return kc(e.remote).execute({...r,baseVersion:n.baseVersion,edits:n.edits,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},gp=async(e,t)=>Bl(e.remote,Zc(e.configDirectory)).execute(ge.parse(t)),_p=async(e,n,r,i)=>{let a={...Pf(e.remote,r,i),"canvas.importAsset":async()=>{let n=t.parse(r);return tl(e.remote,iu(n.source.path)).execute({canvasRef:n.canvasRef,clientToken:i})},"operation.status":async()=>gp(e,r),"canvas.edit":async()=>hp(e,r),"canvas.apply":async()=>cp(e,r),"canvas.render":async()=>Hf(e).execute(r,i),"canvas.writeHtml":async()=>lp(e,r),"canvas.insertHtml":async()=>up(e,r,i),"canvas.capture":async()=>Ql(e.remote,r,i),"canvas.makeEditable":async()=>Vc(e.remote,r),"comment.attention":async()=>dp(e,r),"prototype.publishCanvas":async()=>{let t=xt.parse(r);return xl(e.remote,sp(t.source.kind===`directory`?t.source.directory:void 0)).execute({...t,source:t.source.kind===`directory`?{...t.source,kind:`build`}:t.source,clientToken:i})},"prototype.publish":async()=>fp(e,r,i),"recording.snapshot":async()=>pp(e,r,i),"transcript.read":async()=>mp(e,r)}[n];if(a===void 0)throw TypeError(`${n} has no composite execution`);return a()},vp=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??qt();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?_p(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),yp=`/callback`,bp=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),xp=e=>{let t=x.platform===`darwin`?{executable:`open`,arguments:[e]}:x.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=xn(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Sp=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==yp){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)},Cp=e=>{let t=bp(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},wp=async e=>{e.signal?.throwIfAborted();let t=Promise.withResolvers(),n=Sn((n,r)=>{Sp({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)}${yp}`,a=Cp({...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&&xp(a),{code:await t.promise,redirectUri:i}}finally{clearTimeout(s),e.signal?.removeEventListener(`abort`,o),await new Promise(e=>{n.close(()=>{e()})})}},Tp=e=>({authorize:async t=>{try{let n=Kt(32).toString(`base64url`),r=w(`sha256`).update(n).digest(`base64url`),i=Kt(32).toString(`base64url`),a=await wp({...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 r(`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.`)}}}),Ep={apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`},Dp=e=>URL.canParse(e)?new URL(e).href.replace(/\/+$/u,``):e,Op=(e,t,n,r)=>{let i=URL.canParse(e)?new URL(e).origin:null,a=C.resolve(t),o=Ep;if(i===new URL(o.apiUrl).origin&&a===C.resolve(n,`.config`,r.configDirectoryName)||i===new URL(r.apiUrl).origin&&a===C.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.`)},kp=e=>e===void 0||e===``?void 0:e,Ap=(e,t,n)=>{let r=kp(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=kp(e.ENHANCE3_API_URL),a=C.join(t,`.config`,n.configDirectoryName),o=kp(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&Dp(i)!==Dp(n.apiUrl))throw TypeError(`Enhance development cannot use this API. Use the bundled development endpoint.`);if(o!==void 0&&C.resolve(o)!==C.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}else Op(i??n.apiUrl,o??a,t,n);return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}},jp=()=>Ap(x.env,It(),Ep),Mp=()=>{let e=S.enum([`legacy`,`canvas`]).default(`legacy`).parse(x.env.ENHANCE_MCP_PROFILE),t=S.enum([`true`,`false`]).default(`false`).parse(x.env.ENHANCE_MCP_READ_ONLY)===`true`;if(t&&e!==`canvas`)throw Error(`ENHANCE_MCP_READ_ONLY requires the canvas profile.`);return{...jp(),profile:e,isReadOnly:t,workflowsDirectory:x.env.ENHANCE_WORKFLOWS_DIR}},Np=S.object({token:S.string().startsWith(`enh_`)}),Pp=e=>{let t=C.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await en(t,`utf8`));return Np.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Zt(e,{recursive:!0,mode:448}),await Xt(e,448);let r=C.join(e,`credentials.${String(x.pid)}.tmp`);await sn(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await nn(r,t),await Xt(t,384)},remove:async()=>{try{return await on(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},Fp={path:`direct_cli`},Ip=S.object({access_token:S.string().min(1)}),Lp=S.object({code:S.string().regex(/^[A-Z][A-Z_0-9]+$/u)}),Rp=`Check network access and proxy settings for this API, then run enhance doctor again.`,zp=e=>new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url).origin,Bp=e=>{let t=Lp.safeParse(e);return t.success?t.data.code:e instanceof Error&&e.cause!==void 0?Bp(e.cause):e instanceof Error?e.name:`Network request failed`},Vp=(e,t)=>new r(`INTERNAL`,`${zp(e)} answered HTTP ${String(t)}.`,Rp),Hp=async(e,t)=>{try{return await fetch(e,t)}catch(t){throw new r(`INTERNAL`,`Could not reach ${zp(e)}: ${Bp(t)}.`,Rp)}},Up=async(e,t)=>{let n=await Hp(e,t);if(!n.ok&&n.headers.get(`content-type`)?.includes(`application/json`)!==!0)throw Vp(e,n.status);return n},Wp=(e,t,n=null,r=Fp)=>yn({links:[bn({url:`${e}/trpc`,fetch:async(e,t)=>Up(e,{...t,signal:t?.signal??null}),headers:{[pe]:JSON.stringify(r),...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),Gp=async e=>{try{return await e()}catch(e){throw gt(e)}},Kp=async e=>{let t=await fetch(e);if(!t.ok)throw new r(t.status===404||t.status===403?`NOT_FOUND`:`INTERNAL`,`Render download answered HTTP ${String(t.status)}.`,`The result may have expired. Request a new render.`);return new Uint8Array(await t.arrayBuffer())},qp=async e=>{let t=await Hp(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new r(`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 r(`INTERNAL`,`${zp(e)} CLI authentication discovery answered HTTP ${String(t.status)}.`,Rp);return t.json()},Jp=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await Hp(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw Vp(e,n.status);return n.json()},Yp=async e=>{let t=await Hp(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 r(`INTERNAL`,`${zp(e.issuer)} token exchange answered HTTP ${String(t.status)}`,Rp);return Ip.parse(await t.json()).access_token},Xp=async e=>{try{let t=await Hp(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status,...!t.ok&&{error:Vp(e,t.status).message}}}catch(t){return{url:e,reachable:!1,status:null,error:t instanceof Error?t.message:`Could not reach ${zp(e)}.`}}},Zp=async e=>{let t=!(e.body instanceof Uint8Array),n=t?hn.toWeb(e.body):e.body,i={method:`PUT`,headers:e.headers,body:n,...t&&{duplex:`half`}},a=await fetch(e.url,i);if(!a.ok)throw new r(`INTERNAL`,`Signed upload answered HTTP ${String(a.status)}.`,`Retry the fixture command with the same source file.`);let o=a.headers.get(`etag`);if(o===null||o===``)throw new r(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return o.replaceAll(`"`,``)},Qp=(e,t,n,r=Fp)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>qp(i),oauthMetadata:Jp,exchangeOauthCode:Yp,query:async(e,n,a)=>Gp(async()=>Wp(i,await t.read(),null,r).query(e,n,a)),queryWithToken:async(e,t,n)=>Gp(async()=>Wp(i,n,null,r).query(e,t)),mutate:async(e,a)=>Gp(async()=>Wp(i,await t.read(),n.current(e,a),r).mutation(e,a)),mutateWithToken:async(e,t,n)=>Gp(async()=>Wp(i,n,null,r).mutation(e,t)),download:Kp,upload:Zp,health:async()=>Xp(i)}},$p=e=>Array.isArray(e)?e.map(e=>$p(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$p(t)])),em=(e,t,n)=>w(`sha256`).update(`${e}\0${t}\0${JSON.stringify($p(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),tm=()=>{let e=qt(),t=!1;return{current:(n,r)=>t?em(e,n,r):e,select:(n,r)=>{e=n??qt(),t=r}}};export{Ir as C,Cn as E,zr as S,T,Ti as _,Mp as a,ni as b,Zc as c,G as d,Ac as f,Pi as g,Fi as h,jp as i,Yc as l,Tc as m,Qp as n,Tp as o,kc as p,Pp as r,vp as s,tm as t,Jc as u,xi as v,Fn as w,Zr as x,ai as y};
|