@enhance-eng/enhance-dev 0.1.7-dev.sha-8aeb7ebe4b78 → 0.1.7-dev.sha-be264076fee2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{FailedToExitError as e,parseRouter as t}from"trpc-cli";import{z as n}from"zod";import{createHash as r}from"node:crypto";import{TRPCError as i,initTRPC as a}from"@trpc/server";import{middlewareMarker as o}from"@trpc/server/unstable-core-do-not-import";import{TRPCClientError as s}from"@trpc/client";var c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const l=2048,ee=1e4,u=1024,d=u*u;n.object({cursor:n.string().nullable().default(null),limit:n.number().int().min(1).max(100).default(20)});const f=e=>n.object({items:n.array(e),truncated:n.boolean()}),te=n.enum([`never-captured`,`capture-pending`,`extension-unavailable`,`capture-failed`,`source-mismatch`,`upload-incomplete`,`blob-missing`,`image-load-failed`,`unsupported-legacy-state`]),ne=n.object({thumbnailId:n.uuid(),url:n.string().max(4096),width:n.literal(528),height:n.literal(312),bytes:n.number().int().min(1).max(1048576)}),re=n.object({canvasId:n.uuid(),thumbnailId:n.uuid(),clientReleaseIdentity:n.string().min(1).max(100),attemptedOperation:n.literal(`thumbnail-download`),recoveryOutcome:n.literal(`fallback-shown`)}),ie=n.object({recorded:n.literal(!0)}),ae=n.enum([`invite-only`,`link-view`,`link-comment`]),p=n.enum([`owner`,`can-comment`,`can-view`]),m=n.enum([`can-comment`,`can-view`]),oe=n.object({read:n.boolean(),comment:n.enum([`yes`,`sign-in`,`no`]),share:n.boolean(),manage:n.boolean()}),h=n.object({id:n.uuid(),title:n.string().min(1).max(200),accessState:ae,organisationId:n.uuid().nullable(),sourceUrl:n.string().max(l).nullable(),unresolvedCount:n.number().int().min(0),viewerCan:oe,createdAt:n.iso.datetime(),lastActivityAt:n.iso.datetime()}),g=n.object({title:n.string().trim().min(1).max(200),organisationId:n.uuid().nullable().default(null),sourceUrl:n.string().max(l).nullable().default(null)}),se=n.object({canvasId:n.uuid()}),ce=n.union([n.literal(`own`),n.literal(`everything`),n.uuid()]),le=n.object({collection:ce.default(`own`),title:n.string().trim().min(1).max(200).optional().describe(`Title text to match before returning canvas ids.`),deleted:n.boolean().default(!1),accessState:ae.optional(),scope:n.enum([`all`,`mine`,`shared`]).default(`all`),hasUnresolved:n.boolean().default(!1)}),ue=h.extend({screenCount:n.number().int().min(0),hasRecording:n.boolean()}),de=f(n.union([ue.extend({thumbnail:ne}),ue.extend({thumbnail:n.null(),thumbnailFallbackReason:te})])),fe=n.object({canvasId:n.uuid(),title:n.string().trim().min(1).max(200)}),pe=n.object({canvasId:n.uuid()}),me=n.object({canvasId:n.uuid(),deletedAt:n.iso.datetime()}),he=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)])}),ge=n.object({canvas:h}),_e=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),ve=n.object({canvas:h}),ye=n.object({canvasId:n.uuid(),confirmation:n.string().min(1).max(200)}),be=n.object({canvasId:n.uuid()}),xe=n.object({canvasId:n.uuid(),accessState:ae}),Se=n.object({canvas:h,widened:n.boolean()}),Ce=n.object({canvasId:n.uuid()}),we=n.object({lastViewedAt:n.iso.datetime().nullable()}),Te=n.object({canvasId:n.uuid()}),Ee=n.object({canvasId:n.uuid()}),De=1e5,_=n.number().min(-1e5).max(De),v=n.number().nonnegative().max(De),Oe=n.object({ratio:v,offset:_.optional()}),ke=n.object({min:v.optional(),max:v.optional(),minParent:Oe.optional(),maxParent:Oe.optional()}).refine(({min:e,max:t})=>e===void 0||t===void 0||e<=t,`size minimum cannot exceed maximum`),Ae=n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`fixed`),value:v}),ke.extend({mode:n.literal(`hug`),basis:v.optional()}),ke.extend({mode:n.literal(`fill`),offset:_.optional()})]),je=n.object({top:v,right:v,bottom:v,left:v}),Me=n.union([n.literal(`auto`),_]),Ne=n.object({top:Me,right:Me,bottom:Me,left:Me}),Pe=n.object({basis:v,align:n.enum([`start`,`center`,`end`,`stretch`])}),Fe=n.object({mode:n.enum([`auto-fill`,`auto-fit`]),minimum:n.number().positive().max(De)}),Ie=n.object({x:_,y:_}),Le=n.object({direction:n.enum([`row`,`column`]),alignItems:n.enum([`start`,`center`,`end`,`stretch`]),alignContent:n.enum([`start`,`center`,`end`,`stretch`,`space-between`,`space-around`,`space-evenly`]).optional(),justifyContent:n.enum([`start`,`center`,`end`,`space-between`,`space-around`,`space-evenly`]),gap:v,rowGap:v.optional(),columnGap:v.optional(),wrap:n.enum([`nowrap`,`wrap`]).optional(),gridColumns:n.number().int().positive().max(De).optional(),gridAutoRepeat:Fe.optional(),materialized:n.boolean().optional(),padding:je}),Re=n.object({rotation:_,flipHorizontal:n.boolean().optional(),flipVertical:n.boolean().optional(),aspectRatioLocked:n.boolean().optional(),aspectRatio:n.number().positive().max(De).optional(),horizontal:Ae,vertical:Ae,position:n.enum([`flow`,`absolute`]),alignSelf:n.enum([`auto`,`start`,`center`,`end`,`stretch`]).optional(),flexGrow:v.optional(),flexShrink:v.optional(),flexBasis:n.union([n.literal(`auto`),v,Oe]).optional(),flowOffset:Ie.optional(),order:_.int().optional(),margin:Ne.optional(),gridTrack:Pe.optional(),clipContent:n.boolean().optional(),container:Le.optional()}),ze=_,y=v,b=n.number().min(0).max(1),Be=n.string().min(1).max(200),Ve=n.object({space:n.enum([`srgb`,`display-p3`]),red:b,green:b,blue:b,alpha:b}),He=n.object({id:Be,position:b,color:Ve}),Ue=n.object({x:b,y:b}),We=n.object({id:Be,visible:n.boolean(),opacity:b}),Ge=n.discriminatedUnion(`kind`,[We.extend({kind:n.literal(`solid`),color:Ve}),We.extend({kind:n.literal(`linear-gradient`),angle:ze,stops:n.array(He).min(2).max(32)}),We.extend({kind:n.literal(`radial-gradient`),center:Ue,radius:Ue,stops:n.array(He).min(2).max(32)}),We.extend({kind:n.literal(`image`),assetId:n.string().min(1).max(500),fit:n.enum([`fill`,`fit`,`crop`,`tile`]),crop:n.object({x:b,y:b,width:b,height:b}).optional()})]),Ke=n.object({topLeft:y,topRight:y,bottomRight:y,bottomLeft:y}),qe=n.object({visible:n.boolean(),width:n.object({top:y,right:y,bottom:y,left:y}),style:n.enum([`solid`,`dashed`,`dotted`]),paint:Ge,alignment:n.enum([`inside`,`center`,`outside`])}),Je=n.object({visible:n.boolean(),width:y,offset:ze,style:n.enum([`solid`,`dashed`,`dotted`]),paint:Ge}),Ye=n.object({id:Be,visible:n.boolean(),kind:n.enum([`outer`,`inner`]),color:Ve,offsetX:ze,offsetY:ze,blur:y,spread:ze}),x=n.object({id:Be,visible:n.boolean()}),Xe=n.discriminatedUnion(`kind`,[x.extend({kind:n.literal(`blur`),value:y}),x.extend({kind:n.literal(`brightness`),value:y}),x.extend({kind:n.literal(`contrast`),value:y}),x.extend({kind:n.literal(`grayscale`),value:b}),x.extend({kind:n.literal(`hue-rotate`),value:ze}),x.extend({kind:n.literal(`invert`),value:b}),x.extend({kind:n.literal(`saturate`),value:y}),x.extend({kind:n.literal(`sepia`),value:b})]),Ze=n.enum([`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`plus-lighter`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`]);n.object({opacity:b,blendMode:Ze,fills:n.array(Ge).max(32),border:qe,outline:Je,radius:Ke,shadows:n.array(Ye).max(32),filters:n.array(Xe).max(32),backdropFilters:n.array(Xe).max(32)});const Qe=n.object({opacity:b.optional(),blendMode:Ze.optional(),fills:n.array(Ge).max(32).optional(),border:qe.optional(),outline:Je.optional(),radius:Ke.optional(),shadows:n.array(Ye).max(32).optional(),filters:n.array(Xe).max(32).optional(),backdropFilters:n.array(Xe).max(32).optional()}).refine(e=>Object.keys(e).length>0,`appearance values cannot be empty`),$e=[`opacity`,`blendMode`,`fills`,`border`,`outline`,`radius`,`shadows`,`filters`,`backdropFilters`],et=n.enum($e),tt=n.object({opacity:b.optional(),blendMode:Ze.optional(),fills:n.array(Ge).max(32).optional(),border:qe.optional(),outline:Je.optional(),radius:Ke.optional(),shadows:n.array(Ye).max(32).optional(),filters:n.array(Xe).max(32).optional(),backdropFilters:n.array(Xe).max(32).optional(),clear:n.array(et).min(1).max($e.length).optional()}).refine(e=>Object.keys(e).length>0,`appearance patch cannot be empty`).refine(({clear:e,...t})=>e===void 0||e.every(e=>t[e]===void 0),`appearance patch cannot set and clear the same property`),nt=n.number().min(-1e5).max(De),rt=n.number().nonnegative().max(De),it=n.object({family:n.string().min(1).max(500),fallbackFamilies:n.array(n.string().min(1).max(500)).max(20),size:rt,weight:n.number().int().min(1).max(1e3),style:n.enum([`normal`,`italic`,`oblique`]),lineHeight:n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`normal`)}),n.object({mode:n.literal(`fixed`),value:rt})]),letterSpacing:nt,align:n.enum([`left`,`center`,`right`,`justify`]),verticalAlign:n.enum([`top`,`middle`,`bottom`]),transform:n.enum([`none`,`uppercase`,`lowercase`,`capitalize`]),decoration:n.object({line:n.enum([`none`,`underline`,`line-through`]),style:n.enum([`solid`,`double`,`dotted`,`dashed`,`wavy`]),color:Ve.optional(),thickness:rt.optional()}),stroke:n.object({width:rt,paint:Ge}).optional(),wrapping:n.enum([`wrap`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]),insets:n.object({top:nt,right:nt,bottom:nt,left:nt}).optional()}),at=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,ot=/^(?:behavior|-moz-binding)$/iu,st=n.string().min(1).max(200).regex(/^(?:--[\w-]+|-(?:webkit|moz|ms|o)-[a-z][a-z\d-]*|[a-z][a-z\d-]*)$/iu).refine(e=>!ot.test(e),`unsafe CSS property`),ct=n.string().max(1e4).refine(e=>!at.test(e),`unsafe CSS value`),lt=n.object({id:n.string().min(1).max(200),property:st,value:ct,enabled:n.boolean()}),ut=n.object({declarations:n.array(lt).max(128)}).refine(({declarations:e})=>new Set(e.map(e=>e.id)).size===e.length,`additional style ids must be unique`),S=n.object({x:n.number(),y:n.number(),width:n.number().nonnegative(),height:n.number().nonnegative()}),dt=n.enum([`start`,`center`,`end`,`stretch`,`scale`]),ft=n.object({x:dt,y:dt}),pt=n.enum([`source`,`generated`,`user`]),mt=n.looseObject({id:n.string().min(1).max(200),label:n.string().max(500),component:n.string().min(1).max(100),labelOrigin:pt.optional(),visible:n.boolean().optional(),locked:n.boolean().optional(),constraints:ft.optional(),styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:Re.optional(),responsive:n.never().optional(),appearance:Qe.optional(),typography:it.optional(),additionalStyles:ut.optional(),props:n.record(n.string(),n.unknown()).optional(),box:S.optional()}),ht=n.object({version:n.literal(2),nodes:n.record(n.string(),mt),relationships:n.record(n.string(),n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)})),tombstones:n.record(n.string(),n.literal(!0)).default({})}),gt=()=>({version:2,nodes:{root:{id:`root`,label:`Canvas`,component:`root`,labelOrigin:`generated`,visible:!0,locked:!1,styles:{}}},relationships:{},tombstones:{}}),_t=3e4,C=5e4,vt=n.string().min(1).max(200),yt=n.object({code:n.enum([`asset-unavailable`,`content-omitted`,`cross-origin-frame`,`nodes-truncated`,`responsive-behavior-not-editable`,`style-degraded`,`unsupported-surface`]),message:n.string().min(1).max(500),temporaryId:vt.optional()}),bt=n.object({nodeCount:n.number().int().positive().max(_t),sourceNodeCount:n.number().int().positive().max(C).optional(),collapsedNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedNeutralWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedTransferredWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),layoutContainerCount:n.number().int().nonnegative().max(_t).optional(),removedLeafNodeCount:n.number().int().nonnegative().max(C).optional(),retainedSemanticOwnerNodeCount:n.number().int().nonnegative().max(C).optional(),truncatedNodeCount:n.number().int().nonnegative().max(C).optional(),issues:n.array(yt).max(C)}).refine(({collapsedNeutralWrapperNodeCount:e,collapsedTransferredWrapperNodeCount:t,collapsedWrapperNodeCount:n})=>n===void 0||e===void 0||t===void 0||e+t===n,`wrapper collapse proof classes must explain the collapsed wrapper count`).refine(({collapsedNodeCount:e,collapsedWrapperNodeCount:t,removedLeafNodeCount:n})=>e===void 0||t===void 0||n===void 0||t+n===e,`collapsed node kinds must explain the total collapsed node count`).refine(({collapsedNodeCount:e,nodeCount:t,sourceNodeCount:n,truncatedNodeCount:r})=>n===void 0||e===void 0||n-t===e+(r??0),`collapsed and truncated node counts must explain the source to editable difference`).refine(({layoutContainerCount:e,nodeCount:t})=>e===void 0||e<=t,`layout container count cannot exceed editable node count`),xt=mt.omit({id:!0}).extend({temporaryId:vt}),St=n.object({temporaryId:vt,parentTemporaryId:vt,sortKey:n.string().min(1).max(500)}),Ct=n.object({version:n.literal(1),rootTemporaryId:vt,nodes:n.array(xt).min(1).max(_t),relationships:n.array(St).max(_t-1),report:bt}),wt=n.object({canvasId:n.uuid(),mutationId:n.uuid(),baseVersion:n.number().int().positive(),screenNodeId:n.string().min(1).max(200),draft:Ct}),Tt=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),rootNodeId:n.string().min(1).max(200),idMap:n.record(vt,n.string().min(1).max(200)),insertedNodeIds:n.array(n.string().min(1).max(200)),removedNodeIds:n.array(n.string().min(1).max(200)),boxes:n.record(n.string().min(1).max(200),S),affectedBounds:S}),w=n.object({url:n.url(),expiresAt:n.iso.datetime(),headers:n.record(n.string(),n.string())}),Et=n.object({url:n.url(),expiresAt:n.iso.datetime(),bytes:n.number().int().min(0)}),Dt=[`queued`,`claimed`,`grant`,`navigate`,`document`,`sources`,`fonts`,`layout`,`target`,`capture`,`serialize`,`compile`,`commit`,`upload`,`complete`],Ot=[`queued`,`running`,`succeeded`,`failed`,`cancelled`,`expired`],kt=[`VERSION_CHANGED`,`TARGET_NOT_FOUND`,`TARGET_INVALID`,`OUTPUT_TOO_LARGE`,`READINESS_TIMEOUT`,`SOURCE_FAILED`,`BROWSER_CRASH`,`CAPTURE_FAILED`,`CONVERSION_FAILED`,`UPLOAD_FAILED`,`WORKER_UNAVAILABLE`,`CANCELLED`,`EXPIRED`,`INTERNAL`],At=[`ASSET_UNAVAILABLE`,`FONT_FALLBACK`,`SOURCE_FALLBACK`,`SCALE_REDUCED`],jt=32*d,Mt=64*d,Nt=1e5,Pt=.1,T=n.object({x:n.number(),y:n.number(),width:n.number().positive().max(Nt),height:n.number().positive().max(Nt)}),Ft=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`content`)}),n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`bounds`),bounds:T})]),It=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),Lt=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative()}),Rt=n.object({recordingId:n.uuid(),atMs:n.number().int().nonnegative(),screenId:n.uuid(),screenNodeId:n.string().min(1).max(200),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),box:T,version:n.number().int().positive(),alreadyPresent:n.boolean()}),zt=n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional(),target:Ft.default({kind:`content`}),sourceState:It.optional(),scale:n.number().min(Pt).max(4).default(1),format:n.literal(`png`).default(`png`)}).refine(e=>e.sourceState===void 0||e.target.kind===`node`,{message:`a source state requires a node render target`,path:[`sourceState`]}),Bt=n.enum(Dt);n.enum(Ot);const Vt=n.enum(kt),Ht=n.enum(At),Ut=n.object({code:Ht,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),E=n.object({reason:Vt,phase:Bt,message:n.string().min(1).max(500),retryable:n.boolean(),sourceId:n.string().min(1).max(200).nullable()}),Wt=n.object({phase:Bt,durationMs:n.number().int().min(0)}),Gt=n.object({canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),target:Ft,sourceState:Lt.optional(),snapshot:Rt.optional(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),contentType:n.literal(`image/png`),bytes:n.number().int().positive().max(jt),warnings:n.array(Ut),timings:n.array(Wt),expiresAt:n.iso.datetime()}).refine(e=>e.width*e.height<=16e6,{message:`render output may contain at most 16000000 pixels`,path:[`width`]}),Kt=n.object({id:n.uuid(),canvasId:n.uuid(),purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),phase:Bt,requestedVersion:n.number().int().positive(),target:Ft,sourceState:It.optional(),scale:n.number().positive(),format:n.literal(`png`),attempt:n.number().int().min(0),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),qt=n.discriminatedUnion(`state`,[Kt.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),Kt.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),Kt.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:Gt,failure:n.null()}),Kt.extend({state:n.literal(`failed`),result:n.null(),failure:E}),Kt.extend({state:n.literal(`cancelled`),result:n.null(),failure:E.extend({reason:n.literal(`CANCELLED`)})}),Kt.extend({state:n.literal(`expired`),result:n.null(),failure:E.extend({reason:n.literal(`EXPIRED`)})})]),Jt=n.object({job:qt,alreadyExists:n.boolean()}),Yt=n.object({jobId:n.uuid()}),Xt=n.object({job:qt}),Zt=n.object({jobId:n.uuid()}),Qt=n.object({job:qt}),$t=n.object({jobId:n.uuid()}),en=n.object({jobId:n.uuid(),download:Et}),tn=n.object({canvasId:n.uuid(),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),nn=n.object({job:qt,alreadyExists:n.boolean()}),rn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`adjacent`)}),n.object({kind:n.literal(`insert-children`),targetNodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`replace`),targetNodeId:n.string().min(1).max(200)})]),an=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),html:n.string().min(1).max(262144),label:n.string().min(1).max(500),idPrefix:n.string().min(1).max(80).regex(/^[\w-]+$/u).optional()})]),on=n.object({source:an,destination:rn}).superRefine((e,t)=>{e.source.kind===`screen`&&e.destination.kind!==`adjacent`&&t.addIssue({code:`custom`,message:`stored screens convert beside their source`,path:[`destination`]}),e.source.kind===`html`&&e.destination.kind===`adjacent`&&t.addIssue({code:`custom`,message:`authored HTML requires an editable destination`,path:[`destination`]})}),sn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),label:n.string().min(1).max(500)})]),cn=n.object({id:n.uuid(),canvasId:n.uuid(),source:sn,destination:rn,phase:Bt,requestedVersion:n.number().int().positive(),attempt:n.number().int().nonnegative(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),ln=n.discriminatedUnion(`state`,[cn.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),cn.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),cn.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:Tt.extend({report:bt}),failure:n.null()}),cn.extend({state:n.literal(`failed`),result:n.null(),failure:E}),cn.extend({state:n.literal(`cancelled`),result:n.null(),failure:E.extend({reason:n.literal(`CANCELLED`)})}),cn.extend({state:n.literal(`expired`),result:n.null(),failure:E.extend({reason:n.literal(`EXPIRED`)})})]),un=on.and(n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional()})),dn=n.object({job:ln,alreadyExists:n.boolean()}),fn=n.object({jobId:n.uuid()}),pn=n.object({job:ln}),mn=n.object({jobId:n.uuid()}),hn=n.object({job:ln});n.discriminatedUnion(`state`,[n.object({state:n.literal(`loading`),jobId:n.uuid()}),n.object({state:n.literal(`ready`),jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Ct}),n.object({state:n.literal(`failed`),jobId:n.uuid(),message:n.string().min(1).max(500)})]);const gn=n.record(n.string(),n.unknown()),_n=n.object({canvasId:n.uuid()}),vn=n.object({screenId:n.uuid(),route:n.string().max(l).nullable(),title:n.string().max(200).nullable(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),atMs:n.number().int().min(0).nullable(),sourceRecordingId:n.uuid().nullable(),assetBundle:n.object({assetBundleId:n.uuid(),sourceUrl:n.string().max(l),assets:n.array(n.object({url:n.string().max(l),contentType:n.string().max(200),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0)}).nullable(),download:Et.nullable()}),yn=n.object({version:n.number().int().min(1),document:gn,screens:n.array(vn)}),bn=n.object({canvasId:n.uuid(),baseVersion:n.number().int().min(1),document:gn,screenIds:n.array(n.uuid()).max(2e3)}),xn=n.discriminatedUnion(`outcome`,[n.object({outcome:n.literal(`saved`),version:n.number().int().min(1)}),n.object({outcome:n.literal(`conflict`),version:n.number().int().min(1),document:gn})]),Sn=n.object({canvasId:n.uuid(),contentType:n.enum([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),bytes:n.number().int().positive().max(20971520)}),Cn=n.object({assetId:n.uuid(),path:n.string().startsWith(`/v1/canvas-assets/`),upload:w}),wn=(e,t)=>`/v1/canvas-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,Tn=n.enum([`position`,`layout`,`clip`,`cornerRadius`,`blending`,`typography`,`nativeControl`,`textDecoration`,`fill`,`outline`,`textStroke`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`vector`,`export`,`source`]),En=n.object({id:n.string().min(1).max(200),label:n.string().max(500),kind:n.string().min(1).max(100),parentId:n.string().min(1).max(200).nullable(),childCount:n.number().int().min(0),box:T.nullable(),propertySections:n.array(Tn)}),Dn=n.object({canvasId:n.uuid()}),On=n.object({canvasId:n.uuid(),title:n.string().min(1),version:n.number().int().positive(),nodeCount:n.number().int().min(0),rootChildCount:n.number().int().min(0),bounds:T.nullable(),kinds:n.record(n.string(),n.number().int().min(0)),next:n.array(n.string().min(1))}),kn=n.object({canvasId:n.uuid()}),An=n.object({canvasId:n.uuid(),version:n.number().int().positive(),nodes:n.array(En)}),jn=n.object({canvasId:n.uuid(),nodeId:n.string().min(1).max(200)}),Mn=n.object({canvasId:n.uuid(),version:n.number().int().positive(),node:En.extend({styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:Re.optional(),appearance:Qe.optional(),typography:it.optional(),additionalStyles:ut.optional(),props:n.record(n.string(),n.unknown()),children:n.array(n.string().min(1).max(200))}),next:n.array(n.string().min(1))}),Nn=[`position`,`layout`,`cornerRadius`,`blending`,`fill`,`outline`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`export`],Pn=[`position`,`layout`,`clip`,...Nn.filter(e=>e!==`position`&&e!==`layout`)],Fn=[...Nn,`vector`],In=Object.fromEntries([{objectKind:`prototype`,label:`Prototype`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`node`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`]},{objectKind:`root`,label:`Canvas`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!0,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`page`,label:`Page`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!1,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`screen`,label:`Screen`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`screen`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`,`source`]},{objectKind:`frame`,label:`Frame`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:Pn},{objectKind:`group`,label:`Group`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`,`blending`,`additionalStyles`,`export`]},{objectKind:`rectangle`,label:`Rectangle`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:Nn},{objectKind:`image`,label:`Image`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:Nn},{objectKind:`svg`,label:`SVG`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},capture:{preservesVectorData:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:Fn},{objectKind:`recording`,label:`Recording`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1},capture:{preservesAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:[]},{objectKind:`text`,label:`Text`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`text`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!0},propertySections:[`position`,`layout`,`typography`,`nativeControl`,`textDecoration`,`textStroke`,`blending`,`fill`,`outerShadow`,`filters`,`additionalStyles`,`export`]}].map(e=>[e.objectKind,e])),Ln=e=>In[e]??null,Rn=e=>Ln(e)?.propertySections??[],zn=n.string().regex(/^(?:\d+(?:\.\d+)?|\.\d+)px$/u),Bn=n.string().regex(/^-?(?:\d+(?:\.\d+)?|\.\d+)px$/u),D={color:n.union([n.enum([`var(--note-ink)`,`var(--note-slate)`,`var(--note-red)`,`var(--note-orange)`,`var(--note-amber)`,`var(--note-green)`,`var(--note-teal)`,`var(--note-blue)`,`var(--note-violet)`,`var(--note-magenta)`]),n.string().regex(/^#[\da-f]{6}$/iu)]),"font-family":n.enum([`var(--sans)`,`var(--mono)`]),"font-size":n.union([n.literal(16),n.literal(24),n.literal(40),n.literal(64),n.literal(96)]),"font-weight":n.enum([`400`,`700`]),"font-style":n.enum([`normal`,`italic`,`oblique`]),"letter-spacing":n.number().min(-100).max(100),"line-height":n.union([n.number().positive().max(1e4),n.string().regex(/^(?:\d+(?:\.\d+)?(?:px|em|rem|%)?|normal)$/u)]),"text-align":n.enum([`left`,`center`,`right`]),"white-space":n.enum([`normal`,`nowrap`,`pre`,`pre-wrap`,`pre-line`,`break-spaces`])},Vn=n.strictObject({color:D.color.optional(),"font-family":D[`font-family`].optional(),"font-size":D[`font-size`].optional(),"font-weight":D[`font-weight`].optional(),"font-style":D[`font-style`].optional(),"letter-spacing":D[`letter-spacing`].optional(),"line-height":D[`line-height`].optional(),"text-align":D[`text-align`].optional(),"white-space":D[`white-space`].optional()}),Hn=n.strictObject({color:D.color.nullable().optional(),"font-family":D[`font-family`].nullable().optional(),"font-size":n.union([v,zn]).nullable().optional(),"font-weight":n.string().regex(/^(?:[1-9]\d{0,2}|1000)$/u).nullable().optional(),"font-style":D[`font-style`].nullable().optional(),"font-stretch":n.union([n.enum([`normal`,`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`]),n.string().regex(/^\d+(?:\.\d+)?%$/u)]).nullable().optional(),"letter-spacing":n.union([_,Bn,n.literal(`normal`)]).nullable().optional(),"line-height":D[`line-height`].nullable().optional(),"text-align":D[`text-align`].nullable().optional(),"text-indent":n.union([_,Bn]).nullable().optional(),"white-space":D[`white-space`].nullable().optional(),"word-spacing":n.union([_,Bn,n.literal(`normal`)]).nullable().optional()}),Un=n.enum([`auto`,`clip`,`hidden`,`scroll`,`visible`]),O=n.union([n.string(),_]),Wn=Hn.extend({background:n.string().nullable().optional(),"background-color":n.string().nullable().optional(),"border-bottom-left-radius":O.optional(),"border-bottom-right-radius":O.optional(),"border-bottom-width":O.optional(),"border-color":n.string().nullable().optional(),"border-left-width":O.optional(),"border-radius":O.nullable().optional(),"border-right-width":O.optional(),"border-style":n.enum([`none`,`solid`,`dashed`,`dotted`]).nullable().optional(),"border-top-left-radius":O.optional(),"border-top-right-radius":O.optional(),"border-top-width":O.optional(),"border-width":O.nullable().optional(),"box-shadow":n.string().nullable().optional(),"column-gap":O.optional(),gap:O.optional(),"margin-bottom":O.optional(),"margin-left":O.optional(),"margin-right":O.optional(),"margin-top":O.optional(),opacity:n.union([n.string(),n.number()]).nullable().optional(),"outline-offset":O.optional(),"outline-width":O.optional(),overflow:Un.nullable().optional(),"overflow-x":Un.nullable().optional(),"overflow-y":Un.nullable().optional(),"padding-bottom":O.optional(),"padding-left":O.optional(),"padding-right":O.optional(),"padding-top":O.optional(),"row-gap":O.optional(),"stroke-width":O.optional()}),Gn=n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)}),Kn=n.object({op:n.literal(`insertConvertedSubtree`),destination:rn,sourceNodeId:n.string().min(1).max(200).optional(),rootNodeId:n.string().min(1).max(200),nodes:n.record(n.string().min(1).max(200),mt).refine(e=>Object.keys(e).length<=_t),relationships:n.record(n.string().min(1).max(200),Gn).refine(e=>Object.keys(e).length<_t)}),qn=1e5,Jn=1e3,k=n.string().min(1).max(200),Yn=n.string().min(1).max(500),Xn=S.extend({width:n.number().positive(),height:n.number().positive()}),Zn=n.object({parentId:k,afterId:k.optional()}),Qn=n.object({parentId:k,sortKey:Yn}),$n=n.discriminatedUnion(`op`,[Kn,n.object({op:n.literal(`insertNode`),node:mt,parentage:Qn}),Zn.extend({op:n.literal(`insertText`),nodeId:k,label:n.string().max(500).default(`Text`),text:n.string().max(qn),box:Xn,styles:Vn.default({})}),Zn.extend({op:n.literal(`insertPrototype`),nodeId:k,label:n.string().max(500).default(`Prototype`),prototypeId:n.uuid(),deploymentId:n.uuid(),box:Xn}),n.object({op:n.literal(`setPrototypeDeployment`),nodeId:k,prototypeId:n.uuid(),deploymentId:n.uuid()}),n.object({op:n.literal(`setText`),nodeId:k,text:n.string().max(qn)}),n.object({op:n.literal(`setBox`),nodeId:k,box:S}),n.object({op:n.literal(`setLabel`),nodeId:k,label:n.string().trim().min(1).max(500),labelOrigin:pt.optional()}),n.object({op:n.literal(`setVisibility`),nodeId:k,visible:n.boolean()}),n.object({op:n.literal(`setLocked`),nodeId:k,locked:n.boolean()}),n.object({op:n.literal(`setConstraints`),nodeId:k,constraints:ft}),n.object({op:n.literal(`setStyles`),nodeId:k,styles:Wn}),n.object({op:n.literal(`setAppearance`),nodeId:k,appearance:tt}),n.object({op:n.literal(`setLayout`),nodeId:k,layout:n.union([Re,n.literal(`default`)])}),n.object({op:n.literal(`setTypography`),nodeId:k,typography:n.union([it,n.literal(`default`)])}),n.object({op:n.literal(`setAdditionalStyles`),nodeId:k,additionalStyles:n.union([ut,n.literal(`default`)])}),n.object({op:n.literal(`setProps`),nodeId:k,props:n.record(n.string(),n.unknown())}),n.object({op:n.literal(`setParentage`),nodeId:k,parentage:Qn}),Zn.extend({op:n.literal(`move`),nodeId:k}),n.object({op:n.literal(`remove`),nodeId:k})]),er=n.object({canvasId:n.uuid(),mutationId:n.uuid(),baseVersion:n.number().int().positive(),operations:n.array($n).min(1).max(Jn)}),tr=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),insertedNodeIds:n.array(k),changedNodeIds:n.array(k),removedNodeIds:n.array(k),boxes:n.record(k,S),affectedBounds:Xn.nullable(),next:n.array(n.string().min(1))}),nr=Tt.extend({operation:Kn,next:n.array(n.string().min(1))}),rr=`enhance3.canvas.v1`,ir=n.enum([`blue`,`violet`,`green`,`amber`,`magenta`,`teal`,`red`,`orange`]),ar=n.object({kind:n.literal(`person`),connectionId:n.uuid(),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:ir}),or=n.object({kind:n.literal(`guest`),connectionId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:ir}),sr=n.discriminatedUnion(`kind`,[ar,or]),cr=n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),tokenLabel:n.string().min(1).max(100),colour:ir}),lr=n.discriminatedUnion(`kind`,[ar.omit({connectionId:!0}),cr]),ur=n.object({x:n.number(),y:n.number()}),dr=S.extend({width:n.number().positive(),height:n.number().positive()}),fr=n.object({kind:n.enum([`drag`,`resize`]),baseVersion:n.number().int().positive(),boxes:n.record(n.string().min(1).max(200),dr)}),pr=n.object({cursor:ur.nullable().optional(),input:n.enum([`pointer`,`touch`,`keyboard`]).optional(),focused:n.boolean().optional(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100).optional(),visibleWorldBox:dr.optional(),gesture:fr.nullable().optional(),cursorChat:n.string().max(140).nullable().optional()}).refine(e=>Object.keys(e).length>0,`presence patch cannot be empty`),mr=n.object({actor:sr,seq:n.number().int().nonnegative(),cursor:ur.nullable(),input:n.enum([`pointer`,`touch`,`keyboard`]),focused:n.boolean(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100),visibleWorldBox:dr.nullable(),gesture:fr.nullable(),cursorChat:n.string().max(140).nullable().default(null),expiresAt:n.iso.datetime()}),hr=n.enum([`reading`,`writing`,`creating`,`deleting`,`rendering`]),gr=n.object({activityId:n.uuid(),canvasId:n.uuid(),actor:cr,phase:hr,nodeIds:n.array(n.string().min(1).max(200)).max(100),bounds:dr.nullable(),expiresAt:n.iso.datetime()}),_r=n.object({canvasId:n.uuid(),protocols:n.array(n.literal(rr)).min(1).max(1)}),vr=n.object({endpoint:n.url(),ticket:n.string().min(1).max(4096),protocol:n.literal(rr),expiresAt:n.iso.datetime()}),yr=n.object({canvasId:n.uuid(),phase:hr,nodeIds:n.array(n.string().min(1).max(200)).max(100).default([]),bounds:dr.nullable().default(null)}),br=n.object({activityId:n.uuid(),expiresAt:n.iso.datetime(),renewAfterMs:n.number().int().positive()}),xr=yr.extend({activityId:n.uuid()}),Sr=n.object({canvasId:n.uuid(),activityId:n.uuid()}),Cr=n.object({ended:n.literal(!0)});n.discriminatedUnion(`type`,[n.object({v:n.literal(1),type:n.literal(`presence.patch`),seq:n.number().int().nonnegative(),payload:pr}),n.object({v:n.literal(1),type:n.literal(`room.pong`),seq:n.number().int().nonnegative(),payload:n.object({pingId:n.uuid()})})]);const A={v:n.literal(1),seq:n.number().int().nonnegative()};n.discriminatedUnion(`type`,[n.object({...A,type:n.literal(`room.snapshot`),payload:n.object({connectionId:n.uuid(),peers:n.array(mr),activities:n.array(gr),documentVersion:n.number().int().positive()})}),n.object({...A,type:n.literal(`presence.patch`),payload:mr}),n.object({...A,type:n.literal(`presence.left`),payload:n.object({connectionId:n.uuid()})}),n.object({...A,type:n.literal(`agent.activity`),payload:n.object({activityId:n.uuid(),activity:gr.nullable()})}),n.object({...A,type:n.literal(`document.committed`),payload:n.object({mutationId:n.uuid(),actor:lr,previousVersion:n.number().int().positive(),version:n.number().int().positive(),operations:n.array($n).min(1)})}),n.object({...A,type:n.literal(`sync.required`),payload:n.object({version:n.number().int().positive(),reason:n.enum([`gap`,`relay`,`replace`,`history-restored`])})}),n.object({...A,type:n.literal(`room.ping`),payload:n.object({pingId:n.uuid(),sentAt:n.iso.datetime()})}),n.object({...A,type:n.literal(`room.error`),payload:n.object({code:n.enum([`auth`,`permission`,`protocol`,`payload`,`rate`,`unavailable`]),message:n.string().min(1).max(200)})})]);const wr=n.object({jobId:n.uuid()}),Tr=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),target:Ft,sourceState:It.optional()}),Er=n.discriminatedUnion(`purpose`,[Tr.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),scale:n.number().positive().max(4),format:n.literal(`png`)}),Tr.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:on,scale:n.literal(1),format:n.literal(`json`)})]);n.object({jobId:n.uuid()}),n.object({jobId:n.uuid()});const Dr=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),grantToken:n.string().startsWith(`rgr_`).min(40).max(100),grantCookieName:n.string().min(1).max(100),renderUrl:n.url(),releaseIdentity:n.string().min(1).max(100)});n.discriminatedUnion(`purpose`,[Dr.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),target:Ft,sourceState:It.optional(),scale:n.number().positive(),outputKey:n.string().min(1).max(500)}),Dr.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:on,scale:n.literal(1)})]),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),bytes:n.number().int().positive().max(jt),storageKey:n.string().min(1).max(500),warnings:n.array(Ut),timings:n.array(Wt),sourceState:Lt.optional(),snapshot:n.object({artifactBytes:n.number().int().positive().max(Mt),artifactStorageKey:n.string().min(1).max(500),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}).optional()}),n.object({accepted:n.literal(!0)}),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Ct}),n.object({accepted:n.literal(!0)}),n.object({recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative(),artifact:n.string().min(1).max(Mt),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}),n.object({jobId:n.uuid(),failure:E}),n.object({accepted:n.literal(!0),willRetry:n.boolean()}),n.object({workerId:n.string().regex(/^[\w.-]+$/u).min(1).max(100),releaseIdentity:n.string().min(1).max(100),timestamp:n.coerce.number().int().nonnegative(),nonce:n.uuid(),mac:n.base64().min(32).max(200)});const Or=n.object({total:n.number().int().nonnegative(),loading:n.number().int().nonnegative(),unavailable:n.number().int().nonnegative()}),kr=n.object({jobId:n.uuid(),canvasId:n.uuid().nullable(),requestedVersion:n.number().int().positive().nullable(),loadedVersion:n.number().int().positive().nullable(),phase:Bt.exclude([`queued`,`claimed`,`capture`,`upload`,`complete`]),sources:Or,warnings:n.array(Ut),timings:n.array(Wt),sourceState:Lt.optional()}),Ar=n.object({selector:n.string().min(1).max(500),contentSelector:n.string().min(1).max(500).optional(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive()});n.discriminatedUnion(`state`,[kr.extend({state:n.literal(`loading`),capture:n.null(),failure:n.null()}),kr.extend({state:n.literal(`ready`),phase:n.literal(`target`),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),capture:Ar,failure:n.null()}),kr.extend({state:n.literal(`failed`),failure:n.object({reason:Vt,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),capture:n.null()})]);const jr=n.string().min(1).max(200),Mr=n.object({canvasId:n.uuid()}),Nr=n.object({canvasId:n.uuid(),status:n.enum([`selected`,`none`,`offline`,`stale`]),documentVersion:n.number().int().positive(),selectionRevision:n.number().int().positive().nullable(),selectionChangedAt:n.iso.datetime().nullable(),selectedNodeIds:n.array(jr),missingNodeIds:n.array(jr),nodes:n.array(En),contextRootId:jr.nullable(),visibleWorldBox:T.nullable(),next:n.array(n.string().min(1)).max(12)}),Pr=1e3,Fr=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2)}),n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2),tokenLabel:n.string().min(1).max(200)})]),Ir=n.object({id:n.uuid(),canvasId:n.uuid(),documentVersion:n.number().int().positive(),origin:n.enum([`automatic`,`manual`,`restore`]),restoreRole:n.enum([`before`,`result`]).nullable(),retention:n.enum([`automatic`,`named`,`restore-boundary`]),title:n.string().min(1).max(200).nullable(),description:n.string().max(Pr).nullable(),actor:Fr,sourceVersionEntryId:n.uuid().nullable(),expiresAt:n.iso.datetime().nullable(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime(),screenCount:n.number().int().min(0)}),Lr=n.object({canvasId:n.uuid(),limit:n.number().int().min(1).max(100).default(50),cursor:n.string().min(1).max(1e3).optional(),includeAutomatic:n.boolean().default(!1),actor:n.enum([`all`,`mine`]).default(`all`)}),Rr=n.object({current:n.object({documentVersion:n.number().int().positive(),updatedAt:n.iso.datetime()}),items:n.array(Ir),nextCursor:n.string().min(1).nullable(),hasExpiredHistory:n.boolean()}),zr=n.object({canvasId:n.uuid(),versionId:n.uuid()}),Br=n.object({outcome:n.literal(`ready`),entry:Ir,document:gn,screens:n.array(vn)}),Vr=n.object({outcome:n.literal(`missing-resources`),entry:Ir,document:gn,screens:n.array(vn),missingScreenIds:n.array(n.uuid()).min(1)}),Hr=n.discriminatedUnion(`outcome`,[Br,Vr,n.object({outcome:n.literal(`corrupt`),entry:Ir})]),Ur=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`current`),expectedVersion:n.number().int().positive()}),n.object({kind:n.literal(`version`),versionId:n.uuid()})]),Wr=n.object({canvasId:n.uuid(),target:Ur,title:n.string().trim().min(1).max(200),description:n.string().trim().max(Pr).nullable().default(null)}),Gr=n.object({canvasId:n.uuid(),versionId:n.uuid(),title:n.string().trim().min(1).max(200),description:n.string().trim().max(Pr).nullable().default(null)}),Kr=n.object({canvasId:n.uuid(),versionId:n.uuid()}),qr=n.object({entry:Ir}),Jr=n.object({canvasId:n.uuid(),versionId:n.uuid(),expectedVersion:n.number().int().positive()}),Yr=n.object({canvasId:n.uuid(),version:n.number().int().positive(),beforeVersionId:n.uuid(),restoredVersionId:n.uuid(),restoreFenceVersion:n.number().int().positive()}),Xr=n.object({canvasId:n.uuid(),versionId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),Zr=n.object({canvasId:n.uuid(),title:n.string().min(1).max(200),version:n.literal(1)}),Qr=n.object({inviteId:n.uuid(),email:n.string().max(254),accessLevel:m,sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),$r=n.object({canvasTitle:n.string().min(1),invitedBy:n.string().min(1),email:n.string().max(254).pipe(n.email()),accessLevel:m,expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),ei=n.object({canvasId:n.uuid(),email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email()),accessLevel:m}),ti=n.object({invite:Qr,acceptToken:n.string().max(512).optional()}),ni=n.object({canvasId:n.uuid()}),ri=f(Qr),ii=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),ai=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),oi=n.string().min(1).max(512),si=n.object({token:oi}),ci=n.object({token:oi}),li=n.object({canvasId:n.uuid(),accessLevel:m}),ui=n.object({personId:n.uuid().nullable(),email:n.string().max(254).nullable(),displayName:n.string().max(120).nullable(),initials:n.string().max(4).nullable(),avatarUrl:n.string().max(l).nullable(),accessLevel:p,isPending:n.boolean(),reviewState:n.enum([`not-started`,`in-progress`,`done`]).nullable(),lastViewedAt:n.iso.datetime().nullable()}),di=n.object({canvasId:n.uuid()}),fi=f(ui),pi=n.object({canvasId:n.uuid(),personId:n.uuid(),accessLevel:m}),mi=n.object({canvasId:n.uuid(),personId:n.uuid()}),hi=n.object({personId:n.uuid(),revoked:n.boolean()}),gi=n.object({canvasId:n.uuid(),reviewState:n.enum([`not-started`,`in-progress`,`done`])}),_i=n.object({reviewState:gi.shape.reviewState.nullable()}),vi=n.object({selector:n.string().min(1).max(2e3),tagName:n.string().min(1).max(40),label:n.string().max(80).nullable(),source:n.object({file:n.string().min(1).max(1024),line:n.number().int().min(0).nullable()}).nullable()}),yi=n.object({x:n.number(),y:n.number()}),bi=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1)}),xi=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1),width:n.number().min(0).max(1),height:n.number().min(0).max(1)}),Si=vi.extend({role:n.string().min(1).max(80).optional()}),Ci=n.object({path:n.array(n.number().int().min(0)).max(64),offset:n.number().int().min(0)}),wi=n.discriminatedUnion(`kind`,[n.object({version:n.literal(1),kind:n.literal(`element`),locator:Si,attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`text`),root:Si,quote:n.object({exact:n.string().min(1).max(1e3),prefix:n.string().max(120),suffix:n.string().max(120)}),range:n.object({start:Ci,end:Ci}),attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`elements`),members:n.array(Si).min(2).max(32),truncated:n.boolean(),attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`area`),bounds:xi,attachment:bi})]),Ti=n.discriminatedUnion(`on`,[n.object({on:n.literal(`canvas`),point:yi}),n.object({on:n.literal(`node`),nodeId:n.string().min(1).max(120),point:yi,element:n.null()}),n.object({on:n.literal(`screen`),nodeId:n.string().min(1).max(120),screenId:n.uuid(),point:yi,element:vi.nullable(),target:wi.optional()})]),Ei=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(l).nullable(),tokenLabel:n.string().max(120).nullable()}),Di=n.object({personId:n.uuid(),name:n.string().min(1).max(120)}),Oi=n.object({emoji:n.string().min(1).max(16),people:n.array(Di).min(1)}),ki=n.object({messageId:n.uuid(),seq:n.number().int().min(1),body:n.string().min(1),author:Ei,createdAt:n.iso.datetime(),editedAt:n.iso.datetime().nullable(),mentions:n.array(Di),reactions:n.array(Oi)}),Ai=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),tokenLabel:n.string().max(120).nullable()}),j=n.object({threadId:n.uuid(),canvasId:n.uuid(),anchor:Ti,author:Ei,messages:n.array(ki).min(1).max(50),messageCount:n.number().int().min(1),hasMoreMessages:n.boolean(),isResolved:n.boolean(),resolvedAt:n.iso.datetime().nullable(),resolvedBy:Ai.nullable(),createdAt:n.iso.datetime(),lastMessageAt:n.iso.datetime()}),ji=n.object({canvasId:n.uuid(),filter:n.enum([`open`,`resolved`,`all`]).default(`open`),authorPersonId:n.uuid().optional(),agentActionable:n.boolean().default(!1),query:n.string().trim().max(200).optional()}),Mi=f(j),Ni=n.object({canvasId:n.uuid(),clientThreadId:n.uuid(),anchor:Ti,body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Pi=n.object({canvasId:n.uuid(),threadId:n.uuid(),clientMessageId:n.uuid(),body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Fi=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Ii=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),emoji:n.string().trim().min(1).max(16),reacted:n.boolean()}),Li=n.object({canvasId:n.uuid(),threadId:n.uuid(),anchor:Ti}),Ri=n.object({canvasId:n.uuid(),threadId:n.uuid(),resolved:n.boolean()}),zi=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid().optional()}),Bi=n.object({deletedThreadIds:n.array(n.uuid()),deletedMessageIds:n.array(n.uuid())}),Vi=n.enum([`owner`,`admin`,`member`]),Hi=n.object({id:n.uuid(),name:n.string().min(1).max(120),role:Vi}),Ui=n.object({}),Wi=f(Hi),Gi=n.object({name:n.string().trim().min(1).max(120)}),Ki=n.object({organisation:Hi}),qi=n.object({organisationId:n.uuid(),name:n.string().trim().min(1).max(120)}),Ji=n.object({organisationId:n.uuid()}),Yi=n.object({organisationId:n.uuid(),movedCanvasCount:n.number().int().min(0)}),Xi=n.object({personId:n.uuid(),displayName:n.string().max(120),initials:n.string().max(4),email:n.string().max(254).nullable(),role:Vi}),Zi=n.object({organisationId:n.uuid()}),Qi=f(Xi),$i=n.object({organisationId:n.uuid(),email:n.email().trim().toLowerCase().max(254),role:n.enum([`admin`,`member`]).default(`member`)}),ea=n.object({personId:n.uuid()}),ta=n.object({organisationId:n.uuid(),personId:n.uuid(),role:n.enum([`admin`,`member`])}),na=ta.pick({personId:!0,role:!0}),ra=n.object({organisationId:n.uuid(),personId:n.uuid()}),ia=n.object({personId:n.uuid(),removed:n.literal(!0)}),aa=n.object({organisationId:n.uuid(),personId:n.uuid()}),oa=n.object({ownerPersonId:n.uuid()}),sa=n.object({inviteId:n.uuid(),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),ca=n.object({organisationId:n.uuid(),email:n.string().trim().toLowerCase().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]).default(`member`)}),la=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`member`),personId:n.uuid()}),n.object({kind:n.literal(`invitation`),invite:sa})]),ua=n.object({invite:sa}),da=n.object({organisationId:n.uuid()}),fa=f(sa),pa=n.object({organisationId:n.uuid(),inviteId:n.uuid()}),ma=pa.extend({}),ha=n.string().min(1).max(512),ga=n.object({token:ha}),_a=n.object({token:ha}),va=n.object({teamName:n.string().min(1).max(120),invitedBy:n.string().min(1).max(120),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),ya=n.object({organisationId:n.uuid()}),ba=n.object({id:n.uuid(),label:n.string().min(1).max(120),createdAt:n.iso.datetime(),lastUsedAt:n.iso.datetime().nullable(),expiresAt:n.iso.datetime().nullable(),revoked:n.boolean()}),xa=n.object({label:n.string().trim().min(1).max(120).describe(`Label naming the agent.`),expiresAt:n.iso.datetime().nullable().describe(`Expiry timestamp, or null for a token that does not expire.`)}),Sa=n.object({token:n.string().startsWith(`enh_`),agentToken:ba}),Ca=n.object({}),wa=n.object({items:n.array(ba)}),Ta=n.object({tokenId:n.uuid()}),Ea=n.object({tokenId:n.uuid(),revoked:n.literal(!0)}),Da=n.discriminatedUnion(`method`,[n.object({method:n.literal(`token`)}),n.object({method:n.literal(`browser`),issuer:n.url(),clientId:n.string().min(1),scope:n.literal(`openid`)})]),Oa=n.object({id:n.uuid(),preparedCanvasId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(l).nullable(),email:n.string().max(254).nullable(),createdAt:n.iso.datetime()}),ka=n.object({}),Aa=n.object({person:Oa.nullable(),authentication:n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`anonymous`)}),n.object({kind:n.literal(`person`)}),n.object({kind:n.literal(`agent`),tokenId:n.uuid(),tokenLabel:n.string(),expiresAt:n.iso.datetime().nullable()}),n.object({kind:n.literal(`oauth-agent`),tokenId:n.uuid(),tokenLabel:n.string(),clientId:n.string().min(1),scopes:n.array(n.string()),expiresAt:n.iso.datetime(),resource:n.url()})])}),ja=n.object({displayName:n.string().trim().min(1).max(120)}),Ma=n.object({person:Oa}),Na=n.string().trim().toLowerCase().min(3).max(40).regex(/^[a-z0-9][a-z0-9._-]*$/,`letters, digits, dot, underscore and dash only`),Pa=n.enum([`cookie`,`token`]).default(`cookie`),Fa=n.object({username:Na,password:n.string().min(10).max(200),displayName:n.string().trim().min(1).max(120),deliver:Pa,email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email())}),Ia=n.object({username:Na,password:n.string().min(1).max(200),deliver:Pa}),La=n.object({person:Oa,token:n.string().nullable()}),Ra=La.extend({preparedCanvasId:n.uuid()}),za=n.object({}),Ba=n.object({signedOut:n.literal(!0)}),Va=n.string().max(254).pipe(n.email()),Ha=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),email:Va}),n.object({kind:n.literal(`email`),email:Va})]),Ua=n.object({query:n.string().trim().min(1).max(200)}),Wa=n.object({recipients:n.array(Ha).max(5)}),Ga=n.object({}),Ka=Wa.extend({}),qa=`enhance3:session-handoff`;n.union([n.object({kind:n.literal(qa),body:n.object({token:n.string().min(1),displayName:n.string().min(1)})}),n.object({kind:n.literal(qa),signedOut:n.literal(!0)})]);const Ja=n.string().min(1).max(500).refine(e=>!e.startsWith(`/`)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),Ya=n.object({path:Ja,contentType:n.string().min(1).max(200),bytes:n.number().int().nonnegative().max(26214400)}),Xa=n.enum([`uploading`,`verifying`,`ready`,`failed`,`abandoned`]),Za=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1).max(200),title:n.string().trim().min(1).max(200),entryPath:Ja.default(`index.html`),files:n.array(Ya).min(1).max(2e3),box:S.extend({width:n.number().positive(),height:n.number().positive()})}),Qa=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),state:Xa,alreadyExists:n.boolean(),fileCount:n.number().int().positive(),totalBytes:n.number().int().positive().max(262144e3)}),$a=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),cursor:n.number().int().min(0).default(0)}),eo=n.object({path:Ja,upload:w}),to=n.object({deploymentId:n.uuid(),uploads:n.array(eo).max(50),nextCursor:n.number().int().min(0).optional()}),no=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive()}),ro=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)}),io=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid()}),ao=n.object({deploymentId:n.uuid(),origin:n.url(),bootUrl:n.url(),expiresAt:n.iso.datetime()}),oo=`__enhance/manifest.json`,so=n.string().length(64).refine(e=>{for(let t of e)if(!/[\da-f]/u.test(t))return!1;return!0}),co=e=>{for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&(e===127||e<=31))return!0}return!1},lo=e=>e.normalize(`NFKC`).toUpperCase().toLowerCase(),uo=n.string().min(1).refine(e=>e===e.normalize(`NFC`),{message:`prototype paths must use NFC Unicode normalization`}).refine(e=>!e.startsWith(`/`)&&!/^[A-Za-z]:\//u.test(e)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!co(e)&&!e.startsWith(`__enhance/`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),fo=n.object({path:uo,contentType:n.string().trim().min(1).max(200).refine(e=>!co(e)),bytes:n.number().int().nonnegative().max(2**53-1),sha256:so}),po=n.object({version:n.literal(1),entryPath:uo,files:n.array(fo).min(1)}),mo=n.object({artifactBytes:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1),fileBytes:n.number().int().positive().max(2**53-1),manifestBytes:n.number().int().positive().max(2**53-1),fileCount:n.number().int().positive().max(2**53-1),pathBytes:n.number().int().positive().max(2**53-1)}),ho=n.object({}),go=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),limits:mo}),_o=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),bytes:n.number().int().positive().max(2**53-1),sha256:so,fileCount:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1)}),vo=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1),title:n.string().trim().min(1).max(200),entryPath:uo,artifact:_o,box:S.extend({width:n.number().positive(),height:n.number().positive()})}),yo=n.enum([`uploading`,`queued`,`ingesting`,`ready`,`failed`,`abandoned`]),bo=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),alreadyExists:n.boolean(),artifact:_o}),xo=n.discriminatedUnion(`state`,[bo.extend({state:n.literal(`uploading`),upload:w}),bo.extend({state:n.enum([`queued`,`ingesting`,`ready`,`failed`,`abandoned`])})]),So=n.object({canvasId:n.uuid(),deploymentId:n.uuid()}),Co=n.object({deploymentId:n.uuid(),state:yo}),wo=n.object(So.shape),To=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),fileCount:n.number().int().nonnegative(),totalBytes:n.number().int().nonnegative().max(2**53-1),processedFiles:n.number().int().nonnegative()}),Eo=n.discriminatedUnion(`state`,[To.extend({state:n.literal(`failed`),failure:n.object({code:n.string().min(1),message:n.string().min(1),path:uo.optional()})}),To.extend({state:n.enum([`uploading`,`queued`,`ingesting`,`ready`,`abandoned`])})]),Do=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive()}),Oo=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)});n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.capture`),requestId:n.uuid()}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.ready`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.escape`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.zoom`),deltaX:n.number(),deltaY:n.number(),deltaMode:n.union([n.literal(0),n.literal(1),n.literal(2)]),anchorX:n.number().min(0).max(1),anchorY:n.number().min(0).max(1)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigate`),direction:n.enum([`back`,`forward`])}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigation`),canGoBack:n.boolean(),canGoForward:n.boolean()});const ko=n.object({artifact:n.string().min(1),viewport:n.object({width:n.number().positive(),height:n.number().positive()}),title:n.string()}),Ao=n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.captured`),requestId:n.uuid()});n.discriminatedUnion(`outcome`,[Ao.extend({outcome:n.literal(`captured`),screen:ko}),Ao.extend({outcome:n.literal(`failed`),error:n.string().min(1)})]);const jo=2166136261,Mo=Number.parseInt(`9e3779b9`,16),No=Number.parseInt(`85ebca6b`,16),Po=Number.parseInt(`c2b2ae35`,16);jo^Mo,jo^No,jo^Po;const Fo=(e,t)=>`/v1/recording-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,Io=n.object({width:n.number().int().positive(),height:n.number().int().positive()}),Lo=16*d,Ro=8*d,zo=l,Bo=n.object({mimeType:n.string().min(1).max(100),sampleRate:n.number().int().min(8e3).max(192e3)}),Vo=n.object({sourceUrl:n.string().max(zo),viewport:Io,pageTitle:n.string().max(200).nullable(),audio:Bo.nullable().default(null)}),Ho=n.object({recordingId:n.uuid(),ownerPersonId:n.uuid(),chunkIndex:n.literal(0),upload:w,audioUpload:w.nullable()}),Uo=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),eventCount:n.number().int().min(0),continues:n.boolean().default(!1),bytes:n.number().int().min(1).max(Lo),etag:n.string().min(1).max(200).optional()}),Wo=n.object({nextChunkIndex:n.number().int().min(1),upload:w}),Go=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),bytes:n.number().int().min(1).max(Lo),epoch:n.number().int().min(0).default(0),startsEpoch:n.boolean().default(!1),etag:n.string().min(1).max(200).optional()}),Ko=n.object({nextChunkIndex:n.number().int().min(1),upload:w}),qo=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0).max(144e5),viewport:Io,sourceUrl:n.string().max(zo),interrupted:n.boolean().default(!1),canvasId:n.uuid().optional(),organisationId:n.uuid().optional(),audioChunkCount:n.number().int().min(0).default(0),hasRecoverableBytes:n.boolean().default(!1)}).refine(e=>e.canvasId===void 0||e.organisationId===void 0,{message:`choose an existing canvas or a team for a new canvas, not both`}),Jo=n.enum([`whole`,`recovering`,`partial`]),Yo=n.enum([`dom`,`audio`]),Xo=n.object({recordingId:n.uuid(),canvasId:n.uuid(),canvasTitle:n.string().min(1).max(200),isNewCanvas:n.boolean(),storedChunkCount:n.number().int().min(0),missingChunkIndexes:n.array(n.number().int().min(0)).max(64),missingChunkCount:n.number().int().min(0),storedAudioChunkCount:n.number().int().min(0),missingAudioChunkIndexes:n.array(n.number().int().min(0)).max(64),missingAudioChunkCount:n.number().int().min(0),integrity:Jo}),Zo=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:Io,interrupted:n.boolean(),chunkCount:n.number().int().min(0),startedAt:n.iso.datetime()}),Qo=n.object({recordingId:n.uuid(),assets:n.array(n.object({url:n.url().max(zo),contentType:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Ro)})).max(400)}),$o=n.object({reserved:n.array(n.object({url:n.string(),upload:w}))}),es=n.object({recordingId:n.uuid(),arrived:n.array(n.object({url:n.url().max(zo),etag:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Ro)})).max(400)}),ts=n.object({missingAssetCount:n.number().int().min(0)}),ns=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),rs=n.object({seq:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),continues:n.boolean()}),is=n.discriminatedUnion(`state`,[rs.extend({state:n.literal(`available`),download:Et}),rs.extend({state:n.literal(`missing`)})]),as=n.object({seq:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),epoch:n.number().int().min(0),startsEpoch:n.boolean()}),os=n.discriminatedUnion(`state`,[as.extend({state:n.literal(`available`),download:Et}),as.extend({state:n.literal(`missing`)})]),ss=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:Io,sourceUrl:n.string().max(zo),interrupted:n.boolean(),integrity:Jo,chunks:n.array(is),audio:n.object({mimeType:n.string(),chunks:n.array(os)}).nullable(),assets:n.array(n.object({url:n.string(),contentType:n.string(),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0)}),cs=n.object({recordingId:n.uuid(),track:Yo,index:n.number().int().min(0)}),ls=n.object({upload:w}),us=cs.extend({etag:n.string().min(1).max(200)}),ds=n.object({integrity:Jo}),fs=n.object({canvasId:n.uuid()}),ps=f(Zo),ms=n.object({recordingId:n.uuid()}),hs=n.object({recordingId:n.uuid(),discarded:n.literal(!0)}),gs=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),_s=n.object({recordingId:n.uuid(),detachedScreenCount:n.number().int().min(0)});[`[data-enhance-unsupported]:not([data-enhance-unsupported-hidden]):not([style*="display: none"]) {
2
+ import{FailedToExitError as e,parseRouter as t}from"trpc-cli";import{z as n}from"zod";import{createHash as r}from"node:crypto";import{TRPCError as i,initTRPC as a}from"@trpc/server";import{middlewareMarker as o}from"@trpc/server/unstable-core-do-not-import";import{TRPCClientError as s}from"@trpc/client";var c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const l=2048,ee=1e4,u=1024,d=u*u;n.object({cursor:n.string().nullable().default(null),limit:n.number().int().min(1).max(100).default(20)});const f=e=>n.object({items:n.array(e),truncated:n.boolean()}),te=n.enum([`never-captured`,`capture-pending`,`extension-unavailable`,`capture-failed`,`source-mismatch`,`upload-incomplete`,`blob-missing`,`image-load-failed`,`unsupported-legacy-state`]),ne=n.object({thumbnailId:n.uuid(),url:n.string().max(4096),width:n.literal(528),height:n.literal(312),bytes:n.number().int().min(1).max(1048576)}),re=n.object({canvasId:n.uuid(),thumbnailId:n.uuid(),clientReleaseIdentity:n.string().min(1).max(100),attemptedOperation:n.literal(`thumbnail-download`),recoveryOutcome:n.literal(`fallback-shown`)}),ie=n.object({recorded:n.literal(!0)}),ae=n.enum([`invite-only`,`link-view`,`link-comment`]),p=n.enum([`owner`,`can-comment`,`can-view`]),m=n.enum([`can-comment`,`can-view`]),oe=n.object({read:n.boolean(),comment:n.enum([`yes`,`sign-in`,`no`]),share:n.boolean(),manage:n.boolean()}),h=n.object({id:n.uuid(),title:n.string().min(1).max(200),accessState:ae,organisationId:n.uuid().nullable(),sourceUrl:n.string().max(l).nullable(),unresolvedCount:n.number().int().min(0),viewerCan:oe,createdAt:n.iso.datetime(),lastActivityAt:n.iso.datetime()}),g=n.object({title:n.string().trim().min(1).max(200),organisationId:n.uuid().nullable().default(null),sourceUrl:n.string().max(l).nullable().default(null)}),se=n.object({canvasId:n.uuid()}),ce=n.union([n.literal(`own`),n.literal(`everything`),n.uuid()]),le=n.object({collection:ce.default(`own`),title:n.string().trim().min(1).max(200).optional().describe(`Title text to match before returning canvas ids.`),deleted:n.boolean().default(!1),accessState:ae.optional(),scope:n.enum([`all`,`mine`,`shared`]).default(`all`),hasUnresolved:n.boolean().default(!1)}),ue=h.extend({screenCount:n.number().int().min(0),hasRecording:n.boolean()}),de=f(n.union([ue.extend({thumbnail:ne}),ue.extend({thumbnail:n.null(),thumbnailFallbackReason:te})])),fe=n.object({canvasId:n.uuid(),title:n.string().trim().min(1).max(200)}),pe=n.object({canvasId:n.uuid()}),me=n.object({canvasId:n.uuid(),deletedAt:n.iso.datetime()}),he=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)])}),ge=n.object({canvas:h}),_e=n.object({canvasId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),ve=n.object({canvas:h}),ye=n.object({canvasId:n.uuid(),confirmation:n.string().min(1).max(200)}),be=n.object({canvasId:n.uuid()}),xe=n.object({canvasId:n.uuid(),accessState:ae}),Se=n.object({canvas:h,widened:n.boolean()}),Ce=n.object({canvasId:n.uuid()}),we=n.object({lastViewedAt:n.iso.datetime().nullable()}),Te=n.object({canvasId:n.uuid()}),Ee=n.object({canvasId:n.uuid()}),De=1e5,_=n.number().min(-1e5).max(De),v=n.number().nonnegative().max(De),Oe=n.object({ratio:v,offset:_.optional()}),ke=n.object({min:v.optional(),max:v.optional(),minParent:Oe.optional(),maxParent:Oe.optional()}).refine(({min:e,max:t})=>e===void 0||t===void 0||e<=t,`size minimum cannot exceed maximum`),Ae=n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`fixed`),value:v}),ke.extend({mode:n.literal(`hug`),basis:v.optional()}),ke.extend({mode:n.literal(`fill`),offset:_.optional()})]),je=n.object({top:v,right:v,bottom:v,left:v}),Me=n.union([n.literal(`auto`),_]),Ne=n.object({top:Me,right:Me,bottom:Me,left:Me}),Pe=n.object({basis:v,align:n.enum([`start`,`center`,`end`,`stretch`])}),Fe=n.object({mode:n.enum([`auto-fill`,`auto-fit`]),minimum:n.number().positive().max(De)}),Ie=n.object({x:_,y:_}),Le=n.object({direction:n.enum([`row`,`column`]),alignItems:n.enum([`start`,`center`,`end`,`stretch`]),alignContent:n.enum([`start`,`center`,`end`,`stretch`,`space-between`,`space-around`,`space-evenly`]).optional(),justifyContent:n.enum([`start`,`center`,`end`,`space-between`,`space-around`,`space-evenly`]),gap:v,rowGap:v.optional(),columnGap:v.optional(),wrap:n.enum([`nowrap`,`wrap`]).optional(),gridColumns:n.number().int().positive().max(De).optional(),gridAutoRepeat:Fe.optional(),materialized:n.boolean().optional(),padding:je}),Re=n.object({rotation:_,flipHorizontal:n.boolean().optional(),flipVertical:n.boolean().optional(),aspectRatioLocked:n.boolean().optional(),aspectRatio:n.number().positive().max(De).optional(),horizontal:Ae,vertical:Ae,position:n.enum([`flow`,`absolute`]),alignSelf:n.enum([`auto`,`start`,`center`,`end`,`stretch`]).optional(),flexGrow:v.optional(),flexShrink:v.optional(),flexBasis:n.union([n.literal(`auto`),v,Oe]).optional(),flowOffset:Ie.optional(),order:_.int().optional(),margin:Ne.optional(),gridTrack:Pe.optional(),clipContent:n.boolean().optional(),container:Le.optional()}),ze=_,y=v,b=n.number().min(0).max(1),Be=n.string().min(1).max(200),Ve=n.object({space:n.enum([`srgb`,`display-p3`]),red:b,green:b,blue:b,alpha:b}),He=n.object({id:Be,position:b,color:Ve}),Ue=n.object({x:b,y:b}),We=n.object({id:Be,visible:n.boolean(),opacity:b}),Ge=n.discriminatedUnion(`kind`,[We.extend({kind:n.literal(`solid`),color:Ve}),We.extend({kind:n.literal(`linear-gradient`),angle:ze,stops:n.array(He).min(2).max(32)}),We.extend({kind:n.literal(`radial-gradient`),center:Ue,radius:Ue,stops:n.array(He).min(2).max(32)}),We.extend({kind:n.literal(`image`),assetId:n.string().min(1).max(500),fit:n.enum([`fill`,`fit`,`crop`,`tile`]),crop:n.object({x:b,y:b,width:b,height:b}).optional()})]),Ke=n.object({topLeft:y,topRight:y,bottomRight:y,bottomLeft:y,smoothing:b.optional()}),qe=n.object({visible:n.boolean(),width:n.object({top:y,right:y,bottom:y,left:y}),style:n.enum([`solid`,`dashed`,`dotted`]),paint:Ge,alignment:n.enum([`inside`,`center`,`outside`])}),Je=n.object({visible:n.boolean(),width:y,offset:ze,style:n.enum([`solid`,`dashed`,`dotted`]),paint:Ge}),Ye=n.object({id:Be,visible:n.boolean(),kind:n.enum([`outer`,`inner`]),color:Ve,offsetX:ze,offsetY:ze,blur:y,spread:ze}),x=n.object({id:Be,visible:n.boolean()}),Xe=n.discriminatedUnion(`kind`,[x.extend({kind:n.literal(`blur`),value:y}),x.extend({kind:n.literal(`brightness`),value:y}),x.extend({kind:n.literal(`contrast`),value:y}),x.extend({kind:n.literal(`grayscale`),value:b}),x.extend({kind:n.literal(`hue-rotate`),value:ze}),x.extend({kind:n.literal(`invert`),value:b}),x.extend({kind:n.literal(`saturate`),value:y}),x.extend({kind:n.literal(`sepia`),value:b})]),Ze=n.enum([`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`plus-lighter`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`]);n.object({opacity:b,blendMode:Ze,fills:n.array(Ge).max(32),border:qe,outline:Je,radius:Ke,shadows:n.array(Ye).max(32),filters:n.array(Xe).max(32),backdropFilters:n.array(Xe).max(32)});const Qe=n.object({opacity:b.optional(),blendMode:Ze.optional(),fills:n.array(Ge).max(32).optional(),border:qe.optional(),outline:Je.optional(),radius:Ke.optional(),shadows:n.array(Ye).max(32).optional(),filters:n.array(Xe).max(32).optional(),backdropFilters:n.array(Xe).max(32).optional()}).refine(e=>Object.keys(e).length>0,`appearance values cannot be empty`),$e=[`opacity`,`blendMode`,`fills`,`border`,`outline`,`radius`,`shadows`,`filters`,`backdropFilters`],et=n.enum($e),tt=n.object({opacity:b.optional(),blendMode:Ze.optional(),fills:n.array(Ge).max(32).optional(),border:qe.optional(),outline:Je.optional(),radius:Ke.optional(),shadows:n.array(Ye).max(32).optional(),filters:n.array(Xe).max(32).optional(),backdropFilters:n.array(Xe).max(32).optional(),clear:n.array(et).min(1).max($e.length).optional()}).refine(e=>Object.keys(e).length>0,`appearance patch cannot be empty`).refine(({clear:e,...t})=>e===void 0||e.every(e=>t[e]===void 0),`appearance patch cannot set and clear the same property`),nt=n.number().min(-1e5).max(De),rt=n.number().nonnegative().max(De),it=n.object({family:n.string().min(1).max(500),fallbackFamilies:n.array(n.string().min(1).max(500)).max(20),size:rt,weight:n.number().int().min(1).max(1e3),style:n.enum([`normal`,`italic`,`oblique`]),lineHeight:n.discriminatedUnion(`mode`,[n.object({mode:n.literal(`normal`)}),n.object({mode:n.literal(`fixed`),value:rt})]),letterSpacing:nt,align:n.enum([`left`,`center`,`right`,`justify`]),verticalAlign:n.enum([`top`,`middle`,`bottom`]),transform:n.enum([`none`,`uppercase`,`lowercase`,`capitalize`]),decoration:n.object({line:n.enum([`none`,`underline`,`line-through`]),style:n.enum([`solid`,`double`,`dotted`,`dashed`,`wavy`]),color:Ve.optional(),thickness:rt.optional()}),stroke:n.object({width:rt,paint:Ge}).optional(),wrapping:n.enum([`wrap`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]),insets:n.object({top:nt,right:nt,bottom:nt,left:nt}).optional()}),at=/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu,ot=/^(?:behavior|-moz-binding)$/iu,st=n.string().min(1).max(200).regex(/^(?:--[\w-]+|-(?:webkit|moz|ms|o)-[a-z][a-z\d-]*|[a-z][a-z\d-]*)$/iu).refine(e=>!ot.test(e),`unsafe CSS property`),ct=n.string().max(1e4).refine(e=>!at.test(e),`unsafe CSS value`),lt=n.object({id:n.string().min(1).max(200),property:st,value:ct,enabled:n.boolean()}),ut=n.object({declarations:n.array(lt).max(128)}).refine(({declarations:e})=>new Set(e.map(e=>e.id)).size===e.length,`additional style ids must be unique`),S=n.object({x:n.number(),y:n.number(),width:n.number().nonnegative(),height:n.number().nonnegative()}),dt=n.enum([`start`,`center`,`end`,`stretch`,`scale`]),ft=n.object({x:dt,y:dt}),pt=n.enum([`source`,`generated`,`user`]),mt=n.looseObject({id:n.string().min(1).max(200),label:n.string().max(500),component:n.string().min(1).max(100),labelOrigin:pt.optional(),visible:n.boolean().optional(),locked:n.boolean().optional(),constraints:ft.optional(),styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:Re.optional(),responsive:n.never().optional(),appearance:Qe.optional(),typography:it.optional(),additionalStyles:ut.optional(),props:n.record(n.string(),n.unknown()).optional(),box:S.optional()}),ht=n.object({version:n.literal(2),nodes:n.record(n.string(),mt),relationships:n.record(n.string(),n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)})),tombstones:n.record(n.string(),n.literal(!0)).default({})}),gt=()=>({version:2,nodes:{root:{id:`root`,label:`Canvas`,component:`root`,labelOrigin:`generated`,visible:!0,locked:!1,styles:{}}},relationships:{},tombstones:{}}),_t=3e4,C=5e4,vt=n.string().min(1).max(200),yt=n.object({code:n.enum([`asset-unavailable`,`content-omitted`,`cross-origin-frame`,`nodes-truncated`,`responsive-behavior-not-editable`,`style-degraded`,`unsupported-surface`]),message:n.string().min(1).max(500),temporaryId:vt.optional()}),bt=n.object({nodeCount:n.number().int().positive().max(_t),sourceNodeCount:n.number().int().positive().max(C).optional(),collapsedNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedNeutralWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),collapsedTransferredWrapperNodeCount:n.number().int().nonnegative().max(C).optional(),layoutContainerCount:n.number().int().nonnegative().max(_t).optional(),removedLeafNodeCount:n.number().int().nonnegative().max(C).optional(),retainedSemanticOwnerNodeCount:n.number().int().nonnegative().max(C).optional(),truncatedNodeCount:n.number().int().nonnegative().max(C).optional(),issues:n.array(yt).max(C)}).refine(({collapsedNeutralWrapperNodeCount:e,collapsedTransferredWrapperNodeCount:t,collapsedWrapperNodeCount:n})=>n===void 0||e===void 0||t===void 0||e+t===n,`wrapper collapse proof classes must explain the collapsed wrapper count`).refine(({collapsedNodeCount:e,collapsedWrapperNodeCount:t,removedLeafNodeCount:n})=>e===void 0||t===void 0||n===void 0||t+n===e,`collapsed node kinds must explain the total collapsed node count`).refine(({collapsedNodeCount:e,nodeCount:t,sourceNodeCount:n,truncatedNodeCount:r})=>n===void 0||e===void 0||n-t===e+(r??0),`collapsed and truncated node counts must explain the source to editable difference`).refine(({layoutContainerCount:e,nodeCount:t})=>e===void 0||e<=t,`layout container count cannot exceed editable node count`),xt=mt.omit({id:!0}).extend({temporaryId:vt}),St=n.object({temporaryId:vt,parentTemporaryId:vt,sortKey:n.string().min(1).max(500)}),Ct=n.object({version:n.literal(1),rootTemporaryId:vt,nodes:n.array(xt).min(1).max(_t),relationships:n.array(St).max(_t-1),report:bt}),wt=n.object({canvasId:n.uuid(),mutationId:n.uuid(),baseVersion:n.number().int().positive(),screenNodeId:n.string().min(1).max(200),draft:Ct}),Tt=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),rootNodeId:n.string().min(1).max(200),idMap:n.record(vt,n.string().min(1).max(200)),insertedNodeIds:n.array(n.string().min(1).max(200)),removedNodeIds:n.array(n.string().min(1).max(200)),boxes:n.record(n.string().min(1).max(200),S),affectedBounds:S}),w=n.object({url:n.url(),expiresAt:n.iso.datetime(),headers:n.record(n.string(),n.string())}),Et=n.object({url:n.url(),expiresAt:n.iso.datetime(),bytes:n.number().int().min(0)}),Dt=[`queued`,`claimed`,`grant`,`navigate`,`document`,`sources`,`fonts`,`layout`,`target`,`capture`,`serialize`,`compile`,`commit`,`upload`,`complete`],Ot=[`queued`,`running`,`succeeded`,`failed`,`cancelled`,`expired`],kt=[`VERSION_CHANGED`,`TARGET_NOT_FOUND`,`TARGET_INVALID`,`OUTPUT_TOO_LARGE`,`READINESS_TIMEOUT`,`SOURCE_FAILED`,`BROWSER_CRASH`,`CAPTURE_FAILED`,`CONVERSION_FAILED`,`UPLOAD_FAILED`,`WORKER_UNAVAILABLE`,`CANCELLED`,`EXPIRED`,`INTERNAL`],At=[`ASSET_UNAVAILABLE`,`FONT_FALLBACK`,`SOURCE_FALLBACK`,`SCALE_REDUCED`],jt=32*d,Mt=64*d,Nt=1e5,Pt=.1,T=n.object({x:n.number(),y:n.number(),width:n.number().positive().max(Nt),height:n.number().positive().max(Nt)}),Ft=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`content`)}),n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`bounds`),bounds:T})]),It=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),Lt=n.object({kind:n.literal(`recording`),recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative()}),Rt=n.object({recordingId:n.uuid(),atMs:n.number().int().nonnegative(),screenId:n.uuid(),screenNodeId:n.string().min(1).max(200),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),box:T,version:n.number().int().positive(),alreadyPresent:n.boolean()}),zt=n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional(),target:Ft.default({kind:`content`}),sourceState:It.optional(),scale:n.number().min(Pt).max(4).default(1),format:n.literal(`png`).default(`png`)}).refine(e=>e.sourceState===void 0||e.target.kind===`node`,{message:`a source state requires a node render target`,path:[`sourceState`]}),Bt=n.enum(Dt);n.enum(Ot);const Vt=n.enum(kt),Ht=n.enum(At),Ut=n.object({code:Ht,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),E=n.object({reason:Vt,phase:Bt,message:n.string().min(1).max(500),retryable:n.boolean(),sourceId:n.string().min(1).max(200).nullable()}),Wt=n.object({phase:Bt,durationMs:n.number().int().min(0)}),Gt=n.object({canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),target:Ft,sourceState:Lt.optional(),snapshot:Rt.optional(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),contentType:n.literal(`image/png`),bytes:n.number().int().positive().max(jt),warnings:n.array(Ut),timings:n.array(Wt),expiresAt:n.iso.datetime()}).refine(e=>e.width*e.height<=16e6,{message:`render output may contain at most 16000000 pixels`,path:[`width`]}),Kt=n.object({id:n.uuid(),canvasId:n.uuid(),purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),phase:Bt,requestedVersion:n.number().int().positive(),target:Ft,sourceState:It.optional(),scale:n.number().positive(),format:n.literal(`png`),attempt:n.number().int().min(0),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),qt=n.discriminatedUnion(`state`,[Kt.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),Kt.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),Kt.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:Gt,failure:n.null()}),Kt.extend({state:n.literal(`failed`),result:n.null(),failure:E}),Kt.extend({state:n.literal(`cancelled`),result:n.null(),failure:E.extend({reason:n.literal(`CANCELLED`)})}),Kt.extend({state:n.literal(`expired`),result:n.null(),failure:E.extend({reason:n.literal(`EXPIRED`)})})]),Jt=n.object({job:qt,alreadyExists:n.boolean()}),Yt=n.object({jobId:n.uuid()}),Xt=n.object({job:qt}),Zt=n.object({jobId:n.uuid()}),Qt=n.object({job:qt}),$t=n.object({jobId:n.uuid()}),en=n.object({jobId:n.uuid(),download:Et}),tn=n.object({canvasId:n.uuid(),recordingId:n.uuid(),atMs:n.number().int().nonnegative()}),nn=n.object({job:qt,alreadyExists:n.boolean()}),rn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`adjacent`)}),n.object({kind:n.literal(`insert-children`),targetNodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`replace`),targetNodeId:n.string().min(1).max(200)})]),an=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),html:n.string().min(1).max(262144),label:n.string().min(1).max(500),idPrefix:n.string().min(1).max(80).regex(/^[\w-]+$/u).optional()})]),on=n.object({source:an,destination:rn}).superRefine((e,t)=>{e.source.kind===`screen`&&e.destination.kind!==`adjacent`&&t.addIssue({code:`custom`,message:`stored screens convert beside their source`,path:[`destination`]}),e.source.kind===`html`&&e.destination.kind===`adjacent`&&t.addIssue({code:`custom`,message:`authored HTML requires an editable destination`,path:[`destination`]})}),sn=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`screen`),nodeId:n.string().min(1).max(200)}),n.object({kind:n.literal(`html`),label:n.string().min(1).max(500)})]),cn=n.object({id:n.uuid(),canvasId:n.uuid(),source:sn,destination:rn,phase:Bt,requestedVersion:n.number().int().positive(),attempt:n.number().int().nonnegative(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime()}),ln=n.discriminatedUnion(`state`,[cn.extend({state:n.literal(`queued`),result:n.null(),failure:n.null()}),cn.extend({state:n.literal(`running`),result:n.null(),failure:n.null()}),cn.extend({state:n.literal(`succeeded`),phase:n.literal(`complete`),result:Tt.extend({report:bt}),failure:n.null()}),cn.extend({state:n.literal(`failed`),result:n.null(),failure:E}),cn.extend({state:n.literal(`cancelled`),result:n.null(),failure:E.extend({reason:n.literal(`CANCELLED`)})}),cn.extend({state:n.literal(`expired`),result:n.null(),failure:E.extend({reason:n.literal(`EXPIRED`)})})]),un=on.and(n.object({canvasId:n.uuid(),expectedVersion:n.number().int().positive().optional()})),dn=n.object({job:ln,alreadyExists:n.boolean()}),fn=n.object({jobId:n.uuid()}),pn=n.object({job:ln}),mn=n.object({jobId:n.uuid()}),hn=n.object({job:ln});n.discriminatedUnion(`state`,[n.object({state:n.literal(`loading`),jobId:n.uuid()}),n.object({state:n.literal(`ready`),jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Ct}),n.object({state:n.literal(`failed`),jobId:n.uuid(),message:n.string().min(1).max(500)})]);const gn=n.record(n.string(),n.unknown()),_n=n.object({canvasId:n.uuid()}),vn=n.object({screenId:n.uuid(),route:n.string().max(l).nullable(),title:n.string().max(200).nullable(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()}),atMs:n.number().int().min(0).nullable(),sourceRecordingId:n.uuid().nullable(),assetBundle:n.object({assetBundleId:n.uuid(),sourceUrl:n.string().max(l),assets:n.array(n.object({url:n.string().max(l),contentType:n.string().max(200),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0)}).nullable(),download:Et.nullable()}),yn=n.object({version:n.number().int().min(1),document:gn,screens:n.array(vn)}),bn=n.object({canvasId:n.uuid(),baseVersion:n.number().int().min(1),document:gn,screenIds:n.array(n.uuid()).max(2e3)}),xn=n.discriminatedUnion(`outcome`,[n.object({outcome:n.literal(`saved`),version:n.number().int().min(1)}),n.object({outcome:n.literal(`conflict`),version:n.number().int().min(1),document:gn})]),Sn=n.object({canvasId:n.uuid(),contentType:n.enum([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),bytes:n.number().int().positive().max(20971520)}),Cn=n.object({assetId:n.uuid(),path:n.string().startsWith(`/v1/canvas-assets/`),upload:w}),wn=(e,t)=>`/v1/canvas-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,Tn=n.enum([`position`,`layout`,`clip`,`cornerRadius`,`blending`,`typography`,`nativeControl`,`textDecoration`,`fill`,`outline`,`textStroke`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`vector`,`export`,`source`]),En=n.object({id:n.string().min(1).max(200),label:n.string().max(500),kind:n.string().min(1).max(100),parentId:n.string().min(1).max(200).nullable(),childCount:n.number().int().min(0),box:T.nullable(),propertySections:n.array(Tn)}),Dn=n.object({canvasId:n.uuid()}),On=n.object({canvasId:n.uuid(),title:n.string().min(1),version:n.number().int().positive(),nodeCount:n.number().int().min(0),rootChildCount:n.number().int().min(0),bounds:T.nullable(),kinds:n.record(n.string(),n.number().int().min(0)),next:n.array(n.string().min(1))}),kn=n.object({canvasId:n.uuid()}),An=n.object({canvasId:n.uuid(),version:n.number().int().positive(),nodes:n.array(En)}),jn=n.object({canvasId:n.uuid(),nodeId:n.string().min(1).max(200)}),Mn=n.object({canvasId:n.uuid(),version:n.number().int().positive(),node:En.extend({styles:n.record(n.string(),n.union([n.string(),n.number()])),layout:Re.optional(),appearance:Qe.optional(),typography:it.optional(),additionalStyles:ut.optional(),props:n.record(n.string(),n.unknown()),children:n.array(n.string().min(1).max(200))}),next:n.array(n.string().min(1))}),Nn=[`position`,`layout`,`cornerRadius`,`blending`,`fill`,`outline`,`border`,`outerShadow`,`innerShadow`,`filters`,`additionalStyles`,`export`],Pn=[`position`,`layout`,`clip`,...Nn.filter(e=>e!==`position`&&e!==`layout`)],Fn=[...Nn,`vector`],In=Object.fromEntries([{objectKind:`prototype`,label:`Prototype`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`node`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`]},{objectKind:`root`,label:`Canvas`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!0,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`page`,label:`Page`,category:`container`,capabilities:{canSelect:!1,canContainChildren:!1,canEditProperties:!1},selectionBehavior:{hitTarget:`children`},propertySections:[]},{objectKind:`screen`,label:`Screen`,category:`import`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1,commentAnchor:`screen`},capture:{preservesHtmlCssAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`,`source`]},{objectKind:`frame`,label:`Frame`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:Pn},{objectKind:`group`,label:`Group`,category:`container`,capabilities:{canSelect:!0,canContainChildren:!0,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:[`position`,`layout`,`blending`,`additionalStyles`,`export`]},{objectKind:`rectangle`,label:`Rectangle`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!1},propertySections:Nn},{objectKind:`image`,label:`Image`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:Nn},{objectKind:`svg`,label:`SVG`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},capture:{preservesVectorData:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:Fn},{objectKind:`recording`,label:`Recording`,category:`media`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!1},capture:{preservesAssets:!0},selectionBehavior:{hitTarget:`frame`},resizeBehavior:{mode:`scale`,preservesAspect:!0,heightFollowsContent:!1},propertySections:[]},{objectKind:`text`,label:`Text`,category:`primitive`,capabilities:{canSelect:!0,canContainChildren:!1,canEditProperties:!0,commentAnchor:`node`},selectionBehavior:{hitTarget:`text`},resizeBehavior:{mode:`reflow`,preservesAspect:!1,heightFollowsContent:!0},propertySections:[`position`,`layout`,`typography`,`nativeControl`,`textDecoration`,`textStroke`,`blending`,`fill`,`outerShadow`,`filters`,`additionalStyles`,`export`]}].map(e=>[e.objectKind,e])),Ln=e=>In[e]??null,Rn=e=>Ln(e)?.propertySections??[],zn=n.string().regex(/^(?:\d+(?:\.\d+)?|\.\d+)px$/u),Bn=n.string().regex(/^-?(?:\d+(?:\.\d+)?|\.\d+)px$/u),D={color:n.union([n.enum([`var(--note-ink)`,`var(--note-slate)`,`var(--note-red)`,`var(--note-orange)`,`var(--note-amber)`,`var(--note-green)`,`var(--note-teal)`,`var(--note-blue)`,`var(--note-violet)`,`var(--note-magenta)`]),n.string().regex(/^#[\da-f]{6}$/iu)]),"font-family":n.enum([`var(--sans)`,`var(--mono)`]),"font-size":n.union([n.literal(16),n.literal(24),n.literal(40),n.literal(64),n.literal(96)]),"font-weight":n.enum([`400`,`700`]),"font-style":n.enum([`normal`,`italic`,`oblique`]),"letter-spacing":n.number().min(-100).max(100),"line-height":n.union([n.number().positive().max(1e4),n.string().regex(/^(?:\d+(?:\.\d+)?(?:px|em|rem|%)?|normal)$/u)]),"text-align":n.enum([`left`,`center`,`right`]),"white-space":n.enum([`normal`,`nowrap`,`pre`,`pre-wrap`,`pre-line`,`break-spaces`])},Vn=n.strictObject({color:D.color.optional(),"font-family":D[`font-family`].optional(),"font-size":D[`font-size`].optional(),"font-weight":D[`font-weight`].optional(),"font-style":D[`font-style`].optional(),"letter-spacing":D[`letter-spacing`].optional(),"line-height":D[`line-height`].optional(),"text-align":D[`text-align`].optional(),"white-space":D[`white-space`].optional()}),Hn=n.strictObject({color:D.color.nullable().optional(),"font-family":D[`font-family`].nullable().optional(),"font-size":n.union([v,zn]).nullable().optional(),"font-weight":n.string().regex(/^(?:[1-9]\d{0,2}|1000)$/u).nullable().optional(),"font-style":D[`font-style`].nullable().optional(),"font-stretch":n.union([n.enum([`normal`,`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`]),n.string().regex(/^\d+(?:\.\d+)?%$/u)]).nullable().optional(),"letter-spacing":n.union([_,Bn,n.literal(`normal`)]).nullable().optional(),"line-height":D[`line-height`].nullable().optional(),"text-align":D[`text-align`].nullable().optional(),"text-indent":n.union([_,Bn]).nullable().optional(),"white-space":D[`white-space`].nullable().optional(),"word-spacing":n.union([_,Bn,n.literal(`normal`)]).nullable().optional()}),Un=n.enum([`auto`,`clip`,`hidden`,`scroll`,`visible`]),O=n.union([n.string(),_]),Wn=Hn.extend({background:n.string().nullable().optional(),"background-color":n.string().nullable().optional(),"border-bottom-left-radius":O.optional(),"border-bottom-right-radius":O.optional(),"border-bottom-width":O.optional(),"border-color":n.string().nullable().optional(),"border-left-width":O.optional(),"border-radius":O.nullable().optional(),"border-right-width":O.optional(),"border-style":n.enum([`none`,`solid`,`dashed`,`dotted`]).nullable().optional(),"border-top-left-radius":O.optional(),"border-top-right-radius":O.optional(),"border-top-width":O.optional(),"border-width":O.nullable().optional(),"box-shadow":n.string().nullable().optional(),"column-gap":O.optional(),gap:O.optional(),"margin-bottom":O.optional(),"margin-left":O.optional(),"margin-right":O.optional(),"margin-top":O.optional(),opacity:n.union([n.string(),n.number()]).nullable().optional(),"outline-offset":O.optional(),"outline-width":O.optional(),overflow:Un.nullable().optional(),"overflow-x":Un.nullable().optional(),"overflow-y":Un.nullable().optional(),"padding-bottom":O.optional(),"padding-left":O.optional(),"padding-right":O.optional(),"padding-top":O.optional(),"row-gap":O.optional(),"stroke-width":O.optional()}),Gn=n.object({parentId:n.string().min(1).max(200),sortKey:n.string().min(1).max(500)}),Kn=n.object({op:n.literal(`insertConvertedSubtree`),destination:rn,sourceNodeId:n.string().min(1).max(200).optional(),rootNodeId:n.string().min(1).max(200),nodes:n.record(n.string().min(1).max(200),mt).refine(e=>Object.keys(e).length<=_t),relationships:n.record(n.string().min(1).max(200),Gn).refine(e=>Object.keys(e).length<_t)}),qn=1e5,Jn=1e3,k=n.string().min(1).max(200),Yn=n.string().min(1).max(500),Xn=S.extend({width:n.number().positive(),height:n.number().positive()}),Zn=n.object({parentId:k,afterId:k.optional()}),Qn=n.object({parentId:k,sortKey:Yn}),$n=n.discriminatedUnion(`op`,[Kn,n.object({op:n.literal(`insertNode`),node:mt,parentage:Qn}),Zn.extend({op:n.literal(`insertText`),nodeId:k,label:n.string().max(500).default(`Text`),text:n.string().max(qn),box:Xn,styles:Vn.default({})}),Zn.extend({op:n.literal(`insertPrototype`),nodeId:k,label:n.string().max(500).default(`Prototype`),prototypeId:n.uuid(),deploymentId:n.uuid(),box:Xn}),n.object({op:n.literal(`setPrototypeDeployment`),nodeId:k,prototypeId:n.uuid(),deploymentId:n.uuid()}),n.object({op:n.literal(`setText`),nodeId:k,text:n.string().max(qn)}),n.object({op:n.literal(`setBox`),nodeId:k,box:S}),n.object({op:n.literal(`setLabel`),nodeId:k,label:n.string().trim().min(1).max(500),labelOrigin:pt.optional()}),n.object({op:n.literal(`setVisibility`),nodeId:k,visible:n.boolean()}),n.object({op:n.literal(`setLocked`),nodeId:k,locked:n.boolean()}),n.object({op:n.literal(`setConstraints`),nodeId:k,constraints:ft}),n.object({op:n.literal(`setStyles`),nodeId:k,styles:Wn}),n.object({op:n.literal(`setAppearance`),nodeId:k,appearance:tt}),n.object({op:n.literal(`setLayout`),nodeId:k,layout:n.union([Re,n.literal(`default`)])}),n.object({op:n.literal(`setTypography`),nodeId:k,typography:n.union([it,n.literal(`default`)])}),n.object({op:n.literal(`setAdditionalStyles`),nodeId:k,additionalStyles:n.union([ut,n.literal(`default`)])}),n.object({op:n.literal(`setProps`),nodeId:k,props:n.record(n.string(),n.unknown())}),n.object({op:n.literal(`setParentage`),nodeId:k,parentage:Qn}),Zn.extend({op:n.literal(`move`),nodeId:k}),n.object({op:n.literal(`remove`),nodeId:k})]),er=n.object({canvasId:n.uuid(),mutationId:n.uuid(),baseVersion:n.number().int().positive(),operations:n.array($n).min(1).max(Jn)}),tr=n.object({canvasId:n.uuid(),mutationId:n.uuid(),previousVersion:n.number().int().positive(),version:n.number().int().positive(),insertedNodeIds:n.array(k),changedNodeIds:n.array(k),removedNodeIds:n.array(k),boxes:n.record(k,S),affectedBounds:Xn.nullable(),next:n.array(n.string().min(1))}),nr=Tt.extend({operation:Kn,next:n.array(n.string().min(1))}),rr=`enhance3.canvas.v1`,ir=n.enum([`blue`,`violet`,`green`,`amber`,`magenta`,`teal`,`red`,`orange`]),ar=n.object({kind:n.literal(`person`),connectionId:n.uuid(),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:ir}),or=n.object({kind:n.literal(`guest`),connectionId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),colour:ir}),sr=n.discriminatedUnion(`kind`,[ar,or]),cr=n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(100),initials:n.string().min(1).max(8),tokenLabel:n.string().min(1).max(100),colour:ir}),lr=n.discriminatedUnion(`kind`,[ar.omit({connectionId:!0}),cr]),ur=n.object({x:n.number(),y:n.number()}),dr=S.extend({width:n.number().positive(),height:n.number().positive()}),fr=n.object({kind:n.enum([`drag`,`resize`]),baseVersion:n.number().int().positive(),boxes:n.record(n.string().min(1).max(200),dr)}),pr=n.object({cursor:ur.nullable().optional(),input:n.enum([`pointer`,`touch`,`keyboard`]).optional(),focused:n.boolean().optional(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100).optional(),visibleWorldBox:dr.optional(),gesture:fr.nullable().optional(),cursorChat:n.string().max(140).nullable().optional()}).refine(e=>Object.keys(e).length>0,`presence patch cannot be empty`),mr=n.object({actor:sr,seq:n.number().int().nonnegative(),cursor:ur.nullable(),input:n.enum([`pointer`,`touch`,`keyboard`]),focused:n.boolean(),selectedNodeIds:n.array(n.string().min(1).max(200)).max(100),visibleWorldBox:dr.nullable(),gesture:fr.nullable(),cursorChat:n.string().max(140).nullable().default(null),expiresAt:n.iso.datetime()}),hr=n.enum([`reading`,`writing`,`creating`,`deleting`,`rendering`]),gr=n.object({activityId:n.uuid(),canvasId:n.uuid(),actor:cr,phase:hr,nodeIds:n.array(n.string().min(1).max(200)).max(100),bounds:dr.nullable(),expiresAt:n.iso.datetime()}),_r=n.object({canvasId:n.uuid(),protocols:n.array(n.literal(rr)).min(1).max(1)}),vr=n.object({endpoint:n.url(),ticket:n.string().min(1).max(4096),protocol:n.literal(rr),expiresAt:n.iso.datetime()}),yr=n.object({canvasId:n.uuid(),phase:hr,nodeIds:n.array(n.string().min(1).max(200)).max(100).default([]),bounds:dr.nullable().default(null)}),br=n.object({activityId:n.uuid(),expiresAt:n.iso.datetime(),renewAfterMs:n.number().int().positive()}),xr=yr.extend({activityId:n.uuid()}),Sr=n.object({canvasId:n.uuid(),activityId:n.uuid()}),Cr=n.object({ended:n.literal(!0)});n.discriminatedUnion(`type`,[n.object({v:n.literal(1),type:n.literal(`presence.patch`),seq:n.number().int().nonnegative(),payload:pr}),n.object({v:n.literal(1),type:n.literal(`room.pong`),seq:n.number().int().nonnegative(),payload:n.object({pingId:n.uuid()})})]);const A={v:n.literal(1),seq:n.number().int().nonnegative()};n.discriminatedUnion(`type`,[n.object({...A,type:n.literal(`room.snapshot`),payload:n.object({connectionId:n.uuid(),peers:n.array(mr),activities:n.array(gr),documentVersion:n.number().int().positive()})}),n.object({...A,type:n.literal(`presence.patch`),payload:mr}),n.object({...A,type:n.literal(`presence.left`),payload:n.object({connectionId:n.uuid()})}),n.object({...A,type:n.literal(`agent.activity`),payload:n.object({activityId:n.uuid(),activity:gr.nullable()})}),n.object({...A,type:n.literal(`document.committed`),payload:n.object({mutationId:n.uuid(),actor:lr,previousVersion:n.number().int().positive(),version:n.number().int().positive(),operations:n.array($n).min(1)})}),n.object({...A,type:n.literal(`sync.required`),payload:n.object({version:n.number().int().positive(),reason:n.enum([`gap`,`relay`,`replace`,`history-restored`])})}),n.object({...A,type:n.literal(`room.ping`),payload:n.object({pingId:n.uuid(),sentAt:n.iso.datetime()})}),n.object({...A,type:n.literal(`room.error`),payload:n.object({code:n.enum([`auth`,`permission`,`protocol`,`payload`,`rate`,`unavailable`]),message:n.string().min(1).max(200)})})]);const wr=n.object({jobId:n.uuid()}),Tr=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),target:Ft,sourceState:It.optional()}),Er=n.discriminatedUnion(`purpose`,[Tr.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),scale:n.number().positive().max(4),format:n.literal(`png`)}),Tr.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:on,scale:n.literal(1),format:n.literal(`json`)})]);n.object({jobId:n.uuid()}),n.object({jobId:n.uuid()});const Dr=n.object({jobId:n.uuid(),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),grantToken:n.string().startsWith(`rgr_`).min(40).max(100),grantCookieName:n.string().min(1).max(100),renderUrl:n.url(),releaseIdentity:n.string().min(1).max(100)});n.discriminatedUnion(`purpose`,[Dr.extend({purpose:n.enum([`inspection`,`snapshot`,`thumbnail`]),target:Ft,sourceState:It.optional(),scale:n.number().positive(),outputKey:n.string().min(1).max(500)}),Dr.extend({purpose:n.literal(`conversion`),target:n.object({kind:n.literal(`node`),nodeId:n.string().min(1).max(200)}),sourceState:n.undefined().optional(),conversion:on,scale:n.literal(1)})]),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive(),bytes:n.number().int().positive().max(jt),storageKey:n.string().min(1).max(500),warnings:n.array(Ut),timings:n.array(Wt),sourceState:Lt.optional(),snapshot:n.object({artifactBytes:n.number().int().positive().max(Mt),artifactStorageKey:n.string().min(1).max(500),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}).optional()}),n.object({accepted:n.literal(!0)}),n.object({jobId:n.uuid(),loadedVersion:n.number().int().positive(),draft:Ct}),n.object({accepted:n.literal(!0)}),n.object({recordingId:n.uuid(),requestedAtMs:n.number().int().nonnegative(),settledAtMs:n.number().int().nonnegative(),artifact:n.string().min(1).max(Mt),route:n.string().optional(),title:n.string().optional(),viewport:n.object({width:n.number().int().positive(),height:n.number().int().positive()})}),n.object({jobId:n.uuid(),failure:E}),n.object({accepted:n.literal(!0),willRetry:n.boolean()}),n.object({workerId:n.string().regex(/^[\w.-]+$/u).min(1).max(100),releaseIdentity:n.string().min(1).max(100),timestamp:n.coerce.number().int().nonnegative(),nonce:n.uuid(),mac:n.base64().min(32).max(200)});const Or=n.object({total:n.number().int().nonnegative(),loading:n.number().int().nonnegative(),unavailable:n.number().int().nonnegative()}),kr=n.object({jobId:n.uuid(),canvasId:n.uuid().nullable(),requestedVersion:n.number().int().positive().nullable(),loadedVersion:n.number().int().positive().nullable(),phase:Bt.exclude([`queued`,`claimed`,`capture`,`upload`,`complete`]),sources:Or,warnings:n.array(Ut),timings:n.array(Wt),sourceState:Lt.optional()}),Ar=n.object({selector:n.string().min(1).max(500),contentSelector:n.string().min(1).max(500).optional(),bounds:T,width:n.number().int().positive(),height:n.number().int().positive(),scale:n.number().positive()});n.discriminatedUnion(`state`,[kr.extend({state:n.literal(`loading`),capture:n.null(),failure:n.null()}),kr.extend({state:n.literal(`ready`),phase:n.literal(`target`),canvasId:n.uuid(),requestedVersion:n.number().int().positive(),loadedVersion:n.number().int().positive(),capture:Ar,failure:n.null()}),kr.extend({state:n.literal(`failed`),failure:n.object({reason:Vt,message:n.string().min(1).max(500),sourceId:n.string().min(1).max(200).nullable()}),capture:n.null()})]);const jr=n.string().min(1).max(200),Mr=n.object({canvasId:n.uuid()}),Nr=n.object({canvasId:n.uuid(),status:n.enum([`selected`,`none`,`offline`,`stale`]),documentVersion:n.number().int().positive(),selectionRevision:n.number().int().positive().nullable(),selectionChangedAt:n.iso.datetime().nullable(),selectedNodeIds:n.array(jr),missingNodeIds:n.array(jr),nodes:n.array(En),contextRootId:jr.nullable(),visibleWorldBox:T.nullable(),next:n.array(n.string().min(1)).max(12)}),Pr=1e3,Fr=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2)}),n.object({kind:n.literal(`agent`),personId:n.uuid(),displayName:n.string().min(1).max(200),initials:n.string().min(1).max(2),tokenLabel:n.string().min(1).max(200)})]),Ir=n.object({id:n.uuid(),canvasId:n.uuid(),documentVersion:n.number().int().positive(),origin:n.enum([`automatic`,`manual`,`restore`]),restoreRole:n.enum([`before`,`result`]).nullable(),retention:n.enum([`automatic`,`named`,`restore-boundary`]),title:n.string().min(1).max(200).nullable(),description:n.string().max(Pr).nullable(),actor:Fr,sourceVersionEntryId:n.uuid().nullable(),expiresAt:n.iso.datetime().nullable(),createdAt:n.iso.datetime(),updatedAt:n.iso.datetime(),screenCount:n.number().int().min(0)}),Lr=n.object({canvasId:n.uuid(),limit:n.number().int().min(1).max(100).default(50),cursor:n.string().min(1).max(1e3).optional(),includeAutomatic:n.boolean().default(!1),actor:n.enum([`all`,`mine`]).default(`all`)}),Rr=n.object({current:n.object({documentVersion:n.number().int().positive(),updatedAt:n.iso.datetime()}),items:n.array(Ir),nextCursor:n.string().min(1).nullable(),hasExpiredHistory:n.boolean()}),zr=n.object({canvasId:n.uuid(),versionId:n.uuid()}),Br=n.object({outcome:n.literal(`ready`),entry:Ir,document:gn,screens:n.array(vn)}),Vr=n.object({outcome:n.literal(`missing-resources`),entry:Ir,document:gn,screens:n.array(vn),missingScreenIds:n.array(n.uuid()).min(1)}),Hr=n.discriminatedUnion(`outcome`,[Br,Vr,n.object({outcome:n.literal(`corrupt`),entry:Ir})]),Ur=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`current`),expectedVersion:n.number().int().positive()}),n.object({kind:n.literal(`version`),versionId:n.uuid()})]),Wr=n.object({canvasId:n.uuid(),target:Ur,title:n.string().trim().min(1).max(200),description:n.string().trim().max(Pr).nullable().default(null)}),Gr=n.object({canvasId:n.uuid(),versionId:n.uuid(),title:n.string().trim().min(1).max(200),description:n.string().trim().max(Pr).nullable().default(null)}),Kr=n.object({canvasId:n.uuid(),versionId:n.uuid()}),qr=n.object({entry:Ir}),Jr=n.object({canvasId:n.uuid(),versionId:n.uuid(),expectedVersion:n.number().int().positive()}),Yr=n.object({canvasId:n.uuid(),version:n.number().int().positive(),beforeVersionId:n.uuid(),restoredVersionId:n.uuid(),restoreFenceVersion:n.number().int().positive()}),Xr=n.object({canvasId:n.uuid(),versionId:n.uuid(),organisationId:n.union([n.uuid(),n.literal(`personal`)]),title:n.string().trim().min(1).max(200).optional()}),Zr=n.object({canvasId:n.uuid(),title:n.string().min(1).max(200),version:n.literal(1)}),Qr=n.object({inviteId:n.uuid(),email:n.string().max(254),accessLevel:m,sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),$r=n.object({canvasTitle:n.string().min(1),invitedBy:n.string().min(1),email:n.string().max(254).pipe(n.email()),accessLevel:m,expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),ei=n.object({canvasId:n.uuid(),email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email()),accessLevel:m}),ti=n.object({invite:Qr,acceptToken:n.string().max(512).optional()}),ni=n.object({canvasId:n.uuid()}),ri=f(Qr),ii=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),ai=n.object({canvasId:n.uuid(),inviteId:n.uuid()}),oi=n.string().min(1).max(512),si=n.object({token:oi}),ci=n.object({token:oi}),li=n.object({canvasId:n.uuid(),accessLevel:m}),ui=n.object({personId:n.uuid().nullable(),email:n.string().max(254).nullable(),displayName:n.string().max(120).nullable(),initials:n.string().max(4).nullable(),avatarUrl:n.string().max(l).nullable(),accessLevel:p,isPending:n.boolean(),reviewState:n.enum([`not-started`,`in-progress`,`done`]).nullable(),lastViewedAt:n.iso.datetime().nullable()}),di=n.object({canvasId:n.uuid()}),fi=f(ui),pi=n.object({canvasId:n.uuid(),personId:n.uuid(),accessLevel:m}),mi=n.object({canvasId:n.uuid(),personId:n.uuid()}),hi=n.object({personId:n.uuid(),revoked:n.boolean()}),gi=n.object({canvasId:n.uuid(),reviewState:n.enum([`not-started`,`in-progress`,`done`])}),_i=n.object({reviewState:gi.shape.reviewState.nullable()}),vi=n.object({selector:n.string().min(1).max(2e3),tagName:n.string().min(1).max(40),label:n.string().max(80).nullable(),source:n.object({file:n.string().min(1).max(1024),line:n.number().int().min(0).nullable()}).nullable()}),yi=n.object({x:n.number(),y:n.number()}),bi=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1)}),xi=n.object({x:n.number().min(0).max(1),y:n.number().min(0).max(1),width:n.number().min(0).max(1),height:n.number().min(0).max(1)}),Si=vi.extend({role:n.string().min(1).max(80).optional()}),Ci=n.object({path:n.array(n.number().int().min(0)).max(64),offset:n.number().int().min(0)}),wi=n.discriminatedUnion(`kind`,[n.object({version:n.literal(1),kind:n.literal(`element`),locator:Si,attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`text`),root:Si,quote:n.object({exact:n.string().min(1).max(1e3),prefix:n.string().max(120),suffix:n.string().max(120)}),range:n.object({start:Ci,end:Ci}),attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`elements`),members:n.array(Si).min(2).max(32),truncated:n.boolean(),attachment:bi,fallbackBounds:xi}),n.object({version:n.literal(1),kind:n.literal(`area`),bounds:xi,attachment:bi})]),Ti=n.discriminatedUnion(`on`,[n.object({on:n.literal(`canvas`),point:yi}),n.object({on:n.literal(`node`),nodeId:n.string().min(1).max(120),point:yi,element:n.null()}),n.object({on:n.literal(`screen`),nodeId:n.string().min(1).max(120),screenId:n.uuid(),point:yi,element:vi.nullable(),target:wi.optional()})]),Ei=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(l).nullable(),tokenLabel:n.string().max(120).nullable()}),Di=n.object({personId:n.uuid(),name:n.string().min(1).max(120)}),Oi=n.object({emoji:n.string().min(1).max(16),people:n.array(Di).min(1)}),ki=n.object({messageId:n.uuid(),seq:n.number().int().min(1),body:n.string().min(1),author:Ei,createdAt:n.iso.datetime(),editedAt:n.iso.datetime().nullable(),mentions:n.array(Di),reactions:n.array(Oi)}),Ai=n.object({kind:n.enum([`person`,`agent`]),personId:n.uuid(),name:n.string().min(1).max(120),tokenLabel:n.string().max(120).nullable()}),j=n.object({threadId:n.uuid(),canvasId:n.uuid(),anchor:Ti,author:Ei,messages:n.array(ki).min(1).max(50),messageCount:n.number().int().min(1),hasMoreMessages:n.boolean(),isResolved:n.boolean(),resolvedAt:n.iso.datetime().nullable(),resolvedBy:Ai.nullable(),createdAt:n.iso.datetime(),lastMessageAt:n.iso.datetime()}),ji=n.object({canvasId:n.uuid(),filter:n.enum([`open`,`resolved`,`all`]).default(`open`),authorPersonId:n.uuid().optional(),agentActionable:n.boolean().default(!1),query:n.string().trim().max(200).optional()}),Mi=f(j),Ni=n.object({canvasId:n.uuid(),clientThreadId:n.uuid(),anchor:Ti,body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Pi=n.object({canvasId:n.uuid(),threadId:n.uuid(),clientMessageId:n.uuid(),body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Fi=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),body:n.string().trim().min(1).max(ee),mentionedPersonIds:n.array(n.uuid()).max(10).default([])}),Ii=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid(),emoji:n.string().trim().min(1).max(16),reacted:n.boolean()}),Li=n.object({canvasId:n.uuid(),threadId:n.uuid(),anchor:Ti}),Ri=n.object({canvasId:n.uuid(),threadId:n.uuid(),resolved:n.boolean()}),zi=n.object({canvasId:n.uuid(),threadId:n.uuid(),messageId:n.uuid().optional()}),Bi=n.object({deletedThreadIds:n.array(n.uuid()),deletedMessageIds:n.array(n.uuid())}),Vi=n.enum([`owner`,`admin`,`member`]),Hi=n.object({id:n.uuid(),name:n.string().min(1).max(120),role:Vi}),Ui=n.object({}),Wi=f(Hi),Gi=n.object({name:n.string().trim().min(1).max(120)}),Ki=n.object({organisation:Hi}),qi=n.object({organisationId:n.uuid(),name:n.string().trim().min(1).max(120)}),Ji=n.object({organisationId:n.uuid()}),Yi=n.object({organisationId:n.uuid(),movedCanvasCount:n.number().int().min(0)}),Xi=n.object({personId:n.uuid(),displayName:n.string().max(120),initials:n.string().max(4),email:n.string().max(254).nullable(),role:Vi}),Zi=n.object({organisationId:n.uuid()}),Qi=f(Xi),$i=n.object({organisationId:n.uuid(),email:n.email().trim().toLowerCase().max(254),role:n.enum([`admin`,`member`]).default(`member`)}),ea=n.object({personId:n.uuid()}),ta=n.object({organisationId:n.uuid(),personId:n.uuid(),role:n.enum([`admin`,`member`])}),na=ta.pick({personId:!0,role:!0}),ra=n.object({organisationId:n.uuid(),personId:n.uuid()}),ia=n.object({personId:n.uuid(),removed:n.literal(!0)}),aa=n.object({organisationId:n.uuid(),personId:n.uuid()}),oa=n.object({ownerPersonId:n.uuid()}),sa=n.object({inviteId:n.uuid(),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),sendCount:n.number().int().min(1),lastSentAt:n.iso.datetime(),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`expired`]),deliveryState:n.enum([`queued`,`accepted`,`failed`]),deliveryError:n.string()}),ca=n.object({organisationId:n.uuid(),email:n.string().trim().toLowerCase().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]).default(`member`)}),la=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`member`),personId:n.uuid()}),n.object({kind:n.literal(`invitation`),invite:sa})]),ua=n.object({invite:sa}),da=n.object({organisationId:n.uuid()}),fa=f(sa),pa=n.object({organisationId:n.uuid(),inviteId:n.uuid()}),ma=pa.extend({}),ha=n.string().min(1).max(512),ga=n.object({token:ha}),_a=n.object({token:ha}),va=n.object({teamName:n.string().min(1).max(120),invitedBy:n.string().min(1).max(120),email:n.string().max(254).pipe(n.email()),role:n.enum([`admin`,`member`]),expiresAt:n.iso.datetime(),state:n.enum([`pending`,`accepted`]),hasAccount:n.boolean()}),ya=n.object({organisationId:n.uuid()}),ba=n.object({id:n.uuid(),label:n.string().min(1).max(120),createdAt:n.iso.datetime(),lastUsedAt:n.iso.datetime().nullable(),expiresAt:n.iso.datetime().nullable(),revoked:n.boolean()}),xa=n.object({label:n.string().trim().min(1).max(120).describe(`Label naming the agent.`),expiresAt:n.iso.datetime().nullable().describe(`Expiry timestamp, or null for a token that does not expire.`)}),Sa=n.object({token:n.string().startsWith(`enh_`),agentToken:ba}),Ca=n.object({}),wa=n.object({items:n.array(ba)}),Ta=n.object({tokenId:n.uuid()}),Ea=n.object({tokenId:n.uuid(),revoked:n.literal(!0)}),Da=n.discriminatedUnion(`method`,[n.object({method:n.literal(`token`)}),n.object({method:n.literal(`browser`),issuer:n.url(),clientId:n.string().min(1),scope:n.literal(`openid`)})]),Oa=n.object({id:n.uuid(),preparedCanvasId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),avatarUrl:n.string().max(l).nullable(),email:n.string().max(254).nullable(),createdAt:n.iso.datetime()}),ka=n.object({}),Aa=n.object({person:Oa.nullable(),authentication:n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`anonymous`)}),n.object({kind:n.literal(`person`)}),n.object({kind:n.literal(`agent`),tokenId:n.uuid(),tokenLabel:n.string(),expiresAt:n.iso.datetime().nullable()}),n.object({kind:n.literal(`oauth-agent`),tokenId:n.uuid(),tokenLabel:n.string(),clientId:n.string().min(1),scopes:n.array(n.string()),expiresAt:n.iso.datetime(),resource:n.url()})])}),ja=n.object({displayName:n.string().trim().min(1).max(120)}),Ma=n.object({person:Oa}),Na=n.string().trim().toLowerCase().min(3).max(40).regex(/^[a-z0-9][a-z0-9._-]*$/,`letters, digits, dot, underscore and dash only`),Pa=n.enum([`cookie`,`token`]).default(`cookie`),Fa=n.object({username:Na,password:n.string().min(10).max(200),displayName:n.string().trim().min(1).max(120),deliver:Pa,email:n.string().max(254).transform(e=>e.trim().toLowerCase()).pipe(n.email())}),Ia=n.object({username:Na,password:n.string().min(1).max(200),deliver:Pa}),La=n.object({person:Oa,token:n.string().nullable()}),Ra=La.extend({preparedCanvasId:n.uuid()}),za=n.object({}),Ba=n.object({signedOut:n.literal(!0)}),Va=n.string().max(254).pipe(n.email()),Ha=n.discriminatedUnion(`kind`,[n.object({kind:n.literal(`person`),personId:n.uuid(),displayName:n.string().min(1).max(120),initials:n.string().min(1).max(4),email:Va}),n.object({kind:n.literal(`email`),email:Va})]),Ua=n.object({query:n.string().trim().min(1).max(200)}),Wa=n.object({recipients:n.array(Ha).max(5)}),Ga=n.object({}),Ka=Wa.extend({}),qa=`enhance3:session-handoff`;n.union([n.object({kind:n.literal(qa),body:n.object({token:n.string().min(1),displayName:n.string().min(1)})}),n.object({kind:n.literal(qa),signedOut:n.literal(!0)})]);const Ja=n.string().min(1).max(500).refine(e=>!e.startsWith(`/`)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),Ya=n.object({path:Ja,contentType:n.string().min(1).max(200),bytes:n.number().int().nonnegative().max(26214400)}),Xa=n.enum([`uploading`,`verifying`,`ready`,`failed`,`abandoned`]),Za=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1).max(200),title:n.string().trim().min(1).max(200),entryPath:Ja.default(`index.html`),files:n.array(Ya).min(1).max(2e3),box:S.extend({width:n.number().positive(),height:n.number().positive()})}),Qa=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),state:Xa,alreadyExists:n.boolean(),fileCount:n.number().int().positive(),totalBytes:n.number().int().positive().max(262144e3)}),$a=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),cursor:n.number().int().min(0).default(0)}),eo=n.object({path:Ja,upload:w}),to=n.object({deploymentId:n.uuid(),uploads:n.array(eo).max(50),nextCursor:n.number().int().min(0).optional()}),no=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive()}),ro=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1).max(200),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)}),io=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid()}),ao=n.object({deploymentId:n.uuid(),origin:n.url(),bootUrl:n.url(),expiresAt:n.iso.datetime()}),oo=`__enhance/manifest.json`,so=n.string().length(64).refine(e=>{for(let t of e)if(!/[\da-f]/u.test(t))return!1;return!0}),co=e=>{for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&(e===127||e<=31))return!0}return!1},lo=e=>e.normalize(`NFKC`).toUpperCase().toLowerCase(),uo=n.string().min(1).refine(e=>e===e.normalize(`NFC`),{message:`prototype paths must use NFC Unicode normalization`}).refine(e=>!e.startsWith(`/`)&&!/^[A-Za-z]:\//u.test(e)&&!e.endsWith(`/`)&&!e.includes(`\\`)&&!co(e)&&!e.startsWith(`__enhance/`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{message:`prototype paths must be portable relative file paths`}),fo=n.object({path:uo,contentType:n.string().trim().min(1).max(200).refine(e=>!co(e)),bytes:n.number().int().nonnegative().max(2**53-1),sha256:so}),po=n.object({version:n.literal(1),entryPath:uo,files:n.array(fo).min(1)}),mo=n.object({artifactBytes:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1),fileBytes:n.number().int().positive().max(2**53-1),manifestBytes:n.number().int().positive().max(2**53-1),fileCount:n.number().int().positive().max(2**53-1),pathBytes:n.number().int().positive().max(2**53-1)}),ho=n.object({}),go=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),limits:mo}),_o=n.object({protocolVersion:n.literal(1),format:n.literal(`zip`),bytes:n.number().int().positive().max(2**53-1),sha256:so,fileCount:n.number().int().positive().max(2**53-1),expandedBytes:n.number().int().positive().max(2**53-1)}),vo=n.object({canvasId:n.uuid(),prototypeId:n.uuid().optional(),clientToken:n.uuid(),nodeId:n.string().min(1),title:n.string().trim().min(1).max(200),entryPath:uo,artifact:_o,box:S.extend({width:n.number().positive(),height:n.number().positive()})}),yo=n.enum([`uploading`,`queued`,`ingesting`,`ready`,`failed`,`abandoned`]),bo=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),alreadyExists:n.boolean(),artifact:_o}),xo=n.discriminatedUnion(`state`,[bo.extend({state:n.literal(`uploading`),upload:w}),bo.extend({state:n.enum([`queued`,`ingesting`,`ready`,`failed`,`abandoned`])})]),So=n.object({canvasId:n.uuid(),deploymentId:n.uuid()}),Co=n.object({deploymentId:n.uuid(),state:yo}),wo=n.object(So.shape),To=n.object({prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),fileCount:n.number().int().nonnegative(),totalBytes:n.number().int().nonnegative().max(2**53-1),processedFiles:n.number().int().nonnegative()}),Eo=n.discriminatedUnion(`state`,[To.extend({state:n.literal(`failed`),failure:n.object({code:n.string().min(1),message:n.string().min(1),path:uo.optional()})}),To.extend({state:n.enum([`uploading`,`queued`,`ingesting`,`ready`,`abandoned`])})]),Do=n.object({canvasId:n.uuid(),deploymentId:n.uuid(),baseVersion:n.number().int().positive()}),Oo=n.object({canvasId:n.uuid(),prototypeId:n.uuid(),deploymentId:n.uuid(),nodeId:n.string().min(1),version:n.number().int().positive(),state:n.literal(`ready`),origin:n.url(),openUrl:n.string().startsWith(`/c/`)});n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.capture`),requestId:n.uuid()}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.ready`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.escape`)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.zoom`),deltaX:n.number(),deltaY:n.number(),deltaMode:n.union([n.literal(0),n.literal(1),n.literal(2)]),anchorX:n.number().min(0).max(1),anchorY:n.number().min(0).max(1)}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigate`),direction:n.enum([`back`,`forward`])}),n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.navigation`),canGoBack:n.boolean(),canGoForward:n.boolean()});const ko=n.object({artifact:n.string().min(1),viewport:n.object({width:n.number().positive(),height:n.number().positive()}),title:n.string()}),Ao=n.object({protocol:n.literal(1),type:n.literal(`enhance.prototype.captured`),requestId:n.uuid()});n.discriminatedUnion(`outcome`,[Ao.extend({outcome:n.literal(`captured`),screen:ko}),Ao.extend({outcome:n.literal(`failed`),error:n.string().min(1)})]);const jo=2166136261,Mo=Number.parseInt(`9e3779b9`,16),No=Number.parseInt(`85ebca6b`,16),Po=Number.parseInt(`c2b2ae35`,16);jo^Mo,jo^No,jo^Po;const Fo=(e,t)=>`/v1/recording-assets/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,Io=n.object({width:n.number().int().positive(),height:n.number().int().positive()}),Lo=16*d,Ro=8*d,zo=l,Bo=n.object({mimeType:n.string().min(1).max(100),sampleRate:n.number().int().min(8e3).max(192e3)}),Vo=n.object({sourceUrl:n.string().max(zo),viewport:Io,pageTitle:n.string().max(200).nullable(),audio:Bo.nullable().default(null)}),Ho=n.object({recordingId:n.uuid(),ownerPersonId:n.uuid(),chunkIndex:n.literal(0),upload:w,audioUpload:w.nullable()}),Uo=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),eventCount:n.number().int().min(0),continues:n.boolean().default(!1),bytes:n.number().int().min(1).max(Lo),etag:n.string().min(1).max(200).optional()}),Wo=n.object({nextChunkIndex:n.number().int().min(1),upload:w}),Go=n.object({recordingId:n.uuid(),index:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),bytes:n.number().int().min(1).max(Lo),epoch:n.number().int().min(0).default(0),startsEpoch:n.boolean().default(!1),etag:n.string().min(1).max(200).optional()}),Ko=n.object({nextChunkIndex:n.number().int().min(1),upload:w}),qo=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0).max(144e5),viewport:Io,sourceUrl:n.string().max(zo),interrupted:n.boolean().default(!1),canvasId:n.uuid().optional(),organisationId:n.uuid().optional(),audioChunkCount:n.number().int().min(0).default(0),hasRecoverableBytes:n.boolean().default(!1)}).refine(e=>e.canvasId===void 0||e.organisationId===void 0,{message:`choose an existing canvas or a team for a new canvas, not both`}),Jo=n.enum([`whole`,`recovering`,`partial`]),Yo=n.enum([`dom`,`audio`]),Xo=n.object({recordingId:n.uuid(),canvasId:n.uuid(),canvasTitle:n.string().min(1).max(200),isNewCanvas:n.boolean(),storedChunkCount:n.number().int().min(0),missingChunkIndexes:n.array(n.number().int().min(0)).max(64),missingChunkCount:n.number().int().min(0),storedAudioChunkCount:n.number().int().min(0),missingAudioChunkIndexes:n.array(n.number().int().min(0)).max(64),missingAudioChunkCount:n.number().int().min(0),integrity:Jo}),Zo=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:Io,interrupted:n.boolean(),chunkCount:n.number().int().min(0),startedAt:n.iso.datetime()}),Qo=n.object({recordingId:n.uuid(),assets:n.array(n.object({url:n.url().max(zo),contentType:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Ro)})).max(400)}),$o=n.object({reserved:n.array(n.object({url:n.string(),upload:w}))}),es=n.object({recordingId:n.uuid(),arrived:n.array(n.object({url:n.url().max(zo),etag:n.string().min(1).max(200),byteSize:n.number().int().min(1).max(Ro)})).max(400)}),ts=n.object({missingAssetCount:n.number().int().min(0)}),ns=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),rs=n.object({seq:n.number().int().min(0),firstEventMs:n.number().int().min(0),lastEventMs:n.number().int().min(0),continues:n.boolean()}),is=n.discriminatedUnion(`state`,[rs.extend({state:n.literal(`available`),download:Et}),rs.extend({state:n.literal(`missing`)})]),as=n.object({seq:n.number().int().min(0),firstMs:n.number().int().min(0),lastMs:n.number().int().min(0),epoch:n.number().int().min(0),startsEpoch:n.boolean()}),os=n.discriminatedUnion(`state`,[as.extend({state:n.literal(`available`),download:Et}),as.extend({state:n.literal(`missing`)})]),ss=n.object({recordingId:n.uuid(),durationMs:n.number().int().min(0),viewport:Io,sourceUrl:n.string().max(zo),interrupted:n.boolean(),integrity:Jo,chunks:n.array(is),audio:n.object({mimeType:n.string(),chunks:n.array(os)}).nullable(),assets:n.array(n.object({url:n.string(),contentType:n.string(),path:n.string().startsWith(`/v1/recording-assets/`)})),missingAssetCount:n.number().int().min(0)}),cs=n.object({recordingId:n.uuid(),track:Yo,index:n.number().int().min(0)}),ls=n.object({upload:w}),us=cs.extend({etag:n.string().min(1).max(200)}),ds=n.object({integrity:Jo}),fs=n.object({canvasId:n.uuid()}),ps=f(Zo),ms=n.object({recordingId:n.uuid()}),hs=n.object({recordingId:n.uuid(),discarded:n.literal(!0)}),gs=n.object({canvasId:n.uuid(),recordingId:n.uuid()}),_s=n.object({recordingId:n.uuid(),detachedScreenCount:n.number().int().min(0)});[`[data-enhance-unsupported]:not([data-enhance-unsupported-hidden]):not([style*="display: none"]) {
3
3
  align-items: center !important;
4
4
  background-color: #f7f7f8 !important;
5
5
  background-image: linear-gradient(to top right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)), linear-gradient(to bottom right, transparent calc(50% - 1px), #a8a8b0 50%, transparent calc(50% + 1px)) !important;
package/dist/main.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{A as e,C as t,D as n,E as r,G as i,J as a,K as o,O as s,S as c,T as l,U as u,W as d,X as f,Y as p,Z as ee,c as m,d as te,et as ne,i as h,k as re,l as ie,m as ae,n as g,o as oe,ot as se,p as _,r as v,s as ce,st as le,t as ue,tt as de,u as fe}from"./cli-output-identity.lib-DgzE-BhW.mjs";import{a as pe,c as me,d as he,f as ge,i as y,l as b,n as _e,o as ve,r as ye,s as be,t as xe,u as Se}from"./mutation-key.adapter-Bl-A2kBA.mjs";import{t as Ce}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{Command as we}from"commander";import{createCli as Te,parseRouter as Ee}from"trpc-cli";import{z as x}from"zod";import{hostname as De,tmpdir as Oe}from"node:os";import S from"node:process";import{createInterface as ke}from"node:readline";import{chmodSync as Ae,existsSync as je,lstatSync as Me,mkdirSync as Ne,readFileSync as Pe,readdirSync as Fe,statSync as C,unlinkSync as Ie,writeFileSync as w}from"node:fs";import T from"node:path";import{createHash as Le,randomUUID as E}from"node:crypto";import{readFile as Re}from"node:fs/promises";import{proxify as ze}from"trpc-cli/dist/proxify.js";const Be=()=>({rotation:0,flipHorizontal:!1,flipVertical:!1,horizontal:{mode:`fixed`,value:0},vertical:{mode:`fixed`,value:0},position:`absolute`,clipContent:!1}),D=`root`,Ve=e=>`a${String(e).padStart(4,`0`)}`,He=()=>({version:2,nodes:{[D]:{id:D,label:`Canvas`,component:`root`,styles:{}}},relationships:{}}),Ue=(e,t)=>({...e,nodes:{...e.nodes,[t.id]:t},relationships:{...e.relationships,[t.id]:{parentId:D,sortKey:Ve(Object.keys(e.relationships).length)}}}),We=(e,t)=>Ue(e,{id:t.id,label:t.label,component:`screen`,props:{capture:{viewport:t.viewport,atMs:0,screenId:t.screenId}},styles:{},box:{...t.at,...t.viewport}}),Ge=e=>`${JSON.stringify(e)}\n`,Ke=e=>{if(e<1)throw RangeError(`a chunk has to be able to hold at least one character`);let t=``,n=[],r=!1,i=!1,a=()=>{let e={body:t,continues:r,eventCount:n.length-+!!r,firstEventMs:n.length===0?0:Math.min(...n),lastEventMs:n.length===0?0:Math.max(...n)};return r=!t.endsWith(`
2
+ import{A as e,C as t,D as n,E as r,G as i,J as a,K as o,O as s,S as c,T as l,U as u,W as d,X as f,Y as p,Z as ee,c as m,d as te,et as ne,i as h,k as re,l as ie,m as ae,n as g,o as oe,ot as se,p as _,r as v,s as ce,st as le,t as ue,tt as de,u as fe}from"./cli-output-identity.lib-Bx1wvgKF.mjs";import{a as pe,c as me,d as he,f as ge,i as y,l as b,n as _e,o as ve,r as ye,s as be,t as xe,u as Se}from"./mutation-key.adapter-DjXfl_el.mjs";import{t as Ce}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{Command as we}from"commander";import{createCli as Te,parseRouter as Ee}from"trpc-cli";import{z as x}from"zod";import{hostname as De,tmpdir as Oe}from"node:os";import S from"node:process";import{createInterface as ke}from"node:readline";import{chmodSync as Ae,existsSync as je,lstatSync as Me,mkdirSync as Ne,readFileSync as Pe,readdirSync as Fe,statSync as C,unlinkSync as Ie,writeFileSync as w}from"node:fs";import T from"node:path";import{createHash as Le,randomUUID as E}from"node:crypto";import{readFile as Re}from"node:fs/promises";import{proxify as ze}from"trpc-cli/dist/proxify.js";const Be=()=>({rotation:0,flipHorizontal:!1,flipVertical:!1,horizontal:{mode:`fixed`,value:0},vertical:{mode:`fixed`,value:0},position:`absolute`,clipContent:!1}),D=`root`,Ve=e=>`a${String(e).padStart(4,`0`)}`,He=()=>({version:2,nodes:{[D]:{id:D,label:`Canvas`,component:`root`,styles:{}}},relationships:{}}),Ue=(e,t)=>({...e,nodes:{...e.nodes,[t.id]:t},relationships:{...e.relationships,[t.id]:{parentId:D,sortKey:Ve(Object.keys(e.relationships).length)}}}),We=(e,t)=>Ue(e,{id:t.id,label:t.label,component:`screen`,props:{capture:{viewport:t.viewport,atMs:0,screenId:t.screenId}},styles:{},box:{...t.at,...t.viewport}}),Ge=e=>`${JSON.stringify(e)}\n`,Ke=e=>{if(e<1)throw RangeError(`a chunk has to be able to hold at least one character`);let t=``,n=[],r=!1,i=!1,a=()=>{let e={body:t,continues:r,eventCount:n.length-+!!r,firstEventMs:n.length===0?0:Math.min(...n),lastEventMs:n.length===0?0:Math.max(...n)};return r=!t.endsWith(`
3
3
  `),t=``,n=r?[n.at(-1)??0]:[],e};return{pending:()=>t.length,add:r=>{let o=[],s=Ge(r.event);for(n.push(r.atMs),i=!0;t.length+s.length>=e;){let n=e-t.length;t+=s.slice(0,n),s=s.slice(n),o.push(a())}return t+=s,o},drain:()=>!i||t.length>0?[a()]:[]}},qe=(e,t)=>{let n=Ke(t);return[...e.flatMap(e=>n.add(e)),...n.drain()]},O=[`recording.start`,`recording.appendChunk`,`recording.complete`],Je=t=>async n=>{let r=e.parse(await t.mutate(O[0],{sourceUrl:n.sourceUrl,viewport:n.viewport,pageTitle:n.pageTitle,audio:null})),i=r.upload;try{let e=qe(n.entries,8388608);for(let[n,a]of e.entries()){let e=new TextEncoder().encode(a.body),o=await t.upload({url:i.url,headers:i.headers,body:e});i=s.parse(await t.mutate(O[1],{recordingId:r.recordingId,index:n,firstEventMs:a.firstEventMs,lastEventMs:a.lastEventMs,eventCount:a.eventCount,continues:a.continues,bytes:e.byteLength,etag:o})).upload}let a=Math.max(0,...n.entries.map(e=>e.atMs));return re.parse(await t.mutate(O[2],{recordingId:r.recordingId,durationMs:a,viewport:n.viewport,sourceUrl:n.sourceUrl,interrupted:!1,...n.canvasId!==void 0&&{canvasId:n.canvasId},audioChunkCount:0,hasRecoverableBytes:!1}))}catch{throw new c(`Recording ${r.recordingId} began, but not every chunk was committed.`,`Run 'enhance recording discard --recording-id ${r.recordingId}' to remove the incomplete attempt before retrying the fixture.`)}},Ye=[`screen.create`,`screen.complete`],Xe=e=>async t=>{let i=n.parse(await e.mutate(Ye[0],{clientToken:t.clientToken,provenance:t.provenance,route:t.route,pageTitle:t.pageTitle,viewport:t.viewport,bytes:t.body.byteLength}));try{let n=await e.upload({url:i.upload.url,headers:i.upload.headers,body:t.body}),a=r.parse(await e.mutate(Ye[1],{screenId:i.screenId,etag:n}));return{screenId:a.screenId,route:t.route,title:t.pageTitle,viewport:t.viewport,atMs:t.provenance?.atMs??null,sourceRecordingId:t.provenance?.sourceRecordingId??null,assetBundle:null,download:null,storedBytes:a.storedBytes}}catch{throw new c(`Screen ${i.screenId} was reserved, but its upload did not complete.`,`Retry 'enhance fixture screen' with the same --client-token ${t.clientToken}.`)}},k=[`organisation.create`,`canvas.create`,`screen.create`,`screen.complete`,`canvas.document.get`,`canvas.document.save`],Ze=(e,t)=>async n=>{let r=u.parse(await e.mutate(k[0],{name:n.organisationName})).organisation,i=le.parse(await e.mutate(k[1],{title:n.canvasTitle,organisationId:r.id,sourceUrl:null}));try{let a=[];for(let e of n.screens)a.push(await t(e));let o=f.parse(await e.query(k[4],{canvasId:i.id})),s=He();for(let[e,t]of a.entries())s=We(s,{id:`fixture-screen-${String(e+1)}`,label:`Fixture screen ${String(e+1)}`,screenId:t.screenId,viewport:n.screens[e]?.viewport??{width:1440,height:900},at:{x:48+e*48,y:48+e*48}});let l=ee.parse(await e.mutate(k[5],{canvasId:i.id,baseVersion:o.version,document:s,screenIds:a.map(e=>e.screenId)}));if(l.outcome===`conflict`)throw new c(`World canvas ${i.id} was created, but another writer changed its document.`,`Read 'enhance canvas document get --canvas-id ${i.id}' before adding the screens.`);return{organisationId:r.id,canvasId:i.id,screenIds:a.map(e=>e.screenId),documentVersion:l.version}}catch(e){throw e instanceof c?e:new c(`Organisation ${r.id} and canvas ${i.id} exist, but the world is incomplete.`,`Inspect 'enhance canvas get --canvas-id ${i.id}' before retrying any missing steps.`)}},Qe=async(e,n)=>{if(e!==void 0&&e!==``)return e.trim();if(S.stdin.isTTY)throw new t(`BAD_REQUEST`,`A token is required and interactive prompting is disabled.`,`Pass '--token <token>' or pipe one line to '${n}'.`);let r=ke({input:S.stdin,crlfDelay:1/0});for await(let e of r){r.close();let t=e.trim();if(t!==``)return t;break}throw new t(`BAD_REQUEST`,`A token is required.`,`Pass '--token <token>' or pipe one line to '${n}'.`)},$e=async e=>{if(e!==void 0)return e.trim();if(S.stdin.isTTY)return null;let t=ke({input:S.stdin,crlfDelay:1/0});for await(let e of t){t.close();let n=e.trim();return n===``?null:n}return null},et=(e,t,n)=>{let r=e.command(`auth`).description(`Store and inspect the agent credential.`);r.command(`login`).description(`Authenticate in a browser, then store a revocable agent credential.`).option(`--token <token>`,`Use an existing agent token instead of browser authentication.`).option(`--no-open`,`Print the authorization URL without opening the browser.`).action(async e=>{let r=await $e(e.token);if(r!==null){n.result(await t.loginWithToken(r));return}n.result(await t.loginWithBrowser({label:`CLI on ${De()}`.slice(0,120),openBrowser:e.open,onReady:e=>{n.result({status:`waiting_for_browser`,url:e})}}))}),r.command(`status`).description(`Resolve the stored token to its person, label, and expiry.`).action(async()=>{n.result(await t.status())}),r.command(`logout`).description(`Delete the local credential file; this does not revoke the server token.`).action(async()=>{n.result(await t.logout())})},tt=x.array(a).min(1).max(o),nt=e=>{if(!e.startsWith(`@`))return e;let n=e.slice(1);if(n===``)throw new t(`BAD_REQUEST`,`--operations @ must name a JSON file.`,`Pass --operations @/absolute/path/layout.json or an inline JSON array.`);let r=T.resolve(n);try{let e=C(r);if(!e.isFile()||e.size>1048576)throw Error(`invalid size`);return Pe(r,`utf8`)}catch{throw new t(`BAD_REQUEST`,`Could not read a bounded operations file at ${r}.`,`Use a regular JSON file no larger than 1 MiB.`)}},rt=e=>{try{return JSON.parse(nt(e))}catch(e){throw e instanceof t?e:new t(`BAD_REQUEST`,`--operations must be one valid JSON array.`,`Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.`)}},it=e=>{let n=rt(e),r=tt.safeParse(n);if(!r.success){let e=r.error.issues[0];throw new t(`BAD_REQUEST`,`The canvas operation batch is invalid${e===void 0||e.path.length===0?``:` at ${e.path.join(`.`)}`}.`,`Correct the named operation; run 'enhance canvas apply --help' for the supported vocabulary.`)}return r.data},A=x.uuid(),at=/^\/c\/([^/]+)\/?$/u,ot=e=>{try{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`)return null;let n=at.exec(t.pathname.toLowerCase()),r=A.safeParse(n?.[1]);return r.success?r.data:null}catch{return null}},j=e=>{let n=e.trim(),r=A.safeParse(n);if(r.success)return r.data;let i=ot(n);if(i!==null)return i;throw new t(`BAD_REQUEST`,`The canvas reference is neither a canvas URL nor a UUID.`,`Paste an HTTP(S) URL shaped https://app.example/c/<UUID>, or pass the bare canvas UUID.`)},M=(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},st=x.coerce.number().int().positive(),ct=e=>{let n=st.safeParse(e);if(n.success)return n.data;throw new t(`BAD_REQUEST`,`--base-version is invalid.`,`Run 'enhance canvas apply --help'.`)},lt=(e,n)=>{let r=x.uuid().nullable().safeParse(n??null);if(!r.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying this exact operation batch.`);return e.mutationKey.select(r.data,!1),e.mutationKey.current(`canvas.applyOperations`,{})},ut=(e,t)=>{e.command(`apply`).description(`Apply an atomic canvas edit batch and return its affected bounds.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact version returned by canvas inspect or tree.`).requiredOption(`--operations <json-or-@path>`,`JSON operation array inline, or @path to a JSON file.`).option(`--client-token <uuid>`,`Stable UUID to reuse only when retrying this exact batch.`).addHelpText(`after`,[``,`Supported operations: insertNode, insertText, insertPrototype, setText, setBox, setLabel, setVisibility, setLocked, setConstraints, setStyles, setAppearance, setLayout, setTypography, setAdditionalStyles, setProps, setParentage, move, remove.`,`Example:`,` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`].join(`
4
4
  `)).action(async e=>{lt(t,e.clientToken);let n=await t.invocation.invoke({capability:M(t.catalog(),`canvas.apply`),arguments:{canvasId:j(e.canvas),baseVersion:ct(e.baseVersion),operations:[...it(e.operations)]},clientToken:e.clientToken??null});t.output.result(n)})},N=1e3,dt=x.coerce.number().int().positive(),ft=x.coerce.number().min(.1).max(4),pt=x.uuid(),mt=x.union([x.string(),x.number(),x.null()]),ht=x.record(x.string(),mt),gt=x.array(x.object({nodeId:x.string().min(1).max(200),textContent:x.string().max(1e5)})).min(1).max(N),_t=x.array(x.object({nodeId:x.string().min(1).max(200),name:x.string().max(500)})).min(1).max(N),vt=x.array(x.object({nodeIds:x.array(x.string().min(1).max(200)).min(1).max(100),styles:ht})).min(1).max(100),yt=x.array(x.object({id:x.string().min(1).max(200),parentId:x.string().min(1).max(200).optional()})).min(1).max(100),bt=x.array(x.union([x.object({nodeId:x.string().min(1).max(200),before:x.string().min(1).max(200)}),x.object({nodeId:x.string().min(1).max(200),after:x.string().min(1).max(200)}),x.object({nodeId:x.string().min(1).max(200),parentId:x.string().min(1).max(200),index:x.number().int().nonnegative().optional()})])).min(1).max(100),xt=x.array(x.string().min(1).max(200)).min(1).max(N),St=x.coerce.number().int().min(0).max(20),Ct=e=>{try{return JSON.parse(e)}catch{return}},wt=e=>{if(e===void 0)return null;let n=de.safeParse(Ct(e));if(n.success)return n.data;throw new t(`BAD_REQUEST`,`--bounds must be a positive world rectangle.`,`Pass JSON with x, y, width and height.`)},Tt=e=>e===void 0?[]:e.split(`,`).map(e=>e.trim()).filter(e=>e!==``).slice(0,100),Et=(e,n)=>{e.command(`begin`).description(`Start visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--phase <phase>`,`reading, writing, creating, deleting, or rendering.`).option(`--node-ids <ids>`,`Comma-separated stable node ids.`).option(`--bounds <json>`,`Optional world rectangle for not-yet-created content.`).action(async e=>{let r=i.safeParse(e.phase);if(!r.success)throw new t(`BAD_REQUEST`,`--phase is invalid.`,`Use reading, writing, creating, deleting, or rendering.`);let a=j(e.canvas),o=d.parse(await n.remote.mutate(`canvas.realtime.activity.begin`,{canvasId:a,phase:r.data,nodeIds:Tt(e.nodeIds),bounds:wt(e.bounds)}));n.output.result({...o,next:[`enhance canvas work update --canvas ${a} --activity-id ${o.activityId} --phase ${r.data}`,`enhance canvas finish-working-on-nodes --canvas ${a} --activity-id ${o.activityId}`]})})},Dt=(e,t)=>{e.command(`update`).description(`Move visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by work begin.`).requiredOption(`--phase <phase>`,`Current agent phase.`).option(`--node-ids <ids>`,`Comma-separated current stable node ids.`).option(`--bounds <json>`,`Optional current world rectangle.`).action(async e=>{t.output.result(d.parse(await t.remote.mutate(`canvas.realtime.activity.renew`,{canvasId:j(e.canvas),activityId:pt.parse(e.activityId),phase:i.parse(e.phase),nodeIds:Tt(e.nodeIds),bounds:wt(e.bounds)})))})},Ot=(e,n)=>{e.command(`finish-working-on-nodes`).description(`End visible agent activity.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID.`).requiredOption(`--activity-id <uuid>`,`Lease id returned by canvas work begin.`).action(async e=>{if(!await Se(n.remote).finish(j(e.canvas),pt.parse(e.activityId)))throw new t(`NOT_FOUND`,`The activity could not be finished.`,`It may already have expired; run canvas work begin for new work.`);n.output.result({ended:!0,activityId:e.activityId})})},kt=(e,t)=>{let n=e.command(`work`).description(`Manage visible agent activity.`);Et(n,t),Dt(n,t),Ot(e,t)},At=/^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|order|overflow|padding|position|right|row-gap|top|transform|width)/u,P=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e!=`string`)return null;let t=/^(-?\d+(?:\.\d+)?)(?:px)?$/u.exec(e.trim());return t===null?null:Number(t[1])},jt=(e,t)=>{let n=P(e);return n===null?[`100%`,`fill`].includes(String(e))?{mode:`fill`}:[`fit-content`,`auto`,`hug`].includes(String(e))?{mode:`hug`}:t:{mode:`fixed`,value:Math.max(0,n)}},Mt=(e,t,n)=>{let r=e[t],[i=n.top,a=i,o=i,s=a]=typeof r==`string`?r.split(/\s+/u).map(e=>P(e)??0):typeof r==`number`?[r]:[];return{top:Math.max(0,P(e[`${t}-top`])??i),right:Math.max(0,P(e[`${t}-right`])??a),bottom:Math.max(0,P(e[`${t}-bottom`])??o),left:Math.max(0,P(e[`${t}-left`])??s)}},Nt=(e,t)=>{switch(e){case`center`:case`start`:case`stretch`:return e;case`end`:case`flex-end`:return`end`;case`flex-start`:return`start`;default:return t}},Pt=(e,t)=>{switch(e){case`center`:case`space-around`:case`space-between`:case`space-evenly`:case`start`:return e;case`end`:case`flex-end`:return`end`;case`flex-start`:return`start`;default:return t}},Ft=()=>({direction:`column`,alignItems:`start`,alignContent:`start`,justifyContent:`start`,gap:0,rowGap:0,columnGap:0,wrap:`nowrap`,padding:{top:0,right:0,bottom:0,left:0}}),It=(e,t)=>{let n=t.display;if([`block`,`none`].includes(String(n)))return;let r=[`flex`,`inline-flex`].includes(String(n));if(e===void 0&&!r)return;let i={...e??Ft()},a=t[`flex-direction`];return i.direction=a===void 0?i.direction:String(a).startsWith(`row`)?`row`:`column`,i.alignItems=Nt(t[`align-items`],i.alignItems),i.justifyContent=Pt(t[`justify-content`],i.justifyContent),i.alignContent=Pt(t[`align-content`],i.alignContent===`stretch`?`start`:i.alignContent??`start`),i.gap=Math.max(0,P(t.gap)??i.gap),i.rowGap=Math.max(0,P(t[`row-gap`])??i.rowGap??i.gap),i.columnGap=Math.max(0,P(t[`column-gap`])??i.columnGap??i.gap),i.wrap=t[`flex-wrap`]===`wrap`?`wrap`:i.wrap??`nowrap`,i.padding=Mt(t,`padding`,i.padding),i},Lt=(e,t)=>{let n=P(t[`flex-grow`]),r=P(t[`flex-shrink`]),i=P(t.order);return{horizontal:jt(t.width,e.horizontal),vertical:jt(t.height,e.vertical),...t[`align-self`]!==void 0&&{alignSelf:Nt(t[`align-self`],`start`)},...n!==null&&{flexGrow:Math.max(0,n)},...r!==null&&{flexShrink:Math.max(0,r)},...t[`flex-basis`]!==void 0&&{flexBasis:P(t[`flex-basis`])??`auto`},...i!==null&&{order:Math.round(i)}}},Rt=(e,t)=>{if(Object.keys(t).every(e=>!At.test(e)))return null;let n=e.box??{x:0,y:0,width:1,height:1},r=e.layout??{...Be(),horizontal:{mode:`fixed`,value:n.width},vertical:{mode:`fixed`,value:n.height}},i=/rotate\(\s*(-?\d+(?:\.\d+)?)deg\s*\)/u.exec(String(t.transform??``))?.[1],a=`${String(t.overflow??``)} ${String(t[`overflow-x`]??``)} ${String(t[`overflow-y`]??``)}`,o=It(r.container,t),s=t.position;return{...r,...Lt(r,t),rotation:i===void 0?r.rotation:Number(i),position:s===`absolute`?`absolute`:[`relative`,`flow`].includes(String(s))?`flow`:r.position,clipContent:/\b(?:clip|hidden)\b/u.test(a)||r.clipContent,...o===void 0?{container:void 0}:{container:o}}},zt=(e,t)=>{if(e.box===void 0)return null;let n=P(t.left),r=P(t.top),i=P(t.width),a=P(t.height);return n===null&&r===null&&i===null&&a===null?null:{op:`setBox`,nodeId:e.id,box:{x:n??e.box.x,y:r??e.box.y,width:Math.max(1,i??e.box.width),height:Math.max(1,a??e.box.height)}}},Bt=/^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|margin|order|overflow|padding|position|right|row-gap|top|transform|width)/u,Vt=e=>e.replace(/^Webkit/u,`-webkit-`).replace(/^Moz/u,`-moz-`).replaceAll(/([a-z\d])([A-Z])/gu,`$1-$2`).toLowerCase(),Ht=e=>!/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu.test(e),Ut=(e,n)=>{let r=new Map((e.additionalStyles?.declarations??[]).map(e=>[e.property,e])),i=!1;for(let[e,a]of Object.entries(n)){if(p.safeParse({[e]:a}).success||Bt.test(e))continue;if(i=!0,a===null){r.delete(e);continue}let n=String(a);if(!Ht(n))throw new t(`BAD_REQUEST`,`Style ${e} contains executable CSS.`,`Remove imports, expressions, and executable URL schemes.`);r.set(e,{id:r.get(e)?.id??`css-${e}`.slice(0,200),property:e,value:n,enabled:!0})}let a=[];for(let e of r.values()){if(a.length>=128)break;a.push(e)}return i?{op:`setAdditionalStyles`,nodeId:e.id,additionalStyles:{declarations:a}}:null},Wt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[Vt(e),t])),Gt=(e,t)=>{let n=Wt(t),r=[],i=zt(e,n);i!==null&&r.push(i);let a=Object.fromEntries(Object.entries(n).filter(([e,t])=>p.safeParse({[e]:t}).success));Object.keys(a).length>0&&r.push({op:`setStyles`,nodeId:e.id,styles:p.parse(a)});let o=Rt(e,n);o!==null&&r.push({op:`setLayout`,nodeId:e.id,layout:o});let s=Ut(e,n);return s!==null&&r.push(s),n.display===`none`&&r.push({op:`setVisibility`,nodeId:e.id,visible:!1}),r},Kt=(e,n)=>{let r=e[n];if(r!==void 0)return r;throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use current stable node ids.`)},qt=(e,n)=>{let r=n.flatMap(t=>t.nodeIds.flatMap(n=>Gt(Kt(e,n),t.styles)));if(r.length===0)throw new t(`BAD_REQUEST`,`No style changes were provided.`,`Pass at least one changed CSS property.`);return r},Jt=x.uuid().nullable(),F=(e,n,r)=>{let i=e.safeParse(n);if(i.success)return i.data;throw new t(`BAD_REQUEST`,`${r} is invalid.`,`Run the command with --help.`)},I=e=>F(dt,e,`--base-version`),L=(e,n,r)=>{let i=Jt.safeParse(n??null);if(!i.success)throw new t(`BAD_REQUEST`,`--client-token must be a UUID.`,`Mint one UUID and reuse it only when retrying the exact same command.`);e.mutationKey.select(i.data,r)},R=(e,t)=>e.mutationKey.current(`canvas.applyOperations`,{purpose:t}),z=async(e,n,r)=>{let i=f.safeParse(await e.remote.query(`canvas.document.get`,{canvasId:n}));if(!i.success)throw new t(`INTERNAL`,`The API returned an invalid canvas document.`,"Run `enhance doctor` and report incompatible API and CLI versions.");if(i.data.version!==r)throw new t(`CONFLICT`,`Canvas version ${String(i.data.version)} no longer matches --base-version ${String(r)}.`,`Run 'enhance canvas tree --canvas ${n}' and recompute against version ${String(i.data.version)}.`);let a=se.safeParse(i.data.document);if(a.success)return a.data;throw new t(`INTERNAL`,`The stored canvas is not an editable scene.`,`Open the canvas in the editor and repair or recreate the invalid document.`)},B=async(e,t,n,r)=>(L(e,t.clientToken,!1),b(e.remote).execute({canvasId:j(t.canvas),mutationId:R(e,n),baseVersion:I(t.baseVersion),operations:[...r]})),Yt=(e,n,r)=>{if(!e.startsWith(`@`))return e;let i=e.slice(1);if(i===``)throw new t(`BAD_REQUEST`,`${r} @ must name a file.`,`Pass ${r} @/absolute/path/to/file or an inline value.`);let a=T.resolve(i);try{let e=C(a);if(!e.isFile()||e.size>n)throw Error(`invalid size`);return Pe(a,`utf8`)}catch{throw new t(`BAD_REQUEST`,`Could not read a bounded file at ${a}.`,`Use a regular UTF-8 file no larger than ${String(n)} bytes.`)}},V=(e,n,r)=>{let i=(()=>{try{return JSON.parse(Yt(e,1048576,r))}catch(e){throw e instanceof t?e:new t(`BAD_REQUEST`,`${r} must be valid JSON.`,`Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`)}})(),a=n.safeParse(i);if(a.success)return a.data;let o=a.error.issues[0];throw new t(`BAD_REQUEST`,`${r} is invalid${o===void 0||o.path.length===0?``:` at ${o.path.join(`.`)}`}.`,o?.message??`Correct the JSON shape and retry.`)},Xt=(e,t)=>{e.command(`set-text-content`).description(`Set Text node values.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,textContent} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,gt,`--updates`).map(e=>({op:`setText`,nodeId:e.nodeId,text:e.textContent}));t.output.result(await B(t,e,`set-text-content`,n))})},Zt=(e,t)=>{e.command(`rename-nodes`).description(`Rename layers.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeId,name} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.updates,_t,`--updates`).map(e=>({op:`setLabel`,nodeId:e.nodeId,label:e.name,labelOrigin:`user`}));t.output.result(await B(t,e,`rename-nodes`,n))})},Qt=(e,t)=>{e.command(`delete-nodes`).description(`Delete node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=V(e.nodeIds,xt,`--node-ids`);t.output.result(await B(t,e,`delete-nodes`,n.map(e=>({op:`remove`,nodeId:e}))))})},$t=(e,t)=>{e.command(`update-styles`).description(`Update visual and layout styles.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--updates <json-or-@path>`,`Array of {nodeIds,styles} updates.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{let n=await z(t,j(e.canvas),I(e.baseVersion)),r=V(e.updates,vt,`--updates`);t.output.result(await B(t,e,`update-styles`,qt(n.nodes,r)))})},en=(e,t)=>{Xt(e,t),Zt(e,t),Qt(e,t),$t(e,t)},H=e=>e.space===`display-p3`?`color(display-p3 ${String(e.red)} ${String(e.green)} ${String(e.blue)} / ${String(e.alpha)})`:`rgba(${String(Math.round(e.red*255))}, ${String(Math.round(e.green*255))}, ${String(Math.round(e.blue*255))}, ${String(e.alpha)})`,U=e=>{if(!e.visible)return null;if(e.kind===`solid`)return H(e.color);if(e.kind===`image`)return`url(${JSON.stringify(e.assetId)})`;let t=e.stops.map(e=>`${H(e.color)} ${String(e.position*100)}%`).join(`, `);return e.kind===`linear-gradient`?`linear-gradient(${String(e.angle)}deg, ${t})`:`radial-gradient(at ${String(e.center.x*100)}% ${String(e.center.y*100)}%, ${t})`},tn=e=>{if(e.kind===`blur`)return`blur(${String(e.value)}px)`;if(e.kind===`hue-rotate`)return`hue-rotate(${String(e.value)}deg)`;let t=[`grayscale`,`invert`,`sepia`].includes(e.kind)?`${String(e.value*100)}%`:String(e.value);return`${e.kind}(${t})`},nn=e=>e?.flatMap(e=>{let t=U(e);return t===null?[]:[t]})??[],rn=e=>{if(e?.visible!==!0)return{};let t=U(e.paint);return{"border-width":[e.width.top,e.width.right,e.width.bottom,e.width.left].map(e=>`${String(e)}px`).join(` `),"border-style":e.style,...t!==null&&{"border-color":t}}},an=e=>{if(e?.visible!==!0)return{};let t=U(e.paint);return{"outline-width":`${String(e.width)}px`,"outline-offset":`${String(e.offset)}px`,"outline-style":e.style,...t!==null&&{"outline-color":t}}},on=e=>{let t=e.shadows?.filter(e=>e.visible).map(e=>`${e.kind===`inner`?`inset `:``}${String(e.offsetX)}px ${String(e.offsetY)}px ${String(e.blur)}px ${String(e.spread)}px ${H(e.color)}`),n=e.filters?.filter(e=>e.visible).map(tn),r=e.backdropFilters?.filter(e=>e.visible).map(tn);return{...t!==void 0&&t.length>0&&{"box-shadow":t.join(`, `)},...n!==void 0&&n.length>0&&{filter:n.join(` `)},...r!==void 0&&r.length>0&&{"backdrop-filter":r.join(` `)}}},sn=e=>{if(e===void 0)return{};let t=nn(e.fills),n=e.radius;return{...e.opacity!==void 0&&{opacity:e.opacity},...e.blendMode!==void 0&&{"mix-blend-mode":e.blendMode},...t.length>0&&{background:t.join(`, `)},...n!==void 0&&{"border-radius":[n.topLeft,n.topRight,n.bottomRight,n.bottomLeft].map(e=>`${String(e)}px`).join(` `)},...rn(e.border),...an(e.outline),...on(e)}},cn=e=>e===void 0?{}:{"font-family":[e.family,...e.fallbackFamilies].join(`, `),"font-size":`${String(e.size)}px`,"font-weight":e.weight,"font-style":e.style,"line-height":e.lineHeight.mode===`normal`?`normal`:`${String(e.lineHeight.value)}px`,"letter-spacing":`${String(e.letterSpacing)}px`,"text-align":e.align,"text-transform":e.transform,"text-decoration-line":e.decoration.line,"text-decoration-style":e.decoration.style,"white-space":e.wrapping},W=e=>e===`start`?`flex-start`:e===`end`?`flex-end`:e,ln=(e,t)=>e.mode===`fixed`?`${String(e.value)}px`:e.mode===`fill`?`100%`:`${String(t)}px`,un=(e,t)=>({position:e.position===`absolute`?`absolute`:`relative`,...e.position===`absolute`&&{left:`${String(t.x)}px`,top:`${String(t.y)}px`},width:ln(e.horizontal,t.width),height:ln(e.vertical,t.height),...e.clipContent===!0&&{overflow:`hidden`}}),dn=e=>{let t=[...e.rotation===0?[]:[`rotate(${String(e.rotation)}deg)`],...e.flipHorizontal===!0?[`scaleX(-1)`]:[],...e.flipVertical===!0?[`scaleY(-1)`]:[]];return t.length===0?{}:{transform:t.join(` `)}},fn=e=>{if(typeof e!=`object`)return e===`auto`?e:`${String(e)}px`;let t=`${String(e.ratio*100)}%`,n=e.offset??0;return n===0?t:`calc(${t} ${n<0?`-`:`+`} ${String(Math.abs(n))}px)`},pn=e=>({...e.alignSelf!==void 0&&{"align-self":W(e.alignSelf===`auto`?`start`:e.alignSelf)},...e.flexGrow!==void 0&&{"flex-grow":e.flexGrow},...e.flexShrink!==void 0&&{"flex-shrink":e.flexShrink},...e.flexBasis!==void 0&&{"flex-basis":fn(e.flexBasis)},...e.order!==void 0&&{order:e.order}}),mn=e=>{let t=e.container;return t===void 0?{}:{display:`flex`,"flex-direction":t.direction,"align-items":W(t.alignItems),"align-content":W(t.alignContent??`start`),"justify-content":W(t.justifyContent),gap:`${String(t.gap)}px`,"row-gap":`${String(t.rowGap??t.gap)}px`,"column-gap":`${String(t.columnGap??t.gap)}px`,"flex-wrap":t.wrap??`nowrap`,padding:[t.padding.top,t.padding.right,t.padding.bottom,t.padding.left].map(e=>`${String(e)}px`).join(` `)}},hn=e=>{let t=Object.fromEntries((e.additionalStyles?.declarations??[]).filter(e=>e.enabled).map(e=>[e.property,e.value])),n=e.layout===void 0||e.box===void 0?{}:{...un(e.layout,e.box),...dn(e.layout),...pn(e.layout),...mn(e.layout)};return{...e.styles,...t,...cn(e.typography),...sn(e.appearance),...n,...e.visible===!1&&{display:`none`}}},gn=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),_n=(e,n)=>{let r=e.nodes[n];if(r===void 0)throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use a current stable node id.`);return r},G=(e,t)=>{let n=e.props?.[t];return typeof n==`string`?n:``},vn=e=>`{${JSON.stringify(e)}}`,yn=(e,t,n,r)=>{let i=_n(e,t),a=` `.repeat(n),o=[`data-node-id=${JSON.stringify(i.id)}`,`data-name=${JSON.stringify(i.label)}`,`style={${JSON.stringify(hn(i))}}`];if(i.locked===!0&&o.push(`data-locked="true"`),i.component===`image`)return`${a}<img ${o.join(` `)} alt=${JSON.stringify(G(i,`alt`))} src=${JSON.stringify(G(i,`src`))} />`;if(i.component===`svg`)return`${a}<div ${o.join(` `)} data-component="svg" />`;let s=i.component===`text`?`span`:`div`,c=i.component===`text`?vn(G(i,`text`)):``,l=(n>=r?[]:gn(e,t)).map(t=>yn(e,t,n+1,r));return c===``&&l.length===0?`${a}<${s} ${o.join(` `)} />`:[`${a}<${s} ${o.join(` `)}>`,...c===``?[]:[`${a} ${c}`],...l,`${a}</${s}>`].join(`
5
5
  `)},bn=(e,t,n)=>yn(e,t,0,n),xn=(e,t)=>t.map(t=>{let n=_n(e,t);return{nodeId:t,name:n.label,component:n.component,box:n.box,css:hn(n),layout:n.layout,appearance:n.appearance,typography:n.typography}}),Sn={topic:`canvas-agent-authoring`,workflow:[`Run canvas inspect, then canvas tree, before editing.`,`Render the target before changing it and inspect the PNG.`,`Write small visual groups incrementally with write-html.`,`Use duplicate-nodes, set-text-content, update-styles, and move-nodes instead of rewriting existing structure.`,`Use flex, padding, and gap as the primary layout tools. Avoid margin, grid, tables, and inline layout.`,`Every write requires the exact version returned by the latest read.`,`Inspect the review PNG returned by write-html and correct visual discrepancies.`,`Automatic commands show and clear their work indicator. Finish a manual work lease explicitly.`],html:{modes:[`insert-children`,`replace`],rules:[`Use inline styles and concrete CSS values.`,`Use layer-name for meaningful hierarchy names.`,`One call should add roughly one visual group.`,`Styled text controls become a frame plus an editable text child.`,`Scripts, event handlers, embedded documents, executable URLs, and CSS imports are rejected.`]},completion:[`The hierarchy is natural and uses the fewest useful editable primitives.`,`The affected version and node ids match the intended change.`,`The post-write PNG has been inspected.`,`Text, layout, paint, effects, and additional CSS remain editable in the ordinary inspector.`]},Cn=async(e,t)=>{let n=f.parse(await e.remote.query(`canvas.document.get`,{canvasId:t}));return{held:n,document:se.parse(n.document)}},wn=(e,t)=>{e.command(`guide`).description(`Agent design workflow.`).action(()=>{t.output.result(Sn)}),e.command(`get-jsx`).description(`Read concise subtree JSX.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-id <id>`,`Stable subtree root id.`).option(`--depth <integer>`,`Maximum descendant depth from 0 to 20.`,`8`).action(async e=>{let n=j(e.canvas),{held:r,document:i}=await Cn(t,n);t.output.result({canvasId:n,version:r.version,nodeId:e.nodeId,jsx:bn(i,e.nodeId,F(St,e.depth,`--depth`)),warning:`This is a structural reading projection. Use canvas render as the pixel authority.`})}),e.command(`get-computed-styles`).description(`Read effective node CSS.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to inspect.`).requiredOption(`--node-ids <json-or-@path>`,`JSON array of stable node ids.`).action(async e=>{let n=j(e.canvas),{held:r,document:i}=await Cn(t,n),a=V(e.nodeIds,xt,`--node-ids`);t.output.result({canvasId:n,version:r.version,nodes:xn(i,a)})})},K=(e,t)=>Object.entries(e.relationships).filter(([,e])=>e.parentId===t).toSorted(([e,t],[n,r])=>t.sortKey===r.sortKey?e.localeCompare(n):t.sortKey.localeCompare(r.sortKey)).map(([e])=>e),Tn=e=>e!==void 0&&[`root`,`frame`,`group`].includes(e.component),q=(e,n)=>{let r=e.nodes[n];if(r!==void 0)return r;throw new t(`NOT_FOUND`,`Canvas node ${n} does not exist.`,`Run canvas tree and use a current stable node id.`)},En=(e,t)=>{let n=new Set,r=t=>{for(let i of K(e,t))n.add(i),r(i)};return r(t),n},Dn=e=>{let t=e.normalize(`NFKD`).toLowerCase().replaceAll(/[^a-z0-9_-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``).slice(0,60);return t===``?`copy`:t},On=e=>{let t=0;return n=>(t+=1,`${Dn(e)}_${Dn(n)}_${String(t).padStart(4,`0`)}`.slice(0,200))},kn=(e,t)=>{let n=[],r=t=>{n.push(t);for(let n of K(e,t))r(n)};return r(t),n},An=(e,t,n)=>Object.fromEntries(kn(e,t).map(t=>[t,n(q(e,t).label)])),jn=(e,t)=>{let{document:n,rootId:r,parentId:i,inputIndex:a,sourceSortKey:o,map:s}=e,c=q(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}}},Mn=e=>{let{document:n,input:r,inputIndex:i,nextId:a}=e,o=q(n,r.id);if(r.id===`root`)throw new t(`BAD_REQUEST`,`The canvas root cannot be duplicated.`,`Duplicate one or more root children instead.`);let s=n.relationships[r.id];if(s===void 0)throw new t(`BAD_REQUEST`,`Canvas node ${r.id} is detached.`,`Choose a reachable node from canvas tree.`);let c=r.parentId??s.parentId;if(!Tn(n.nodes[c]))throw new t(`BAD_REQUEST`,`Canvas node ${c} cannot contain duplicates.`,`Choose a frame, group, or root as the destination.`);let l=An(n,r.id,a),u={document:n,rootId:r.id,parentId:c,inputIndex:i,sourceSortKey:s.sortKey,map:l},d=kn(n,r.id).map(e=>jn(u,e)),f=l[r.id];if(f===void 0)throw Error(`Missing duplicate root id for ${r.id}`);return{operations:d,summary:{sourceId:r.id,newId:f,name:o.label,component:o.component,descendantIdMap:Object.fromEntries(Object.entries(l).filter(([e])=>e!==r.id))}}},Nn=(e,n,r)=>{if(n.length===0)throw new t(`BAD_REQUEST`,`No nodes were provided to duplicate.`,`Pass at least one stable node id.`);let i=On(r),a=n.map((t,n)=>Mn({document:e,input:t,inputIndex:n,nextId:i}));return{operations:a.flatMap(e=>e.operations),duplicatedNodes:a.map(e=>e.summary)}},Pn=e=>({document:e,children:new Map(Object.keys(e.nodes).map(t=>[t,K(e,t)])),parentOf:new Map(Object.entries(e.relationships).map(([e,t])=>[e,t.parentId])),affected:new Set}),Fn=(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))}},In=(e,n)=>{let r=`before`in e?e.before:e.after;if(r===e.nodeId||n.document.nodes[r]===void 0)throw new t(`BAD_REQUEST`,`Sibling ${r} is not a valid move target.`,`Choose another current sibling node.`);let i=n.parentOf.get(r);if(i===void 0)throw new t(`BAD_REQUEST`,`Sibling ${r} is detached.`,`Choose a reachable sibling from canvas tree.`);let a=(n.children.get(i)??[]).filter(t=>t!==e.nodeId).indexOf(r);return{parentId:i,index:`before`in e?a:a+1}},Ln=(e,t)=>`parentId`in e?Fn(e,t):In(e,t),Rn=(e,n,r)=>{if(e.nodeId===`root`||r.document.nodes[e.nodeId]===void 0)throw new t(`BAD_REQUEST`,`Canvas node ${e.nodeId} cannot be moved.`,`Choose a current non-root node.`);if(En(r.document,e.nodeId).has(n.parentId)||!Tn(r.document.nodes[n.parentId]))throw new t(`BAD_REQUEST`,`Canvas node ${n.parentId} is not a valid parent for ${e.nodeId}.`,`Choose a frame, group, or root outside the moving subtree.`)},zn=(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)??[]];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);let a=i[t.index-1];return{op:`move`,nodeId:e.nodeId,parentId:t.parentId,...a!==void 0&&{afterId:a}}},Bn=(e,n)=>{if(n.length===0)throw new t(`BAD_REQUEST`,`No moves were provided.`,`Pass at least one move operation.`);let r=Pn(e),i=[];return{operations:n.map(e=>{let t=Ln(e,r);return Rn(e,t,r),i.push({nodeId:e.nodeId,...t}),zn(e,t,r)}),moves:i,affectedParents:Array.from(r.affected,e=>({parentId:e,children:[...r.children.get(e)??[]]}))}},Vn=(e,t)=>{e.command(`duplicate-nodes`).description(`Deep-clone node subtrees.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--nodes <json-or-@path>`,`Array of {id,parentId?} requests.`).option(`--id-prefix <prefix>`,`Stable namespace for cloned ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{L(t,e.clientToken,!1);let n=j(e.canvas),r=I(e.baseVersion),i=await z(t,n,r),a=R(t,`duplicate-nodes`),o=Nn(i,V(e.nodes,yt,`--nodes`),e.idPrefix??`copy_${a.replaceAll(`-`,``)}`),s=await b(t.remote).execute({canvasId:n,mutationId:a,baseVersion:r,operations:[...o.operations]});t.output.result({duplicatedNodes:o.duplicatedNodes,apply:s})})},Hn=(e,t)=>{e.command(`move-nodes`).description(`Reorder or reparent nodes.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--moves <json-or-@path>`,`Sequential before, after, or parent/index moves.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact batch.`).action(async e=>{L(t,e.clientToken,!1);let n=j(e.canvas),r=I(e.baseVersion),i=Bn(await z(t,n,r),V(e.moves,bt,`--moves`)),a=await b(t.remote).execute({canvasId:n,mutationId:R(t,`move-nodes`),baseVersion:r,operations:[...i.operations]});t.output.result({moves:i.moves,affectedParents:i.affectedParents,apply:a})})},Un=(e,t)=>{Vn(e,t),Hn(e,t)},Wn=262144,Gn=e=>{let n=Yt(e,Wn,`--html`);if(Buffer.byteLength(n,`utf8`)>Wn)throw new t(`BAD_REQUEST`,`--html exceeds 262144 bytes.`,`Write one visual group at a time, as taught by canvas guide.`);return n},Kn=new Set([`flex-grow`,`flex-shrink`,`font-weight`,`opacity`,`order`,`z-index`]),qn=(e,n)=>{e.command(`write-html`).description(`Compile HTML/CSS primitives.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID to edit.`).requiredOption(`--base-version <integer>`,`Exact current canvas version.`).requiredOption(`--target-node-id <id>`,`Container receiving children, or node to replace.`).requiredOption(`--html <html-or-@path>`,`Inline HTML fragment or @path to a UTF-8 file.`).option(`--mode <mode>`,`insert-children or replace.`,`insert-children`).option(`--id-prefix <prefix>`,`Stable namespace for generated node ids.`).option(`--client-token <uuid>`,`Stable UUID for retrying this exact write and review.`).option(`--output <path>`,`Write the review PNG to this path.`).option(`--force`,`Replace an existing --output file deliberately.`,!1).option(`--scale <number>`,`Review pixels per canvas unit, from 0.1 to 4.`,`1`).option(`--timeout-ms <integer>`,`Review render polling deadline.`,`120000`).addHelpText(`after`,`
@@ -11,4 +11,4 @@ For transcript-led selection, inspect nearby --at-ms renders and reject transiti
11
11
  Preview first: canvas render --node-id rec_<recording-uuid> --at-ms <integer>, then inspect its PNG. This command persists the accepted moment.
12
12
  `).action(async e=>{let r=x.uuid().nullable().safeParse(e.clientToken??null),i=x.uuid().safeParse(e.recordingId);if(!r.success||!i.success)throw new t(`BAD_REQUEST`,`The recording id or client token is not a UUID.`,"Use the recording id from `recording list`; mint one client token per accepted moment.");n.output.result(await n.invocation.invoke({capability:M(n.catalog(),`recording.snapshot`),arguments:{canvasId:j(e.canvas),recordingId:i.data,atMs:Jr(e.atMs,`--at-ms`,!1),timeoutMs:Jr(e.timeoutMs,`--timeout-ms`,!0)},clientToken:r.data}))})},Xr=(e,n,r)=>{if(e!==`canvas.document.save`||typeof r!=`object`||!r||!(`outcome`in r)||r.outcome!==`conflict`)return r;throw new t(`CONFLICT`,`The canvas document changed before this save landed.`,`Run 'enhance canvas document get --canvas-id ${typeof n==`object`&&n&&`canvasId`in n&&typeof n.canvasId==`string`?n.canvasId:`<canvas-id>`}', merge your change into that document, then retry with its version.`)},Zr=(e,t)=>ze(e,e=>({[e]:{query:async n=>t.query(e,n),mutate:async n=>Xr(e,n,await t.mutate(e,n))}})),Qr=(e,n)=>{let r=e.commands.find(e=>e.name()===`transcript`);if(r===void 0)throw TypeError(`the API router did not supply transcript commands`);r.command(`get`).description(`Read timestamped speech cues as candidate moments; render and inspect candidate PNGs before snapshotting.`).requiredOption(`--canvas <url-or-id>`,`Canvas URL or UUID containing the recording.`).requiredOption(`--recording-id <uuid>`,`Recording UUID returned by recording list.`).action(async e=>{let r=x.uuid().safeParse(e.recordingId);if(!r.success)throw new t(`BAD_REQUEST`,`--recording-id must be a UUID.`,"Use the recording id returned by `enhance recording list`.");n.output.result(await n.invocation.invoke({capability:M(n.catalog(),`transcript.read`),arguments:{canvasId:j(e.canvas),recordingId:r.data},clientToken:null}))})},$r={jsonInput:`auto`,prompts:!1,logger:`ndjson`,errorMapping:`stable-exit-codes`},ei=e=>{let t=e.state;return{logger:e.output.logger,prompts:$r.prompts,process:mr(),formatError:e=>{let n=h(e,t.pendingParserMessage);return t.exitCode=v(n,!1,e),t.pendingParserMessage=null,JSON.stringify(n)}}},ti=e=>typeof e==`object`&&e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):null,ni=e=>{let t=ti(e),n=t===null?void 0:t.description;return typeof n==`string`&&n!==``?n:null},ri=e=>{let t=Ee({router:e});return{descriptions:new Map(t.flatMap(([e,t])=>{let n=ni(t.meta);return n===null?[]:[[e,n]]})),mutationPaths:new Set(t.flatMap(([e,t])=>t.type===`mutation`?[e]:[]))}},ii=()=>{let e=null;return()=>(e??=ie(),e)},ai=(e,t,n)=>{let r=Xe(t.remote),i=ve({remote:t.remote,mutationKey:t.mutationKey,configDirectory:t.configDirectory,now:()=>new Date,progress:t.output.result});et(e,ge(t.credentials,t.remote,pe(t.remote)),t.output),Nr(e,i,n,t.output),Pr(e,{version:t.version,credentials:t.credentials,remote:t.remote,output:t.output}),Ur(e,{screen:r,recording:Je(t.remote),world:Ze(t.remote,r)},t.output),Mr(e,t.output,n),dr(e,{remote:t.remote,mutationKey:t.mutationKey,invocation:i,catalog:n,output:t.output,configDirectory:t.configDirectory,now:()=>new Date}),Yr(e,{invocation:i,catalog:n,output:t.output}),qr(e,i,n,t.output),Qr(e,{invocation:i,catalog:n,output:t.output})},oi=e=>{let t=fe(),n=ii(),{descriptions:r,mutationPaths:i}=ri(t),a=Te({router:Zr(t,e.remote),name:e.commandName,version:e.version,description:`Operate Enhance as the authenticated person.`,jsonInput:$r.jsonInput}),o=ei(e),s=a.buildProgram(o);if(!(s instanceof we))throw TypeError(`trpc-cli did not return a Commander program`);kr(s),ai(s,e,n),Tr(s,{descriptions:r,mutationPaths:i,mutationKey:e.mutationKey,output:e.output}),s.description(`Operate Enhance as the authenticated person.`);let c=e.state;return{program:s,run:async()=>{try{await a.run(o,s)}catch(t){if(!(t instanceof m))throw t;if(t.requestedCode!==0&&c.pendingParserMessage!==null){let n=h(t,c.pendingParserMessage);c.exitCode=v(n,!0),c.pendingParserMessage=null,e.output.failure(n)}throw t}}}},si=e=>S.exit(e),Z=36e5,Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ci=e=>{if(Array.isArray(e))return e.map(e=>JSON.stringify(e));if(!Q(e)||!Array.isArray(e.items))return[JSON.stringify(e)];let t=e.items;if(t.length===0)return[JSON.stringify(e)];let n=e.truncated===!0;return t.map(e=>JSON.stringify(Q(e)?{...e,truncated:n}:{value:e,truncated:n}))},li=e=>{let t=`${e.join(`
13
13
  `)}\n`;if(!(t.length>25e3||e.some(e=>e.length>2e3))){S.stdout.write(t);return}let n=Le(`sha256`).update(t).digest(`hex`).slice(0,16),r=T.join(Oe(),`enhance-${n}.ndjson`);w(r,t,{mode:384}),S.stdout.write(`${JSON.stringify({path:r,characters:t.length,records:e.length})}\n`)},ui=e=>{try{let t=new URL(e),n=new Set;for(let e of t.searchParams.keys())n.add(e.toLowerCase());return n.has(`x-amz-signature`)||n.has(`x-amz-credential`)||n.has(`x-amz-algorithm`)}catch{return!1}},$=e=>typeof e==`string`?ui(e):Array.isArray(e)?e.some(e=>$(e)):Q(e)?Object.values(e).some(e=>$(e)):!1,di=e=>{Ne(e,{recursive:!0,mode:448}),Ae(e,448)},fi=e=>{if(!je(e))return;let t=Date.now()-Z,n=Fe(e,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!r.name.startsWith(`result-`))continue;let n=T.join(e,r.name);Me(n).mtimeMs<t&&Ie(n)}},pi=e=>({...e,sensitive:!0,cleanup:`unlink-after-use`,deleteAfter:new Date(Date.now()+Z).toISOString()}),mi=(e,t)=>{let n=ci(e),r=`${n.join(`
14
- `)}\n`;di(t);let i=T.join(t,`result-${E()}.ndjson`);w(i,r,{mode:384,flag:`wx`}),S.stdout.write(`${JSON.stringify(pi({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},hi=e=>Q(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,gi=(e,t,n)=>{let r=`${t.value}\n`;di(n);let i=T.join(n,`result-${E()}.token`);w(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));S.stdout.write(`${JSON.stringify({...a,secret:pi({path:i,field:t.field,characters:r.length})})}\n`)},_i=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),vi=l.omit({fields:!0}).extend({remediation:x.string(),fields:x.array(x.object({path:x.string(),message:x.string()})).optional()}),yi=e=>{try{let t=JSON.parse(e),n=vi.safeParse(t);return n.success?{code:n.data.code,message:n.data.message,remediation:n.data.remediation,...n.data.fields!==void 0&&{fields:n.data.fields}}:null}catch{return null}},bi=(e,t)=>{if(typeof e==`string`&&_i(e)){S.stdout.write(e);return}let n=hi(e);if(n!==null&&Q(e)){gi(e,n,t);return}if($(e)){mi(e,t);return}li(ci(e))},xi=e=>{S.stderr.write(`${JSON.stringify(e)}\n`)},Si=(e,t,n=`enhance`)=>{let r=e,i=T.join(t,`sensitive`);return fi(i),{result:e=>{bi(g(e,n),i)},failure:e=>{xi(ue(e,n))},logger:{info:(...e)=>{bi(g(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(g(e.map(String).join(``),n)),i=yi(t);i===null?r.pendingParserMessage=t:xi(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=Si(e,y.configDirectory,y.commandName),n=ye(y.configDirectory),r=xe(),i=oi({version:`0.1.7-dev.sha-8aeb7ebe4b78`,credentials:n,remote:_e(y.apiUrl,n,r),mutationKey:r,output:t,state:e,configDirectory:y.configDirectory,commandName:y.commandName});try{await i.run()}catch(n){n instanceof m&&si(n.requestedCode===0?0:e.exitCode),t.failure(h(n,null)),si(1)}})();export{};
14
+ `)}\n`;di(t);let i=T.join(t,`result-${E()}.ndjson`);w(i,r,{mode:384,flag:`wx`}),S.stdout.write(`${JSON.stringify(pi({path:i,characters:r.length,records:n.length,reason:`signed-url`}))}\n`)},hi=e=>Q(e)?typeof e.token==`string`?{field:`token`,value:e.token}:typeof e.acceptToken==`string`?{field:`acceptToken`,value:e.acceptToken}:null:null,gi=(e,t,n)=>{let r=`${t.value}\n`;di(n);let i=T.join(n,`result-${E()}.token`);w(i,r,{mode:384,flag:`wx`});let a=Object.fromEntries(Object.entries(e).filter(([e])=>e!==t.field));S.stdout.write(`${JSON.stringify({...a,secret:pi({path:i,field:t.field,characters:r.length})})}\n`)},_i=e=>e.includes(`Usage:`)||e.includes(`Options:`)||e.includes(`Commands:`),vi=l.omit({fields:!0}).extend({remediation:x.string(),fields:x.array(x.object({path:x.string(),message:x.string()})).optional()}),yi=e=>{try{let t=JSON.parse(e),n=vi.safeParse(t);return n.success?{code:n.data.code,message:n.data.message,remediation:n.data.remediation,...n.data.fields!==void 0&&{fields:n.data.fields}}:null}catch{return null}},bi=(e,t)=>{if(typeof e==`string`&&_i(e)){S.stdout.write(e);return}let n=hi(e);if(n!==null&&Q(e)){gi(e,n,t);return}if($(e)){mi(e,t);return}li(ci(e))},xi=e=>{S.stderr.write(`${JSON.stringify(e)}\n`)},Si=(e,t,n=`enhance`)=>{let r=e,i=T.join(t,`sensitive`);return fi(i),{result:e=>{bi(g(e,n),i)},failure:e=>{xi(ue(e,n))},logger:{info:(...e)=>{bi(g(e.length===1?e[0]:e,n),i)},error:(...e)=>{let t=String(g(e.map(String).join(``),n)),i=yi(t);i===null?r.pendingParserMessage=t:xi(i)}}}};(async()=>{let e={exitCode:1,pendingParserMessage:null},t=Si(e,y.configDirectory,y.commandName),n=ye(y.configDirectory),r=xe(),i=oi({version:`0.1.7-dev.sha-be264076fee2`,credentials:n,remote:_e(y.apiUrl,n,r),mutationKey:r,output:t,state:e,configDirectory:y.configDirectory,commandName:y.commandName});try{await i.run()}catch(n){n instanceof m&&si(n.requestedCode===0?0:e.exitCode),t.failure(h(n,null)),si(1)}})();export{};
package/dist/mcp-main.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{f as e,l as t}from"./cli-output-identity.lib-DgzE-BhW.mjs";import{a as n,f as r,i,n as a,o,r as s,t as c}from"./mutation-key.adapter-Bl-A2kBA.mjs";import{t as l}from"./mcp-server.adapter-BV7bBzR6.mjs";import{z as u}from"zod";import d from"node:process";import{serveStdio as f}from"@modelcontextprotocol/server/stdio";const p=new Set([`auth.login`,`auth.logout`,`auth.status`,`doctor`]),m=u.object({openBrowser:u.boolean()}),h=async e=>{let t=r(e.credentials,e.remote,n(e.remote));switch(e.capability){case`auth.login`:{let n=m.parse(e.arguments);return t.loginWithBrowser({label:`Agent plugin`,openBrowser:n.openBrowser,onReady:()=>null})}case`auth.logout`:return t.logout();case`auth.status`:return await e.credentials.read()===null?{authenticated:!1}:t.status();case`doctor`:{let[t,n]=await Promise.all([e.remote.health(),e.credentials.read()]);return{status:n!==null&&t.reachable?`ok`:`degraded`,runtimeVersion:e.version,api:{reachable:t.reachable,status:t.status},credential:{present:n!==null}}}default:throw TypeError(`${e.capability} has no MCP transport execution`)}},g=(e,t,n,r)=>{let i=a(e,t,c());return{invoke:async s=>{if(p.has(s.capability.id))return h({capability:s.capability.id,arguments:s.arguments,credentials:t,remote:i,version:r});let l=c();return o({remote:a(e,t,l),mutationKey:l,configDirectory:n}).invoke(s)}}},_=u.object({authenticated:u.literal(!1)}),v=u.object({authenticated:u.literal(!0),personId:u.uuid(),displayName:u.string().min(1),tokenId:u.uuid(),tokenLabel:u.string().min(1),expiresAt:u.iso.datetime().nullable()}),y=u.object({openBrowser:u.boolean().default(!0).describe(`Open the system browser for the human sign-in and wait for completion.`)}),b=u.strictObject({}),x=u.union([_,v]),S=u.object({loggedOut:u.boolean()}),C=u.object({status:u.enum([`ok`,`degraded`]),runtimeVersion:u.string().min(1),api:u.object({reachable:u.boolean(),status:u.number().int().nullable()}),credential:u.object({present:u.boolean()})}),w=e=>({summary:e.summary,useWhen:e.useWhen,preconditions:[`Run through the local Enhance MCP runtime, which owns the user-scoped credential.`,`Keep credential values outside model-visible input and output.`],input:[],output:[],result:e.result,recovery:[`BAD_REQUEST: correct the named option and call again.`,`UNAUTHORIZED: start browser sign-in and let the person complete consent.`,`FORBIDDEN: leave the credential unchanged and report the governing account policy.`,`INTERNAL: call doctor, report the failing boundary, and stop repeating the call.`],next:e.next,examples:[{input:e.exampleInput,output:e.exampleOutput}]}),T=t=>e({...t,source:`composite`,idempotency:t.operation===`query`?`none`:`single`,execution:{kind:`composite`,procedures:[]},meta:{description:t.guide.summary},policy:{exposure:`mcp-transport`,reason:`The local MCP runtime owns its own authentication and installation diagnostics.`,owner:`mcp`},cliPath:null,inputExample:t.guide.examples[0]?.input,outputExample:t.guide.examples[0]?.output}),E=[T({id:`auth.login`,operation:`mutation`,effect:`external`,inputSchema:y,outputSchema:v,guide:w({summary:`Open browser sign-in and store a revocable user-scoped Enhance credential.`,useWhen:`Use when Enhance is not authenticated or its credential was revoked.`,result:`Waits for browser consent, stores the credential locally, and returns safe identity metadata.`,next:[`Call auth.status, then read the target canvas.`],exampleInput:{openBrowser:!0},exampleOutput:{authenticated:!0,personId:`00000000-0000-4000-8000-000000000001`,displayName:`Ada`,tokenId:`00000000-0000-4000-8000-000000000002`,tokenLabel:`Agent plugin`,expiresAt:null}})}),T({id:`auth.logout`,operation:`mutation`,effect:`delete`,inputSchema:b,outputSchema:S,guide:w({summary:`Remove the user-scoped local Enhance credential.`,useWhen:`Use only when the person asks to disconnect this local agent host.`,result:`Reports whether a local credential was removed without returning its value.`,next:[`Call auth.status to confirm the local runtime is disconnected.`],exampleInput:{},exampleOutput:{loggedOut:!0}})}),T({id:`auth.status`,operation:`query`,effect:`read`,inputSchema:b,outputSchema:x,guide:w({summary:`Check whether the local Enhance MCP runtime is authenticated.`,useWhen:`Use before a workflow or after login, logout, expiry, or an authorization failure.`,result:`Returns safe identity metadata or authenticated false, never a credential value.`,next:[`When unauthenticated, call auth.login; otherwise continue with the requested workflow.`],exampleInput:{},exampleOutput:{authenticated:!1}})}),T({id:`doctor`,operation:`query`,effect:`read`,inputSchema:b,outputSchema:C,guide:w({summary:`Check MCP runtime identity, API reachability, and credential presence without changes.`,useWhen:`Use after repeated connection, authentication, or compatibility failure.`,result:`Returns bounded diagnostics without machine paths, credentials, or customer data.`,next:[`Follow the failing boundary; do not repeat a mutation while diagnostics are degraded.`],exampleInput:{},exampleOutput:{status:`ok`,runtimeVersion:`0.1.7`,api:{reachable:!0,status:200},credential:{present:!0}}})})].toSorted((e,t)=>e.id.localeCompare(t.id)),D=()=>E,O=s(i.configDirectory),k=g(i.apiUrl,O,i.configDirectory,`0.1.7-dev.sha-8aeb7ebe4b78`),A=[...t(),...D()];f(()=>l({version:`0.1.7-dev.sha-8aeb7ebe4b78`,name:i.mcpServiceName,commandName:i.commandName,invocation:k,catalog:A,exposures:[`shared`,`mcp-transport`]}),{legacy:`serve`,onerror:()=>d.stderr.write(`${i.mcpServiceName} transport failure\n`)});export{};
2
+ import{f as e,l as t}from"./cli-output-identity.lib-Bx1wvgKF.mjs";import{a as n,f as r,i,n as a,o,r as s,t as c}from"./mutation-key.adapter-DjXfl_el.mjs";import{t as l}from"./mcp-server.adapter-Mz_hL-XC.mjs";import{z as u}from"zod";import d from"node:process";import{serveStdio as f}from"@modelcontextprotocol/server/stdio";const p=new Set([`auth.login`,`auth.logout`,`auth.status`,`doctor`]),m=u.object({openBrowser:u.boolean()}),h=async e=>{let t=r(e.credentials,e.remote,n(e.remote));switch(e.capability){case`auth.login`:{let n=m.parse(e.arguments);return t.loginWithBrowser({label:`Agent plugin`,openBrowser:n.openBrowser,onReady:()=>null})}case`auth.logout`:return t.logout();case`auth.status`:return await e.credentials.read()===null?{authenticated:!1}:t.status();case`doctor`:{let[t,n]=await Promise.all([e.remote.health(),e.credentials.read()]);return{status:n!==null&&t.reachable?`ok`:`degraded`,runtimeVersion:e.version,api:{reachable:t.reachable,status:t.status},credential:{present:n!==null}}}default:throw TypeError(`${e.capability} has no MCP transport execution`)}},g=(e,t,n,r)=>{let i=a(e,t,c());return{invoke:async s=>{if(p.has(s.capability.id))return h({capability:s.capability.id,arguments:s.arguments,credentials:t,remote:i,version:r});let l=c();return o({remote:a(e,t,l),mutationKey:l,configDirectory:n}).invoke(s)}}},_=u.object({authenticated:u.literal(!1)}),v=u.object({authenticated:u.literal(!0),personId:u.uuid(),displayName:u.string().min(1),tokenId:u.uuid(),tokenLabel:u.string().min(1),expiresAt:u.iso.datetime().nullable()}),y=u.object({openBrowser:u.boolean().default(!0).describe(`Open the system browser for the human sign-in and wait for completion.`)}),b=u.strictObject({}),x=u.union([_,v]),S=u.object({loggedOut:u.boolean()}),C=u.object({status:u.enum([`ok`,`degraded`]),runtimeVersion:u.string().min(1),api:u.object({reachable:u.boolean(),status:u.number().int().nullable()}),credential:u.object({present:u.boolean()})}),w=e=>({summary:e.summary,useWhen:e.useWhen,preconditions:[`Run through the local Enhance MCP runtime, which owns the user-scoped credential.`,`Keep credential values outside model-visible input and output.`],input:[],output:[],result:e.result,recovery:[`BAD_REQUEST: correct the named option and call again.`,`UNAUTHORIZED: start browser sign-in and let the person complete consent.`,`FORBIDDEN: leave the credential unchanged and report the governing account policy.`,`INTERNAL: call doctor, report the failing boundary, and stop repeating the call.`],next:e.next,examples:[{input:e.exampleInput,output:e.exampleOutput}]}),T=t=>e({...t,source:`composite`,idempotency:t.operation===`query`?`none`:`single`,execution:{kind:`composite`,procedures:[]},meta:{description:t.guide.summary},policy:{exposure:`mcp-transport`,reason:`The local MCP runtime owns its own authentication and installation diagnostics.`,owner:`mcp`},cliPath:null,inputExample:t.guide.examples[0]?.input,outputExample:t.guide.examples[0]?.output}),E=[T({id:`auth.login`,operation:`mutation`,effect:`external`,inputSchema:y,outputSchema:v,guide:w({summary:`Open browser sign-in and store a revocable user-scoped Enhance credential.`,useWhen:`Use when Enhance is not authenticated or its credential was revoked.`,result:`Waits for browser consent, stores the credential locally, and returns safe identity metadata.`,next:[`Call auth.status, then read the target canvas.`],exampleInput:{openBrowser:!0},exampleOutput:{authenticated:!0,personId:`00000000-0000-4000-8000-000000000001`,displayName:`Ada`,tokenId:`00000000-0000-4000-8000-000000000002`,tokenLabel:`Agent plugin`,expiresAt:null}})}),T({id:`auth.logout`,operation:`mutation`,effect:`delete`,inputSchema:b,outputSchema:S,guide:w({summary:`Remove the user-scoped local Enhance credential.`,useWhen:`Use only when the person asks to disconnect this local agent host.`,result:`Reports whether a local credential was removed without returning its value.`,next:[`Call auth.status to confirm the local runtime is disconnected.`],exampleInput:{},exampleOutput:{loggedOut:!0}})}),T({id:`auth.status`,operation:`query`,effect:`read`,inputSchema:b,outputSchema:x,guide:w({summary:`Check whether the local Enhance MCP runtime is authenticated.`,useWhen:`Use before a workflow or after login, logout, expiry, or an authorization failure.`,result:`Returns safe identity metadata or authenticated false, never a credential value.`,next:[`When unauthenticated, call auth.login; otherwise continue with the requested workflow.`],exampleInput:{},exampleOutput:{authenticated:!1}})}),T({id:`doctor`,operation:`query`,effect:`read`,inputSchema:b,outputSchema:C,guide:w({summary:`Check MCP runtime identity, API reachability, and credential presence without changes.`,useWhen:`Use after repeated connection, authentication, or compatibility failure.`,result:`Returns bounded diagnostics without machine paths, credentials, or customer data.`,next:[`Follow the failing boundary; do not repeat a mutation while diagnostics are degraded.`],exampleInput:{},exampleOutput:{status:`ok`,runtimeVersion:`0.1.7`,api:{reachable:!0,status:200},credential:{present:!0}}})})].toSorted((e,t)=>e.id.localeCompare(t.id)),D=()=>E,O=s(i.configDirectory),k=g(i.apiUrl,O,i.configDirectory,`0.1.7-dev.sha-be264076fee2`),A=[...t(),...D()];f(()=>l({version:`0.1.7-dev.sha-be264076fee2`,name:i.mcpServiceName,commandName:i.commandName,invocation:k,catalog:A,exposures:[`shared`,`mcp-transport`]}),{legacy:`serve`,onerror:()=>d.stderr.write(`${i.mcpServiceName} transport failure\n`)});export{};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{C as e,a as t,i as n,l as r,n as i,s as a,t as o}from"./cli-output-identity.lib-DgzE-BhW.mjs";import{z as s}from"zod";import{createHash as c,randomUUID as l}from"node:crypto";import{readFile as u,rm as d}from"node:fs/promises";import{McpServer as f}from"@modelcontextprotocol/server";const p=e=>e.replaceAll(/\s+/gu,` `).trim(),m=e=>{let t=`${e.id} [${e.effect}] — `,n=p(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},h=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>m(e)),r=c(`sha256`).update(n.join(`
2
+ import{C as e,a as t,i as n,l as r,n as i,s as a,t as o}from"./cli-output-identity.lib-Bx1wvgKF.mjs";import{z as s}from"zod";import{createHash as c,randomUUID as l}from"node:crypto";import{readFile as u,rm as d}from"node:fs/promises";import{McpServer as f}from"@modelcontextprotocol/server";const p=e=>e.replaceAll(/\s+/gu,` `).trim(),m=e=>{let t=`${e.id} [${e.effect}] — `,n=p(e.guide.summary),r=180-t.length;return`${t}${n.slice(0,r)}`},h=(e,t)=>{let n=e.toSorted((e,t)=>e.id.localeCompare(t.id)).map(e=>m(e)),r=c(`sha256`).update(n.join(`
3
3
  `)).digest(`hex`),i=[`Enhance MCP ${t} — ${String(n.length)} capabilities — sha256:${r}`,...n].join(`
4
4
  `);if(Buffer.byteLength(i)>24576)throw RangeError(`the complete capability catalogue exceeds 24 KiB`);return{digest:r,text:i}},g=(e,t,n=`enhance`)=>{let r=h(e,t),a=String(i(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:s.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:a}]}))}}},_=s.object({ok:s.literal(!1),error:s.object({code:s.string(),message:s.string(),remediation:s.string(),fields:s.array(s.object({path:s.string(),message:s.string()})).optional()})}),v=s.object({ok:s.literal(!0),artifact:s.object({uri:s.string(),mimeType:s.string(),bytes:s.number().int().nonnegative()})}),y=s.object({id:s.string(),operation:s.enum([`query`,`mutation`]),effect:s.enum([`read`,`write`,`delete`,`external`]),idempotency:s.enum([`none`,`single`,`composite`]),summary:s.string(),useWhen:s.string(),preconditions:s.array(s.string()),inputSchema:s.unknown(),exampleInput:s.unknown(),output:s.array(s.object({name:s.string(),required:s.boolean(),meaning:s.string()})),result:s.string(),recovery:s.array(s.string()),next:s.array(s.string()),schemaDigest:s.string(),guidanceDigest:s.string(),behaviorDigest:s.string()}),b=y.pick({id:!0,operation:!0,effect:!0,summary:!0,useWhen:!0}),x=s.union([s.object({ok:s.literal(!0),result:s.unknown()}),v,_]),S=s.union([s.object({ok:s.literal(!0),result:s.object({matches:s.array(b),totalMatches:s.number().int().nonnegative(),truncated:s.boolean()})}),_]),C=s.union([s.object({ok:s.literal(!0),result:y}),_]),w=s.object({capability:s.string().min(1).describe(`Exact capability id returned by capability.search or capability.catalogue.`)}),T=(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:w,outputSchema:C,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)})}}),E=/(?:^|_)(?:accept)?(?:token|secret|credential|authorization)(?:$|_)/iu,D=/[?&](?:X-Amz-(?:Algorithm|Credential|Signature)|Signature)=/iu,O=e=>JSON.stringify(e),k=(e,t=``)=>typeof e==`string`?D.test(e)||E.test(t)&&!t.endsWith(`Id`):Array.isArray(e)?e.some(e=>k(e,t)):typeof e!=`object`||!e?!1:Reflect.get(e,`sensitive`)===!0||Object.entries(e).some(([e,t])=>k(t,e)),A=async(e,t,n)=>{if(typeof t!=`object`||!t)return null;let r=Reflect.get(t,`path`);if(typeof r!=`string`)return null;let i=Reflect.get(t,`contentType`);if(typeof i!=`string`||!i.startsWith(`image/`)||Reflect.get(t,`sensitive`)!==!0)return null;let a=await u(r),o=l(),s=`enhance://artifact/${o}`;if(n===`embedded`){await d(r,{force:!0});let e={ok:!0,artifact:{uri:s,mimeType:i,bytes:a.byteLength}};return{content:[{type:`text`,text:O(e)},{type:`image`,data:a.toString(`base64`),mimeType:i}],structuredContent:e}}e.registerResource(`artifact-${o}`,s,{title:`Enhance artifact`,mimeType:i},e=>({contents:[{uri:e.href,mimeType:i,blob:a.toString(`base64`)}]}));let c={ok:!0,artifact:{uri:s,mimeType:i,bytes:a.byteLength}};return{content:[{type:`text`,text:O(c)},{type:`resource_link`,name:`Enhance artifact`,uri:s,mimeType:i}],structuredContent:c}},j=(e,t,n)=>{let r=l(),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:O(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:O(o)},{type:`resource_link`,name:`Protected Enhance result`,uri:i,mimeType:`application/json`}],structuredContent:o}},M=t=>new e(`BAD_REQUEST`,`Input validation error.`,`Call capability.search again and rewrite every rejected input field.`,Object.fromEntries(t.issues.map(e=>[e.path.length===0?`input`:e.path.join(`.`),e.message]))),N=(e=`enhance`)=>({success:async(t,n,r)=>{let a=i(n,e),o=await A(t,a,r);if(o!==null)return o;let s=O(a);if(Buffer.byteLength(s)>2e4||k(a))return j(t,s,r);let c={ok:!0,result:a};return{content:[{type:`text`,text:O(c)}],structuredContent:c}},inline:t=>{let n={ok:!0,result:i(t,e)};return{content:[{type:`text`,text:O(n)}],structuredContent:n}},failure:t=>{let r={ok:!1,error:o(n(t instanceof s.ZodError?M(t):t,null),e)};return{content:[{type:`text`,text:O(r)}],structuredContent:r,isError:!0}}}),P=s.object({query:s.string().trim().min(1).max(200).describe(`Plain-language task, domain, or exact capability id to discover.`),operation:s.enum([`any`,`query`,`mutation`]).default(`any`).describe(`Limit matches to reads or mutations when the intended effect is known.`),limit:s.number().int().min(1).max(10).default(5).describe(`Maximum contracts to return.`)}),F=s.object({capability:s.string().min(1).describe(`Exact query id returned by capability.describe.`),input:s.record(s.string(),s.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`)}),I=s.object({capability:s.string().min(1).describe(`Exact mutation id returned by capability.describe.`),input:s.record(s.string(),s.unknown()).default({}).describe(`Input matching the discovered capability inputSchema.`),clientToken:s.uuid().optional().describe(`Stable UUID reused only when retrying this exact mutation input.`)}),L=(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},R=(e,t,n,r)=>{e.registerTool(`capability.search`,{title:`Discover Enhance capabilities`,description:`Search the Enhance capability catalogue for a specific likely action. Returns only the most relevant summaries; use capability.catalogue when the request is broad or the matches look wrong, then call capability.describe before invoking.`,inputSchema:P,outputSchema:S,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"ai.enhancelabs/catalogSize":t.length,"enhance/disclosure":`progressive`,"enhance/catalogSize":t.length}},async({query:e,operation:t,limit:i})=>r.inline(n.search({query:e,operation:t,limit:i})))},z=(e,t,n,r)=>{e.registerTool(`capability.query`,{title:`Run a discovered Enhance query`,description:`Run one read-only capability using the exact id and input loaded by capability.describe. Search and describe first whenever the contract is not already present in the conversation.`,inputSchema:F,outputSchema:x,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a})=>{try{return await r.results.success(e,await n.invoke({capability:L(t,i,`query`),arguments:a,clientToken:null}),r.delivery)}catch(e){return r.results.failure(e)}})},B=(e,t,n,r)=>{e.registerTool(`capability.mutate`,{title:`Run a discovered Enhance mutation`,description:`Run one state-changing capability using the exact id and input loaded by capability.describe. Search and describe first, respect its preconditions, and reuse clientToken only when retrying the identical mutation.`,inputSchema:I,outputSchema:x,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},_meta:{"ai.enhancelabs/disclosure":`progressive`,"enhance/disclosure":`progressive`}},async({capability:i,input:a,clientToken:o})=>{try{return await r.results.success(e,await n.invoke({capability:L(t,i,`mutation`),arguments:a,clientToken:o??null}),r.delivery)}catch(e){return r.results.failure(e)}})},V=e=>{let n=new f({name:e.name??`enhance-mcp`,version:e.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!0}}}),i=t(e.catalog??r(),e.exposures??[`shared`]),o=a(i),s=e.delivery??`linked`,c=N(e.commandName);g(i,e.version,e.commandName).register(n),R(n,i,o,c),T(o,c).register(n);let l={delivery:s,results:c};return z(n,i,e.invocation,l),B(n,i,e.invocation,l),n};export{V as t};
package/dist/mcp.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{l as e,o as t}from"./cli-output-identity.lib-DgzE-BhW.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-BV7bBzR6.mjs";export{e as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,t as toSharedCapabilities};
2
+ import{l as e,o as t}from"./cli-output-identity.lib-Bx1wvgKF.mjs";import{t as n}from"./capability-inventory.mapper-B_GMS9z3.mjs";import{t as r}from"./mcp-server.adapter-Mz_hL-XC.mjs";export{e as createCapabilityCatalogAdapter,r as createEnhanceMcpServer,n as toCapabilityInventory,t as toSharedCapabilities};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{$ as e,B as t,C as n,F as r,H as i,I as a,L as o,M as s,N as c,P as l,Q as u,R as ee,S as te,V as ne,W as re,X as ie,_ as ae,at as d,b as oe,g as se,h as ce,it as le,j as ue,nt as de,ot as fe,q as pe,rt as me,v as he,w as ge,x as _e,y as ve,z as ye}from"./cli-output-identity.lib-DgzE-BhW.mjs";import{z as f}from"zod";import{homedir as be,tmpdir as xe}from"node:os";import p from"node:process";import{chmodSync as m,createReadStream as h,createWriteStream as Se,mkdirSync as Ce,writeFileSync as we}from"node:fs";import g from"node:path";import{createHash as _,randomBytes as v,randomUUID as y}from"node:crypto";import{setTimeout as Te}from"node:timers/promises";import{chmod as b,mkdir as Ee,mkdtemp as De,readFile as Oe,realpath as ke,rename as Ae,rm as x,stat as S,unlink as C,writeFile as je}from"node:fs/promises";import{Readable as Me,Transform as w}from"node:stream";import{pipeline as Ne}from"node:stream/promises";import{ZipFile as Pe}from"yazl";import{createTRPCUntypedClient as Fe,httpLink as Ie}from"@trpc/client";import{spawn as Le}from"node:child_process";import{createServer as Re}from"node:http";const ze=/^enh_[\w-]{43}$/,T=e=>{let r=t.parse(e);if(r.authentication.kind!==`agent`||r.person===null)throw new n(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:r.person.id,displayName:r.person.displayName,tokenId:r.authentication.tokenId,tokenLabel:r.authentication.tokenLabel,expiresAt:r.authentication.expiresAt}},Be=(e,t,r)=>({loginWithToken:async r=>{if(!ze.test(r))throw new n(`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=T(await t.queryWithToken(`person.me`,{},r));return await e.write(r),i},loginWithBrowser:async a=>{let o=ne.parse(await t.authenticationConfig());if(o.method===`token`)throw new n(`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 s=await r.authorize({issuer:o.issuer,clientId:o.clientId,scope:o.scope,openBrowser:a.openBrowser,onReady:a.onReady}),c=i.parse(await t.mutateWithToken(`person.createAgentToken`,{label:a.label,expiresAt:null},s)),l=T(await t.queryWithToken(`person.me`,{},c.token));return await e.write(c.token),l},status:async()=>{if(await e.read()===null)throw new n(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return T(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),Ve=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),He=e=>{if(e.byteLength<24||Ve.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)}},Ue=async(e,t)=>{let r=le.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!r.success)throw new n(`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(r.data.download.url),a=He(i);if(a===null||i.byteLength!==t.result.bytes||a.width!==t.result.width||a.height!==t.result.height)throw new n(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return i},E=[`canvas.render.create`,`canvas.render.get`],D=e=>new n(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),We=e=>{let t=e.failure;if(t===null)return D(`render job`);let r=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 n(r,t.message,i,{jobId:e.id,reason:t.reason,phase:t.phase})},Ge=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Ke=async(e,t)=>{let n=d.safeParse(await e.query(E[1],{jobId:t}));if(!n.success)throw D(`render status`);return n.data.job},qe=async(e,t)=>{let r=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-r,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),i=s,a=c),s>=t.deadline)throw new n(`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 Ge(250),o=await Ke(e,o.id)}if(o.state!==`succeeded`)throw We(o);return o},Je=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]},Ye=(e,t)=>({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:Je(e)}),Xe=async(e,t)=>{let n=de.safeParse(await e.remote.mutate(E[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,format:`png`}));if(!n.success)throw D(`render creation`);let r=await qe(e.remote,{initial:n.data.job,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress}),i=await Ue(e.remote,r),a=e.files.write({body:i,outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()});return Ye(r,a)},O=(e,t,n,r=()=>null)=>({execute:async i=>Xe({remote:e,files:t,now:n,progress:r},i)}),k={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},A=async e=>{try{return await e(),!0}catch{return!1}},Ze=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await A(async()=>e.mutate(k.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 A(async()=>e.mutate(k.end,{canvasId:i.canvasId,activityId:n})))}}},j=e=>({begin:async t=>{try{let n=re.safeParse(await e.mutate(k.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?Ze(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>A(async()=>e.mutate(k.end,{canvasId:t,activityId:n}))}),Qe=new Set([`insertPrototype`,`insertText`,`setBox`]),$e=e=>Qe.has(e.op),et=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,tt=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],nt=e=>[...new Set(e.operations.flatMap(e=>tt(e)))].slice(0,100),rt=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:$e(e)?e.box:null,it=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}},M=async(e,t)=>{let r=await e.mutate(`canvas.applyOperations`,t),i=pe.safeParse(r);if(!i.success)throw new n(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return i.data},N=e=>({execute:async(t,n)=>{if(n?.activity===!1)return M(e,t);let r=await j(e).begin({canvasId:t.canvasId,phase:et(t),nodeIds:nt(t),bounds:it(t.operations.flatMap(e=>{let t=rt(e);return t===null?[]:[t]}))});try{return await M(e,t)}finally{await r?.finish()}}}),P=e=>new n(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),at=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),ot=e=>{let t=e.failure;return new n(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 tree and correct the HTML or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},st=async(t,n)=>{let r=e.safeParse(await t.query(`canvas.render.getImport`,{jobId:n}));if(!r.success)throw P(`HTML import status`);return r.data.job},ct=async(e,t,r)=>{let i=Date.now()+r,a=t;for(;a.state===`queued`||a.state===`running`;){if(Date.now()>=i)throw new n(`INTERNAL`,`HTML import ${a.id} did not finish before the local timeout.`,"Retry the exact command with a larger --timeout-ms. If the queue remains stuck, run `enhance doctor`.",{jobId:a.id,phase:a.phase});await at(250),a=await st(e,a.id)}if(a.state!==`succeeded`)throw ot(a);return a},lt=async(e,t)=>{let n=u.safeParse(await e.mutate(`canvas.render.importSource`,{canvasId:t.canvasId,expectedVersion:t.baseVersion,source:{kind:`html`,html:t.html,label:`Agent-authored HTML`,...t.idPrefix!==void 0&&{idPrefix:t.idPrefix}},destination:{kind:t.mode,targetNodeId:t.targetNodeId}}));if(!n.success)throw P(`HTML import creation`);return ct(e,n.data.job,t.renderTimeoutMs)},ut=(e,t,r)=>({state:`failed`,mutationCommitted:!0,requestedVersion:r,...e instanceof n?{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:`Read the current canvas version, then render the affected area again.`},next:[`enhance canvas inspect --canvas ${t.canvasId}`,`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(r)}`,`Do not replay the committed write with a new mutation id.`]}),dt=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 ut(e,t,n.result.version)}},ft=async(e,t)=>{let n=ie.safeParse(await e.query(`canvas.document.get`,{canvasId:t.canvasId}));if(!n.success)throw P(`canvas document`);let r=fe.safeParse(n.data.document);if(!r.success)throw P(`editable canvas document`);return t.result.insertedNodeIds.map(e=>{let t=r.data.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},pt=async(e,t,n,r)=>({canvasId:t.canvasId,mutationCommitted:!0,mode:t.mode,targetNodeId:t.targetNodeId,previousVersion:n.result.previousVersion,version:n.result.version,createdNodes:await ft(e,n),removedNodeIds:n.result.removedNodeIds,affectedBounds:n.result.affectedBounds,review:r,next:[`enhance canvas tree --canvas ${t.canvasId}`,`Inspect the review PNG before continuing.`]}),F=(e,t)=>({execute:async n=>{let r=await j(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await lt(e,n);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await dt(t,n,i);return await pt(e,n,i,a)}finally{await r?.finish()}}}),I=(e,t,r)=>{try{we(e,t,{flag:r?`w`:`wx`,mode:384}),m(e,384)}catch(t){let r=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new n(r,r===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,r===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},L=e=>({write:t=>{if(t.outputPath!==null){let e=g.resolve(t.outputPath);return I(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=g.join(e,`sensitive`);Ce(n,{recursive:!0,mode:448}),m(n,448);let r=g.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return I(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),R=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],z=e=>new n(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),mt=async(e,t)=>{let r=Date.now()+3e5,i=50;for(;Date.now()<r;){let r=a.safeParse(await e.query(R[3],t));if(!r.success)throw z(`status`);if(r.data.state===`ready`||r.data.state===`failed`)return r.data;if(r.data.state===`abandoned`)throw new n(`NOT_FOUND`,`Prototype deployment ${t.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);await Te(i),i=Math.min(i*2,1e3)}throw Error(`prototype ingestion is still running`)},ht=async(e,t,n,r)=>{let i=c.safeParse(await e.mutate(R[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw z(`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`)&&!ye.safeParse(await e.mutate(R[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId})).success)throw z(`artifact submission`);return i.data},gt=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new n(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},_t=async(e,t,i)=>{let a=r.safeParse(await e.query(R[0],{}));if(!a.success)throw z(`capabilities`);let o=await t.package({directory:i.directory,entryPath:i.entryPath,limits:a.data.limits}),c={deploymentId:null};try{let t=await ht(e,i,o,e=>{c.deploymentId=e}),n=await mt(e,{canvasId:i.canvasId,deploymentId:t.deploymentId});gt(n);let r=s.safeParse(await e.mutate(R[4],{canvasId:i.canvasId,deploymentId:t.deploymentId,baseVersion:i.baseVersion}));if(!r.success)throw z(`attachment`);return{...r.data,fileCount:n.fileCount,totalBytes:n.totalBytes,alreadyExists:t.alreadyExists,next:[r.data.openUrl,`enhance canvas render --canvas ${i.canvasId} --node-id ${r.data.nodeId} --expected-version ${String(r.data.version)}`]}}catch(e){throw e instanceof n&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||c.deploymentId===null?e:new te(`Prototype deployment ${c.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${i.clientToken}.`)}finally{await o.dispose()}},vt=(e,t)=>({execute:async n=>_t(e,t,n)}),yt=[`transcript.get`],bt=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),xt=e=>({execute:async t=>{let r=ge.safeParse(await e.query(yt[0],t));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data.state===`ready`?{...r.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:bt(t.canvasId,t.recordingId,r.data.cues.map(e=>e.startMs))}:r.data}}),B=[`canvas.render.get`,`canvas.render.snapshot`],St=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Ct=e=>new n(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}),wt=async(e,t)=>{let r=d.safeParse(await e.query(B[0],{jobId:t}));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return r.data.job},Tt=async(e,t,r,i)=>{let a=Date.now()+r.timeoutMs,o=Date.now(),s=t,c=0,l=``;for(;s.state===`queued`||s.state===`running`;){let t=Date.now(),u=`${s.state}:${s.phase}`;if((u!==l||t-c>=5e3)&&(i({event:`snapshot.progress`,jobId:s.id,state:s.state,phase:s.phase,elapsedMs:t-o,timeoutMs:r.timeoutMs,retryClientToken:r.retryClientToken}),c=t,l=u),t>=a)throw new n(`INTERNAL`,`Snapshot ${s.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${r.retryClientToken} and a larger --timeout-ms.`,{jobId:s.id,phase:s.phase});await St(),s=await wt(e,s.id)}if(s.state!==`succeeded`||s.result.snapshot===void 0)throw Ct(s);return{...s,result:{...s.result,snapshot:s.result.snapshot}}},Et=async(e,t,r)=>{let i=me.safeParse(await e.mutate(B[1],{canvasId:r.canvasId,recordingId:r.recordingId,atMs:r.atMs}));if(!i.success)throw new n(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");let a=await Tt(e,i.data.job,r,t),o=a.result.snapshot;return{jobId:a.id,canvasId:a.canvasId,...o,warnings:a.result.warnings,retryClientToken:r.retryClientToken,next:[`enhance canvas node --canvas ${a.canvasId} --node-id ${o.screenNodeId}`,`enhance canvas render --canvas ${a.canvasId} --node-id ${o.screenNodeId} --expected-version ${String(o.version)}`]}},Dt=(e,t)=>({execute:async n=>Et(e,t,n)}),V=new Date(`1980-01-01T00:00:00.000Z`),H=33188,U=(e,t)=>new n(`BAD_REQUEST`,e,t),Ot=(e,t)=>{let n=_(`sha256`),r=0;return new w({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}t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}})},kt=e=>{let t=o.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),n=Buffer.from(JSON.stringify(t),`utf8`);if(n.byteLength>e.limits.manifestBytes)throw U(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,ue,{mtime:V,mode:H,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},At=async e=>{let t=new Pe,n=_(`sha256`),r=new w({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Ne(t.outputStream,r,Se(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=n=>{i.set(n.path,n),a.manifest===null&&i.size===e.files.length&&(a.manifest=kt({zip:t,completed:i,...e}))};for(let n of e.files)t.addReadStreamLazy(n.path,{size:n.bytes,mtime:V,mode:H,compress:!0,forceDosTimestamp:!0},e=>{e(null,h(n.absolutePath).pipe(Ot(n,s)))});if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await S(e.artifactPath);if(c.size>e.limits.artifactBytes)throw U(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:c.size,sha256:n.digest(`hex`)}},jt={".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`},Mt=e=>jt[g.extname(e).toLowerCase()]??`application/octet-stream`,W=async e=>{try{return await S(e)}catch{return null}},Nt=e=>Buffer.byteLength(e,`utf8`),G=(e,t)=>new n(`BAD_REQUEST`,e,t),K=(e,t)=>{if(!ee.safeParse(e).success)throw G(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Nt(e)>t.pathBytes)throw G(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},q=async(e,t,n,r)=>{let i=await ke(t);if(n.has(i))throw G(`Cannot package the circular directory link at ${t}.`,`Pass a directory tree that can be read once from top to bottom.`);let a=new Set(n).add(i),{readdir:o}=await import(`node:fs/promises`),s=await o(t,{withFileTypes:!0}),c=[],l=s.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of l){let i=g.join(t,n.name),o=await W(i);if(o?.isDirectory()===!0){c.push(...await q(e,i,a,r));continue}if(o?.isFile()!==!0)throw G(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=g.relative(e,i).split(g.sep).join(`/`).normalize(`NFC`);K(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:Mt(i)})}return c},Pt=(e,t,n)=>{if(e.length===0)throw G(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw G(`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=l(t.path);if(r.has(e))throw G(`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 G(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,i>n.expandedBytes)throw G(`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 G(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw G(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},Ft=async e=>{let t=g.resolve(e.directory),r=await W(t);if(r===null)throw new n(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!r.isDirectory())throw G(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let i=e.entryPath.split(g.sep).join(`/`).normalize(`NFC`);K(i,e.limits);let a=await q(t,t,new Set,e.limits);Pt(a,i,e.limits);let o=await De(g.join(xe(),`enhance-prototype-artifact-`)),s=g.join(o,`artifact.zip`);try{let t=await At({artifactPath:s,files:a,entryPath:i,limits:e.limits});return{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:()=>h(s),dispose:async()=>x(o,{recursive:!0})}}catch(e){throw await x(o,{recursive:!0}),e}},It=()=>({package:Ft}),J=e=>O(e.remote,L(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Lt=async(e,t)=>{let n=ce.parse(t);return N(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Rt=async(e,t,n)=>{let r=se.parse(t);return J(e).execute({...r,retryClientToken:n})},zt=async(e,t)=>{let n=ae.parse(t);return F(e.remote,J(e)).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},Bt=async(e,t)=>{let n=he.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Vt=async(e,t,n)=>{let r=ve.parse(t);return vt(e.remote,It()).execute({...r,clientToken:n})},Ht=async(e,t,n)=>{let r=oe.parse(t);return Dt(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Ut=async(e,t)=>{let n=_e.parse(t);return xt(e.remote).execute(n)},Wt=async(e,t,n,r)=>{switch(t){case`canvas.apply`:return Lt(e,n);case`canvas.render`:return Rt(e,n,r);case`canvas.writeHtml`:return zt(e,n);case`comment.attention`:return Bt(e,n);case`prototype.publish`:return Vt(e,n,r);case`recording.snapshot`:return Ht(e,n,r);case`transcript.read`:return Ut(e,n);default:throw TypeError(`${t} has no composite execution`)}},Gt=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??y();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Wt(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),Y=`/callback`,Kt=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),qt=e=>{let t=p.platform===`darwin`?{executable:`open`,arguments:[e]}:p.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=Le(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Jt=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==Y){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)},Yt=e=>{let t=Kt(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},Xt=async e=>{let t=Promise.withResolvers(),n=Re((n,r)=>{Jt({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)}${Y}`,a=Yt({...e,redirectUri:i});e.onReady(a),e.openBrowser&&qt(a);let o=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return{code:await t.promise,redirectUri:i}}finally{clearTimeout(o),await new Promise(e=>{n.close(()=>{e()})})}},X=e=>({authorize:async t=>{try{let n=v(32).toString(`base64url`),r=_(`sha256`).update(n).digest(`base64url`),i=v(32).toString(`base64url`),a=await Xt({...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 n(`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.`)}}}),Z=e=>e===void 0||e===``?void 0:e,Zt=((e,t,n)=>{let r=Z(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Z(e.ENHANCE3_API_URL),a=g.join(t,`.config`,n.configDirectoryName),o=Z(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&i!==n.apiUrl)throw TypeError(`Enhance development cannot use ${i}`);if(o!==void 0&&g.resolve(o)!==g.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}})(p.env,be(),{apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`}),Qt=f.object({token:f.string().startsWith(`enh_`)}),$t=e=>{let t=g.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Oe(t,`utf8`));return Qt.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Ee(e,{recursive:!0,mode:448}),await b(e,448);let r=g.join(e,`credentials.${String(p.pid)}.tmp`);await je(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ae(r,t),await b(t,384)},remove:async()=>{try{return await C(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},en=f.object({access_token:f.string().min(1)}),Q=(e,t,n=null)=>Fe({links:[Ie({url:`${e}/trpc`,headers:{...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),tn=async e=>{let t=await fetch(e);if(!t.ok)throw new n(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())},nn=async e=>{let t=await fetch(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new n(`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 n(`INTERNAL`,`CLI authentication discovery answered HTTP ${String(t.status)}.`,`Run 'enhance doctor', report the result, and stop.`);return t.json()},rn=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await fetch(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw Error(`OAuth discovery answered HTTP ${String(n.status)}`);return n.json()},an=async e=>{let t=await fetch(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 Error(`token exchange answered HTTP ${String(t.status)}`);return en.parse(await t.json()).access_token},on=async e=>{try{let t=await fetch(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status}}catch{return{url:e,reachable:!1,status:null}}},sn=(e,t,r)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>nn(i),oauthMetadata:rn,exchangeOauthCode:an,query:async(e,n)=>Q(i,await t.read()).query(e,n),queryWithToken:async(e,t,n)=>Q(i,n).query(e,t),mutate:async(e,n)=>Q(i,await t.read(),r.current(e,n)).mutation(e,n),mutateWithToken:async(e,t,n)=>Q(i,n).mutation(e,t),download:tn,upload:async e=>{let t=!(e.body instanceof Uint8Array),r=t?Me.toWeb(e.body):e.body,i={method:`PUT`,headers:e.headers,body:r,...t&&{duplex:`half`}},a=await fetch(e.url,i);if(!a.ok)throw new n(`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 n(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return o.replaceAll(`"`,``)},health:async()=>on(i)}},$=e=>Array.isArray(e)?e.map(e=>$(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$(t)])),cn=(e,t,n)=>_(`sha256`).update(`${e}\0${t}\0${JSON.stringify($(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),ln=()=>{let e=y(),t=!1;return{current:(n,r)=>t?cn(e,n,r):e,select:(n,r)=>{e=n??y(),t=r}}};export{X as a,F as c,O as d,Be as f,Zt as i,N as l,sn as n,Gt as o,$t as r,L as s,ln as t,j as u};
2
+ import{$ as e,B as t,C as n,F as r,H as i,I as a,L as o,M as s,N as c,P as l,Q as u,R as ee,S as te,V as ne,W as re,X as ie,_ as ae,at as d,b as oe,g as se,h as ce,it as le,j as ue,nt as de,ot as fe,q as pe,rt as me,v as he,w as ge,x as _e,y as ve,z as ye}from"./cli-output-identity.lib-Bx1wvgKF.mjs";import{z as f}from"zod";import{homedir as be,tmpdir as xe}from"node:os";import p from"node:process";import{chmodSync as m,createReadStream as h,createWriteStream as Se,mkdirSync as Ce,writeFileSync as we}from"node:fs";import g from"node:path";import{createHash as _,randomBytes as v,randomUUID as y}from"node:crypto";import{setTimeout as Te}from"node:timers/promises";import{chmod as b,mkdir as Ee,mkdtemp as De,readFile as Oe,realpath as ke,rename as Ae,rm as x,stat as S,unlink as C,writeFile as je}from"node:fs/promises";import{Readable as Me,Transform as w}from"node:stream";import{pipeline as Ne}from"node:stream/promises";import{ZipFile as Pe}from"yazl";import{createTRPCUntypedClient as Fe,httpLink as Ie}from"@trpc/client";import{spawn as Le}from"node:child_process";import{createServer as Re}from"node:http";const ze=/^enh_[\w-]{43}$/,T=e=>{let r=t.parse(e);if(r.authentication.kind!==`agent`||r.person===null)throw new n(`UNAUTHORIZED`,`The credential is missing, expired, revoked, or invalid.`,`Run 'enhance auth login' and complete authentication in the browser.`);return{authenticated:!0,personId:r.person.id,displayName:r.person.displayName,tokenId:r.authentication.tokenId,tokenLabel:r.authentication.tokenLabel,expiresAt:r.authentication.expiresAt}},Be=(e,t,r)=>({loginWithToken:async r=>{if(!ze.test(r))throw new n(`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=T(await t.queryWithToken(`person.me`,{},r));return await e.write(r),i},loginWithBrowser:async a=>{let o=ne.parse(await t.authenticationConfig());if(o.method===`token`)throw new n(`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 s=await r.authorize({issuer:o.issuer,clientId:o.clientId,scope:o.scope,openBrowser:a.openBrowser,onReady:a.onReady}),c=i.parse(await t.mutateWithToken(`person.createAgentToken`,{label:a.label,expiresAt:null},s)),l=T(await t.queryWithToken(`person.me`,{},c.token));return await e.write(c.token),l},status:async()=>{if(await e.read()===null)throw new n(`UNAUTHORIZED`,`No credential exists at ${e.path}.`,`A human must run 'enhance auth login'.`);return T(await t.query(`person.me`,{}))},logout:async()=>({loggedOut:await e.remove()})}),Ve=Uint8Array.from(globalThis.atob(`iVBORw0KGgo=`),e=>e.codePointAt(0)??0),He=e=>{if(e.byteLength<24||Ve.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)}},Ue=async(e,t)=>{let r=le.safeParse(await e.query(`canvas.render.download`,{jobId:t.id}));if(!r.success)throw new n(`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(r.data.download.url),a=He(i);if(a===null||i.byteLength!==t.result.bytes||a.width!==t.result.width||a.height!==t.result.height)throw new n(`INTERNAL`,`The downloaded render did not match its completed job metadata.`,`Do not use the image. Report render job ${t.id}.`);return i},E=[`canvas.render.create`,`canvas.render.get`],D=e=>new n(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),We=e=>{let t=e.failure;if(t===null)return D(`render job`);let r=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 n(r,t.message,i,{jobId:e.id,reason:t.reason,phase:t.phase})},Ge=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),Ke=async(e,t)=>{let n=d.safeParse(await e.query(E[1],{jobId:t}));if(!n.success)throw D(`render status`);return n.data.job},qe=async(e,t)=>{let r=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-r,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken}),i=s,a=c),s>=t.deadline)throw new n(`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 Ge(250),o=await Ke(e,o.id)}if(o.state!==`succeeded`)throw We(o);return o},Je=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]},Ye=(e,t)=>({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:Je(e)}),Xe=async(e,t)=>{let n=de.safeParse(await e.remote.mutate(E[0],{canvasId:t.canvasId,...t.expectedVersion!==null&&{expectedVersion:t.expectedVersion},target:t.target,...t.sourceState!==null&&{sourceState:t.sourceState},scale:t.scale,format:`png`}));if(!n.success)throw D(`render creation`);let r=await qe(e.remote,{initial:n.data.job,deadline:Date.now()+t.timeoutMs,timeoutMs:t.timeoutMs,retryClientToken:t.retryClientToken,progress:e.progress}),i=await Ue(e.remote,r),a=e.files.write({body:i,outputPath:t.outputPath,overwrite:t.overwrite,at:e.now()});return Ye(r,a)},O=(e,t,n,r=()=>null)=>({execute:async i=>Xe({remote:e,files:t,now:n,progress:r},i)}),k={begin:`canvas.realtime.activity.begin`,renew:`canvas.realtime.activity.renew`,end:`canvas.realtime.activity.end`},A=async e=>{try{return await e(),!0}catch{return!1}},Ze=(e,t,n,r)=>{let i=t,a=!1,o=!1,s=async()=>{a||o||(o=!0,await A(async()=>e.mutate(k.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 A(async()=>e.mutate(k.end,{canvasId:i.canvasId,activityId:n})))}}},j=e=>({begin:async t=>{try{let n=re.safeParse(await e.mutate(k.begin,{...t,nodeIds:[...t.nodeIds]}));return n.success?Ze(e,t,n.data.activityId,n.data.renewAfterMs):null}catch{return null}},finish:async(t,n)=>A(async()=>e.mutate(k.end,{canvasId:t,activityId:n}))}),Qe=new Set([`insertPrototype`,`insertText`,`setBox`]),$e=e=>Qe.has(e.op),et=e=>e.operations.some(e=>e.op===`insertNode`||e.op===`insertText`)?`creating`:e.operations.some(e=>e.op===`remove`)?`deleting`:`writing`,tt=e=>e.op===`insertConvertedSubtree`?Object.keys(e.nodes):e.op===`insertNode`?[e.node.id]:[e.nodeId],nt=e=>[...new Set(e.operations.flatMap(e=>tt(e)))].slice(0,100),rt=e=>e.op===`insertConvertedSubtree`?e.nodes[e.rootNodeId]?.box??null:e.op===`insertNode`?e.node.box??null:$e(e)?e.box:null,it=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}},M=async(e,t)=>{let r=await e.mutate(`canvas.applyOperations`,t),i=pe.safeParse(r);if(!i.success)throw new n(`INTERNAL`,`The API returned an invalid canvas apply response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return i.data},N=e=>({execute:async(t,n)=>{if(n?.activity===!1)return M(e,t);let r=await j(e).begin({canvasId:t.canvasId,phase:et(t),nodeIds:nt(t),bounds:it(t.operations.flatMap(e=>{let t=rt(e);return t===null?[]:[t]}))});try{return await M(e,t)}finally{await r?.finish()}}}),P=e=>new n(`INTERNAL`,`The API returned an invalid ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),at=async e=>new Promise(t=>{globalThis.setTimeout(t,e)}),ot=e=>{let t=e.failure;return new n(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 tree and correct the HTML or destination before retrying.`,{jobId:e.id,phase:t.phase,reason:t.reason})},st=async(t,n)=>{let r=e.safeParse(await t.query(`canvas.render.getImport`,{jobId:n}));if(!r.success)throw P(`HTML import status`);return r.data.job},ct=async(e,t,r)=>{let i=Date.now()+r,a=t;for(;a.state===`queued`||a.state===`running`;){if(Date.now()>=i)throw new n(`INTERNAL`,`HTML import ${a.id} did not finish before the local timeout.`,"Retry the exact command with a larger --timeout-ms. If the queue remains stuck, run `enhance doctor`.",{jobId:a.id,phase:a.phase});await at(250),a=await st(e,a.id)}if(a.state!==`succeeded`)throw ot(a);return a},lt=async(e,t)=>{let n=u.safeParse(await e.mutate(`canvas.render.importSource`,{canvasId:t.canvasId,expectedVersion:t.baseVersion,source:{kind:`html`,html:t.html,label:`Agent-authored HTML`,...t.idPrefix!==void 0&&{idPrefix:t.idPrefix}},destination:{kind:t.mode,targetNodeId:t.targetNodeId}}));if(!n.success)throw P(`HTML import creation`);return ct(e,n.data.job,t.renderTimeoutMs)},ut=(e,t,r)=>({state:`failed`,mutationCommitted:!0,requestedVersion:r,...e instanceof n?{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:`Read the current canvas version, then render the affected area again.`},next:[`enhance canvas inspect --canvas ${t.canvasId}`,`enhance canvas render --canvas ${t.canvasId} --expected-version ${String(r)}`,`Do not replay the committed write with a new mutation id.`]}),dt=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 ut(e,t,n.result.version)}},ft=async(e,t)=>{let n=ie.safeParse(await e.query(`canvas.document.get`,{canvasId:t.canvasId}));if(!n.success)throw P(`canvas document`);let r=fe.safeParse(n.data.document);if(!r.success)throw P(`editable canvas document`);return t.result.insertedNodeIds.map(e=>{let t=r.data.nodes[e];return{id:e,name:t?.label??``,component:t?.component??``}})},pt=async(e,t,n,r)=>({canvasId:t.canvasId,mutationCommitted:!0,mode:t.mode,targetNodeId:t.targetNodeId,previousVersion:n.result.previousVersion,version:n.result.version,createdNodes:await ft(e,n),removedNodeIds:n.result.removedNodeIds,affectedBounds:n.result.affectedBounds,review:r,next:[`enhance canvas tree --canvas ${t.canvasId}`,`Inspect the review PNG before continuing.`]}),F=(e,t)=>({execute:async n=>{let r=await j(e).begin({canvasId:n.canvasId,phase:`creating`,nodeIds:[n.targetNodeId],bounds:null});try{let i=await lt(e,n);await r?.update({phase:`rendering`,nodeIds:i.result.insertedNodeIds.slice(0,100),bounds:i.result.affectedBounds});let a=await dt(t,n,i);return await pt(e,n,i,a)}finally{await r?.finish()}}}),I=(e,t,r)=>{try{we(e,t,{flag:r?`w`:`wx`,mode:384}),m(e,384)}catch(t){let r=typeof t==`object`&&t&&Reflect.get(t,`code`)===`EEXIST`?`CONFLICT`:`INTERNAL`;throw new n(r,r===`CONFLICT`?`Refusing to replace ${e}.`:`Could not write ${e}.`,r===`CONFLICT`?`Choose another --output path or pass --force deliberately.`:`Create the parent directory and verify it is writable, then retry.`)}},L=e=>({write:t=>{if(t.outputPath!==null){let e=g.resolve(t.outputPath);return I(e,t.body,t.overwrite),{path:e,temporary:!1,deleteAfter:null}}let n=g.join(e,`sensitive`);Ce(n,{recursive:!0,mode:448}),m(n,448);let r=g.join(n,`render-${globalThis.crypto.randomUUID()}.png`);return I(r,t.body,!1),{path:r,temporary:!0,deleteAfter:new Date(t.at.getTime()+36e5)}}}),R=[`prototype.getArtifactCapabilities`,`prototype.createArtifact`,`prototype.submitArtifact`,`prototype.getPublishStatus`,`prototype.attach`],z=e=>new n(`INTERNAL`,`The API returned an invalid prototype ${e} response.`,"Run `enhance doctor`; report the API and CLI versions if they differ."),mt=async(e,t)=>{let r=Date.now()+3e5,i=50;for(;Date.now()<r;){let r=a.safeParse(await e.query(R[3],t));if(!r.success)throw z(`status`);if(r.data.state===`ready`||r.data.state===`failed`)return r.data;if(r.data.state===`abandoned`)throw new n(`NOT_FOUND`,`Prototype deployment ${t.deploymentId} was abandoned.`,`Publish the directory again with a new client token.`);await Te(i),i=Math.min(i*2,1e3)}throw Error(`prototype ingestion is still running`)},ht=async(e,t,n,r)=>{let i=c.safeParse(await e.mutate(R[1],{canvasId:t.canvasId,...t.prototypeId!==null&&{prototypeId:t.prototypeId},clientToken:t.clientToken,nodeId:t.nodeId,title:t.title,entryPath:n.manifest.entryPath,artifact:n.identity,box:t.box}));if(!i.success)throw z(`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`)&&!ye.safeParse(await e.mutate(R[2],{canvasId:t.canvasId,deploymentId:i.data.deploymentId})).success)throw z(`artifact submission`);return i.data},gt=e=>{if(e.state!==`failed`)return;let{failure:t}=e;throw new n(`BAD_REQUEST`,t.message,`Fix the build and publish it with a new client token.`,t.path===void 0?void 0:{path:t.path})},_t=async(e,t,i)=>{let a=r.safeParse(await e.query(R[0],{}));if(!a.success)throw z(`capabilities`);let o=await t.package({directory:i.directory,entryPath:i.entryPath,limits:a.data.limits}),c={deploymentId:null};try{let t=await ht(e,i,o,e=>{c.deploymentId=e}),n=await mt(e,{canvasId:i.canvasId,deploymentId:t.deploymentId});gt(n);let r=s.safeParse(await e.mutate(R[4],{canvasId:i.canvasId,deploymentId:t.deploymentId,baseVersion:i.baseVersion}));if(!r.success)throw z(`attachment`);return{...r.data,fileCount:n.fileCount,totalBytes:n.totalBytes,alreadyExists:t.alreadyExists,next:[r.data.openUrl,`enhance canvas render --canvas ${i.canvasId} --node-id ${r.data.nodeId} --expected-version ${String(r.data.version)}`]}}catch(e){throw e instanceof n&&(e.code===`BAD_REQUEST`||e.code===`NOT_FOUND`)||c.deploymentId===null?e:new te(`Prototype deployment ${c.deploymentId} was created, but publishing did not complete.`,`Retry 'enhance prototype publish' with the same --client-token ${i.clientToken}.`)}finally{await o.dispose()}},vt=(e,t)=>({execute:async n=>_t(e,t,n)}),yt=[`transcript.get`],bt=(e,t,n)=>[...new Set(n)].slice(0,3).map(n=>`enhance canvas render --canvas ${e} --node-id rec_${t} --at-ms ${String(n)}`),xt=e=>({execute:async t=>{let r=ge.safeParse(await e.query(yt[0],t));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid transcript response.`,"Run `enhance doctor`; report the API and CLI versions if they differ.");return r.data.state===`ready`?{...r.data,guidance:`Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.`,next:bt(t.canvasId,t.recordingId,r.data.cues.map(e=>e.startMs))}:r.data}}),B=[`canvas.render.get`,`canvas.render.snapshot`],St=async()=>new Promise(e=>{globalThis.setTimeout(e,250)}),Ct=e=>new n(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}),wt=async(e,t)=>{let r=d.safeParse(await e.query(B[0],{jobId:t}));if(!r.success)throw new n(`INTERNAL`,`The API returned an invalid snapshot status response.`,`Run \`enhance doctor\` and report snapshot job ${t}.`);return r.data.job},Tt=async(e,t,r,i)=>{let a=Date.now()+r.timeoutMs,o=Date.now(),s=t,c=0,l=``;for(;s.state===`queued`||s.state===`running`;){let t=Date.now(),u=`${s.state}:${s.phase}`;if((u!==l||t-c>=5e3)&&(i({event:`snapshot.progress`,jobId:s.id,state:s.state,phase:s.phase,elapsedMs:t-o,timeoutMs:r.timeoutMs,retryClientToken:r.retryClientToken}),c=t,l=u),t>=a)throw new n(`INTERNAL`,`Snapshot ${s.id} did not finish before the local timeout.`,`Retry this exact command with --client-token ${r.retryClientToken} and a larger --timeout-ms.`,{jobId:s.id,phase:s.phase});await St(),s=await wt(e,s.id)}if(s.state!==`succeeded`||s.result.snapshot===void 0)throw Ct(s);return{...s,result:{...s.result,snapshot:s.result.snapshot}}},Et=async(e,t,r)=>{let i=me.safeParse(await e.mutate(B[1],{canvasId:r.canvasId,recordingId:r.recordingId,atMs:r.atMs}));if(!i.success)throw new n(`INTERNAL`,`The API returned an invalid snapshot creation response.`,"Run `enhance doctor` and report the API and CLI versions.");let a=await Tt(e,i.data.job,r,t),o=a.result.snapshot;return{jobId:a.id,canvasId:a.canvasId,...o,warnings:a.result.warnings,retryClientToken:r.retryClientToken,next:[`enhance canvas node --canvas ${a.canvasId} --node-id ${o.screenNodeId}`,`enhance canvas render --canvas ${a.canvasId} --node-id ${o.screenNodeId} --expected-version ${String(o.version)}`]}},Dt=(e,t)=>({execute:async n=>Et(e,t,n)}),V=new Date(`1980-01-01T00:00:00.000Z`),H=33188,U=(e,t)=>new n(`BAD_REQUEST`,e,t),Ot=(e,t)=>{let n=_(`sha256`),r=0;return new w({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}t({path:e.path,contentType:e.contentType,bytes:r,sha256:n.digest(`hex`)}),i()}})},kt=e=>{let t=o.parse({version:1,entryPath:e.entryPath,files:e.files.map(t=>e.completed.get(t.path))}),n=Buffer.from(JSON.stringify(t),`utf8`);if(n.byteLength>e.limits.manifestBytes)throw U(`The prototype manifest is too large.`,`Shorten paths or reduce metadata below ${String(e.limits.manifestBytes)} bytes.`);return e.zip.addBuffer(n,ue,{mtime:V,mode:H,compress:!0,forceDosTimestamp:!0}),e.zip.end({forceZip64Format:e.files.length>=65535,comment:``}),t},At=async e=>{let t=new Pe,n=_(`sha256`),r=new w({transform:(e,t,r)=>{n.update(e),r(null,e)}}),i=new Map,a={manifest:null},o=Ne(t.outputStream,r,Se(e.artifactPath));t.on(`error`,e=>r.destroy(e instanceof Error?e:Error(`prototype ZIP failed`)));let s=n=>{i.set(n.path,n),a.manifest===null&&i.size===e.files.length&&(a.manifest=kt({zip:t,completed:i,...e}))};for(let n of e.files)t.addReadStreamLazy(n.path,{size:n.bytes,mtime:V,mode:H,compress:!0,forceDosTimestamp:!0},e=>{e(null,h(n.absolutePath).pipe(Ot(n,s)))});if(await o,a.manifest===null)throw Error(`prototype ZIP completed without a manifest`);let c=await S(e.artifactPath);if(c.size>e.limits.artifactBytes)throw U(`The packaged prototype artifact is too large.`,`This environment accepts ${String(e.limits.artifactBytes)} compressed bytes.`);return{manifest:a.manifest,bytes:c.size,sha256:n.digest(`hex`)}},jt={".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`},Mt=e=>jt[g.extname(e).toLowerCase()]??`application/octet-stream`,W=async e=>{try{return await S(e)}catch{return null}},Nt=e=>Buffer.byteLength(e,`utf8`),G=(e,t)=>new n(`BAD_REQUEST`,e,t),K=(e,t)=>{if(!ee.safeParse(e).success)throw G(`Cannot package the prototype path ${e}.`,`Use portable relative NFC paths outside the reserved __enhance directory.`);if(Nt(e)>t.pathBytes)throw G(`The prototype path ${e} is too long.`,`Shorten it to at most ${String(t.pathBytes)} UTF-8 bytes.`)},q=async(e,t,n,r)=>{let i=await ke(t);if(n.has(i))throw G(`Cannot package the circular directory link at ${t}.`,`Pass a directory tree that can be read once from top to bottom.`);let a=new Set(n).add(i),{readdir:o}=await import(`node:fs/promises`),s=await o(t,{withFileTypes:!0}),c=[],l=s.toSorted((e,t)=>e.name.localeCompare(t.name));for(let n of l){let i=g.join(t,n.name),o=await W(i);if(o?.isDirectory()===!0){c.push(...await q(e,i,a,r));continue}if(o?.isFile()!==!0)throw G(`Cannot read ${i} as a prototype file.`,`Pass a directory containing only regular files and directory links.`);let s=g.relative(e,i).split(g.sep).join(`/`).normalize(`NFC`);K(s,r),c.push({absolutePath:i,path:s,bytes:Number(o.size),contentType:Mt(i)})}return c},Pt=(e,t,n)=>{if(e.length===0)throw G(`The prototype build is empty.`,`Build the app before publishing it.`);if(e.length>n.fileCount)throw G(`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=l(t.path);if(r.has(e))throw G(`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 G(`The prototype file ${t.path} is too large.`,`This environment accepts ${String(n.fileBytes)} bytes in one runtime file.`);if(i+=t.bytes,i>n.expandedBytes)throw G(`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 G(`The prototype entry ${t} is missing.`,`Pass --entry with an HTML file inside the build directory.`);if(!a.contentType.startsWith(`text/html`))throw G(`The prototype entry ${t} is not HTML.`,`Pass an HTML entry file such as index.html.`)},Ft=async e=>{let t=g.resolve(e.directory),r=await W(t);if(r===null)throw new n(`NOT_FOUND`,`The prototype directory ${t} does not exist.`,`Build the app or pass the correct unpacked build directory.`);if(!r.isDirectory())throw G(`${t} is not an unpacked build directory.`,`Pass the build directory; the CLI creates the ZIP artifact automatically.`);let i=e.entryPath.split(g.sep).join(`/`).normalize(`NFC`);K(i,e.limits);let a=await q(t,t,new Set,e.limits);Pt(a,i,e.limits);let o=await De(g.join(xe(),`enhance-prototype-artifact-`)),s=g.join(o,`artifact.zip`);try{let t=await At({artifactPath:s,files:a,entryPath:i,limits:e.limits});return{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:()=>h(s),dispose:async()=>x(o,{recursive:!0})}}catch(e){throw await x(o,{recursive:!0}),e}},It=()=>({package:Ft}),J=e=>O(e.remote,L(e.configDirectory),e.now??(()=>new Date),e.progress??(()=>null)),Lt=async(e,t)=>{let n=ce.parse(t);return N(e.remote).execute({...n,mutationId:e.mutationKey.current(`canvas.applyOperations`,n)})},Rt=async(e,t,n)=>{let r=se.parse(t);return J(e).execute({...r,retryClientToken:n})},zt=async(e,t)=>{let n=ae.parse(t);return F(e.remote,J(e)).execute({...n,renderClientToken:e.mutationKey.current(`canvas.render.create`,{purpose:`write-html-review`})})},Bt=async(e,t)=>{let n=he.parse(t);return e.remote.query(`comment.list`,{canvasId:n.canvasId,filter:`open`,agentActionable:!1})},Vt=async(e,t,n)=>{let r=ve.parse(t);return vt(e.remote,It()).execute({...r,clientToken:n})},Ht=async(e,t,n)=>{let r=oe.parse(t);return Dt(e.remote,e.progress??(()=>null)).execute({...r,retryClientToken:n})},Ut=async(e,t)=>{let n=_e.parse(t);return xt(e.remote).execute(n)},Wt=async(e,t,n,r)=>{switch(t){case`canvas.apply`:return Lt(e,n);case`canvas.render`:return Rt(e,n,r);case`canvas.writeHtml`:return zt(e,n);case`comment.attention`:return Bt(e,n);case`prototype.publish`:return Vt(e,n,r);case`recording.snapshot`:return Ht(e,n,r);case`transcript.read`:return Ut(e,n);default:throw TypeError(`${t} has no composite execution`)}},Gt=e=>({invoke:async({capability:t,arguments:n,clientToken:r})=>{let i=t.inputSchema.parse(n),a=r??y();return e.mutationKey.select(a,t.idempotency===`composite`),t.execution.kind===`composite`?Wt(e,t.id,i,a):t.operation===`query`?e.remote.query(t.execution.procedure,i):e.remote.mutate(t.execution.procedure,i)}}),Y=`/callback`,Kt=(e,t)=>new URL(t,e.endsWith(`/`)?e:`${e}/`),qt=e=>{let t=p.platform===`darwin`?{executable:`open`,arguments:[e]}:p.platform===`win32`?{executable:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,e]}:{executable:`xdg-open`,arguments:[e]},n=Le(t.executable,t.arguments,{detached:!0,stdio:`ignore`});n.once(`error`,()=>!1),n.unref()},Jt=(e,t,n)=>{let r=new URL(t.url??`/`,`http://127.0.0.1`);if(t.method!==`GET`||r.pathname!==Y){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)},Yt=e=>{let t=Kt(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},Xt=async e=>{let t=Promise.withResolvers(),n=Re((n,r)=>{Jt({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)}${Y}`,a=Yt({...e,redirectUri:i});e.onReady(a),e.openBrowser&&qt(a);let o=setTimeout(()=>{t.reject(Error(`browser authorization timed out`))},12e4);try{return{code:await t.promise,redirectUri:i}}finally{clearTimeout(o),await new Promise(e=>{n.close(()=>{e()})})}},X=e=>({authorize:async t=>{try{let n=v(32).toString(`base64url`),r=_(`sha256`).update(n).digest(`base64url`),i=v(32).toString(`base64url`),a=await Xt({...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 n(`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.`)}}}),Z=e=>e===void 0||e===``?void 0:e,Zt=((e,t,n)=>{let r=Z(e.ENHANCE3_ENVIRONMENT);if(r!==void 0&&r!==n.environment)throw TypeError(`the Enhance ${n.environment} CLI cannot target ${r}`);let i=Z(e.ENHANCE3_API_URL),a=g.join(t,`.config`,n.configDirectoryName),o=Z(e.ENHANCE3_CONFIG_DIR);if(n.environment===`development`){if(i!==void 0&&i!==n.apiUrl)throw TypeError(`Enhance development cannot use ${i}`);if(o!==void 0&&g.resolve(o)!==g.resolve(a))throw TypeError(`Enhance development credentials must stay in ${a}`)}return{apiUrl:i??n.apiUrl,commandName:n.commandName,configDirectory:o??a,mcpServiceName:n.mcpServiceName}})(p.env,be(),{apiUrl:`https://api.enhance3.karunalabs.ai`,commandName:`enhance-dev`,configDirectoryName:`enhance-development`,environment:`development`,mcpServiceName:`enhance-dev-mcp`}),Qt=f.object({token:f.string().startsWith(`enh_`)}),$t=e=>{let t=g.join(e,`credentials.json`);return{path:t,read:async()=>{try{let e=JSON.parse(await Oe(t,`utf8`));return Qt.parse(e).token}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return null;throw e}},write:async n=>{await Ee(e,{recursive:!0,mode:448}),await b(e,448);let r=g.join(e,`credentials.${String(p.pid)}.tmp`);await je(r,`${JSON.stringify({token:n})}\n`,{mode:384,flag:`wx`}),await Ae(r,t),await b(t,384)},remove:async()=>{try{return await C(t),!0}catch(e){if(typeof e==`object`&&e&&Reflect.get(e,`code`)===`ENOENT`)return!1;throw e}}}},en=f.object({access_token:f.string().min(1)}),Q=(e,t,n=null)=>Fe({links:[Ie({url:`${e}/trpc`,headers:{...t!==null&&{authorization:`Bearer ${t}`},...n!==null&&{"x-enhance-idempotency-key":n}}})]}),tn=async e=>{let t=await fetch(e);if(!t.ok)throw new n(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())},nn=async e=>{let t=await fetch(`${e}/v1/cli-auth`);if(!t.ok)throw t.status===404?new n(`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 n(`INTERNAL`,`CLI authentication discovery answered HTTP ${String(t.status)}.`,`Run 'enhance doctor', report the result, and stop.`);return t.json()},rn=async e=>{let t=e.endsWith(`/`)?e:`${e}/`,n=await fetch(new URL(`.well-known/oauth-authorization-server`,t));if(!n.ok)throw Error(`OAuth discovery answered HTTP ${String(n.status)}`);return n.json()},an=async e=>{let t=await fetch(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 Error(`token exchange answered HTTP ${String(t.status)}`);return en.parse(await t.json()).access_token},on=async e=>{try{let t=await fetch(`${e}/health`,{signal:AbortSignal.timeout(4e3)});return{url:e,reachable:t.ok,status:t.status}}catch{return{url:e,reachable:!1,status:null}}},sn=(e,t,r)=>{let i=e.replace(/\/$/,``);return{authenticationConfig:async()=>nn(i),oauthMetadata:rn,exchangeOauthCode:an,query:async(e,n)=>Q(i,await t.read()).query(e,n),queryWithToken:async(e,t,n)=>Q(i,n).query(e,t),mutate:async(e,n)=>Q(i,await t.read(),r.current(e,n)).mutation(e,n),mutateWithToken:async(e,t,n)=>Q(i,n).mutation(e,t),download:tn,upload:async e=>{let t=!(e.body instanceof Uint8Array),r=t?Me.toWeb(e.body):e.body,i={method:`PUT`,headers:e.headers,body:r,...t&&{duplex:`half`}},a=await fetch(e.url,i);if(!a.ok)throw new n(`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 n(`INTERNAL`,`Signed upload returned no ETag.`,`Report the storage response and stop.`);return o.replaceAll(`"`,``)},health:async()=>on(i)}},$=e=>Array.isArray(e)?e.map(e=>$(e)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,$(t)])),cn=(e,t,n)=>_(`sha256`).update(`${e}\0${t}\0${JSON.stringify($(n))}`).digest(`hex`).replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u,`$1-$2-5$3-8$4-$5`),ln=()=>{let e=y(),t=!1;return{current:(n,r)=>t?cn(e,n,r):e,select:(n,r)=>{e=n??y(),t=r}}};export{X as a,F as c,O as d,Be as f,Zt as i,N as l,sn as n,Gt as o,$t as r,L as s,ln as t,j as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enhance-eng/enhance-dev",
3
- "version": "0.1.7-dev.sha-8aeb7ebe4b78",
3
+ "version": "0.1.7-dev.sha-be264076fee2",
4
4
  "private": false,
5
5
  "description": "Development command-line interface for Enhance.",
6
6
  "keywords": [