epiq 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -40,7 +40,7 @@ ${o.message}`):l("Staged state branch event file",void 0)},mi=async({repoRoot:e,
40
40
  `+n.message):mt({cwd:t,message:n.value})},Bt=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Cr(t);if(d(n))return s(n.message);let r=Je(e);if(d(r))return r;let o=r.value,i=n.value?await H.push({cwd:t}):await H.push({cwd:t,remote:xe,branch:o,setUpstream:!0});return d(i)?s(`Failed during state branch push
41
41
  ${i.message}`):l("Pushed state branch",!0)},pi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Je(e);if(d(o))return o;let i=o.value,a=[xn(),await pd({repoRoot:e,stateBranchName:i}),await Er({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await vd({stateBranchRoot:t,stateBranchName:i}),await ci(t),n?await yd({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of a){if(d(c))return s(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import En from"node:fs";import br from"node:path";import{decodeTime as xd}from"ulid";var Ir=e=>{let[t,n]=e.id;return`${t}:${n??""}`},fi=e=>{let[t]=e.id;return xd(t)},hd=e=>{let{userId:t,userName:n,...r}=e;return r},Cd=e=>e.length===0?"":e.map(t=>JSON.stringify(hd(t))).join(`
42
42
  `)+`
43
- `,Nd=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Ir(r),r);return[...n.values()].sort((r,o)=>{let i=fi(r)-fi(o);return i!==0?i:Ir(r).localeCompare(Ir(o))})},Sr=({sourceFile:e,targetFile:t})=>{let n=ln(e);if(d(n))return s(n.message);let r=ln(t);if(d(r))return s(r.message);let o=Nd(r.value,n.value),i=Cd(o);return(En.existsSync(t)?En.readFileSync(t,"utf8"):"")===i?l("Event file already merged",!1):(En.mkdirSync(br.dirname(t),{recursive:!0}),En.writeFileSync(t,i,"utf8"),l("Merged event file",!0))},Ut=({repoRoot:e,stateBranchRoot:t})=>{let n=ai(t);if(d(n))return s(n.message);let r=Qe(t),o=Qe(e),i=!1;for(let a of n.value){let c=br.join(r,a),u=br.join(o,a),m=Sr({sourceFile:c,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return l("Hydrated event files from state branch",i)};var vi=async(e=process.cwd())=>{fr("Syncing from remote");let t=await yi({cwd:e,ensureUpstream:!1});if(d(t))return oe(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=Je(e);if(d(o))return oe(o.message);let i=o.value,a=await vn({cwd:r,branch:i});if(d(a))return oe(a.message);let c=Ut({repoRoot:n,stateBranchRoot:r});return d(c)?oe(c.message):(gr("Synced from remote"),l("Synced state branch",{repoRoot:n,stateBranchRoot:r}))},Id=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Nr({root:e,fileName:n}),o=Nr({root:t,fileName:n});return Ed.existsSync(r)?Sr({sourceFile:r,targetFile:o}):l("Local own event file missing, nothing to merge",!1)},yi=async({cwd:e,ensureUpstream:t})=>{let n=await hn(e);if(d(n))return s(n.message);let r=n.value,o=ii({repoRoot:r});if(d(o))return s(o.message);let i=o.value,a=await Dt(r);if(d(a))return s(a.message);if(a.value)return s("Cannot sync while a git operation is in progress in the current repo");let c=await ui(r);if(d(c))return s(c.message);let u=await pi({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await Dt(i);if(d(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=di(r,i);return d(p)?s(p.message):l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},gi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Id({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(d(r))return s(r.message);let o=await Zo(t);if(d(o))return s(o.message);if(!r.value&&!o.value)return l("Own event file already up to date in state branch",{createdCommit:!1});let i=await Nn({stateBranchRoot:t,eventFileName:n});if(d(i))return s(i.message);let a=await mi({repoRoot:e,stateBranchRoot:t});return d(a)?s(a.message):l("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},In=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");fr("Syncing");let n=await yi({cwd:e,ensureUpstream:!0});if(d(n))return oe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await ei(r);if(d(a))return oe(a.message);if(a.value)return oe("Cannot run :sync while the repository is in detached HEAD state");let c=!1,u,m=!1,p=!1,g=!1,x=Je(r);if(d(x))return oe(x.message);let E=x.value,A=await vn({cwd:o,branch:E});if(d(A))return oe(A.message);m=A.value;let R=Ut({repoRoot:r,stateBranchRoot:o});if(d(R))return oe(R.message);g=R.value;let b=await gi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(b))return oe(b.message);if(c=b.value.createdCommit,u=b.value.commitSha,c||i){let w=await Bt({stateBranchRoot:o,repoRoot:r}),U=w;if(d(w)&&Qo(w.message)){let le=await vn({cwd:o,branch:E});if(d(le))return oe(le.message);let ne=await gi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(ne))return oe(ne.message);ne.value.createdCommit&&(c=!0,u=ne.value.commitSha),U=await Bt({stateBranchRoot:o,repoRoot:r})}if(d(U))return oe(U.message);p=U.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(c){let w=await F({args:["rev-parse","HEAD"],cwd:o});if(d(w))return oe(w.message);u=w.value.stdout.trim()}return gr(p?"Synced and pushed":m||g||c?"Synced local state":"Already synced"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,hydrated:g,bootstrapped:i})};var ft=3e3,xi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<ft?null:t},hi=0,Rr,Ar=!1,$t=!1,wr=()=>Ar||v().syncStatus.status==="syncing",bd=()=>{let e=L().autoSyncIntervalMs??15e3,t=Date.now()-hi;return Math.max(0,e-t)},Ci=()=>{Rr||(Rr=setTimeout(async()=>{if(Rr=void 0,wr()){$t=!0;return}$t=!1,await Sd()},bd()))},Sd=async()=>{if(wr())return $t=!0,s("Sync already in progress");let e=K();if(d(e)||!e.value)return s("Unable to resolve event log path");Ar=!0,hi=Date.now();try{let t=Xe(e.value);return await In({ownEventFileName:t})}finally{Ar=!1,$t&&Ci()}},Ni=()=>{$t=!0,!wr()&&Ci()};var ie={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:a=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:a}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:a=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:a})};import{ulid as wd}from"ulid";var Ze=24n,Rd=Ze*4n,et=(1n<<Rd)-1n,Ad=/^[0-9a-f]+$/;function Ei(e){return!e||!Ad.test(e)?s(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Pe(e,t=Ze){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function z(e,t){if(!e&&!t)return Pe(et/2n,Ze);let n=e?Ei(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Ei(t):l("Resolved upper bound",et);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Pe(et/2n,Ze);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):Pe(a,Ze)}function Ii(){return Pe(et/2n,Ze)}function bi(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=et*BigInt(r+1)/(t+1n),i=Pe(o,Ze);if(d(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var Tr=(e,t)=>{let n=O(e),r=bi(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],c=r.value[i];if(!a||!c)return s("Unable to assign rebalance rank");o[a.id]=c}return l("Created rebalance event",{id:wd(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var Y={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var Td=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ke,bn]=Td;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Md={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ie.workspace(t,n,r),i=jt(o);if(d(i))return k(i.message,e);let a=I.createNode(o);return d(a)?k(a.message??"Failed to initialize workspace",e):cr(a.value)?l("Workspace initialized",{action:e.action,result:a.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ie.workspace(t,n,r),i=I.createNode(o);return d(i)?k(i.message??"Failed to add workspace",e):cr(i.value)?l("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.board(t,n,r,o));return d(i)?k(i.message??"Unable to create board",e):Po(i.value)?l("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.swimlane(t,n,r,o));return d(i)?k(i.message??"Unable to create swimlane",e):lt(i.value)?l("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.ticket(t,n,r,o));return d(i)?k(i.message??"Unable to create issue",e):ye(i.value)?l("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,a=I.createNode(ie.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(Y.DESCRIPTION)?"vertical":"horizontal"}));return d(a)?k(a.message??`Unable to create field: ${n}`,e):Mo(a.value)?l("Added field",{action:e.action,result:a.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=I.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=I.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=I.tag(n,r,t,o);return d(i)?k(i.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=I.untag(t,n);return d(r)?k(r.message??"Unable to untag ",e):l("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=I.assign(r,n,t,o);return d(i)?k(i.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=I.unassign(t,n);return d(r)?k(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=I.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ye(o))return k("Can only close issues",e);let i=I.getNode(ke);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let a=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(a)?k(a.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ye(o))return k("Can only reopen issues",e);let i=I.getNode(ke);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return k("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=I.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let a=I.updateNode({...i,rank:o});if(d(a))return k(a.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}},Pd=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},kd=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function Wt(e,t=!1){let n=Md[e.action](e);if(d(n))return n;t||([...new Set(kd(e))].forEach(a=>Pd(a,e)),he(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(I.createContributor({name:o,id:r}),n)}var _t=e=>e.map(t=>Wt(t));function _(e){let t=Wt(e);if(t.status!==Ue.Success)return t;let n=mn({event:e});return d(n)?n:t}function Sn(e){return e.map(t=>_(t))}var Si=e=>Mr(O(e),{at:"end"}),Mr=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(z(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(z(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(z(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Ri(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(z(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=Ri(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(z(o.rank,i?.rank)):s("Sibling not found")}}},O=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ri=(e,t)=>e.findIndex(n=>n.id===t),Ai=(e,t,n={at:"end"})=>Mr(O(t).filter(r=>r.id!==e),n),tt=(e,t,n,r)=>{let o=Ai(t,e,n);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let i=Tr(e,r);if(d(i))return i;let a=_(i.value);if(d(a))return a;let c=Ai(t,e,n);return d(c)?c:c.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",c.value.rank)},gt=(e,t)=>{let n=Si(e);if(d(n))return n;if(!n.value.needsRebalance)return l("Resolved rank",n.value.rank);let r=Tr(e,t);if(d(r))return r;let o=_(r.value);if(d(o))return o;let i=Si(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var je=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},kr=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Pr=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),I={deleteNode(e){he(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=Pr(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return this.updateNode(i),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Pr(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return O(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=Pr(o,"move");if(a)return a;if(kr(t,e))return s("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of O(m.id))a(p.id)}};a(e);let c={...structuredClone(t)};for(let u of i){if(!c[u])return s("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(S({nodes:c}),l("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=he(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):l("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let a=this.getFieldByTitle(i.id,"Assignees");if(!a)return s("Unable to locate assignees field");if(O(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=ie.field({id:n,name:o.name,parentNodeId:a.id,rank:r,props:{value:t}}),m=this.createNode(u);return d(m)?m:l("Assigned contributor",u)},createTag(e){let t=he(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):l("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let a=this.getFieldByTitle(i.id,"Tags");if(!a)return s("Unable to locate tags field");if(O(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=ie.field({id:n,name:o.name,parentNodeId:a.id,rank:r,props:{value:t}}),m=this.createNode(u);return d(m)?m:l("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=O(o.id).find(c=>c.props?.value===t);if(!i)return l("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Tag removed",a)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=O(o.id).find(c=>c.props?.value===t);if(!i)return l("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Assignee removed",a)},createNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?s("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=he(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):l("Locked node",n)},updateNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return O(e)}};var se={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},N={accent:se.cyan,accent2:se.magenta,primary:se.white,secondary:se.grayDark,secondary2:se.grayLight,gray:se.gray,green:se.green,yellow:se.yellow,red:se.red};var C={red:se.red,yellow:se.yellow,green:se.green,blue:se.blue,magenta:se.magenta,cyan:se.cyan},vt={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan};var wi=(e,t)=>{let r=T(e.id).find(o=>o.title===t);return r?T(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Dr=e=>wi(e,"Tags").map(t=>I.getTag(t)).filter(t=>!!t),Rn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Dr(n)??[])},An=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Fr(n)??[])},Fr=e=>wi(e,"Assignees").map(t=>I.getContributor(t)).filter(t=>!!t);var y={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var Dd=/^(\d+)(h|d|w|mo|y)$/,Fd=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ld=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},Od=(e,t=new Date)=>{let n=e.match(Dd);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},Bd=e=>{let t=e.match(Fd);if(!t)return null;let[,n,r,o,i,a]=t,c=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,g=a?Number(a):0;return Ld({year:c,month:u,day:m,hour:p,minute:g})?new Date(c,u-1,m,p,g):null},wn=e=>{let t=e.trim().toLowerCase();return Od(t)??Bd(t)},Ti=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ud=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Mi=(e=Ud)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var $d=["BOARD","TICKET","SWIMLANE"],X={EDITOR:"editor",VIEW:"view",USERNAME:"userName",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},He={TITLE:"title",DESCRIPTION:"description"},Wd=[X.EDITOR,X.VIEW,X.USERNAME,X.AUTOSYNC,X.SYNC_DEBOUNCE_MS],_d=[He.TITLE,He.DESCRIPTION],Or=[String(ft),"5000","15000","30000","60000"],nt=[y.SYNC,y.HELP,y.EXPORT,y.CONFIG],Tn=[y.NEW,y.EDIT,y.DELETE,y.MOVE],Lr=[y.TAG,y.UNTAG,y.ASSIGN,y.UNASSIGN,y.CLOSE_ISSUE,y.RE_OPEN_ISSUE,y.EDIT],Pi=[y.FILTER,y.PEEK],jd={WORKSPACE:[...nt,...Tn],BOARD:[...Pi,...nt,...Tn],SWIMLANE:[...Pi,...nt,...Tn],TICKET:[...nt,...Tn,...Lr],FIELD:[...nt,...Lr],FIELD_LIST:[...nt,...Lr],TEXT:[...nt]},Hd=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Kd=()=>{let{selectedNode:e,readOnly:t,breadCrumb:n}=v(),{isSetupDone:r}=_e();if(!r)return[y.HELP,y.CONFIG];if(!Ao())return[y.HELP,y.INIT];if(t)return[y.HELP,y.PEEK,y.EXPORT,y.CONFIG];let o=e?.context,i=o&&$d.includes(o);return[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?jd[c]:[]))].filter(c=>c===y.MOVE?!1:c===y.EDIT||c===y.DELETE?i:!0)},ae=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[y.NONE]:Kd(),[y.EXIT]:["confirm"],[y.EXPORT]:[],[y.SYNC]:[],[y.INIT]:[],[y.HELP]:[],[y.PEEK]:[...Mi(),"now","prev","next"],[y.EDIT]:[..._d],[y.DELETE]:["confirm"],[y.RE_OPEN_ISSUE]:["confirm"],[y.CLOSE_ISSUE]:["confirm"],[y.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[y.FILTER]:["tag","assignee","description","title","clear"],[y.TAG]:[...new Set([...Object.keys(vt),...I.getExistingTags()])],[y.UNTAG]:[...Rn()?.value?.map(({name:o})=>o)??[]],[y.UNASSIGN]:[...An()?.value?.map(({name:o})=>o)??[]],[y.ASSIGN]:I.getExistingAssignees(),[y.NEW]:Hd(n),[y.CONFIG]:[...Wd]}[e]??[]};import xt from"chalk";var ki=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Di}from"ulid";var Fi=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},Li=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Mn=e=>{try{return l("Decoded date",new Date(Di(e)))}catch(t){return s("Decoding failed + "+t.message)}},Br=e=>{if(!e?.id)return null;try{return Di(e.id)}catch{return null}};import yt from"chalk";var $r={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Vd=(e,t,n)=>Math.max(t,Math.min(n,e)),Ur=(e,t,n)=>e+(t-e)*n,Oi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Gd=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,c=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=c):a>=1&&a<2?(u=c,m=i):a>=2&&a<3?(m=i,p=c):a>=3&&a<4?(m=c,p=i):a>=4&&a<5?(u=c,p=i):(u=i,p=c);let g=o-i/2;return[Math.round((u+g)*255),Math.round((m+g)*255),Math.round((p+g)*255)]},qd=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,zd=(e,t,n)=>[Math.round(Ur(e[0],t[0],n)),Math.round(Ur(e[1],t[1],n)),Math.round(Ur(e[2],t[2],n))],Ht=e=>{let n=Oi(e)%360,r=Gd(n,$r.stringColor.saturation,$r.stringColor.lightness);return qd(r)},Yd=e=>{let t=$r.gradient.stops,n=Vd(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),a=o-i;return zd(t[i],t[i+1],a)},Pn=e=>Oi(e.toLowerCase().trim())/4294967295,Bi=e=>{let t=Pn(e);return Yd(t)},Xd=e=>{let[t,n,r]=Bi(e);return{normal:o=>yt.bgRgb(t,n,r).black(o),cursor:o=>yt.bgRgb(t,n,r).white.bold(o)}},Wr=e=>{let[t,n,r]=Bi(e);return{fg:o=>yt.rgb(t,n,r)(o),fgCursor:o=>yt.rgb(t,n,r).inverse(o),bg:o=>yt.bgRgb(t,n,r).black(o),bgCursor:o=>yt.bgRgb(t,n,r).white.bold(o)}},_r=e=>Xd(e).normal(` ${e} `),de=(e,t=vt)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Ht(r)};var rt={None:"none",Invalid:"invalid",Valid:"valid"};var Jd=["BOARD","TICKET","SWIMLANE"],Hr=()=>{let e=v().selectedNode;return e?.context?Jd.includes(e.context)?W():B({message:"Command not available in this context"}):B({message:"Missing target context"})},J="<ENTER> to confirm",W=(e="",t=[])=>({message:e,validity:rt.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:rt.Invalid,message:e,completionWordList:t}),kn=e=>e.length===0,fe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let a=o.trim();if(a.length<i)return"";let p=[...t.filter(Boolean).filter(g=>g.startsWith(a))].sort((g,x)=>Pn(g)-Pn(x)).slice(0,r).map(_r).join(" ");return p?`${e}${p}${n}`:""},jr=({modifier:e})=>{let t="confirm";return e===t?W(J):B({message:kn(e)?`if you are certain, enter ${_r(t)}`:"",completionWordList:[t]})},Qd=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?B({message:n}):W():B({message:kn(r)?t:"",completionWordList:[...e]}),Kt=({hint:e})=>({modifier:t,inputString:n})=>kn(t)&&kn(n)?B({message:e,completionWordList:[]}):W(J),Zd=({modifier:e,inputString:t})=>{let n=ae(y.CONFIG);if(!n.includes(e))return B({message:fe({prefix:"config... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case X.EDITOR:{let r=[...ki];return t.trim()?r.includes(t.trim())?W(J):B({message:fe({prefix:"known editors... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):B({message:fe({prefix:"editor... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?W(J):B({message:fe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.USERNAME:return t.trim()?W(J):B({message:`Enter a username. Saved in ${xt.bgBlack("~/.epiq-global/config.json")}`});case X.AUTOSYNC:{let r=["yes","no"],o=L().autoSync;return r.includes(t.trim())?W(J):B({message:fe({prefix:`should auto-sync (recommended), currently: ${wo(o)} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.SYNC_DEBOUNCE_MS:{let r=L().autoSyncIntervalMs,o=xi(t);if(!t.trim()||o===null||o<ft){let i=fe({prefix:" examples: ",wordList:Or,minLengthForHints:0,inputString:t});return B({message:`provide duration above ${ft}ms. current duration: ${r}ms.`+i,completionWordList:Or})}return W(J)}default:return B({message:"Unknown config option",completionWordList:n})}},ec=({modifier:e})=>{let t=ae(y.EDIT);if(!t.includes(e)){let r=fe({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return B({message:r||"Unknown edit option",completionWordList:t})}let n=Hr();if(n.validity==="invalid")return n;switch(e){case He.TITLE:return W(J);case He.DESCRIPTION:return W("<ENTER> to edit in "+L().preferredEditor);default:return B({message:"Unknown edit option",completionWordList:t})}},tc={[y.EXPORT]:()=>W(J+", and create export markdown file"),[y.PEEK]:e=>{let t=e.modifier;if(t==="now")return W(J);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return W(J);let r=wn(t);if(!t||!r)return B(n);let o=Se(v().breadCrumb,"BOARD");if(d(o))return B({message:"Command is not applicable in this context"});let i=Mn(o.value.id);return d(i)?B({message:"Unable to peek: board id is not a valid ULID"}):Ti({date:r,horizonDate:i.value})?W(J):B({message:xt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[y.EXIT]:()=>W(J+" and exit the application"),[y.INIT]:()=>W(J),[y.FILTER]:e=>{if(e.modifier==="clear")return W();let t=i=>ae(y.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return B({message:fe({wordList:ae(y.FILTER),inputString:e.inputString}),completionWordList:ae(y.FILTER)});let n=Object.values(v().tags).map(i=>i.name),r=Object.values(v().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?B({message:fe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):W():B({message:fe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[y.NONE]:e=>{let t=ae(y.NONE);return e.command?W():B({message:fe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[y.NEW]:e=>Qd({list:ae(y.NEW),hint:fe({wordList:ae(y.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[y.HELP]:()=>W(J),[y.EDIT]:ec,[y.CONFIG]:Zd,[y.DELETE]:e=>{let t=Hr();return t.validity==="invalid"?t:jr(e)},[y.CLOSE_ISSUE]:e=>jr(e),[y.RE_OPEN_ISSUE]:e=>jr(e),[y.MOVE]:e=>{let t=Hr();return t.validity==="invalid"?t:Kt({hint:fe({prefix:"hey hacker! These commands are blocked for you... ",wordList:ae(y.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[y.TAG]:e=>{let n=I.getExistingTags().map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10).join("");return Kt({hint:n.length?"existing tags ... "+n:"create tag ..."})(e)},[y.UNTAG]:e=>{let t=Rn();if(d(t))return B({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10);return n.length?Kt({hint:" ... "+n.join("")})(e):B({message:"Issue has no tags",completionWordList:[]})},[y.ASSIGN]:e=>{let t=I.getExistingAssignees().map(n=>` ${xt.bgHex(de(n))(" "+n+" ")} `).slice(0,10);return Kt({hint:"assign to... "+t.join("")})(e)},[y.UNASSIGN]:e=>{let t=An();if(d(t))return B({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10);return n.length?Kt({hint:"remove assignee... "+n.join("")})(e):B({message:"Issue has no assignees",completionWordList:[]})},[y.SYNC]:()=>W(J)},Ui=Object.fromEntries(Object.entries(tc).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var $i=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var M={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Wi=e=>Object.values(y).includes(e),_i=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:c,completionWordList:u}=Ui[n].validate(n,r,i),m=o==="command"||o==="modifier"?ae(n):$i;return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Oo(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var ji=e=>{let t=e.trimStart(),n=rc(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=oc(e),c=Wi(r)?r:null,u=c!==null,m=r!=="",p=c?ae(c)??[]:[],g=c&&p.includes(o)?o:"",x="word";n.length===0||n.length===1&&!i?x="command":(n.length===1&&i||n.length===2&&!i)&&(x="modifier");let E=i?"":a,A=nc(t,c,g);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:g,target:x,inputToMatch:E,inputString:A}},nc=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},rc=e=>e.trim()?e.trim().split(/\s+/):[],oc=e=>e.trimEnd().split(/\s+/).at(-1)??"";var ht=e=>e===Kr||e===":",Kr=" ",ce={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:rt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Vr=new Set,Hi=()=>{for(let e of Vr)e()},Ki=e=>(Vr.add(e),()=>Vr.delete(e)),De=e=>{let n=e(ce),r=ji(n.value),o=n.cursorPosition===n.value.length;ce={...n,commandMeta:_i(r,o)},Hi()},Vt=({message:e,status:t})=>{let n=structuredClone(ce);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ce=n,Hi(),l(e,null)},Gr=e=>{De(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},qr=e=>{De(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&ht(n[o-1]);)o--;for(;o>0&&!ht(n[o-1]);)o--}else{for(;o<n.length&&!ht(n[o]);)o++;for(;o<n.length&&ht(n[o]);)o++}return{...t,cursorPosition:o}})},Vi=()=>{De(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Gi=()=>{De(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&ht(t[r-1]);)r--;for(;r>0&&!ht(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},$=e=>{De(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),a=i+o,c=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:c,commandIsPending:!1}})},qi=()=>{De(e=>({...e,commandIsPending:!0}))},zi=({addToHistory:e=!0})=>{De(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ic()},Yi=()=>{De(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Xi=()=>{De(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ic=()=>$(()=>""),Q=()=>ce,Ji=()=>{let[e,...t]=ce.value.split(Kr);return t.join(Kr).trim()};var sc=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",ac=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",dc=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Qi=(e,t)=>{if(ac(e,e.sequence))return h.MoveCursorLeftOfWord;if(dc(e,e.sequence))return h.MoveCursorRightOfWord;if(sc(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};var h={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function cc(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function lc(e,t,n){let r=v().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Zi(e,t){let n=Q();if(e.sequence===":"&&n.value==="")return h.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===f.COMMAND_LINE)return Qi(e,n.value);let r=cc(e);if(r){let o=t===f.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return lc(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"e":return h.Edit;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return L().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;case"s":return h.Sync;default:return null}}var es=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case y.EXIT:return M.Exit;case y.EXPORT:return M.Export;case y.INIT:return M.Init;case y.DELETE:return M.Delete;case y.EDIT:return M.Edit;case y.HELP:return M.ViewHelp;case y.RE_OPEN_ISSUE:return M.ReopenIssue;case y.CLOSE_ISSUE:return M.CloseIssue;case y.TAG:return M.TagTicket;case y.UNTAG:return M.UntagTicket;case y.ASSIGN:return M.AssignUserToTicket;case y.UNASSIGN:return M.UnassignUserFromTicket;case y.NEW:return M.NewItem;case y.FILTER:return M.Filter;case y.MOVE:return M.Move;case y.PEEK:return M.Peek;case y.CONFIG:return M.Config;case y.SYNC:return M.Sync;default:return M.None}};import{ulid as V}from"ulid";import vs from"node:fs";import Uc from"node:path";import $c from"react";import{Box as Oc}from"ink";import Un from"react";import{Box as Xr,Text as Ec}from"ink";import Re from"react";import{Text as ts}from"ink";import ns,{useEffect as rs,useState as uc}from"react";var os={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},me=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=G(),r=os[n]??os.default,[o,i]=uc(0);if(rs(()=>{i(0)},[r]),rs(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return ns.createElement(ts,null,t);let a=r[o]??r[0]??t;return ns.createElement(ts,{color:N.accent,dimColor:o===1},a)};import{Box as zr,Text as mc}from"ink";import Dn from"react";var Fn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),g=p+c,x=e.slice(p,g),E=e.length>c,A=i,R=E?Math.max(1,Math.floor(c/e.length*A)):A,b=Math.max(0,A-R),w=Math.max(1,e.length-c),U=E?Math.floor(p/w*b):0;return Dn.createElement(zr,{flexDirection:"row",height:i,width:"100%"},Dn.createElement(zr,{flexDirection:"column",flexGrow:1,height:i},x),Dn.createElement(zr,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((le,ne)=>Dn.createElement(mc,{key:ne,color:E&&ne>=U&&ne<U+R?N.accent:N.secondary},E?"\u2502":" "))))};import{Box as Ln,Text as hc}from"ink";import ot from"react";import{Text as pc}from"ink";import fc from"react";var gc=e=>e.toLowerCase().trim(),vc=(e,t=vt)=>{let n=gc(e);return t[n]?t[n]:Ht(n)},Ct=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return fc.createElement(pc,{underline:t,color:vc(n.name)},"@"+n.name)};import{Text as yc}from"ink";import xc from"react";var Nt=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return xc.createElement(yc,{underline:t,backgroundColor:de(n.name),color:N.primary}," "+n.name+" ")};var is=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=dn(lr(t.title),r),i=Dr(t),a=Fr(t);return ot.createElement(Ln,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?N.accent:N.secondary,justifyContent:"space-between"},ot.createElement(Ln,{borderBottom:!0},ot.createElement(Ln,{paddingLeft:1,flexDirection:"column"},ot.createElement(hc,{color:N.primary},o))),ot.createElement(Ln,{flexDirection:"row",paddingLeft:1},i.map(c=>ot.createElement(Nt,{key:c.id,id:c.id})),a.map(c=>ot.createElement(Ct,{key:c.id,id:c.id}))))};import Cc from"chalk";import{Box as Gt,Text as Yr}from"ink";import Fe from"react";var Nc=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ss=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=T(t.id),a=R=>{let b=i.find(w=>w.title===R);return b?T(b.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},c=a("Tags").map(R=>I.getTag(R)).filter(R=>!!R),u=a("Assignees").map(R=>I.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),g=u.length*(2+m),x=c.map(R=>Fe.createElement(Gt,{key:R.id,paddingRight:m},Fe.createElement(Yr,{color:de(R.name)},"\u25A0"))),E=u.map(R=>Fe.createElement(Gt,{key:R.id,paddingRight:m},Fe.createElement(Yr,{color:Ht(R.name)},"@"+R.name.at(0)))),A=n?N.accent:o===f.MOVE?N.secondary:N.primary;return Fe.createElement(Gt,{borderBottom:!0,justifyContent:"space-between"},Fe.createElement(Gt,null,Fe.createElement(me,{isSelected:n,placeholder:Cc.dim.gray(r+1+" ")}),Fe.createElement(Yr,{wrap:"truncate",color:A},Nc(t.title,e-p-g-14))),Fe.createElement(Gt,null,x,E))};var Ic=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:c})=>{let{renderedChildrenIndex:u}=G(),m=u[e.id]??[],p=`${e.title} (${m.length})`,g=3,x=o?1:4,E=r-g-(o?2:1),A=Re.createElement(Xr,{borderStyle:"round",borderColor:N.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Re.createElement(me,{isSelected:t}),Re.createElement(Ec,{bold:!0,color:t?N.accent:N.primary},p," ",e.readonly?"\u{1F512}":"")),R=(b,w)=>{let U=i&&a===w;return o?Re.createElement(ss,{key:b.id,index:w,width:n,ticket:b,isSelected:U,mode:c}):Re.createElement(is,{key:b.id,width:n,ticket:b,isSelected:U})};return Re.createElement(Xr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?N.accent:N.secondary,paddingRight:1,paddingLeft:1,height:r},A,Re.createElement(Xr,{padding:o?1:0},m.length>0&&Re.createElement(Fn,{selectedIndex:a,height:E,itemHeight:x},m.map(R)),Re.createElement(me,{isSelected:i&&a===-1})))},as=Re.memo(Ic);import{Box as Zr,Text as Fc}from"ink";import Ke,{useEffect as eo,useMemo as ps}from"react";import it from"chalk";import ds from"string-width";import{decodeTime as bc}from"ulid";var Sc=(e,t)=>e+" ".repeat(Math.max(0,t-ds(e))),Rc=(e,t)=>" ".repeat(Math.max(0,t-ds(e)))+e,Ac=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),wc=e=>{switch(e.action){case"move.node":{let t=I.getNode(e.payload.parent);return`to ${t?it.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?it.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?it.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?it.hex(de(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?it.hex(de(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Tc=e=>{let t=Fi(bc(e));return it.gray(Rc(t,8))},Mc=12,Pc=e=>Sc(`${e}`,Mc),cs=e=>{let t=Tc(e.id),n=Pc(e.userName),r=Ac(e.action),o=wc(e),i=it.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=T(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:T(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=T(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>ls(1),navigateToPreviousItem:()=>ls(-1),navigateToNextContainer:()=>us(1),navigateToPreviousContainer:()=>us(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{S({currentNodeId:e.id,selectedIndex:t})}},ls=e=>{let t=v(),n=T(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},us=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=T(o.id),a=i.findIndex(x=>x.id===t.id);if(a<0)return;let c=i.at(a+e)??i.at(0);if(!c)return;let u=T(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),g=u.length?p:-1;D.navigate({currentNode:c,selectedIndex:g})};import{Box as On,Text as kc}from"ink";import Le from"react";var ms=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=G(),{title:o}=t,i=T(t.id).map(a=>{let c=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return I.getContributor(c)?.id;if(o==="Tags")return I.getTag(c)?.id}).filter(a=>!!a);return Le.createElement(On,{alignItems:"center",paddingTop:1},Le.createElement(On,{minWidth:12},Le.createElement(me,{isSelected:n}),Le.createElement(kc,{color:n?N.accent:N.secondary2},o,":")),Le.createElement(On,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,c)=>{let u=r.id===t.id&&c===e;return Le.createElement(On,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Le.createElement(me,{isSelected:u}),o==="Assignees"?Le.createElement(Ct,{isSelected:u,id:a}):o==="Tags"?Le.createElement(Nt,{isSelected:u,id:a}):null)})))};import{Box as Bn,Text as Jr}from"ink";import Oe,{useEffect as Dc}from"react";var Qr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:c}=G(),u=x=>String(x).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Dc(()=>{let x=[];return m.forEach((E,A)=>{let R=Pe(BigInt(A+1));if(!Ee(R))return;let b=ie.text({id:`${e}-${A}`,name:`Line ${A+1}`,parentNodeId:e,rank:R.value,props:{value:E},readonly:!0,isVirtual:!0}),w=I.createNode(b);Ee(w)&&x.push(w.value.id)}),()=>x.forEach(I.deleteNode)},[e,n]);let p="\u2029",g=m.map((x,E)=>{let A=c.id===e&&a===E;return Oe.createElement(Bn,{key:`${e}-${E}`},Oe.createElement(Jr,{color:A?N.primary:N.secondary2,dimColor:!A},`${E+1} `.padStart(5,"\xA0")),Oe.createElement(Jr,{backgroundColor:A?"gray":""},u(x.length?dn(x,i-10):p)))});return Oe.createElement(Bn,{flexDirection:"column",paddingTop:1},Oe.createElement(Bn,null,Oe.createElement(me,{isSelected:o}),Oe.createElement(Jr,{color:o?N.accent:N.secondary2},t)),Oe.createElement(Bn,{flexDirection:"row",borderStyle:"round",borderColor:N.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Oe.createElement(Fn,{scrollByOne:!0,children:g,height:r-2,selectedIndex:a,itemHeight:1})))};var Lc=e=>`${e}::log`,fs=e=>e==="Assignees"||e==="Tags",gs=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=G(),o=process.stdout.columns||120,i=ps(()=>Lc(e.id),[e.id]),a=ps(()=>[...e.log].reverse().map(cs).join(`
43
+ `,Nd=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Ir(r),r);return[...n.values()].sort((r,o)=>{let i=fi(r)-fi(o);return i!==0?i:Ir(r).localeCompare(Ir(o))})},Sr=({sourceFile:e,targetFile:t})=>{let n=ln(e);if(d(n))return s(n.message);let r=ln(t);if(d(r))return s(r.message);let o=Nd(r.value,n.value),i=Cd(o);return(En.existsSync(t)?En.readFileSync(t,"utf8"):"")===i?l("Event file already merged",!1):(En.mkdirSync(br.dirname(t),{recursive:!0}),En.writeFileSync(t,i,"utf8"),l("Merged event file",!0))},Ut=({repoRoot:e,stateBranchRoot:t})=>{let n=ai(t);if(d(n))return s(n.message);let r=Qe(t),o=Qe(e),i=!1;for(let a of n.value){let c=br.join(r,a),u=br.join(o,a),m=Sr({sourceFile:c,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return l("Hydrated event files from state branch",i)};var vi=async(e=process.cwd())=>{fr("Syncing from remote");let t=await yi({cwd:e,ensureUpstream:!1});if(d(t))return oe(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=Je(e);if(d(o))return oe(o.message);let i=o.value,a=await vn({cwd:r,branch:i});if(d(a))return oe(a.message);let c=Ut({repoRoot:n,stateBranchRoot:r});return d(c)?oe(c.message):(gr("Synced from remote"),l("Synced state branch",{repoRoot:n,stateBranchRoot:r}))},Id=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Nr({root:e,fileName:n}),o=Nr({root:t,fileName:n});return Ed.existsSync(r)?Sr({sourceFile:r,targetFile:o}):l("Local own event file missing, nothing to merge",!1)},yi=async({cwd:e,ensureUpstream:t})=>{let n=await hn(e);if(d(n))return s(n.message);let r=n.value,o=ii({repoRoot:r});if(d(o))return s(o.message);let i=o.value,a=await Dt(r);if(d(a))return s(a.message);if(a.value)return s("Cannot sync while a git operation is in progress in the current repo");let c=await ui(r);if(d(c))return s(c.message);let u=await pi({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await Dt(i);if(d(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=di(r,i);return d(p)?s(p.message):l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},gi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Id({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(d(r))return s(r.message);let o=await Zo(t);if(d(o))return s(o.message);if(!r.value&&!o.value)return l("Own event file already up to date in state branch",{createdCommit:!1});let i=await Nn({stateBranchRoot:t,eventFileName:n});if(d(i))return s(i.message);let a=await mi({repoRoot:e,stateBranchRoot:t});return d(a)?s(a.message):l("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},In=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");fr("Syncing");let n=await yi({cwd:e,ensureUpstream:!0});if(d(n))return oe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await ei(r);if(d(a))return oe(a.message);if(a.value)return oe("Cannot run :sync while the repository is in detached HEAD state");let c=!1,u,m=!1,p=!1,g=!1,x=Je(r);if(d(x))return oe(x.message);let E=x.value,A=await vn({cwd:o,branch:E});if(d(A))return oe(A.message);m=A.value;let R=Ut({repoRoot:r,stateBranchRoot:o});if(d(R))return oe(R.message);g=R.value;let b=await gi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(b))return oe(b.message);if(c=b.value.createdCommit,u=b.value.commitSha,c||i){let w=await Bt({stateBranchRoot:o,repoRoot:r}),U=w;if(d(w)&&Qo(w.message)){let le=await vn({cwd:o,branch:E});if(d(le))return oe(le.message);let ne=await gi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(ne))return oe(ne.message);ne.value.createdCommit&&(c=!0,u=ne.value.commitSha),U=await Bt({stateBranchRoot:o,repoRoot:r})}if(d(U))return oe(U.message);p=U.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(c){let w=await F({args:["rev-parse","HEAD"],cwd:o});if(d(w))return oe(w.message);u=w.value.stdout.trim()}return gr(p?"Synced and pushed":m||g||c?"Synced local state":"Already synced"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,hydrated:g,bootstrapped:i})};var ft=3e3,xi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<ft?null:t},hi=0,Rr,Ar=!1,$t=!1,wr=()=>Ar||v().syncStatus.status==="syncing",bd=()=>{let e=L().autoSyncIntervalMs??15e3,t=Date.now()-hi;return Math.max(0,e-t)},Ci=()=>{Rr||(Rr=setTimeout(async()=>{if(Rr=void 0,wr()){$t=!0;return}$t=!1,await Sd()},bd()))},Sd=async()=>{if(wr())return $t=!0,s("Sync already in progress");let e=K();if(d(e)||!e.value)return s("Unable to resolve event log path");Ar=!0,hi=Date.now();try{let t=Xe(e.value);return await In({ownEventFileName:t})}finally{Ar=!1,$t&&Ci()}},Ni=()=>{$t=!0,!wr()&&Ci()};var ie={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:a=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:a}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:a=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:a})};import{ulid as wd}from"ulid";var Ze=24n,Rd=Ze*4n,et=(1n<<Rd)-1n,Ad=/^[0-9a-f]+$/;function Ei(e){return!e||!Ad.test(e)?s(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Pe(e,t=Ze){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function z(e,t){if(!e&&!t)return Pe(et/2n,Ze);let n=e?Ei(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Ei(t):l("Resolved upper bound",et);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Pe(et/2n,Ze);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):Pe(a,Ze)}function Ii(){return Pe(et/2n,Ze)}function bi(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=et*BigInt(r+1)/(t+1n),i=Pe(o,Ze);if(d(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var Tr=(e,t)=>{let n=O(e),r=bi(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],c=r.value[i];if(!a||!c)return s("Unable to assign rebalance rank");o[a.id]=c}return l("Created rebalance event",{id:wd(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var Y={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var Td=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ke,bn]=Td;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Md={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ie.workspace(t,n,r),i=jt(o);if(d(i))return k(i.message,e);let a=I.createNode(o);return d(a)?k(a.message??"Failed to initialize workspace",e):cr(a.value)?l("Workspace initialized",{action:e.action,result:a.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ie.workspace(t,n,r),i=I.createNode(o);return d(i)?k(i.message??"Failed to add workspace",e):cr(i.value)?l("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.board(t,n,r,o));return d(i)?k(i.message??"Unable to create board",e):Po(i.value)?l("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.swimlane(t,n,r,o));return d(i)?k(i.message??"Unable to create swimlane",e):lt(i.value)?l("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.ticket(t,n,r,o));return d(i)?k(i.message??"Unable to create issue",e):ye(i.value)?l("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,a=I.createNode(ie.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(Y.DESCRIPTION)?"vertical":"horizontal"}));return d(a)?k(a.message??`Unable to create field: ${n}`,e):Mo(a.value)?l("Added field",{action:e.action,result:a.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=I.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=I.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=I.tag(n,r,t,o);return d(i)?k(i.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=I.untag(t,n);return d(r)?k(r.message??"Unable to untag ",e):l("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=I.assign(r,n,t,o);return d(i)?k(i.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=I.unassign(t,n);return d(r)?k(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=I.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ye(o))return k("Can only close issues",e);let i=I.getNode(ke);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let a=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(a)?k(a.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ye(o))return k("Can only reopen issues",e);let i=I.getNode(ke);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return k("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=I.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let a=I.updateNode({...i,rank:o});if(d(a))return k(a.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}},Pd=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},kd=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function Wt(e,t=!1){let n=Md[e.action](e);if(d(n))return n;t||([...new Set(kd(e))].forEach(a=>Pd(a,e)),he(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(I.createContributor({name:o,id:r}),n)}var _t=e=>e.map(t=>Wt(t));function _(e){let t=Wt(e);if(t.status!==Ue.Success)return t;let n=mn({event:e});return d(n)?n:t}function Sn(e){return e.map(t=>_(t))}var Si=e=>Mr(O(e),{at:"end"}),Mr=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(z(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(z(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(z(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Ri(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(z(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=Ri(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(z(o.rank,i?.rank)):s("Sibling not found")}}},O=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ri=(e,t)=>e.findIndex(n=>n.id===t),Ai=(e,t,n={at:"end"})=>Mr(O(t).filter(r=>r.id!==e),n),tt=(e,t,n,r)=>{let o=Ai(t,e,n);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let i=Tr(e,r);if(d(i))return i;let a=_(i.value);if(d(a))return a;let c=Ai(t,e,n);return d(c)?c:c.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",c.value.rank)},gt=(e,t)=>{let n=Si(e);if(d(n))return n;if(!n.value.needsRebalance)return l("Resolved rank",n.value.rank);let r=Tr(e,t);if(d(r))return r;let o=_(r.value);if(d(o))return o;let i=Si(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var je=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},kr=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Pr=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),I={deleteNode(e){he(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=Pr(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return this.updateNode(i),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Pr(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return O(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=Pr(o,"move");if(a)return a;if(kr(t,e))return s("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of O(m.id))a(p.id)}};a(e);let c={...structuredClone(t)};for(let u of i){if(!c[u])return s("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(S({nodes:c}),l("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=he(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):l("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let a=this.getFieldByTitle(i.id,"Assignees");if(!a)return s("Unable to locate assignees field");if(O(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=ie.field({id:n,name:o.name,parentNodeId:a.id,rank:r,props:{value:t}}),m=this.createNode(u);return d(m)?m:l("Assigned contributor",u)},createTag(e){let t=he(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):l("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let a=this.getFieldByTitle(i.id,"Tags");if(!a)return s("Unable to locate tags field");if(O(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=ie.field({id:n,name:o.name,parentNodeId:a.id,rank:r,props:{value:t}}),m=this.createNode(u);return d(m)?m:l("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=O(o.id).find(c=>c.props?.value===t);if(!i)return l("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Tag removed",a)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=O(o.id).find(c=>c.props?.value===t);if(!i)return l("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Assignee removed",a)},createNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?s("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=he(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):l("Locked node",n)},updateNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return O(e)}};var se={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},N={accent:se.cyan,accent2:se.magenta,primary:se.white,secondary:se.grayDark,secondary2:se.grayLight,gray:se.gray,green:se.green,yellow:se.yellow,red:se.red};var C={red:se.red,yellow:se.yellow,green:se.green,blue:se.blue,magenta:se.magenta,cyan:se.cyan},vt={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan};var wi=(e,t)=>{let r=T(e.id).find(o=>o.title===t);return r?T(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Dr=e=>wi(e,"Tags").map(t=>I.getTag(t)).filter(t=>!!t),Rn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Dr(n)??[])},An=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Fr(n)??[])},Fr=e=>wi(e,"Assignees").map(t=>I.getContributor(t)).filter(t=>!!t);var y={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var Dd=/^(\d+)(h|d|w|mo|y)$/,Fd=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ld=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},Od=(e,t=new Date)=>{let n=e.match(Dd);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},Bd=e=>{let t=e.match(Fd);if(!t)return null;let[,n,r,o,i,a]=t,c=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,g=a?Number(a):0;return Ld({year:c,month:u,day:m,hour:p,minute:g})?new Date(c,u-1,m,p,g):null},wn=e=>{let t=e.trim().toLowerCase();return Od(t)??Bd(t)},Ti=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ud=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Mi=(e=Ud)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var $d=["BOARD","TICKET","SWIMLANE"],X={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},He={TITLE:"title",DESCRIPTION:"description"},Wd=[X.EDITOR,X.VIEW,X.USERNAME,X.AUTOSYNC,X.SYNC_DEBOUNCE_MS],_d=[He.TITLE,He.DESCRIPTION],Or=[String(ft),"5000","15000","30000","60000"],nt=[y.SYNC,y.HELP,y.EXPORT,y.CONFIG],Tn=[y.NEW,y.EDIT,y.DELETE,y.MOVE],Lr=[y.TAG,y.UNTAG,y.ASSIGN,y.UNASSIGN,y.CLOSE_ISSUE,y.RE_OPEN_ISSUE,y.EDIT],Pi=[y.FILTER,y.PEEK],jd={WORKSPACE:[...nt,...Tn],BOARD:[...Pi,...nt,...Tn],SWIMLANE:[...Pi,...nt,...Tn],TICKET:[...nt,...Tn,...Lr],FIELD:[...nt,...Lr],FIELD_LIST:[...nt,...Lr],TEXT:[...nt]},Hd=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Kd=()=>{let{selectedNode:e,readOnly:t,breadCrumb:n}=v(),{isSetupDone:r}=_e();if(!r)return[y.HELP,y.CONFIG];if(!Ao())return[y.HELP,y.INIT];if(t)return[y.HELP,y.PEEK,y.EXPORT,y.CONFIG];let o=e?.context,i=o&&$d.includes(o);return[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?jd[c]:[]))].filter(c=>c===y.MOVE?!1:c===y.EDIT||c===y.DELETE?i:!0)},ae=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[y.NONE]:Kd(),[y.EXIT]:["confirm"],[y.EXPORT]:[],[y.SYNC]:[],[y.INIT]:[],[y.HELP]:[],[y.PEEK]:[...Mi(),"now","prev","next"],[y.EDIT]:[..._d],[y.DELETE]:["confirm"],[y.RE_OPEN_ISSUE]:["confirm"],[y.CLOSE_ISSUE]:["confirm"],[y.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[y.FILTER]:["tag","assignee","description","title","clear"],[y.TAG]:[...new Set([...Object.keys(vt),...I.getExistingTags()])],[y.UNTAG]:[...Rn()?.value?.map(({name:o})=>o)??[]],[y.UNASSIGN]:[...An()?.value?.map(({name:o})=>o)??[]],[y.ASSIGN]:I.getExistingAssignees(),[y.NEW]:Hd(n),[y.CONFIG]:[...Wd]}[e]??[]};import xt from"chalk";var ki=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Di}from"ulid";var Fi=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},Li=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Mn=e=>{try{return l("Decoded date",new Date(Di(e)))}catch(t){return s("Decoding failed + "+t.message)}},Br=e=>{if(!e?.id)return null;try{return Di(e.id)}catch{return null}};import yt from"chalk";var $r={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Vd=(e,t,n)=>Math.max(t,Math.min(n,e)),Ur=(e,t,n)=>e+(t-e)*n,Oi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Gd=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,c=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=c):a>=1&&a<2?(u=c,m=i):a>=2&&a<3?(m=i,p=c):a>=3&&a<4?(m=c,p=i):a>=4&&a<5?(u=c,p=i):(u=i,p=c);let g=o-i/2;return[Math.round((u+g)*255),Math.round((m+g)*255),Math.round((p+g)*255)]},qd=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,zd=(e,t,n)=>[Math.round(Ur(e[0],t[0],n)),Math.round(Ur(e[1],t[1],n)),Math.round(Ur(e[2],t[2],n))],Ht=e=>{let n=Oi(e)%360,r=Gd(n,$r.stringColor.saturation,$r.stringColor.lightness);return qd(r)},Yd=e=>{let t=$r.gradient.stops,n=Vd(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),a=o-i;return zd(t[i],t[i+1],a)},Pn=e=>Oi(e.toLowerCase().trim())/4294967295,Bi=e=>{let t=Pn(e);return Yd(t)},Xd=e=>{let[t,n,r]=Bi(e);return{normal:o=>yt.bgRgb(t,n,r).black(o),cursor:o=>yt.bgRgb(t,n,r).white.bold(o)}},Wr=e=>{let[t,n,r]=Bi(e);return{fg:o=>yt.rgb(t,n,r)(o),fgCursor:o=>yt.rgb(t,n,r).inverse(o),bg:o=>yt.bgRgb(t,n,r).black(o),bgCursor:o=>yt.bgRgb(t,n,r).white.bold(o)}},_r=e=>Xd(e).normal(` ${e} `),de=(e,t=vt)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Ht(r)};var rt={None:"none",Invalid:"invalid",Valid:"valid"};var Jd=["BOARD","TICKET","SWIMLANE"],Hr=()=>{let e=v().selectedNode;return e?.context?Jd.includes(e.context)?W():B({message:"Command not available in this context"}):B({message:"Missing target context"})},J="<ENTER> to confirm",W=(e="",t=[])=>({message:e,validity:rt.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:rt.Invalid,message:e,completionWordList:t}),kn=e=>e.length===0,fe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let a=o.trim();if(a.length<i)return"";let p=[...t.filter(Boolean).filter(g=>g.startsWith(a))].sort((g,x)=>Pn(g)-Pn(x)).slice(0,r).map(_r).join(" ");return p?`${e}${p}${n}`:""},jr=({modifier:e})=>{let t="confirm";return e===t?W(J):B({message:kn(e)?`if you are certain, enter ${_r(t)}`:"",completionWordList:[t]})},Qd=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?B({message:n}):W():B({message:kn(r)?t:"",completionWordList:[...e]}),Kt=({hint:e})=>({modifier:t,inputString:n})=>kn(t)&&kn(n)?B({message:e,completionWordList:[]}):W(J),Zd=({modifier:e,inputString:t})=>{let n=ae(y.CONFIG);if(!n.includes(e))return B({message:fe({prefix:"config... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case X.EDITOR:{let r=[...ki];return t.trim()?r.includes(t.trim())?W(J):B({message:fe({prefix:"known editors... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):B({message:fe({prefix:"editor... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?W(J):B({message:fe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.USERNAME:return t.trim()?W(J):B({message:`Enter a username. Saved in ${xt.bgBlack("~/.epiq-global/config.json")}`});case X.AUTOSYNC:{let r=["yes","no"],o=L().autoSync;if(!r.includes(t.trim())){let i=wo(o);return B({message:fe({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return W(J)}case X.SYNC_DEBOUNCE_MS:{let r=L().autoSyncIntervalMs,o=xi(t);if(!t.trim()||o===null||o<ft){let i=fe({prefix:" examples: ",wordList:Or,minLengthForHints:0,inputString:t});return B({message:`provide duration above ${ft}ms. current duration: ${r}ms.`+i,completionWordList:Or})}return W(J)}default:return B({message:"Unknown config option",completionWordList:n})}},ec=({modifier:e})=>{let t=ae(y.EDIT);if(!t.includes(e)){let r=fe({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return B({message:r||"Unknown edit option",completionWordList:t})}let n=Hr();if(n.validity==="invalid")return n;switch(e){case He.TITLE:return W(J);case He.DESCRIPTION:return W("<ENTER> to edit in "+L().preferredEditor);default:return B({message:"Unknown edit option",completionWordList:t})}},tc={[y.EXPORT]:()=>W(J+", and create export markdown file"),[y.PEEK]:e=>{let t=e.modifier;if(t==="now")return W(J);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return W(J);let r=wn(t);if(!t||!r)return B(n);let o=Se(v().breadCrumb,"BOARD");if(d(o))return B({message:"Command is not applicable in this context"});let i=Mn(o.value.id);return d(i)?B({message:"Unable to peek: board id is not a valid ULID"}):Ti({date:r,horizonDate:i.value})?W(J):B({message:xt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[y.EXIT]:()=>W(J+" and exit the application"),[y.INIT]:()=>W(J),[y.FILTER]:e=>{if(e.modifier==="clear")return W();let t=i=>ae(y.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return B({message:fe({wordList:ae(y.FILTER),inputString:e.inputString}),completionWordList:ae(y.FILTER)});let n=Object.values(v().tags).map(i=>i.name),r=Object.values(v().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?B({message:fe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):W():B({message:fe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[y.NONE]:e=>{let t=ae(y.NONE);return e.command?W():B({message:fe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[y.NEW]:e=>Qd({list:ae(y.NEW),hint:fe({wordList:ae(y.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[y.HELP]:()=>W(J),[y.EDIT]:ec,[y.CONFIG]:Zd,[y.DELETE]:e=>{let t=Hr();return t.validity==="invalid"?t:jr(e)},[y.CLOSE_ISSUE]:e=>jr(e),[y.RE_OPEN_ISSUE]:e=>jr(e),[y.MOVE]:e=>{let t=Hr();return t.validity==="invalid"?t:Kt({hint:fe({prefix:"hey hacker! These commands are blocked for you... ",wordList:ae(y.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[y.TAG]:e=>{let n=I.getExistingTags().map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10).join("");return Kt({hint:n.length?"existing tags ... "+n:"create tag ..."})(e)},[y.UNTAG]:e=>{let t=Rn();if(d(t))return B({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10);return n.length?Kt({hint:" ... "+n.join("")})(e):B({message:"Issue has no tags",completionWordList:[]})},[y.ASSIGN]:e=>{let t=I.getExistingAssignees().map(n=>` ${xt.bgHex(de(n))(" "+n+" ")} `).slice(0,10);return Kt({hint:"assign to... "+t.join("")})(e)},[y.UNASSIGN]:e=>{let t=An();if(d(t))return B({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10);return n.length?Kt({hint:"remove assignee... "+n.join("")})(e):B({message:"Issue has no assignees",completionWordList:[]})},[y.SYNC]:()=>W(J)},Ui=Object.fromEntries(Object.entries(tc).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var $i=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var M={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Wi=e=>Object.values(y).includes(e),_i=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:c,completionWordList:u}=Ui[n].validate(n,r,i),m=o==="command"||o==="modifier"?ae(n):$i;return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Oo(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var ji=e=>{let t=e.trimStart(),n=rc(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=oc(e),c=Wi(r)?r:null,u=c!==null,m=r!=="",p=c?ae(c)??[]:[],g=c&&p.includes(o)?o:"",x="word";n.length===0||n.length===1&&!i?x="command":(n.length===1&&i||n.length===2&&!i)&&(x="modifier");let E=i?"":a,A=nc(t,c,g);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:g,target:x,inputToMatch:E,inputString:A}},nc=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},rc=e=>e.trim()?e.trim().split(/\s+/):[],oc=e=>e.trimEnd().split(/\s+/).at(-1)??"";var ht=e=>e===Kr||e===":",Kr=" ",ce={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:rt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Vr=new Set,Hi=()=>{for(let e of Vr)e()},Ki=e=>(Vr.add(e),()=>Vr.delete(e)),De=e=>{let n=e(ce),r=ji(n.value),o=n.cursorPosition===n.value.length;ce={...n,commandMeta:_i(r,o)},Hi()},Vt=({message:e,status:t})=>{let n=structuredClone(ce);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ce=n,Hi(),l(e,null)},Gr=e=>{De(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},qr=e=>{De(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&ht(n[o-1]);)o--;for(;o>0&&!ht(n[o-1]);)o--}else{for(;o<n.length&&!ht(n[o]);)o++;for(;o<n.length&&ht(n[o]);)o++}return{...t,cursorPosition:o}})},Vi=()=>{De(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Gi=()=>{De(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&ht(t[r-1]);)r--;for(;r>0&&!ht(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},$=e=>{De(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),a=i+o,c=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:c,commandIsPending:!1}})},qi=()=>{De(e=>({...e,commandIsPending:!0}))},zi=({addToHistory:e=!0})=>{De(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ic()},Yi=()=>{De(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Xi=()=>{De(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ic=()=>$(()=>""),Q=()=>ce,Ji=()=>{let[e,...t]=ce.value.split(Kr);return t.join(Kr).trim()};var sc=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",ac=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",dc=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Qi=(e,t)=>{if(ac(e,e.sequence))return h.MoveCursorLeftOfWord;if(dc(e,e.sequence))return h.MoveCursorRightOfWord;if(sc(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};var h={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function cc(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function lc(e,t,n){let r=v().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Zi(e,t){let n=Q();if(e.sequence===":"&&n.value==="")return h.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===f.COMMAND_LINE)return Qi(e,n.value);let r=cc(e);if(r){let o=t===f.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return lc(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"e":return h.Edit;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return L().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;case"s":return h.Sync;default:return null}}var es=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case y.EXIT:return M.Exit;case y.EXPORT:return M.Export;case y.INIT:return M.Init;case y.DELETE:return M.Delete;case y.EDIT:return M.Edit;case y.HELP:return M.ViewHelp;case y.RE_OPEN_ISSUE:return M.ReopenIssue;case y.CLOSE_ISSUE:return M.CloseIssue;case y.TAG:return M.TagTicket;case y.UNTAG:return M.UntagTicket;case y.ASSIGN:return M.AssignUserToTicket;case y.UNASSIGN:return M.UnassignUserFromTicket;case y.NEW:return M.NewItem;case y.FILTER:return M.Filter;case y.MOVE:return M.Move;case y.PEEK:return M.Peek;case y.CONFIG:return M.Config;case y.SYNC:return M.Sync;default:return M.None}};import{ulid as V}from"ulid";import vs from"node:fs";import Uc from"node:path";import $c from"react";import{Box as Oc}from"ink";import Un from"react";import{Box as Xr,Text as Ec}from"ink";import Re from"react";import{Text as ts}from"ink";import ns,{useEffect as rs,useState as uc}from"react";var os={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},me=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=G(),r=os[n]??os.default,[o,i]=uc(0);if(rs(()=>{i(0)},[r]),rs(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return ns.createElement(ts,null,t);let a=r[o]??r[0]??t;return ns.createElement(ts,{color:N.accent,dimColor:o===1},a)};import{Box as zr,Text as mc}from"ink";import Dn from"react";var Fn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),g=p+c,x=e.slice(p,g),E=e.length>c,A=i,R=E?Math.max(1,Math.floor(c/e.length*A)):A,b=Math.max(0,A-R),w=Math.max(1,e.length-c),U=E?Math.floor(p/w*b):0;return Dn.createElement(zr,{flexDirection:"row",height:i,width:"100%"},Dn.createElement(zr,{flexDirection:"column",flexGrow:1,height:i},x),Dn.createElement(zr,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((le,ne)=>Dn.createElement(mc,{key:ne,color:E&&ne>=U&&ne<U+R?N.accent:N.secondary},E?"\u2502":" "))))};import{Box as Ln,Text as hc}from"ink";import ot from"react";import{Text as pc}from"ink";import fc from"react";var gc=e=>e.toLowerCase().trim(),vc=(e,t=vt)=>{let n=gc(e);return t[n]?t[n]:Ht(n)},Ct=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return fc.createElement(pc,{underline:t,color:vc(n.name)},"@"+n.name)};import{Text as yc}from"ink";import xc from"react";var Nt=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return xc.createElement(yc,{underline:t,backgroundColor:de(n.name),color:N.primary}," "+n.name+" ")};var is=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=dn(lr(t.title),r),i=Dr(t),a=Fr(t);return ot.createElement(Ln,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?N.accent:N.secondary,justifyContent:"space-between"},ot.createElement(Ln,{borderBottom:!0},ot.createElement(Ln,{paddingLeft:1,flexDirection:"column"},ot.createElement(hc,{color:N.primary},o))),ot.createElement(Ln,{flexDirection:"row",paddingLeft:1},i.map(c=>ot.createElement(Nt,{key:c.id,id:c.id})),a.map(c=>ot.createElement(Ct,{key:c.id,id:c.id}))))};import Cc from"chalk";import{Box as Gt,Text as Yr}from"ink";import Fe from"react";var Nc=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ss=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=T(t.id),a=R=>{let b=i.find(w=>w.title===R);return b?T(b.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},c=a("Tags").map(R=>I.getTag(R)).filter(R=>!!R),u=a("Assignees").map(R=>I.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),g=u.length*(2+m),x=c.map(R=>Fe.createElement(Gt,{key:R.id,paddingRight:m},Fe.createElement(Yr,{color:de(R.name)},"\u25A0"))),E=u.map(R=>Fe.createElement(Gt,{key:R.id,paddingRight:m},Fe.createElement(Yr,{color:Ht(R.name)},"@"+R.name.at(0)))),A=n?N.accent:o===f.MOVE?N.secondary:N.primary;return Fe.createElement(Gt,{borderBottom:!0,justifyContent:"space-between"},Fe.createElement(Gt,null,Fe.createElement(me,{isSelected:n,placeholder:Cc.dim.gray(r+1+" ")}),Fe.createElement(Yr,{wrap:"truncate",color:A},Nc(t.title,e-p-g-14))),Fe.createElement(Gt,null,x,E))};var Ic=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:c})=>{let{renderedChildrenIndex:u}=G(),m=u[e.id]??[],p=`${e.title} (${m.length})`,g=3,x=o?1:4,E=r-g-(o?2:1),A=Re.createElement(Xr,{borderStyle:"round",borderColor:N.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Re.createElement(me,{isSelected:t}),Re.createElement(Ec,{bold:!0,color:t?N.accent:N.primary},p," ",e.readonly?"\u{1F512}":"")),R=(b,w)=>{let U=i&&a===w;return o?Re.createElement(ss,{key:b.id,index:w,width:n,ticket:b,isSelected:U,mode:c}):Re.createElement(is,{key:b.id,width:n,ticket:b,isSelected:U})};return Re.createElement(Xr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?N.accent:N.secondary,paddingRight:1,paddingLeft:1,height:r},A,Re.createElement(Xr,{padding:o?1:0},m.length>0&&Re.createElement(Fn,{selectedIndex:a,height:E,itemHeight:x},m.map(R)),Re.createElement(me,{isSelected:i&&a===-1})))},as=Re.memo(Ic);import{Box as Zr,Text as Fc}from"ink";import Ke,{useEffect as eo,useMemo as ps}from"react";import it from"chalk";import ds from"string-width";import{decodeTime as bc}from"ulid";var Sc=(e,t)=>e+" ".repeat(Math.max(0,t-ds(e))),Rc=(e,t)=>" ".repeat(Math.max(0,t-ds(e)))+e,Ac=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),wc=e=>{switch(e.action){case"move.node":{let t=I.getNode(e.payload.parent);return`to ${t?it.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?it.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?it.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?it.hex(de(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?it.hex(de(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Tc=e=>{let t=Fi(bc(e));return it.gray(Rc(t,8))},Mc=12,Pc=e=>Sc(`${e}`,Mc),cs=e=>{let t=Tc(e.id),n=Pc(e.userName),r=Ac(e.action),o=wc(e),i=it.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=T(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:T(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=T(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>ls(1),navigateToPreviousItem:()=>ls(-1),navigateToNextContainer:()=>us(1),navigateToPreviousContainer:()=>us(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{S({currentNodeId:e.id,selectedIndex:t})}},ls=e=>{let t=v(),n=T(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},us=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=T(o.id),a=i.findIndex(x=>x.id===t.id);if(a<0)return;let c=i.at(a+e)??i.at(0);if(!c)return;let u=T(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),g=u.length?p:-1;D.navigate({currentNode:c,selectedIndex:g})};import{Box as On,Text as kc}from"ink";import Le from"react";var ms=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=G(),{title:o}=t,i=T(t.id).map(a=>{let c=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return I.getContributor(c)?.id;if(o==="Tags")return I.getTag(c)?.id}).filter(a=>!!a);return Le.createElement(On,{alignItems:"center",paddingTop:1},Le.createElement(On,{minWidth:12},Le.createElement(me,{isSelected:n}),Le.createElement(kc,{color:n?N.accent:N.secondary2},o,":")),Le.createElement(On,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,c)=>{let u=r.id===t.id&&c===e;return Le.createElement(On,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Le.createElement(me,{isSelected:u}),o==="Assignees"?Le.createElement(Ct,{isSelected:u,id:a}):o==="Tags"?Le.createElement(Nt,{isSelected:u,id:a}):null)})))};import{Box as Bn,Text as Jr}from"ink";import Oe,{useEffect as Dc}from"react";var Qr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:c}=G(),u=x=>String(x).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Dc(()=>{let x=[];return m.forEach((E,A)=>{let R=Pe(BigInt(A+1));if(!Ee(R))return;let b=ie.text({id:`${e}-${A}`,name:`Line ${A+1}`,parentNodeId:e,rank:R.value,props:{value:E},readonly:!0,isVirtual:!0}),w=I.createNode(b);Ee(w)&&x.push(w.value.id)}),()=>x.forEach(I.deleteNode)},[e,n]);let p="\u2029",g=m.map((x,E)=>{let A=c.id===e&&a===E;return Oe.createElement(Bn,{key:`${e}-${E}`},Oe.createElement(Jr,{color:A?N.primary:N.secondary2,dimColor:!A},`${E+1} `.padStart(5,"\xA0")),Oe.createElement(Jr,{backgroundColor:A?"gray":""},u(x.length?dn(x,i-10):p)))});return Oe.createElement(Bn,{flexDirection:"column",paddingTop:1},Oe.createElement(Bn,null,Oe.createElement(me,{isSelected:o}),Oe.createElement(Jr,{color:o?N.accent:N.secondary2},t)),Oe.createElement(Bn,{flexDirection:"row",borderStyle:"round",borderColor:N.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Oe.createElement(Fn,{scrollByOne:!0,children:g,height:r-2,selectedIndex:a,itemHeight:1})))};var Lc=e=>`${e}::log`,fs=e=>e==="Assignees"||e==="Tags",gs=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=G(),o=process.stdout.columns||120,i=ps(()=>Lc(e.id),[e.id]),a=ps(()=>[...e.log].reverse().map(cs).join(`
44
44
  `),[e.log]);eo(()=>{if(I.getNode(i))return;let w=Pe(et);if(d(w))return;let U={...ie.field({id:i,name:Y.HISTORY,parentNodeId:e.id,rank:w.value,props:{value:a},isVirtual:!0}),readonly:!0,childRenderAxis:"vertical"};return I.createNode(U),()=>{I.deleteNode(i)}},[i,e.id,a]),eo(()=>{let b=I.getNode(i);b&&b.props.value!==a&&I.updateNode({...b,props:{...b.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let c=r.id===e.id,u=r.id===i||r.parentNodeId===i;eo(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=T(e.id);if(u){let b=I.getNode(i),U=t-3;return Ke.createElement(Zr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},b?Ke.createElement(Qr,{id:b.id,label:"Event log",text:b.props.value??"",selected:!1,maxWidth:o,height:U}):null)}let p=m.reduce((b,w)=>fs(w.title)||w.id===i?b+1:b,0),g=2,x=p*1,A=t-3-x-g,R=(b,w)=>fs(b.title)?Ke.createElement(ms,{key:b.id,parent:b,selected:w,selectedIndex:n}):b.id===i?Ke.createElement(Zr,{key:b.id,paddingTop:1},Ke.createElement(me,{isSelected:w}),Ke.createElement(Fc,{backgroundColor:N.secondary,color:w?N.accent:N.primary}," History \u203A\u203A ")):b.title===Y.DESCRIPTION?Ke.createElement(Qr,{label:"Description (press e to edit)",key:b.id,id:b.id,text:b.props.value??"",selected:w,maxWidth:o,height:A}):null;return Ke.createElement(Zr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((b,w)=>R(b,c&&n===w)))};var Bc=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,g=u===P.TICKET?t:r.find(b=>b.context===P.TICKET),x=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),A=Math.min(E,x),R=i==="dense";return Un.createElement(Oc,{flexDirection:"row",height:a},p&&e.map((b,w)=>{let U=t.id===b.id,le=U?n:-1,ne=t.context===P.BOARD&&n===w;return Un.createElement(as,{key:b.id,height:a,width:A,swimlane:b,isSelected:ne,isDense:R,isFocused:U,listSelectedIndex:le,mode:o})}),m&&g&&Un.createElement(gs,{height:a,ticket:g}))},$n=Un.memo(Bc);import{render as Wc}from"ink";import{Writable as _c}from"node:stream";var qt=e=>String(e).padStart(2,"0"),jc=e=>{let t=e.getUTCFullYear(),n=qt(e.getUTCMonth()+1),r=qt(e.getUTCDate()),o=qt(e.getUTCHours()),i=qt(e.getUTCMinutes()),a=qt(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},Hc=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Kc=async(e,{width:t,height:n})=>{let r="",o=new _c({write(a,c,u){let m=Vc(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Wc(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),r},Vc=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ys=async()=>{let{viewMode:e}=L(),{currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),a=r.find(w=>w.context==="BOARD");if(!a)return s("No board found to export");let c=120,u=40,m=await Kc($c.createElement($n,{height:u,width:c,swimlanes:(i[a.id]??[]).filter(w=>w!==void 0&&lt(w)),currentNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return s("Failed to render board export");let p=$e(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let g=new Date,x=jc(g),E=`board_${Hc(a.title)}_${x}.md`,A=Eo(p.value);vs.mkdirSync(A,{recursive:!0});let R=Uc.join(A,E),b=`# Board - ${a.title}
45
45
  Date: ${g.toISOString()}
46
46
 
@@ -56,7 +56,7 @@ ${r.map(o=>o.message).join(`
56
56
 
57
57
  ${c}
58
58
  `,ro.writeFileSync(t,n,"utf8"),ue.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var fl=async e=>{let t=await F({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},j=(e,t)=>s(`[${e}] ${t}`),$s=async()=>{let e=bo(),t=await hn(process.cwd());if(d(t))return j(1,t.message);let n=t.value,r=await Dt(n);if(d(r))return j(2,r.message);if(r.value)return j(2,"Cannot initialize Epiq while a git operation is in progress");let o=await fl(n);if(d(o))return j(2.5,o.message);if(o.value)return j(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(dr(n))return j(4,"Epiq project already initialized");let i=_e();if(!i.isSetupDone||!i.userName)return j(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let a=L(),c=a.userName,u=a.userId;if(!u||!c)return j(5,"Missing Epiq user id");let m=e.stateBranch,p=await fn({repoRoot:n,branch:m});if(d(p))return j(6,p.message);let g=await Cn({repoRoot:n,stateBranchName:e.stateBranch});if(d(g))return j(6,g.message);let x=xn();if(d(x))return j(7,x.message);let E=Us.join(yn(),e.projectId),A=await Er({repoRoot:n,stateBranchRoot:E,stateBranchName:e.stateBranch});if(d(A))return j(8,A.message);let R=Us.join(E,".epiq");pl.mkdirSync(R,{recursive:!0});let b=Ps({userId:u,userName:c});if(d(b))return j(9,b.message);for(let sr of b.value){let No=mn({event:sr,rootDir:E});if(d(No))return j(9,No.message)}let w=await Nn({stateBranchRoot:E,eventFileName:Xe({userId:u,userName:c})});if(d(w))return j(10,w.message);let U=await mt({cwd:E,message:"[epiq:init]"});if(d(U))return j(10,U.message);let le=await Bs(n);if(d(le))return j(12,le.message);let ne=Ro({repoRoot:n,fileContents:e});if(d(ne))return j(13,ne.message);let Zt=await H.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(Zt))return j(14,Zt.message);let St=await H.commit({cwd:n,message:"[epiq:init-project]"});if(d(St))return j(14,St.message);let Rt=Ut({repoRoot:n,stateBranchRoot:E});if(d(Rt))return j(15,Rt.message);let q="Project initialized!",re=await Bt({repoRoot:n,stateBranchRoot:E});d(re)&&(q+=` Warn: [init:16] ${re.message}`);let ct=await H.push({cwd:n});d(ct)&&(q+=` Warn: [init:17] ${ct.message}`);let Co=Sn(b.value).filter(d);if(Co.length>0)return j(18,Co.map(sr=>sr.message).join(`
59
- `));let{rootNodeId:Da,nodes:Fa}=v();return D.navigate({currentNode:Fa[Da],selectedIndex:0}),S({hasProject:!0,mode:f.DEFAULT}),l(q,null)};import{ulid as vl}from"ulid";import{ulid as gl}from"ulid";var Ws=null,Ve=()=>structuredClone(Ws),Yt=e=>Ws=e,_s=()=>{let{currentNode:e,selectedIndex:t}=v(),r=T(e.id)[t];return r?l("Resolved selected child",r):s("Target node not found")};var js=({id:e,parentId:t,position:n={at:"end"}})=>{let r=K();if(d(r))return s("Unable to resolve user ID");let o=tt(t,e,n,r.value);return d(o)?o:l("Created pending move state",{id:gl(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},Hs=e=>{Yt(e);let t=Wt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function oo(e){let t=_s();if(d(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=O(o.id),a=i.findIndex(({id:m})=>m===n.id);if(a<0)return s("Current node not found among siblings");let c=i[a+e];if(!c)return s("Missing sibling node");let u=js({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Hs(u.value)}function io(e){let t=_s();if(d(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=O(n.id)[r+e];if(!i)return s("Missing sibling node");let a=js({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:Hs(a.value)}var Ks=()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=Q().commandMeta,n=()=>{let c=Ve();if(!c)return s("No pending move state");let u=c.payload.id;if(!v().nodes[u])return s("Moved node not found");let p=c.payload.parent,g=v().nodes[p];if(!g)return s("Move parent not found");let x=T(p).findIndex(E=>E.id===u);return x===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:g,selectedIndex:x}),l("Synchronized navigation to moved node",null))},r=c=>{if(d(c))return s(c.message);let u=n();return d(u)?s(u.message):l("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=T(o.id)[i];if(!a)return S({mode:f.DEFAULT}),s("No move target");if(t==="start"){if(a.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!a.parentNodeId)return s("Target has no parent");let c=O(a.parentNodeId),u=c.findIndex(({id:A})=>A===a.id);if(u===-1)return s("Target not found among siblings");let m=c[u-1],p=c[u+1],g=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},x=tt(a.parentNodeId,a.id,g,e.value);if(d(x))return x;Yt({id:vl(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:x.value},...e.value}),S({mode:f.MOVE});let E=n();return d(E)?s(E.message):l("Move initialized",null)}if(t==="next")return S({mode:f.MOVE}),r(io(1));if(t==="previous")return S({mode:f.MOVE}),r(io(-1));if(t==="to-next")return S({mode:f.MOVE}),r(oo(1));if(t==="to-previous")return S({mode:f.MOVE}),r(oo(-1));if(t==="confirm"){S({mode:f.DEFAULT});let c=Ve();if(!c)return s("No pending move to confirm");let u=_(c);if(d(u))return u;let m=n();return d(m)?s(m.message):(Yt(null),l("Moved item",null))}return t==="cancel"?(Yt(null),S({mode:f.DEFAULT}),l("Cancelling move",null)):s("Invalid move modifier")};import yl from"zod";var Vs=()=>{let e=Q().commandMeta.inputString,t=yl.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return s("Auto sync duration must be a number of at least 3000 ms");let n=at({autoSyncDebounceMs:t.data});return d(n)?n:(pe({autoSyncIntervalMs:t.data}),S({mode:f.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Gs=()=>{let e=Q().commandMeta.modifier;if(e!=="yes"&&e!=="no")return s("Invalid response");let t=To(e),n=at({autoSync:t});return d(n)?n:(pe({autoSync:t}),S({mode:f.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var qs=e=>Object.values(v().tags).find(t=>t.name===e),zs=e=>Object.values(v().contributors).find(t=>t.name===e),Ys=[{systemOnly:!0,intent:M.Move,mode:f.COMMAND_LINE,action:Ks},{intent:M.Delete,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];return r?_({id:V(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Filter,mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Q().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(c=>ae(y.FILTER).map(u=>u.split(n)[0]).includes(c))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return he(c=>({...c,filters:e==="clear"?[]:[...c.filters,a],mode:f.DEFAULT})),l("Viewing help",null)}},{intent:M.ViewHelp,mode:f.COMMAND_LINE,action:()=>(S({mode:f.HELP}),l("Viewing help",null))},{intent:M.CloseIssue,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!ye(r))return s("Cannot close in this context");let o=v().nodes[ke];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=tt(o.id,r.id,{at:"end"},e.value);if(d(i))return i;let a=_({id:V(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return d(a)?a:l("Issue closed",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.ReopenIssue,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):je(r.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=v().nodes[ke];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!ye(i))return s("Target node is not issue");let c=ks(i);if(!c)return s("Unable to resolve previous parent from issue history");if(c===a.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[c];if(!u)return s("Previous parent no longer exists");let m=tt(u.id,i.id,{at:"end"},e.value);if(d(m))return m;let p=_({id:V(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return d(p)?p:l("Issue reopened",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Init,mode:f.COMMAND_LINE,action:$s},{intent:M.NewItem,mode:f.COMMAND_LINE,action:(e,t)=>{let n=K();if(d(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=v(),a=c=>{let u=_(c);if(d(u))return u;let m=I.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=I.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:I.getSiblings(m.parentNodeId).findIndex(({id:g})=>g===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:c}=v(),u=I.getNode(c);if(!u)return s("Workspace not found");let m=gt(u.id,n.value);return d(m)?m:a({id:V(),action:"add.board",payload:{id:V(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let c=Se(r,"BOARD");if(d(c))return s("Unable to add swimlane in this context");let u=gt(c.value.id,n.value);return d(u)?u:a({id:V(),action:"add.swimlane",payload:{id:V(),name:t.inputString,parent:c.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let c=T(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&c?.context==="SWIMLANE"?c:(()=>{let b=Se(r,"SWIMLANE");return d(b)?null:b.value})();if(!u)return s("Unable to add issue in this context");let m=gt(u.id,n.value);if(d(m))return m;let p=Ms({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(d(p))return p;let g=p.value,x=Sn(g);if(x.some(b=>d(b)))return s("Issue create failed: "+x.filter(d).map(b=>b.message).filter(Boolean).join(", "));let E=x[0];if(!E||d(E))return s("Issue creation failed");let R=g.find(b=>b.action==="add.issue")?.payload.id;return R?(D.navigate({currentNode:u,selectedIndex:I.getSiblings(u.id).findIndex(({id:b})=>b===R)}),l("Issue created",null)):s("Unable to determine ticket id")}return l("Success",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Rename,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Ji();return o?_({id:V(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.UntagTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=qs(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=je(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let c=a.value,u=I.getFieldByTitle(c.id,"Tags");if(!u)return s("Unable to locate tags field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?_({id:V(),action:"untag.issue",payload:{id:m.id,target:c.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.TagTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=T(i.id)[o];if(!a)return s("Invalid tag target");let c=je(a.id,"TICKET");if(d(c))return s("Unable to tag issue in this context");let u=c.value,m=qs(r),p;if(m)p=m.id;else{let A=V(),R=_({id:V(),action:"create.tag",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(R))return R;p=R.value.result.id}let g=I.getFieldByTitle(u.id,"Tags");if(!g)return s("Unable to locate tags field");if(T(g.id).some(A=>A.props?.value===p))return s("Already tagged with that tag");let E=gt(g.id,e.value);return d(E)?E:_({id:V(),action:"tag.issue",payload:{id:V(),target:u.id,tagId:p,rank:E.value},...e.value})},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.AssignUserToTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=T(i.id)[o];if(!a)return s("Invalid assign target");let c=je(a.id,"TICKET");if(d(c))return s("Unable to assign issue in this context");let u=c.value,m=zs(r),p;if(m)p=m.id;else{let A=V(),R=_({id:V(),action:"create.contributor",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(R))return R;p=R.value.result.id}let g=I.getFieldByTitle(u.id,"Assignees");if(!g)return s("Unable to locate assignees field");if(T(g.id).some(A=>A.props?.value===p))return s("Assignee already assigned");let E=gt(g.id,e.value);return d(E)?E:_({id:V(),action:"assign.issue",payload:{id:V(),target:u.id,contributor:p,rank:E.value},...e.value})},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=zs(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=je(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let c=a.value,u=I.getFieldByTitle(c.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?_({id:V(),action:"unassign.issue",payload:{id:m.id,target:c.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Sync,mode:f.COMMAND_LINE,action:async()=>{if(v().syncStatus.status==="syncing")return s("Sync already in progress");let e=hs();$(()=>""),S({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=L();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=K();if(d(r)||!r.value)return s("Unable to resolve event log path");let o=Xe(r.value),i=await In({ownEventFileName:o});if(d(i))return S({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let a=be(process.cwd());if(d(a))return a;let c=Mt(a.value);if(d(c))return s(`Unable to load events. ${c.message}`);let u=Hn({eventLog:c.value,hasProject:!0});if(d(u))return s(`Unable to boot synced state. ${u.message}`);S({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:f.DEFAULT});let m=Cs(e);return d(m)?m:l("Synced",!0)}},{intent:M.Peek,mode:f.COMMAND_LINE,action:async()=>{let e=Se(v().breadCrumb,"BOARD");if(d(e))return e;let t=$e(process.cwd());if(d(t))throw new Error(t.message);let n=Mt(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=Q().commandMeta,i;if(o==="now"){let x=so();if(d(x))return x;let E=_t(r);return E.some(d)?s(E.map(A=>A.message).join(", ")):(S({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let x=v().eventLog.at(-2),E=Br(x);if(E===null)return s("No previous event to peek");i=E}else if(o==="next"){let x=v().unappliedEvents.at(0),E=Br(x);if(E===null)return s("No next event to peek");i=E}else{let x=wn(o);if(!x)return s("Invalid peek date");i=x.getTime()}let a=e.value.id,{appliedEvents:c,unappliedEvents:u}=$o(r,i),m=so();if(d(m))return m;let p=_t(c);if(p.some(d))return s(p.map(x=>x.message).join(", "));let g=v().nodes[a];return g?(D.navigate({currentNode:g,selectedIndex:0}),S({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),l("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:f.COMMAND_LINE,action:async()=>{let e=await ys();return d(e)?e:(S({mode:f.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,mode:f.COMMAND_LINE,action:async()=>(D.exit(),l("Exit successful",!0))},{intent:M.Edit,mode:f.COMMAND_LINE,action:(e,t)=>{if(t.modifier===He.DESCRIPTION)return Os();if(t.modifier===He.TITLE){let n=K();if(d(n))return s("Unable to resolve user ID");let{currentNode:r,selectedIndex:o}=v(),i=T(r.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let a=t.inputString.trim();return a?_({id:V(),action:"edit.title",payload:{id:i.id,name:a},...n.value}):s("Provide a new name")}return s("Unknown edit command")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Config,mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case X.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=L(),a=n||i,c=r??V();if(!a||!c)return s("Unable to resolve user name or id");let u=at({userName:a,userId:c,preferredEditor:o??""});return d(u)?u:(pe({userName:a,userId:c}),S({mode:f.DEFAULT}),l(`Username set to "${a}"`,null))}case X.EDITOR:{if(!n)return s("No editor provided");let r=at({preferredEditor:n});return d(r)?r:(pe({preferredEditor:n}),S({mode:f.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case X.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(pe({viewMode:n}),l(`View set to "${n}"`,null));case X.AUTOSYNC:return Gs();case X.SYNC_DEBOUNCE_MS:return Vs();default:return s("Unknown config command")}}}];var xl=new Set(["peek","filter","view-help"]),Ce=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=Q();if(!t)return s("No command to confirm");if(!e&&n===rt.Invalid)return s("Invalid command");let i=es(t);qi();let{readOnly:a}=v();if(a&&!xl.has(i))return Vt({status:Ue.Fail,message:"Command not available in readonly state",value:null});let c=Ys.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!c)return Vt({status:Ue.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return Vt({status:Ue.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Vt(u):(zi({addToHistory:!e}),c.onSuccess?.(),L().autoSync&&Ni(),u)};var Kn=[{intent:h.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move cancel"),Ce({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move start"),Ce({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:f.MOVE,action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move confirm"),Ce({isForceExecutedBySystem:!0}))}],Vn=[{intent:h.MovePreviousItem,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move previous"),Ce({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveNextItem,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move next"),Ce({isForceExecutedBySystem:!0})):s("No pending move")}],Xs=[{intent:h.MoveToNextContainer,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move to-next"),Ce({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveToPreviousContainer,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move to-previous"),Ce({isForceExecutedBySystem:!0})):s("No pending move")}];var Js={[P.WORKSPACE]:[...Kn,...Vn],[P.BOARD]:[...Kn,...Vn],[P.SWIMLANE]:[...Kn,...Vn,...Xs],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Qs=[{intent:h.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>`${y.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>`${y.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>""),l("Entering command line mode",null))},{intent:h.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=v();if(!O(e?.id??"")?.length){if(e?.title===Y.DESCRIPTION)return $(()=>y.EDIT+"description "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(e?.title===Y.ASSIGNEES)return $(()=>y.ASSIGN+" "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(e?.title===Y.TAGS)return $(()=>y.TAG+" "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(t.title===Y.DESCRIPTION&&e?.context==="TEXT")return $(()=>y.EDIT+"description "),S({mode:f.COMMAND_LINE}),l("Propose command",!0)}return D.enterChildNode(),l("Entering context",null)}},{intent:h.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:f.DEFAULT,action:()=>(D.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(D.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:f.DEFAULT,action:()=>(D.navigateToNextContainer(),l("Navigating to next container",null))},{intent:h.Edit,mode:f.DEFAULT,action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"edit"),Ce(),l("Fired command",!0))},{intent:h.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(pe({viewMode:"dense"}),l("View set",null))},{intent:h.SetViewWide,mode:f.DEFAULT,action:()=>(pe({viewMode:"wide"}),l("View set",null))}];var hl=500,Cl=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Zs=e=>{let t=Cl(e);t&&$(n=>(n+t).slice(0,hl))};var ea=[{intent:h.ViewHelp,mode:f.DEFAULT,action:()=>(S({mode:f.HELP}),l("Viewing help",null))},{intent:h.Exit,mode:f.HELP,action:()=>(S({mode:f.DEFAULT}),l("Exiting help",null))},{intent:h.Confirm,mode:f.COMMAND_LINE,action:()=>(Ce(),l("Executing command",null))},{intent:h.MoveCursorLeft,mode:f.COMMAND_LINE,action:()=>(Gr(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:f.COMMAND_LINE,action:()=>(Gr(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:f.COMMAND_LINE,action:()=>(qr("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:f.COMMAND_LINE,action:()=>(qr("right"),l("Moving cursor right of word",null))},{intent:h.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(S({mode:f.DEFAULT}),l("Exiting command line",null))},{intent:h.AutoCompleteCommand,mode:f.COMMAND_LINE,action:()=>($((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:f.COMMAND_LINE,action:(e,{sequence:t})=>(Zs(t??""),l("Capturing input",null))},{intent:h.EraseInput,mode:f.COMMAND_LINE,action:()=>(Vi(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:f.COMMAND_LINE,action:()=>(Gi(),l("Erasing input word",null))},{intent:h.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Yi(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Xi(),l("Getting next command from history",null))}];import Nl from"chalk";var Gn=": for command line",ta="q to exit",na=`${Nl.hex(N.accent)("m")} to confirm`,ao={[P.WORKSPACE]:[Gn],[P.BOARD]:[Gn],[P.BOARD+f.COMMAND_LINE]:[Gn],[P.SWIMLANE]:[Gn],[P.TICKET+f.HELP]:[ta],[P.SWIMLANE+f.HELP]:[ta],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+f.MOVE]:[na],[P.TICKET+f.MOVE]:[na]};var qn=e=>e.trim().toLocaleLowerCase(),El=(e,t)=>{let n=I.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Il=e=>{let{tags:t}=v(),n=I.getFieldByTitle(e,"Tags");return n?O(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},bl=e=>{let{contributors:t}=v(),n=I.getFieldByTitle(e,"Assignees");return n?O(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},ra=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return qn(e.title??"").includes(n);case"description":return qn(El(e.id,Y.DESCRIPTION)).includes(n);case"tag":return Il(e.id).map(qn).some(c=>c.includes(n));case"assignee":return bl(e.id).map(qn).some(c=>c.includes(n));default:return!0}};function oa(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var ia=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var zn,co,lo=new Set,sa=()=>{for(let e of lo)e()},Rl=e=>(lo.add(e),()=>lo.delete(e));function aa(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let c=o[t];if(!c)return s("Unable to derive state, currentNode not found");let u=oa(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,g=ao[p+n]??ao[p]??[],x=[...Qs,...Js[p]??[],...ea],E=ia(x),A=Al(o,i),R=A[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:c,breadCrumb:m,availableHints:g,availableActions:x,actionIndex:E,selectedNode:R,renderedChildrenIndex:A})}var v=()=>(zn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),zn);function jt(e){co=e;let t=be(process.cwd()),n=!1;if(!d(t)){let i=We(t.value);if(d(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:n},o=aa(r);return d(o)?o:(zn=o.value,sa(),l("State initialized",null))}function he(e){let t=v(),n=e(t),r=aa(n);return d(r)?s(r.message??"Unable to update state"):(zn=r.value,sa(),l("State updated",null))}var S=e=>he(t=>({...t,...e}));var G=()=>Sl(Rl,v,v),Al=(e,t)=>{let n={};for(let r of Object.values(e))ye(r)&&t.length>0&&!t.every(o=>ra(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,i)=>{let a=e[o.id],c=e[i.id];return!a||!c?0:a.rank.localeCompare(c.rank)});return n},T=e=>v()?.renderedChildrenIndex[e]??[],so=()=>co?jt(co):s("Cannot reset state: no initial workspace found");import{Box as Wl}from"ink";import po from"react";import Jt from"chalk";import{Box as uo,Text as da}from"ink";import Xt,{useEffect as wl,useMemo as Tl,useState as Ml}from"react";var ca=Jt.gray,Pl=Jt.inverse,kl=Jt.inverse.gray,Dl={hint:"",hints:[],overlap:0,remainder:""},ua=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},Fl=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=de(t);return{bg:r=>Jt.bgHex(n).black(r),bgCursor:r=>Jt.bgHex(n).inverse.black(r)}}return Wr(t)},Ll=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=ua({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,a=r.end+i;return e.slice(a,a+n.length)!==n?null:{start:a,end:a+n.length}},la=()=>({value:ce.value,cursorPosition:ce.cursorPosition,commandIsPending:ce.commandIsPending,autoCompletion:ce.commandMeta.autoCompletion??Dl,infoMessage:ce.commandMeta.infoMessage,validationStatus:ce.commandMeta.validity,command:ce.commandMeta.command,inputString:ce.commandMeta.inputString,modifier:ce.commandMeta.modifier}),Ol=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,ma=({width:e})=>{let[t,n]=Ml(la());wl(()=>{let g=()=>{let E=la();n(A=>Ol(A,E)?A:E)},x=Ki(g);return g(),()=>{x()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:c,command:u,modifier:m}=t,p=Tl(()=>{let g=Math.max(0,Math.min(o,r.length)),x=ua({value:r,command:u}),E=Ll({value:r,command:u,modifier:m}),A=u?Wr(u):null,R=Fl({command:u,modifier:m}),b=(q,re)=>{let ct=x&&re>=x.start&&re<x.end,en=E&&re>=E.start&&re<E.end;return ct&&A?A.fg(q):en&&R?R.bg(q):q},w=(q,re)=>{let ct=x&&re>=x.start&&re<x.end,en=E&&re>=E.start&&re<E.end;return ct&&A?A.fgCursor(q):en&&R?R.bgCursor(q):Pl(q)},U=r.slice(0,g),le=r[g]??" ",ne=g<r.length?r.slice(g+1):"",Zt=Array.from(U).map((q,re)=>b(q,re)).join(""),St=w(le,g),Rt=Array.from(ne).map((q,re)=>b(q,g+1+re)).join("");if(c.hint){let q=c.hint[c.overlap]??le;St=kl(q),Rt=ca(c.remainder.slice(1)+ne)}return ca(":")+Zt+St+Rt},[r,o,c,u,m]);return Xt.createElement(uo,{flexDirection:"column",justifyContent:"flex-start"},Xt.createElement(uo,{flexDirection:"column",paddingX:1,borderColor:N.secondary,borderStyle:"round",width:e},Xt.createElement(uo,null,Xt.createElement(da,null,p),i&&Xt.createElement(da,{wrap:"truncate",color:a?N.red:N.secondary2},` ${i} `))))};import pa from"chalk";import{Box as Bl,Text as mo}from"ink";import Yn from"react";var Ul=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),$l=(e,t)=>{let n=[],r=0;for(let o of e){let a=(n.length>0?" | ":"").length+o.length;if(r+a>t-4)break;n.push(o),r+=a}return n},fa=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=$l(t,e).join(" | "),o=pa.hex(N.secondary),i=pa.hex(N.secondary2),a=o(`\u256D${"\u2500".repeat(n)}\u256E`),c=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(Ul(` ${r} `,n))}${o("\u2502")}`;return Yn.createElement(Bl,{flexDirection:"column",width:e},Yn.createElement(mo,null,a),Yn.createElement(mo,null,u),Yn.createElement(mo,null,c))};var Xn=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let c=(r.length>0?" | ":"").length+i.length;if(o+c>e+2)break;r.push(i),o+=c}return po.createElement(Wl,null,t===f.COMMAND_LINE?po.createElement(ma,{width:e}):po.createElement(fa,{width:e,mode:t,availableHints:n}))};import{Box as It,Text as ga}from"ink";import Ge from"react";var va=({width:e})=>{let t=[...v().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),Ge.createElement(It,{flexDirection:"column",marginTop:3,borderColor:N.secondary,borderStyle:"round",width:e,minHeight:19},Ge.createElement(It,{flexDirection:"column",width:e},v().mode===f.HELP?t.map(([n,r],o)=>Ge.createElement(It,{paddingLeft:1,key:o,flexDirection:"row"},Ge.createElement(It,{key:o,flexDirection:"row",paddingBottom:o?0:1},Ge.createElement(It,{width:20,justifyContent:"flex-end"},Ge.createElement(ga,{color:o?N.accent:N.secondary},n)),Ge.createElement(It,{flexGrow:1,width:40,paddingLeft:2},Ge.createElement(ga,{color:o?N.primary:N.secondary},r))))):null))};import _l from"chalk";import{Box as Jn,Text as qe}from"ink";import Ne from"react";var ya=({width:e,height:t})=>Ne.createElement(Jn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},Ne.createElement(qe,{color:N.accent,bold:!0},"Initialize project"),Ne.createElement(qe,null,`This folder is not an ${_l.hex(N.accent)("epiq")} project yet.`),Ne.createElement(qe,{color:N.primary},"To start tracking issues here, we need to initialize a new"," ",Ne.createElement(qe,{color:N.primary,backgroundColor:N.secondary}," .epiq/project.json ")," ","file in this repository."),Ne.createElement(Jn,{marginTop:1,flexDirection:"column"},Ne.createElement(Jn,null,Ne.createElement(qe,{color:N.accent}," "),Ne.createElement(qe,{color:N.primary},"Type "),Ne.createElement(qe,{backgroundColor:N.secondary}," :init "))),Ne.createElement(Jn,{marginTop:1},Ne.createElement(qe,{color:N.secondary2},"(This will create the local epiq project files)")));import{Box as Qn,Text as Ae}from"ink";import Z from"react";var jl=({isDone:e,command:t,value:n})=>Z.createElement(Qn,null,Z.createElement(Ae,{color:N.accent,dimColor:e},e?" \u2714 ":" "),Z.createElement(Ae,{dimColor:e},"Type "),Z.createElement(Ae,{backgroundColor:N.secondary,dimColor:e}," "+t+" "),n!==void 0&&Z.createElement(Z.Fragment,null,Z.createElement(Ae,{dimColor:e}," "),Z.createElement(Ae,{color:N.secondary,dimColor:e},"<"+n+">"))),Hl=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function fo({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:a,isSetAutoSync:c}=_e(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:i,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:a,message:"Almost there. Configure auto sync."}],m=u.findIndex(g=>!g.done),p=m===-1?void 0:u[m];return Z.createElement(Qn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},Z.createElement(Ae,{color:N.accent,bold:!0},"Welcome! \u{1F539}"),Z.createElement(Ae,null,"Lets get you started - its a breeze."),Z.createElement(Ae,{color:N.secondary2},"And remember, you can always get help with"," ",Z.createElement(Ae,{color:N.accent},":help"),"."),p&&Z.createElement(Ae,{color:N.secondary2},p.message),Z.createElement(Qn,{flexDirection:"column"},u.map((g,x)=>m===-1||x<=m?Z.createElement(Qn,{key:g.key,marginBottom:1},Z.createElement(jl,{isDone:g.done,command:g.command,value:g.done?Hl(g.value):void 0})):null)))}import Sa from"chalk";import{Box as er,Text as ze}from"ink";import ee from"react";import{Box as go,Text as Kl}from"ink";import bt from"react";var Vl=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",xa=({width:e})=>{let{viewMode:t}=L(),{breadCrumb:n,currentNode:r,selectedIndex:o}=v(),i=O(r.id)[o],a=je(i?.id??r.id,"TICKET"),c=Ee(a)?a.value:void 0,u=c?.id?O(c.id):[],m=R=>{let b=u.find(w=>w.title===R);return b?O(b.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},p=m("Tags"),g=m("Assignees"),x=c?.parentNodeId?!kr(r.id,c?.parentNodeId)&&t==="dense":!1,E=n.map((R,b)=>{let w=b===n.length-1,U=O(R.id),le=w?U?.[o]?.title:void 0;return`${b?" / ":""}${R.title??""}${le?` \u25B8 ${le}`:""}`}).join(""),A=Vl(E,e);return bt.createElement(go,null,bt.createElement(Kl,{color:N.secondary2},A),x?p.map(R=>bt.createElement(go,{key:R,paddingLeft:2},bt.createElement(Nt,{id:R}))):null,x?g.map(R=>bt.createElement(go,{key:R,paddingLeft:2},bt.createElement(Ct,{id:R}))):null)};import{Box as Gl,Text as ha}from"ink";import Zn from"react";var ql=({filters:e})=>Zn.createElement(Gl,{columnGap:1},Zn.createElement(ha,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Zn.createElement(ha,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ca=Zn.memo(ql);var Na="0.5.1";import Ea from"chalk";import{Text as zl}from"ink";import Yl,{useEffect as Xl,useState as Jl}from"react";var Ql=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Ia=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Zl=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},eu=(e,t,n)=>{let r=Ia(e),o=Ia(t);return Zl({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},tu=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],a=e[Math.min(r+1,e.length-1)];return eu(i,a,o)};function ba({syncStatus:e}){let[t,n]=Jl(0);Xl(()=>{if(e.status!=="syncing"){n(0);return}let a=setInterval(()=>{n(c=>c+1)},50);return()=>clearInterval(a)},[e.status]);let r={synced:"synced ",outOfSync:"unsynced",syncing:"syncing "},i={synced:N.secondary2,outOfSync:N.yellow,syncing:tu(Ql,(Math.sin(t*.12)+1)/2)??""}[e.status];return Yl.createElement(zl,null,Ea.hex(i)("\u25CF")+Ea.dim(` ${r[e.status].padEnd(2)} `))}function tr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o,syncStatus:i}=G(),{userName:a,preferredEditor:c}=L(),u=56,m=process.stdout.columns-u-8,p=r.at(-1)?.id,g=Mn(p??""),x=Ee(g)?Li(g.value):"INVALID DATE";return ee.createElement(er,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?ee.createElement(ze,null," "):ee.createElement(er,{paddingLeft:1},e.length>0?ee.createElement(Ca,{filters:e}):ee.createElement(xa,{width:m})),n==="live"?ee.createElement(er,{columnGap:1,paddingRight:2,"max-width":u,overflow:"hidden",justifyContent:"flex-end"},ee.createElement(ba,{syncStatus:i}),ee.createElement(ze,{dimColor:!0,color:N.secondary2},Na+" "),ee.createElement(Ra,{icon:"@",value:a}),ee.createElement(Ra,{icon:"\u276F",value:c})):"",n==="peek"?ee.createElement(er,{paddingLeft:1},ee.createElement(ze,{backgroundColor:N.yellow}," Readonly "),ee.createElement(ze,{color:N.yellow}," "+o.length+" edits ago at "),ee.createElement(ze,{backgroundColor:N.yellow,color:N.accent}," "+x+" "),ee.createElement(ze,{color:N.yellow},". Resume with "),ee.createElement(ze,{backgroundColor:N.yellow}," :peek now ")):"")}function Ra({icon:e,value:t}){return ee.createElement(ze,null,Sa.dim(e)+Sa.hex(N.accent)(` ${t??"-"} `))}import{Box as nu,Text as ru}from"ink";import Qt from"react";import{Box as nr,Text as vo}from"ink";import Ye from"react";function yo(){let e=G(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?T(t?.id):[];return Ye.createElement(nr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:N.secondary,width:i},Ye.createElement(nr,{padding:1,paddingTop:0,paddingBottom:0},Ye.createElement(vo,null,"Select a board:")),Ye.createElement(nr,{padding:1,flexDirection:"column"},a.map((c,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,g=T(c.id).flatMap(({id:x})=>O(x)).length;return Ye.createElement(nr,{key:c.id??u},Ye.createElement(vo,{color:m?N.accent:N.secondary2},Ye.createElement(me,{isSelected:m})),Ye.createElement(vo,{color:m?N.accent:N.secondary2},c.title," (",g," issues)",c.readonly?" \u{1F512}":""))})))}var ou=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:c}=G(),u=n.find(({context:x})=>x==="BOARD"),g=i-1-3;return Qt.createElement(nu,{flexDirection:"row"},e.context==="WORKSPACE"?Qt.createElement(yo,null):u?Qt.createElement($n,{height:g,width:a,swimlanes:(c[u.id]??[]).filter(x=>x!==void 0&&lt(x)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Qt.createElement(ru,null))},Aa=Qt.memo(ou);function xo({width:e,height:t}){let n=G(),r=n.filters;if(n.mode===f.HELP)return te.createElement(dt,{flexDirection:"column"},te.createElement(va,{width:e}));let{isSetupDone:o}=_e(),i=!o,a=o&&!n.hasProject;if(i)return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{hideBreadCrumb:!0,filters:r}),te.createElement(fo,{height:t,width:e})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(a)return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{hideBreadCrumb:!0,filters:r}),te.createElement(ya,{height:t,width:e})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));let c=Se(v().breadCrumb??[],"BOARD");if(Ee(c)){let u=c.value.id,m=T(u).length,p=3,g=Math.floor(e/p),x=Math.floor(e/Math.max(m,1));e=Math.min(x,g)*Math.max(m,p)}return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{filters:r}),te.createElement(Aa,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:L().viewMode??"dense",mode:n.mode})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import iu from"readline";var rr,or,we,su=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),wa=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Zi(e,n);if(!o||r&&!su.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},au=()=>async function(t,n){n.name!=="escape"&&(we&&(clearTimeout(we),we=void 0),await wa(n))},du=()=>async function(t){if(t.length===1&&t[0]===27){we&&clearTimeout(we),we=setTimeout(()=>{wa({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),we=void 0},25);return}we&&(clearTimeout(we),we=void 0)};function Ta(){rr&&process.stdin.removeListener("keypress",rr),or&&process.stdin.removeListener("data",or),rr=au(),or=du(),iu.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",or),process.stdin.on("keypress",rr)}lu(`${ho.bold("Epiq CLI")}
59
+ `));let{rootNodeId:Da,nodes:Fa}=v();return D.navigate({currentNode:Fa[Da],selectedIndex:0}),S({hasProject:!0,mode:f.DEFAULT}),l(q,null)};import{ulid as vl}from"ulid";import{ulid as gl}from"ulid";var Ws=null,Ve=()=>structuredClone(Ws),Yt=e=>Ws=e,_s=()=>{let{currentNode:e,selectedIndex:t}=v(),r=T(e.id)[t];return r?l("Resolved selected child",r):s("Target node not found")};var js=({id:e,parentId:t,position:n={at:"end"}})=>{let r=K();if(d(r))return s("Unable to resolve user ID");let o=tt(t,e,n,r.value);return d(o)?o:l("Created pending move state",{id:gl(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},Hs=e=>{Yt(e);let t=Wt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function oo(e){let t=_s();if(d(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=O(o.id),a=i.findIndex(({id:m})=>m===n.id);if(a<0)return s("Current node not found among siblings");let c=i[a+e];if(!c)return s("Missing sibling node");let u=js({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Hs(u.value)}function io(e){let t=_s();if(d(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=O(n.id)[r+e];if(!i)return s("Missing sibling node");let a=js({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:Hs(a.value)}var Ks=()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=Q().commandMeta,n=()=>{let c=Ve();if(!c)return s("No pending move state");let u=c.payload.id;if(!v().nodes[u])return s("Moved node not found");let p=c.payload.parent,g=v().nodes[p];if(!g)return s("Move parent not found");let x=T(p).findIndex(E=>E.id===u);return x===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:g,selectedIndex:x}),l("Synchronized navigation to moved node",null))},r=c=>{if(d(c))return s(c.message);let u=n();return d(u)?s(u.message):l("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=T(o.id)[i];if(!a)return S({mode:f.DEFAULT}),s("No move target");if(t==="start"){if(a.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!a.parentNodeId)return s("Target has no parent");let c=O(a.parentNodeId),u=c.findIndex(({id:A})=>A===a.id);if(u===-1)return s("Target not found among siblings");let m=c[u-1],p=c[u+1],g=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},x=tt(a.parentNodeId,a.id,g,e.value);if(d(x))return x;Yt({id:vl(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:x.value},...e.value}),S({mode:f.MOVE});let E=n();return d(E)?s(E.message):l("Move initialized",null)}if(t==="next")return S({mode:f.MOVE}),r(io(1));if(t==="previous")return S({mode:f.MOVE}),r(io(-1));if(t==="to-next")return S({mode:f.MOVE}),r(oo(1));if(t==="to-previous")return S({mode:f.MOVE}),r(oo(-1));if(t==="confirm"){S({mode:f.DEFAULT});let c=Ve();if(!c)return s("No pending move to confirm");let u=_(c);if(d(u))return u;let m=n();return d(m)?s(m.message):(Yt(null),l("Moved item",null))}return t==="cancel"?(Yt(null),S({mode:f.DEFAULT}),l("Cancelling move",null)):s("Invalid move modifier")};import yl from"zod";var Vs=()=>{let e=Q().commandMeta.inputString,t=yl.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return s("Auto sync duration must be a number of at least 3000 ms");let n=at({autoSyncDebounceMs:t.data});return d(n)?n:(pe({autoSyncIntervalMs:t.data}),S({mode:f.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Gs=()=>{let e=Q().commandMeta.inputString.trim();if(e!=="yes"&&e!=="no")return s("Invalid response");let t=To(e),n=at({autoSync:t});return d(n)?n:(pe({autoSync:t}),S({mode:f.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var qs=e=>Object.values(v().tags).find(t=>t.name===e),zs=e=>Object.values(v().contributors).find(t=>t.name===e),Ys=[{systemOnly:!0,intent:M.Move,mode:f.COMMAND_LINE,action:Ks},{intent:M.Delete,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];return r?_({id:V(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Filter,mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Q().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(c=>ae(y.FILTER).map(u=>u.split(n)[0]).includes(c))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return he(c=>({...c,filters:e==="clear"?[]:[...c.filters,a],mode:f.DEFAULT})),l("Viewing help",null)}},{intent:M.ViewHelp,mode:f.COMMAND_LINE,action:()=>(S({mode:f.HELP}),l("Viewing help",null))},{intent:M.CloseIssue,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!ye(r))return s("Cannot close in this context");let o=v().nodes[ke];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=tt(o.id,r.id,{at:"end"},e.value);if(d(i))return i;let a=_({id:V(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return d(a)?a:l("Issue closed",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.ReopenIssue,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):je(r.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=v().nodes[ke];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!ye(i))return s("Target node is not issue");let c=ks(i);if(!c)return s("Unable to resolve previous parent from issue history");if(c===a.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[c];if(!u)return s("Previous parent no longer exists");let m=tt(u.id,i.id,{at:"end"},e.value);if(d(m))return m;let p=_({id:V(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return d(p)?p:l("Issue reopened",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Init,mode:f.COMMAND_LINE,action:$s},{intent:M.NewItem,mode:f.COMMAND_LINE,action:(e,t)=>{let n=K();if(d(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=v(),a=c=>{let u=_(c);if(d(u))return u;let m=I.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=I.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:I.getSiblings(m.parentNodeId).findIndex(({id:g})=>g===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:c}=v(),u=I.getNode(c);if(!u)return s("Workspace not found");let m=gt(u.id,n.value);return d(m)?m:a({id:V(),action:"add.board",payload:{id:V(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let c=Se(r,"BOARD");if(d(c))return s("Unable to add swimlane in this context");let u=gt(c.value.id,n.value);return d(u)?u:a({id:V(),action:"add.swimlane",payload:{id:V(),name:t.inputString,parent:c.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let c=T(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&c?.context==="SWIMLANE"?c:(()=>{let b=Se(r,"SWIMLANE");return d(b)?null:b.value})();if(!u)return s("Unable to add issue in this context");let m=gt(u.id,n.value);if(d(m))return m;let p=Ms({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(d(p))return p;let g=p.value,x=Sn(g);if(x.some(b=>d(b)))return s("Issue create failed: "+x.filter(d).map(b=>b.message).filter(Boolean).join(", "));let E=x[0];if(!E||d(E))return s("Issue creation failed");let R=g.find(b=>b.action==="add.issue")?.payload.id;return R?(D.navigate({currentNode:u,selectedIndex:I.getSiblings(u.id).findIndex(({id:b})=>b===R)}),l("Issue created",null)):s("Unable to determine ticket id")}return l("Success",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Rename,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Ji();return o?_({id:V(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.UntagTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=qs(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=je(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let c=a.value,u=I.getFieldByTitle(c.id,"Tags");if(!u)return s("Unable to locate tags field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?_({id:V(),action:"untag.issue",payload:{id:m.id,target:c.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.TagTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=T(i.id)[o];if(!a)return s("Invalid tag target");let c=je(a.id,"TICKET");if(d(c))return s("Unable to tag issue in this context");let u=c.value,m=qs(r),p;if(m)p=m.id;else{let A=V(),R=_({id:V(),action:"create.tag",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(R))return R;p=R.value.result.id}let g=I.getFieldByTitle(u.id,"Tags");if(!g)return s("Unable to locate tags field");if(T(g.id).some(A=>A.props?.value===p))return s("Already tagged with that tag");let E=gt(g.id,e.value);return d(E)?E:_({id:V(),action:"tag.issue",payload:{id:V(),target:u.id,tagId:p,rank:E.value},...e.value})},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.AssignUserToTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=T(i.id)[o];if(!a)return s("Invalid assign target");let c=je(a.id,"TICKET");if(d(c))return s("Unable to assign issue in this context");let u=c.value,m=zs(r),p;if(m)p=m.id;else{let A=V(),R=_({id:V(),action:"create.contributor",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(R))return R;p=R.value.result.id}let g=I.getFieldByTitle(u.id,"Assignees");if(!g)return s("Unable to locate assignees field");if(T(g.id).some(A=>A.props?.value===p))return s("Assignee already assigned");let E=gt(g.id,e.value);return d(E)?E:_({id:V(),action:"assign.issue",payload:{id:V(),target:u.id,contributor:p,rank:E.value},...e.value})},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=zs(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=je(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let c=a.value,u=I.getFieldByTitle(c.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?_({id:V(),action:"unassign.issue",payload:{id:m.id,target:c.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Sync,mode:f.COMMAND_LINE,action:async()=>{if(v().syncStatus.status==="syncing")return s("Sync already in progress");let e=hs();$(()=>""),S({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=L();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=K();if(d(r)||!r.value)return s("Unable to resolve event log path");let o=Xe(r.value),i=await In({ownEventFileName:o});if(d(i))return S({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let a=be(process.cwd());if(d(a))return a;let c=Mt(a.value);if(d(c))return s(`Unable to load events. ${c.message}`);let u=Hn({eventLog:c.value,hasProject:!0});if(d(u))return s(`Unable to boot synced state. ${u.message}`);S({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:f.DEFAULT});let m=Cs(e);return d(m)?m:l("Synced",!0)}},{intent:M.Peek,mode:f.COMMAND_LINE,action:async()=>{let e=Se(v().breadCrumb,"BOARD");if(d(e))return e;let t=$e(process.cwd());if(d(t))throw new Error(t.message);let n=Mt(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=Q().commandMeta,i;if(o==="now"){let x=so();if(d(x))return x;let E=_t(r);return E.some(d)?s(E.map(A=>A.message).join(", ")):(S({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let x=v().eventLog.at(-2),E=Br(x);if(E===null)return s("No previous event to peek");i=E}else if(o==="next"){let x=v().unappliedEvents.at(0),E=Br(x);if(E===null)return s("No next event to peek");i=E}else{let x=wn(o);if(!x)return s("Invalid peek date");i=x.getTime()}let a=e.value.id,{appliedEvents:c,unappliedEvents:u}=$o(r,i),m=so();if(d(m))return m;let p=_t(c);if(p.some(d))return s(p.map(x=>x.message).join(", "));let g=v().nodes[a];return g?(D.navigate({currentNode:g,selectedIndex:0}),S({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),l("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:f.COMMAND_LINE,action:async()=>{let e=await ys();return d(e)?e:(S({mode:f.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,mode:f.COMMAND_LINE,action:async()=>(D.exit(),l("Exit successful",!0))},{intent:M.Edit,mode:f.COMMAND_LINE,action:(e,t)=>{if(t.modifier===He.DESCRIPTION)return Os();if(t.modifier===He.TITLE){let n=K();if(d(n))return s("Unable to resolve user ID");let{currentNode:r,selectedIndex:o}=v(),i=T(r.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let a=t.inputString.trim();return a?_({id:V(),action:"edit.title",payload:{id:i.id,name:a},...n.value}):s("Provide a new name")}return s("Unknown edit command")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Config,mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case X.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=L(),a=n||i,c=r??V();if(!a||!c)return s("Unable to resolve user name or id");let u=at({userName:a,userId:c,preferredEditor:o??""});return d(u)?u:(pe({userName:a,userId:c}),S({mode:f.DEFAULT}),l(`Username set to "${a}"`,null))}case X.EDITOR:{if(!n)return s("No editor provided");let r=at({preferredEditor:n});return d(r)?r:(pe({preferredEditor:n}),S({mode:f.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case X.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(pe({viewMode:n}),l(`View set to "${n}"`,null));case X.AUTOSYNC:return Gs();case X.SYNC_DEBOUNCE_MS:return Vs();default:return s("Unknown config command")}}}];var xl=new Set(["peek","filter","view-help"]),Ce=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=Q();if(!t)return s("No command to confirm");if(!e&&n===rt.Invalid)return s("Invalid command");let i=es(t);qi();let{readOnly:a}=v();if(a&&!xl.has(i))return Vt({status:Ue.Fail,message:"Command not available in readonly state",value:null});let c=Ys.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!c)return Vt({status:Ue.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return Vt({status:Ue.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Vt(u):(zi({addToHistory:!e}),c.onSuccess?.(),L().autoSync&&Ni(),u)};var Kn=[{intent:h.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move cancel"),Ce({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move start"),Ce({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:f.MOVE,action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move confirm"),Ce({isForceExecutedBySystem:!0}))}],Vn=[{intent:h.MovePreviousItem,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move previous"),Ce({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveNextItem,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move next"),Ce({isForceExecutedBySystem:!0})):s("No pending move")}],Xs=[{intent:h.MoveToNextContainer,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move to-next"),Ce({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveToPreviousContainer,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move to-previous"),Ce({isForceExecutedBySystem:!0})):s("No pending move")}];var Js={[P.WORKSPACE]:[...Kn,...Vn],[P.BOARD]:[...Kn,...Vn],[P.SWIMLANE]:[...Kn,...Vn,...Xs],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Qs=[{intent:h.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>`${y.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>`${y.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>""),l("Entering command line mode",null))},{intent:h.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=v();if(!O(e?.id??"")?.length){if(e?.title===Y.DESCRIPTION)return $(()=>y.EDIT+"description "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(e?.title===Y.ASSIGNEES)return $(()=>y.ASSIGN+" "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(e?.title===Y.TAGS)return $(()=>y.TAG+" "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(t.title===Y.DESCRIPTION&&e?.context==="TEXT")return $(()=>y.EDIT+"description "),S({mode:f.COMMAND_LINE}),l("Propose command",!0)}return D.enterChildNode(),l("Entering context",null)}},{intent:h.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:f.DEFAULT,action:()=>(D.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(D.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:f.DEFAULT,action:()=>(D.navigateToNextContainer(),l("Navigating to next container",null))},{intent:h.Edit,mode:f.DEFAULT,action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"edit"),Ce(),l("Fired command",!0))},{intent:h.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(pe({viewMode:"dense"}),l("View set",null))},{intent:h.SetViewWide,mode:f.DEFAULT,action:()=>(pe({viewMode:"wide"}),l("View set",null))}];var hl=500,Cl=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Zs=e=>{let t=Cl(e);t&&$(n=>(n+t).slice(0,hl))};var ea=[{intent:h.ViewHelp,mode:f.DEFAULT,action:()=>(S({mode:f.HELP}),l("Viewing help",null))},{intent:h.Exit,mode:f.HELP,action:()=>(S({mode:f.DEFAULT}),l("Exiting help",null))},{intent:h.Confirm,mode:f.COMMAND_LINE,action:()=>(Ce(),l("Executing command",null))},{intent:h.MoveCursorLeft,mode:f.COMMAND_LINE,action:()=>(Gr(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:f.COMMAND_LINE,action:()=>(Gr(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:f.COMMAND_LINE,action:()=>(qr("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:f.COMMAND_LINE,action:()=>(qr("right"),l("Moving cursor right of word",null))},{intent:h.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(S({mode:f.DEFAULT}),l("Exiting command line",null))},{intent:h.AutoCompleteCommand,mode:f.COMMAND_LINE,action:()=>($((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:f.COMMAND_LINE,action:(e,{sequence:t})=>(Zs(t??""),l("Capturing input",null))},{intent:h.EraseInput,mode:f.COMMAND_LINE,action:()=>(Vi(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:f.COMMAND_LINE,action:()=>(Gi(),l("Erasing input word",null))},{intent:h.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Yi(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Xi(),l("Getting next command from history",null))}];import Nl from"chalk";var Gn=": for command line",ta="q to exit",na=`${Nl.hex(N.accent)("m")} to confirm`,ao={[P.WORKSPACE]:[Gn],[P.BOARD]:[Gn],[P.BOARD+f.COMMAND_LINE]:[Gn],[P.SWIMLANE]:[Gn],[P.TICKET+f.HELP]:[ta],[P.SWIMLANE+f.HELP]:[ta],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+f.MOVE]:[na],[P.TICKET+f.MOVE]:[na]};var qn=e=>e.trim().toLocaleLowerCase(),El=(e,t)=>{let n=I.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Il=e=>{let{tags:t}=v(),n=I.getFieldByTitle(e,"Tags");return n?O(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},bl=e=>{let{contributors:t}=v(),n=I.getFieldByTitle(e,"Assignees");return n?O(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},ra=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return qn(e.title??"").includes(n);case"description":return qn(El(e.id,Y.DESCRIPTION)).includes(n);case"tag":return Il(e.id).map(qn).some(c=>c.includes(n));case"assignee":return bl(e.id).map(qn).some(c=>c.includes(n));default:return!0}};function oa(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var ia=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var zn,co,lo=new Set,sa=()=>{for(let e of lo)e()},Rl=e=>(lo.add(e),()=>lo.delete(e));function aa(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let c=o[t];if(!c)return s("Unable to derive state, currentNode not found");let u=oa(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,g=ao[p+n]??ao[p]??[],x=[...Qs,...Js[p]??[],...ea],E=ia(x),A=Al(o,i),R=A[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:c,breadCrumb:m,availableHints:g,availableActions:x,actionIndex:E,selectedNode:R,renderedChildrenIndex:A})}var v=()=>(zn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),zn);function jt(e){co=e;let t=be(process.cwd()),n=!1;if(!d(t)){let i=We(t.value);if(d(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:n},o=aa(r);return d(o)?o:(zn=o.value,sa(),l("State initialized",null))}function he(e){let t=v(),n=e(t),r=aa(n);return d(r)?s(r.message??"Unable to update state"):(zn=r.value,sa(),l("State updated",null))}var S=e=>he(t=>({...t,...e}));var G=()=>Sl(Rl,v,v),Al=(e,t)=>{let n={};for(let r of Object.values(e))ye(r)&&t.length>0&&!t.every(o=>ra(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,i)=>{let a=e[o.id],c=e[i.id];return!a||!c?0:a.rank.localeCompare(c.rank)});return n},T=e=>v()?.renderedChildrenIndex[e]??[],so=()=>co?jt(co):s("Cannot reset state: no initial workspace found");import{Box as Wl}from"ink";import po from"react";import Jt from"chalk";import{Box as uo,Text as da}from"ink";import Xt,{useEffect as wl,useMemo as Tl,useState as Ml}from"react";var ca=Jt.gray,Pl=Jt.inverse,kl=Jt.inverse.gray,Dl={hint:"",hints:[],overlap:0,remainder:""},ua=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},Fl=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=de(t);return{bg:r=>Jt.bgHex(n).black(r),bgCursor:r=>Jt.bgHex(n).inverse.black(r)}}return Wr(t)},Ll=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=ua({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,a=r.end+i;return e.slice(a,a+n.length)!==n?null:{start:a,end:a+n.length}},la=()=>({value:ce.value,cursorPosition:ce.cursorPosition,commandIsPending:ce.commandIsPending,autoCompletion:ce.commandMeta.autoCompletion??Dl,infoMessage:ce.commandMeta.infoMessage,validationStatus:ce.commandMeta.validity,command:ce.commandMeta.command,inputString:ce.commandMeta.inputString,modifier:ce.commandMeta.modifier}),Ol=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,ma=({width:e})=>{let[t,n]=Ml(la());wl(()=>{let g=()=>{let E=la();n(A=>Ol(A,E)?A:E)},x=Ki(g);return g(),()=>{x()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:c,command:u,modifier:m}=t,p=Tl(()=>{let g=Math.max(0,Math.min(o,r.length)),x=ua({value:r,command:u}),E=Ll({value:r,command:u,modifier:m}),A=u?Wr(u):null,R=Fl({command:u,modifier:m}),b=(q,re)=>{let ct=x&&re>=x.start&&re<x.end,en=E&&re>=E.start&&re<E.end;return ct&&A?A.fg(q):en&&R?R.bg(q):q},w=(q,re)=>{let ct=x&&re>=x.start&&re<x.end,en=E&&re>=E.start&&re<E.end;return ct&&A?A.fgCursor(q):en&&R?R.bgCursor(q):Pl(q)},U=r.slice(0,g),le=r[g]??" ",ne=g<r.length?r.slice(g+1):"",Zt=Array.from(U).map((q,re)=>b(q,re)).join(""),St=w(le,g),Rt=Array.from(ne).map((q,re)=>b(q,g+1+re)).join("");if(c.hint){let q=c.hint[c.overlap]??le;St=kl(q),Rt=ca(c.remainder.slice(1)+ne)}return ca(":")+Zt+St+Rt},[r,o,c,u,m]);return Xt.createElement(uo,{flexDirection:"column",justifyContent:"flex-start"},Xt.createElement(uo,{flexDirection:"column",paddingX:1,borderColor:N.secondary,borderStyle:"round",width:e},Xt.createElement(uo,null,Xt.createElement(da,null,p),i&&Xt.createElement(da,{wrap:"truncate",color:a?N.red:N.secondary2},` ${i} `))))};import pa from"chalk";import{Box as Bl,Text as mo}from"ink";import Yn from"react";var Ul=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),$l=(e,t)=>{let n=[],r=0;for(let o of e){let a=(n.length>0?" | ":"").length+o.length;if(r+a>t-4)break;n.push(o),r+=a}return n},fa=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=$l(t,e).join(" | "),o=pa.hex(N.secondary),i=pa.hex(N.secondary2),a=o(`\u256D${"\u2500".repeat(n)}\u256E`),c=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(Ul(` ${r} `,n))}${o("\u2502")}`;return Yn.createElement(Bl,{flexDirection:"column",width:e},Yn.createElement(mo,null,a),Yn.createElement(mo,null,u),Yn.createElement(mo,null,c))};var Xn=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let c=(r.length>0?" | ":"").length+i.length;if(o+c>e+2)break;r.push(i),o+=c}return po.createElement(Wl,null,t===f.COMMAND_LINE?po.createElement(ma,{width:e}):po.createElement(fa,{width:e,mode:t,availableHints:n}))};import{Box as It,Text as ga}from"ink";import Ge from"react";var va=({width:e})=>{let t=[...v().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),Ge.createElement(It,{flexDirection:"column",marginTop:3,borderColor:N.secondary,borderStyle:"round",width:e,minHeight:19},Ge.createElement(It,{flexDirection:"column",width:e},v().mode===f.HELP?t.map(([n,r],o)=>Ge.createElement(It,{paddingLeft:1,key:o,flexDirection:"row"},Ge.createElement(It,{key:o,flexDirection:"row",paddingBottom:o?0:1},Ge.createElement(It,{width:20,justifyContent:"flex-end"},Ge.createElement(ga,{color:o?N.accent:N.secondary},n)),Ge.createElement(It,{flexGrow:1,width:40,paddingLeft:2},Ge.createElement(ga,{color:o?N.primary:N.secondary},r))))):null))};import _l from"chalk";import{Box as Jn,Text as qe}from"ink";import Ne from"react";var ya=({width:e,height:t})=>Ne.createElement(Jn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},Ne.createElement(qe,{color:N.accent,bold:!0},"Initialize project"),Ne.createElement(qe,null,`This folder is not an ${_l.hex(N.accent)("epiq")} project yet.`),Ne.createElement(qe,{color:N.primary},"To start tracking issues here, we need to initialize a new"," ",Ne.createElement(qe,{color:N.primary,backgroundColor:N.secondary}," .epiq/project.json ")," ","file in this repository."),Ne.createElement(Jn,{marginTop:1,flexDirection:"column"},Ne.createElement(Jn,null,Ne.createElement(qe,{color:N.accent}," "),Ne.createElement(qe,{color:N.primary},"Type "),Ne.createElement(qe,{backgroundColor:N.secondary}," :init "))),Ne.createElement(Jn,{marginTop:1},Ne.createElement(qe,{color:N.secondary2},"(This will create the local epiq project files)")));import{Box as Qn,Text as Ae}from"ink";import Z from"react";var jl=({isDone:e,command:t,value:n})=>Z.createElement(Qn,null,Z.createElement(Ae,{color:N.accent,dimColor:e},e?" \u2714 ":" "),Z.createElement(Ae,{dimColor:e},"Type "),Z.createElement(Ae,{backgroundColor:N.secondary,dimColor:e}," "+t+" "),n!==void 0&&Z.createElement(Z.Fragment,null,Z.createElement(Ae,{dimColor:e}," "),Z.createElement(Ae,{color:N.secondary,dimColor:e},"<"+n+">"))),Hl=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function fo({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:a,isSetAutoSync:c}=_e(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:i,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:a,message:"Almost there. Configure auto sync."}],m=u.findIndex(g=>!g.done),p=m===-1?void 0:u[m];return Z.createElement(Qn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},Z.createElement(Ae,{color:N.accent,bold:!0},"Welcome! \u{1F539}"),Z.createElement(Ae,null,"Lets get you started - its a breeze."),Z.createElement(Ae,{color:N.secondary2},"And remember, you can always get help with"," ",Z.createElement(Ae,{color:N.accent},":help"),"."),p&&Z.createElement(Ae,{color:N.secondary2},p.message),Z.createElement(Qn,{flexDirection:"column"},u.map((g,x)=>m===-1||x<=m?Z.createElement(Qn,{key:g.key,marginBottom:1},Z.createElement(jl,{isDone:g.done,command:g.command,value:g.done?Hl(g.value):void 0})):null)))}import Sa from"chalk";import{Box as er,Text as ze}from"ink";import ee from"react";import{Box as go,Text as Kl}from"ink";import bt from"react";var Vl=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",xa=({width:e})=>{let{viewMode:t}=L(),{breadCrumb:n,currentNode:r,selectedIndex:o}=v(),i=O(r.id)[o],a=je(i?.id??r.id,"TICKET"),c=Ee(a)?a.value:void 0,u=c?.id?O(c.id):[],m=R=>{let b=u.find(w=>w.title===R);return b?O(b.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},p=m("Tags"),g=m("Assignees"),x=c?.parentNodeId?!kr(r.id,c?.parentNodeId)&&t==="dense":!1,E=n.map((R,b)=>{let w=b===n.length-1,U=O(R.id),le=w?U?.[o]?.title:void 0;return`${b?" / ":""}${R.title??""}${le?` \u25B8 ${le}`:""}`}).join(""),A=Vl(E,e);return bt.createElement(go,null,bt.createElement(Kl,{color:N.secondary2},A),x?p.map(R=>bt.createElement(go,{key:R,paddingLeft:2},bt.createElement(Nt,{id:R}))):null,x?g.map(R=>bt.createElement(go,{key:R,paddingLeft:2},bt.createElement(Ct,{id:R}))):null)};import{Box as Gl,Text as ha}from"ink";import Zn from"react";var ql=({filters:e})=>Zn.createElement(Gl,{columnGap:1},Zn.createElement(ha,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Zn.createElement(ha,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ca=Zn.memo(ql);var Na="0.5.2";import Ea from"chalk";import{Text as zl}from"ink";import Yl,{useEffect as Xl,useState as Jl}from"react";var Ql=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Ia=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Zl=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},eu=(e,t,n)=>{let r=Ia(e),o=Ia(t);return Zl({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},tu=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],a=e[Math.min(r+1,e.length-1)];return eu(i,a,o)};function ba({syncStatus:e}){let[t,n]=Jl(0);Xl(()=>{if(e.status!=="syncing"){n(0);return}let a=setInterval(()=>{n(c=>c+1)},50);return()=>clearInterval(a)},[e.status]);let r={synced:"synced ",outOfSync:"unsynced",syncing:"syncing "},i={synced:N.secondary2,outOfSync:N.yellow,syncing:tu(Ql,(Math.sin(t*.12)+1)/2)??""}[e.status];return Yl.createElement(zl,null,Ea.hex(i)("\u25CF")+Ea.dim(` ${r[e.status].padEnd(2)} `))}function tr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o,syncStatus:i}=G(),{userName:a,preferredEditor:c}=L(),u=56,m=process.stdout.columns-u-8,p=r.at(-1)?.id,g=Mn(p??""),x=Ee(g)?Li(g.value):"INVALID DATE";return ee.createElement(er,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?ee.createElement(ze,null," "):ee.createElement(er,{paddingLeft:1},e.length>0?ee.createElement(Ca,{filters:e}):ee.createElement(xa,{width:m})),n==="live"?ee.createElement(er,{columnGap:1,paddingRight:2,"max-width":u,overflow:"hidden",justifyContent:"flex-end"},ee.createElement(ba,{syncStatus:i}),ee.createElement(ze,{dimColor:!0,color:N.secondary2},Na+" "),ee.createElement(Ra,{icon:"@",value:a}),ee.createElement(Ra,{icon:"\u276F",value:c})):"",n==="peek"?ee.createElement(er,{paddingLeft:1},ee.createElement(ze,{backgroundColor:N.yellow}," Readonly "),ee.createElement(ze,{color:N.yellow}," "+o.length+" edits ago at "),ee.createElement(ze,{backgroundColor:N.yellow,color:N.accent}," "+x+" "),ee.createElement(ze,{color:N.yellow},". Resume with "),ee.createElement(ze,{backgroundColor:N.yellow}," :peek now ")):"")}function Ra({icon:e,value:t}){return ee.createElement(ze,null,Sa.dim(e)+Sa.hex(N.accent)(` ${t??"-"} `))}import{Box as nu,Text as ru}from"ink";import Qt from"react";import{Box as nr,Text as vo}from"ink";import Ye from"react";function yo(){let e=G(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?T(t?.id):[];return Ye.createElement(nr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:N.secondary,width:i},Ye.createElement(nr,{padding:1,paddingTop:0,paddingBottom:0},Ye.createElement(vo,null,"Select a board:")),Ye.createElement(nr,{padding:1,flexDirection:"column"},a.map((c,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,g=T(c.id).flatMap(({id:x})=>O(x)).length;return Ye.createElement(nr,{key:c.id??u},Ye.createElement(vo,{color:m?N.accent:N.secondary2},Ye.createElement(me,{isSelected:m})),Ye.createElement(vo,{color:m?N.accent:N.secondary2},c.title," (",g," issues)",c.readonly?" \u{1F512}":""))})))}var ou=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:c}=G(),u=n.find(({context:x})=>x==="BOARD"),g=i-1-3;return Qt.createElement(nu,{flexDirection:"row"},e.context==="WORKSPACE"?Qt.createElement(yo,null):u?Qt.createElement($n,{height:g,width:a,swimlanes:(c[u.id]??[]).filter(x=>x!==void 0&&lt(x)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Qt.createElement(ru,null))},Aa=Qt.memo(ou);function xo({width:e,height:t}){let n=G(),r=n.filters;if(n.mode===f.HELP)return te.createElement(dt,{flexDirection:"column"},te.createElement(va,{width:e}));let{isSetupDone:o}=_e(),i=!o,a=o&&!n.hasProject;if(i)return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{hideBreadCrumb:!0,filters:r}),te.createElement(fo,{height:t,width:e})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(a)return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{hideBreadCrumb:!0,filters:r}),te.createElement(ya,{height:t,width:e})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));let c=Se(v().breadCrumb??[],"BOARD");if(Ee(c)){let u=c.value.id,m=T(u).length,p=3,g=Math.floor(e/p),x=Math.floor(e/Math.max(m,1));e=Math.min(x,g)*Math.max(m,p)}return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{filters:r}),te.createElement(Aa,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:L().viewMode??"dense",mode:n.mode})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import iu from"readline";var rr,or,we,su=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),wa=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Zi(e,n);if(!o||r&&!su.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},au=()=>async function(t,n){n.name!=="escape"&&(we&&(clearTimeout(we),we=void 0),await wa(n))},du=()=>async function(t){if(t.length===1&&t[0]===27){we&&clearTimeout(we),we=setTimeout(()=>{wa({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),we=void 0},25);return}we&&(clearTimeout(we),we=void 0)};function Ta(){rr&&process.stdin.removeListener("keypress",rr),or&&process.stdin.removeListener("data",or),rr=au(),or=du(),iu.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",or),process.stdin.on("keypress",rr)}lu(`${ho.bold("Epiq CLI")}
60
60
 
61
61
  ${ho.dim("Boot in directory:")}
62
62
  ${ho.cyan("$ epiq")}
package/dist/mcp.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import{McpServer as Rc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Ac}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as F}from"zod";var Me={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Me.Fail,message:e,value:null}),c=(e,t)=>({status:Me.Success,message:e,value:t}),a=e=>e.status==="fail",ct=e=>e.status==="success";import{ulid as hs}from"ulid";import Ic from"node:fs";import{useSyncExternalStore as yc}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Mn(e){return e.context==="WORKSPACE"}function ne(e){return e.context==="TICKET"}function Lr(e){return e.context==="FIELD"}var kt=e=>e.context==="SWIMLANE",Or=e=>e.context==="BOARD";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Ft(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Dt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Xe=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Ur=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},Br=(e,t)=>t?e.get(t)??[]:[];var _r=new WeakMap,ks=e=>{let t=_r.get(e);return t||(t=Ur(e),_r.set(e,t)),t};var $r=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Br(ks(e),r).filter(i=>Ft(r,i)>=n)};var Fs={hint:"",hints:[],overlap:0,remainder:""},Wr=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Fs;let o=$r({wordList:r,inputToMatch:e,overlapThreshold:1});return Ds(t,o)},Ds=(e,t)=>{let n=t[0]??"",r=Ft(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),d=r<(o??"").length,l=!!i,p=(l&&d?o:n)+(l&&d?":":" "),x=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:x}};import qs from"node:fs";import Vs from"node:path";import{decodeTime as zs,monotonicFactory as Gs}from"ulid";import{z as pt}from"zod";var Lt={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},_=()=>Lt,ge=e=>(Lt={...Lt,...e},Lt);import lt from"node:fs";import he from"node:path";var Pn=process.env.IS_LOCAL==="true",Ie=".epiq",de=".epiq-global",Ot="events",Ls="project.json",jr=e=>he.join(e,Ie),Ut=e=>he.join(e,Ie),Bt=e=>he.join(Ut(e),Ls),ut=e=>he.join(Ut(e),Ot),Os=e=>{let t=he.join(e,Ie);return lt.existsSync(t)&&lt.statSync(t).isDirectory()},kn=e=>{let t=Bt(e);return lt.existsSync(t)&&lt.statSync(t).isFile()},fe=e=>{let t=he.resolve(e);for(;;){if(Os(t))return c("Resolved closest .epiq root",t);let n=he.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},Pe=e=>{let t=he.resolve(e);for(;;){if(kn(t))return c("Resolved closest epiq project root",t);let n=he.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},Hr=e=>{let t=ut(e);try{return lt.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return s(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}};import _t from"node:fs";import Dn from"node:path";import{decodeTime as Us}from"ulid";import{z as Fn}from"zod";var Bs=Fn.object({userId:Fn.string().min(1).default("unknown"),userName:Fn.string().min(1).default("unknown")}),_s=e=>{let[t,n]=Dn.basename(e,".jsonl").split("."),r=Bs.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${Dn.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},$s=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Ws=(e,t)=>t in e,js=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Hs=e=>{let{userId:t,userName:n,...r}=e,o=$s(r);if(a(o))return s(o.message);let i=o.value,d=e.id?.[0];return d?Ws(r,i)?c("Decoded persisted event",js({id:d,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},$t=e=>{if(!_t.existsSync(e))return c("Event file missing",[]);let t=_s(e);if(a(t))return s(t.message);let n=_t.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
3
3
  `)){let i=o.trim();if(!i)continue;let d;try{d=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let l=Ln(d);if(a(l))return s(`${l.message} in ${e}: ${i}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function Kr(e){let t=ut(e);if(!_t.existsSync(t))return c("No events found",[]);let n=_t.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Dn.join(t,o)),r=[];for(let o of n){let i=$t(o);if(a(i))return s(i.message);r.push(...i.value)}return c("All events loaded",Ks(r))}function mt(e){let t=Kr(e);if(a(t))return s(t.message);let n=[];for(let r of t.value){let o=Hs(r);if(a(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return c("Loaded merged events",n)}function qr(e=process.cwd()){let t=Kr(e);return a(t)?s(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Ks=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],x=m.id[1]??null;t.set(p,m);let h=n.get(x)??[];h.push(m),n.set(x,h)}for(let m of n.values())m.sort((p,x)=>p.id[0].localeCompare(x.id[0]));let r=[],o=new Set,i=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let x=n.get(p)??[];for(let h of x)i(h)},d=n.get(null)??[];for(let m of d)i(m);let l=e.filter(m=>{let p=m.id[0],x=m.id[1]??null;return!o.has(p)&&x!==null&&!t.has(x)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)i(m);return r},Vr=(e,t)=>{let n=e.findIndex(r=>{try{return Us(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var zr=e=>({action:e.action,payload:e.payload});var Yr=1,Gr=Gs(),Ys=pt.tuple([pt.string().min(1),pt.string().min(1).nullable()]),Xs=pt.looseObject({v:pt.literal(Yr),id:Ys}),Ln=e=>{let t=Xs.safeParse(e);return t.success?c("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Wt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",q=()=>{let{userName:e,userId:t}=_();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Wt(t),userName:Wt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Ee=({userId:e,userName:t})=>`${Wt(e)}.${Wt(t)}.jsonl`,Js=(e,{userId:t,userName:n})=>{let r=Ee({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Vs.join(ut(e),r);return c("Successfully resolved event log path",i)},Zs=(e,t)=>{let n={[e.action]:e.payload,v:Yr,id:t};return Ln(n)};function jt({event:e,rootDir:t=process.cwd()}){try{let n=fe(t);if(a(n))return n;let r=Hr(n.value);if(a(r))return r;let o=Js(n.value,{userId:e.userId,userName:e.userName});if(a(o))return o;let i=qr(n.value);if(a(i))return s(i.message);let d=i.value?Gr(Math.max(Date.now(),zs(i.value)+1)):Gr(),l=Zs(zr(e),[d,i.value]);return a(l)?s(l.message):(qs.appendFileSync(o.value,`${JSON.stringify(l.value)}
4
4
  `,"utf8"),c("Event persisted",{path:o.value,entry:l.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}var Je=3e3,Xr=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Je?null:t},Jr=0,On,Un=!1,gt=!1,Bn=()=>Un||f().syncStatus.status==="syncing",Qs=()=>{let e=_().autoSyncIntervalMs??15e3,t=Date.now()-Jr;return Math.max(0,e-t)},Zr=()=>{On||(On=setTimeout(async()=>{if(On=void 0,Bn()){gt=!0;return}gt=!1,await ea()},Qs()))},ea=async()=>{if(Bn())return gt=!0,s("Sync already in progress");let e=q();if(a(e)||!e.value)return s("Unable to resolve event log path");Un=!0,Jr=Date.now();try{let t=Ee(e.value);return await Ze({ownEventFileName:t})}finally{Un=!1,gt&&Zr()}},Qr=()=>{gt=!0,!Bn()&&Zr()};import ft from"node:fs";import{ulid as ta}from"ulid";import{z as Ht}from"zod";var na="_epiq/_evt",ra=Ht.object({projectId:Ht.string().min(1),stateBranch:Ht.string().min(1),createdAt:Ht.iso.datetime()}),eo=()=>({projectId:ta(),stateBranch:na,createdAt:new Date().toISOString()}),ke=e=>{let t=Bt(e);if(!ft.existsSync(t))return s("Missing .epiq/project.json");try{let n=ft.readFileSync(t,"utf8"),r=JSON.parse(n),o=ra.safeParse(r);return o.success?c("Read project.json",o.data):s(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return s(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},to=e=>{let t=ke(e);return a(t)?s(t.message):c("Read projectId",t.value.projectId)},no=({repoRoot:e,fileContents:t})=>{let n=Ut(e),r=Bt(e);try{if(ft.mkdirSync(n,{recursive:!0}),ft.existsSync(r)){let o=ke(e);return a(o)?s(o.message):c("Project already initialized",null)}return ft.writeFileSync(r,JSON.stringify(t,null,2)+`
5
- `,"utf8"),c("Created project.json",null)}catch(o){return s(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var Kt=()=>{let e=_(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},ro=()=>{let e=Pe(process.cwd());if(a(e))return s("Unable to determine if repository is initialized");let t=ke(e.value);return ct(t)},oo=e=>e===!0?"yes":e===!1?"no":null,io=e=>e==="yes"?!0:e==="no"?!1:null;var J={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:d})};import{ulid as sa}from"ulid";var $e=24n,oa=$e*4n,We=(1n<<oa)-1n,ia=/^[0-9a-f]+$/;function so(e){return!e||!ia.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ce(e,t=$e){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function z(e,t){if(!e&&!t)return Ce(We/2n,$e);let n=e?so(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?so(t):c("Resolved upper bound",We);if(a(r))return r;let o=n.value,i=r.value;if(i<=o)return Ce(We/2n,$e);let d=(o+i)/2n;return d===o||d===i?s("No rank space available between neighbors"):Ce(d,$e)}function ao(){return Ce(We/2n,$e)}function co(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=We*BigInt(r+1)/(t+1n),i=Ce(o,$e);if(a(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var _n=(e,t)=>{let n=$(e),r=co(n.length);if(a(r))return r;let o={};for(let i=0;i<n.length;i++){let d=n[i],l=r.value[i];if(!d||!l)return s("Unable to assign rebalance rank");o[d.id]=l}return c("Created rebalance event",{id:sa(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var G={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var aa=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[te,qt]=aa;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),da={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=J.workspace(t,n,r),i=xt(o);if(a(i))return k(i.message,e);let d=N.createNode(o);return a(d)?k(d.message??"Failed to initialize workspace",e):Mn(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=J.workspace(t,n,r),i=N.createNode(o);return a(i)?k(i.message??"Failed to add workspace",e):Mn(i.value)?c("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(J.board(t,n,r,o));return a(i)?k(i.message??"Unable to create board",e):Or(i.value)?c("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(J.swimlane(t,n,r,o));return a(i)?k(i.message??"Unable to create swimlane",e):kt(i.value)?c("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(J.ticket(t,n,r,o));return a(i)?k(i.message??"Unable to create issue",e):ne(i.value)?c("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,d=N.createNode(J.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(G.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?k(d.message??`Unable to create field: ${n}`,e):Lr(d.value)?c("Added field",{action:e.action,result:d.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?k(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=N.tombstoneNode(t);return a(n)?k(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=N.createTag({id:t,name:n});return a(r)?k(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=N.createContributor({id:t,name:n});return a(r)?k(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=N.tag(n,r,t,o);return a(i)?k(i.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=N.untag(t,n);return a(r)?k(r.message??"Unable to untag ",e):c("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=N.assign(r,n,t,o);return a(i)?k(i.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=N.unassign(t,n);return a(r)?k(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?k(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=N.editValue(t,n);return a(r)?k(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ne(o))return k("Can only close issues",e);let i=N.getNode(te);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let d=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?k(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ne(o))return k("Can only reopen issues",e);let i=N.getNode(te);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return k("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?k(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return a(n)?k(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=N.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let d=N.updateNode({...i,rank:o});if(a(d))return k(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}},ca=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},la=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=f().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function vt(e,t=!1){let n=da[e.action](e);if(a(n))return n;t||([...new Set(la(e))].forEach(d=>ca(d,e)),ce(d=>({...d,eventLog:[...d.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(N.createContributor({name:o,id:r}),n)}var yt=e=>e.map(t=>vt(t));function W(e){let t=vt(e);if(t.status!==Me.Success)return t;let n=jt({event:e});return a(n)?n:t}function Fe(e){return e.map(t=>W(t))}var lo=e=>$n($(e),{at:"end"}),$n=(e,t={at:"end"})=>{let n=r=>a(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(z(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(z(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(z(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=uo(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(z(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=uo(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(z(o.rank,i?.rank)):s("Sibling not found")}}},$=e=>Object.values(f().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),uo=(e,t)=>e.findIndex(n=>n.id===t),mo=(e,t,n={at:"end"})=>$n($(t).filter(r=>r.id!==e),n),ye=(e,t,n,r)=>{let o=mo(t,e,n);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let i=_n(e,r);if(a(i))return i;let d=W(i.value);if(a(d))return d;let l=mo(t,e,n);return a(l)?l:l.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",l.value.rank)},De=(e,t)=>{let n=lo(e);if(a(n))return n;if(!n.value.needsRebalance)return c("Resolved rank",n.value.rank);let r=_n(e,t);if(a(r))return r;let o=W(r.value);if(a(o))return o;let i=lo(e);return a(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",i.value.rank)};var Qe=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},ua=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Wn=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),N={deleteNode(e){ce(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return s("Edit target node not found");let o=Wn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return this.updateNode(i),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Wn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return $(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let d=Wn(o,"move");if(d)return d;if(ua(t,e))return s("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=f(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,d=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of $(m.id))d(p.id)}};d(e);let l={...structuredClone(t)};for(let u of i){if(!l[u])return s("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(I({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ce(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let d=this.getFieldByTitle(i.id,"Assignees");if(!d)return s("Unable to locate assignees field");if($(d.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=J.field({id:n,name:o.name,parentNodeId:d.id,rank:r,props:{value:t}}),m=this.createNode(u);return a(m)?m:c("Assigned contributor",u)},createTag(e){let t=ce(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?s("Could not create tag"):c("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let d=this.getFieldByTitle(i.id,"Tags");if(!d)return s("Unable to locate tags field");if($(d.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=J.field({id:n,name:o.name,parentNodeId:d.id,rank:r,props:{value:t}}),m=this.createNode(u);return a(m)?m:c("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=$(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not tagged with that tag",null);let d={...i,isDeleted:!0};return this.updateNode(d),c("Tag removed",d)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=$(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not assigned to that contributor",null);let d={...i,isDeleted:!0};return this.updateNode(d),c("Assignee removed",d)},createNode(e){let t=ce(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?s("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=ce(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=ce(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return $(e)}};var Z={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},M={accent:Z.cyan,accent2:Z.magenta,primary:Z.white,secondary:Z.grayDark,secondary2:Z.grayLight,gray:Z.gray,green:Z.green,yellow:Z.yellow,red:Z.red};var y={red:Z.red,yellow:Z.yellow,green:Z.green,blue:Z.blue,magenta:Z.magenta,cyan:Z.cyan},et={urgent:y.red,critical:y.red,important:y.red,blocker:y.red,asap:y.red,immediate:y.red,fail:y.red,failure:y.red,broken:y.red,bug:y.red,error:y.red,incident:y.red,outage:y.red,production:y.red,crash:y.red,security:y.red,warning:y.yellow,warn:y.yellow,risky:y.yellow,risk:y.yellow,attention:y.yellow,pending:y.yellow,review:y.yellow,"needs-review":y.yellow,qa:y.yellow,testing:y.yellow,test:y.yellow,validate:y.yellow,verification:y.yellow,staging:y.yellow,check:y.yellow,"follow-up":y.yellow,followup:y.yellow,waiting:y.yellow,blocked:y.yellow,hold:y.yellow,done:y.green,complete:y.green,completed:y.green,success:y.green,ok:y.green,stable:y.green,resolved:y.green,fixed:y.green,closed:y.green,merged:y.green,released:y.green,deployed:y.green,approved:y.green,verified:y.green,working:y.green,healthy:y.green,pass:y.green,passing:y.green,info:y.blue,information:y.blue,note:y.blue,docs:y.blue,documentation:y.blue,doc:y.blue,guide:y.blue,help:y.blue,explanation:y.blue,detail:y.blue,details:y.blue,context:y.blue,design:y.blue,discussion:y.blue,proposal:y.blue,idea:y.blue,feature:y.magenta,enhancement:y.magenta,improvement:y.magenta,refactor:y.magenta,refactoring:y.magenta,cleanup:y.magenta,optimize:y.magenta,optimization:y.magenta,perf:y.magenta,performance:y.magenta,upgrade:y.magenta,migration:y.magenta,modernize:y.magenta,debt:y.magenta,todo:y.cyan,next:y.cyan,planned:y.cyan,plan:y.cyan,future:y.cyan,backlog:y.cyan,investigate:y.cyan,explore:y.cyan,prototype:y.cyan};var po=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r?b(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},jn=e=>po(e,"Tags").map(t=>N.getTag(t)).filter(t=>!!t),Vt=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ne(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",jn(n)??[])},zt=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ne(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Hn(n)??[])},Hn=e=>po(e,"Assignees").map(t=>N.getContributor(t)).filter(t=>!!t);var go=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?Xe(r.props.value):""};var v={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var ma=/^(\d+)(h|d|w|mo|y)$/,pa=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,ga=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},fa=(e,t=new Date)=>{let n=e.match(ma);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-i),d;case"d":return d.setDate(d.getDate()-i),d;case"w":return d.setDate(d.getDate()-i*7),d;case"mo":return d.setMonth(d.getMonth()-i),d;case"y":return d.setFullYear(d.getFullYear()-i),d;default:return null}},va=e=>{let t=e.match(pa);if(!t)return null;let[,n,r,o,i,d]=t,l=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,x=d?Number(d):0;return ga({year:l,month:u,day:m,hour:p,minute:x})?new Date(l,u-1,m,p,x):null},Gt=e=>{let t=e.trim().toLowerCase();return fa(t)??va(t)},fo=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,ya=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],vo=(e=ya)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var xa=["BOARD","TICKET","SWIMLANE"],Y={EDITOR:"editor",VIEW:"view",USERNAME:"userName",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},Le={TITLE:"title",DESCRIPTION:"description"},Na=[Y.EDITOR,Y.VIEW,Y.USERNAME,Y.AUTOSYNC,Y.SYNC_DEBOUNCE_MS],ha=[Le.TITLE,Le.DESCRIPTION],qn=[String(Je),"5000","15000","30000","60000"],je=[v.SYNC,v.HELP,v.EXPORT,v.CONFIG],Yt=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Kn=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT],yo=[v.FILTER,v.PEEK],Ia={WORKSPACE:[...je,...Yt],BOARD:[...yo,...je,...Yt],SWIMLANE:[...yo,...je,...Yt],TICKET:[...je,...Yt,...Kn],FIELD:[...je,...Kn],FIELD_LIST:[...je,...Kn],TEXT:[...je]},Ea=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ca=()=>{let{selectedNode:e,readOnly:t,breadCrumb:n}=f(),{isSetupDone:r}=Kt();if(!r)return[v.HELP,v.CONFIG];if(!ro())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.EXPORT,v.CONFIG];let o=e?.context,i=o&&xa.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Ia[l]:[]))].filter(l=>l===v.MOVE?!1:l===v.EDIT||l===v.DELETE?i:!0)},Q=e=>{let{currentNode:t}=f(),n=t.context??"WORKSPACE";return{[v.NONE]:Ca(),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...vo(),"now","prev","next"],[v.EDIT]:[...ha],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","clear"],[v.TAG]:[...new Set([...Object.keys(et),...N.getExistingTags()])],[v.UNTAG]:[...Vt()?.value?.map(({name:o})=>o)??[]],[v.UNASSIGN]:[...zt()?.value?.map(({name:o})=>o)??[]],[v.ASSIGN]:N.getExistingAssignees(),[v.NEW]:Ea(n),[v.CONFIG]:[...Na]}[e]??[]};import tt from"chalk";var xo=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as No}from"ulid";var ho=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"};var Io=e=>{try{return c("Decoded date",new Date(No(e)))}catch(t){return s("Decoding failed + "+t.message)}},Vn=e=>{if(!e?.id)return null;try{return No(e.id)}catch{return null}};var Oe=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):s("Unable to find node in breadcrumb")};import Eo from"chalk";var Gn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ba=(e,t,n)=>Math.max(t,Math.min(n,e)),zn=(e,t,n)=>e+(t-e)*n,Co=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Sa=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,d=e/60,l=i*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=i,m=l):d>=1&&d<2?(u=l,m=i):d>=2&&d<3?(m=i,p=l):d>=3&&d<4?(m=l,p=i):d>=4&&d<5?(u=l,p=i):(u=i,p=l);let x=o-i/2;return[Math.round((u+x)*255),Math.round((m+x)*255),Math.round((p+x)*255)]},Ra=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Aa=(e,t,n)=>[Math.round(zn(e[0],t[0],n)),Math.round(zn(e[1],t[1],n)),Math.round(zn(e[2],t[2],n))],Nt=e=>{let n=Co(e)%360,r=Sa(n,Gn.stringColor.saturation,Gn.stringColor.lightness);return Ra(r)},wa=e=>{let t=Gn.gradient.stops,n=ba(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),d=o-i;return Aa(t[i],t[i+1],d)},Xt=e=>Co(e.toLowerCase().trim())/4294967295,Ta=e=>{let t=Xt(e);return wa(t)},Ma=e=>{let[t,n,r]=Ta(e);return{normal:o=>Eo.bgRgb(t,n,r).black(o),cursor:o=>Eo.bgRgb(t,n,r).white.bold(o)}};var Yn=e=>Ma(e).normal(` ${e} `),re=(e,t=et)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Nt(r)};var He={None:"none",Invalid:"invalid",Valid:"valid"};var Pa=["BOARD","TICKET","SWIMLANE"],Jn=()=>{let e=f().selectedNode;return e?.context?Pa.includes(e.context)?B():O({message:"Command not available in this context"}):O({message:"Missing target context"})},X="<ENTER> to confirm",B=(e="",t=[])=>({message:e,validity:He.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:He.Invalid,message:e,completionWordList:t}),Jt=e=>e.length===0,se=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let d=o.trim();if(d.length<i)return"";let p=[...t.filter(Boolean).filter(x=>x.startsWith(d))].sort((x,h)=>Xt(x)-Xt(h)).slice(0,r).map(Yn).join(" ");return p?`${e}${p}${n}`:""},Xn=({modifier:e})=>{let t="confirm";return e===t?B(X):O({message:Jt(e)?`if you are certain, enter ${Yn(t)}`:"",completionWordList:[t]})},ka=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:n}):B():O({message:Jt(r)?t:"",completionWordList:[...e]}),ht=({hint:e})=>({modifier:t,inputString:n})=>Jt(t)&&Jt(n)?O({message:e,completionWordList:[]}):B(X),Fa=({modifier:e,inputString:t})=>{let n=Q(v.CONFIG);if(!n.includes(e))return O({message:se({prefix:"config... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case Y.EDITOR:{let r=[...xo];return t.trim()?r.includes(t.trim())?B(X):O({message:se({prefix:"known editors... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):O({message:se({prefix:"editor... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case Y.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?B(X):O({message:se({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case Y.USERNAME:return t.trim()?B(X):O({message:`Enter a username. Saved in ${tt.bgBlack("~/.epiq-global/config.json")}`});case Y.AUTOSYNC:{let r=["yes","no"],o=_().autoSync;return r.includes(t.trim())?B(X):O({message:se({prefix:`should auto-sync (recommended), currently: ${oo(o)} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}case Y.SYNC_DEBOUNCE_MS:{let r=_().autoSyncIntervalMs,o=Xr(t);if(!t.trim()||o===null||o<Je){let i=se({prefix:" examples: ",wordList:qn,minLengthForHints:0,inputString:t});return O({message:`provide duration above ${Je}ms. current duration: ${r}ms.`+i,completionWordList:qn})}return B(X)}default:return O({message:"Unknown config option",completionWordList:n})}},Da=({modifier:e})=>{let t=Q(v.EDIT);if(!t.includes(e)){let r=se({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return O({message:r||"Unknown edit option",completionWordList:t})}let n=Jn();if(n.validity==="invalid")return n;switch(e){case Le.TITLE:return B(X);case Le.DESCRIPTION:return B("<ENTER> to edit in "+_().preferredEditor);default:return O({message:"Unknown edit option",completionWordList:t})}},La={[v.EXPORT]:()=>B(X+", and create export markdown file"),[v.PEEK]:e=>{let t=e.modifier;if(t==="now")return B(X);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return B(X);let r=Gt(t);if(!t||!r)return O(n);let o=Oe(f().breadCrumb,"BOARD");if(a(o))return O({message:"Command is not applicable in this context"});let i=Io(o.value.id);return a(i)?O({message:"Unable to peek: board id is not a valid ULID"}):fo({date:r,horizonDate:i.value})?B(X):O({message:tt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[v.EXIT]:()=>B(X+" and exit the application"),[v.INIT]:()=>B(X),[v.FILTER]:e=>{if(e.modifier==="clear")return B();let t=i=>Q(v.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return O({message:se({wordList:Q(v.FILTER),inputString:e.inputString}),completionWordList:Q(v.FILTER)});let n=Object.values(f().tags).map(i=>i.name),r=Object.values(f().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?O({message:se({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):B():O({message:se({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[v.NONE]:e=>{let t=Q(v.NONE);return e.command?B():O({message:se({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>ka({list:Q(v.NEW),hint:se({wordList:Q(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>B(X),[v.EDIT]:Da,[v.CONFIG]:Fa,[v.DELETE]:e=>{let t=Jn();return t.validity==="invalid"?t:Xn(e)},[v.CLOSE_ISSUE]:e=>Xn(e),[v.RE_OPEN_ISSUE]:e=>Xn(e),[v.MOVE]:e=>{let t=Jn();return t.validity==="invalid"?t:ht({hint:se({prefix:"hey hacker! These commands are blocked for you... ",wordList:Q(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=N.getExistingTags().map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10).join("");return ht({hint:n.length?"existing tags ... "+n:"create tag ..."})(e)},[v.UNTAG]:e=>{let t=Vt();if(a(t))return O({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10);return n.length?ht({hint:" ... "+n.join("")})(e):O({message:"Issue has no tags",completionWordList:[]})},[v.ASSIGN]:e=>{let t=N.getExistingAssignees().map(n=>` ${tt.bgHex(re(n))(" "+n+" ")} `).slice(0,10);return ht({hint:"assign to... "+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=zt();if(a(t))return O({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10);return n.length?ht({hint:"remove assignee... "+n.join("")})(e):O({message:"Issue has no assignees",completionWordList:[]})},[v.SYNC]:()=>B(X)},bo=Object.fromEntries(Object.entries(La).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var So=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var w={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Ro=e=>Object.values(v).includes(e),Ao=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:d,validity:l,completionWordList:u}=bo[n].validate(n,r,i),m=o==="command"||o==="modifier"?Q(n):So;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:d??"",autoCompletion:t?Wr(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var wo=e=>{let t=e.trimStart(),n=Ua(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),d=Ba(e),l=Ro(r)?r:null,u=l!==null,m=r!=="",p=l?Q(l)??[]:[],x=l&&p.includes(o)?o:"",h="word";n.length===0||n.length===1&&!i?h="command":(n.length===1&&i||n.length===2&&!i)&&(h="modifier");let C=i?"":d,R=Oa(t,l,x);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:x,target:h,inputToMatch:C,inputString:R}},Oa=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},Ua=e=>e.trim()?e.trim().split(/\s+/):[],Ba=e=>e.trimEnd().split(/\s+/).at(-1)??"";var nt=e=>e===Zn||e===":",Zn=" ",rt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:He.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_a=new Set,To=()=>{for(let e of _a)e()};var be=e=>{let n=e(rt),r=wo(n.value),o=n.cursorPosition===n.value.length;rt={...n,commandMeta:Ao(r,o)},To()},It=({message:e,status:t})=>{let n=structuredClone(rt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,rt=n,To(),c(e,null)},Qn=e=>{be(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},er=e=>{be(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&nt(n[o-1]);)o--;for(;o>0&&!nt(n[o-1]);)o--}else{for(;o<n.length&&!nt(n[o]);)o++;for(;o<n.length&&nt(n[o]);)o++}return{...t,cursorPosition:o}})},Mo=()=>{be(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Po=()=>{be(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&nt(t[r-1]);)r--;for(;r>0&&!nt(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},U=e=>{be(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),d=i+o,l=Math.max(0,Math.min(i.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},ko=()=>{be(e=>({...e,commandIsPending:!0}))},Fo=({addToHistory:e=!0})=>{be(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),$a()},Do=()=>{be(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Lo=()=>{be(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},$a=()=>U(()=>""),ee=()=>rt,Oo=()=>{let[e,...t]=rt.value.split(Zn);return t.join(Zn).trim()};var T={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};var Uo=e=>{let{context:t}=f()?.currentNode;if(!t)return w.None;switch(e){case v.EXIT:return w.Exit;case v.EXPORT:return w.Export;case v.INIT:return w.Init;case v.DELETE:return w.Delete;case v.EDIT:return w.Edit;case v.HELP:return w.ViewHelp;case v.RE_OPEN_ISSUE:return w.ReopenIssue;case v.CLOSE_ISSUE:return w.CloseIssue;case v.TAG:return w.TagTicket;case v.UNTAG:return w.UntagTicket;case v.ASSIGN:return w.AssignUserToTicket;case v.UNASSIGN:return w.UnassignUserFromTicket;case v.NEW:return w.NewItem;case v.FILTER:return w.Filter;case v.MOVE:return w.Move;case v.PEEK:return w.Peek;case v.CONFIG:return w.Config;case v.SYNC:return w.Sync;default:return w.None}};import{ulid as V}from"ulid";import ei from"node:fs";import gd from"node:path";import fd from"react";import{Box as md}from"ink";import sn from"react";import{Box as rr,Text as Za}from"ink";import Ne from"react";import{Text as Bo}from"ink";import _o,{useEffect as $o,useState as Wa}from"react";var Wo={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},le=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=xe(),r=Wo[n]??Wo.default,[o,i]=Wa(0);if($o(()=>{i(0)},[r]),$o(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return _o.createElement(Bo,null,t);let d=r[o]??r[0]??t;return _o.createElement(Bo,{color:M.accent,dimColor:o===1},d)};import{Box as tr,Text as ja}from"ink";import Zt from"react";var Qt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(i/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=o?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),x=p+l,h=e.slice(p,x),C=e.length>l,R=i,S=C?Math.max(1,Math.floor(l/e.length*R)):R,E=Math.max(0,R-S),A=Math.max(1,e.length-l),K=C?Math.floor(p/A*E):0;return Zt.createElement(tr,{flexDirection:"row",height:i,width:"100%"},Zt.createElement(tr,{flexDirection:"column",flexGrow:1,height:i},h),Zt.createElement(tr,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((Te,ie)=>Zt.createElement(ja,{key:ie,color:C&&ie>=K&&ie<K+S?M.accent:M.secondary},C?"\u2502":" "))))};import{Box as nn,Text as Ya}from"ink";import Ke from"react";import{Text as Ha}from"ink";import Ka from"react";var qa=e=>e.toLowerCase().trim(),Va=(e,t=et)=>{let n=qa(e);return t[n]?t[n]:Nt(n)},en=({id:e,isSelected:t})=>{let n=N.getContributor(e);if(n)return Ka.createElement(Ha,{underline:t,color:Va(n.name)},"@"+n.name)};import{Text as za}from"ink";import Ga from"react";var tn=({id:e,isSelected:t})=>{let n=N.getTag(e);if(n)return Ga.createElement(za,{underline:t,backgroundColor:re(n.name),color:M.primary}," "+n.name+" ")};var jo=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Dt(Xe(t.title),r),i=jn(t),d=Hn(t);return Ke.createElement(nn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?M.accent:M.secondary,justifyContent:"space-between"},Ke.createElement(nn,{borderBottom:!0},Ke.createElement(nn,{paddingLeft:1,flexDirection:"column"},Ke.createElement(Ya,{color:M.primary},o))),Ke.createElement(nn,{flexDirection:"row",paddingLeft:1},i.map(l=>Ke.createElement(tn,{key:l.id,id:l.id})),d.map(l=>Ke.createElement(en,{key:l.id,id:l.id}))))};import Xa from"chalk";import{Box as Et,Text as nr}from"ink";import Se from"react";var Ja=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ho=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=b(t.id),d=S=>{let E=i.find(A=>A.title===S);return E?b(E.id).map(A=>typeof A.props?.value=="string"?A.props.value:"").filter(A=>!!A):[]},l=d("Tags").map(S=>N.getTag(S)).filter(S=>!!S),u=d("Assignees").map(S=>N.getContributor(S)).filter(S=>!!S),m=1,p=l.length*(1+m),x=u.length*(2+m),h=l.map(S=>Se.createElement(Et,{key:S.id,paddingRight:m},Se.createElement(nr,{color:re(S.name)},"\u25A0"))),C=u.map(S=>Se.createElement(Et,{key:S.id,paddingRight:m},Se.createElement(nr,{color:Nt(S.name)},"@"+S.name.at(0)))),R=n?M.accent:o===g.MOVE?M.secondary:M.primary;return Se.createElement(Et,{borderBottom:!0,justifyContent:"space-between"},Se.createElement(Et,null,Se.createElement(le,{isSelected:n,placeholder:Xa.dim.gray(r+1+" ")}),Se.createElement(nr,{wrap:"truncate",color:R},Ja(t.title,e-p-x-14))),Se.createElement(Et,null,h,C))};var Qa=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=xe(),m=u[e.id]??[],p=`${e.title} (${m.length})`,x=3,h=o?1:4,C=r-x-(o?2:1),R=Ne.createElement(rr,{borderStyle:"round",borderColor:M.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Ne.createElement(le,{isSelected:t}),Ne.createElement(Za,{bold:!0,color:t?M.accent:M.primary},p," ",e.readonly?"\u{1F512}":"")),S=(E,A)=>{let K=i&&d===A;return o?Ne.createElement(Ho,{key:E.id,index:A,width:n,ticket:E,isSelected:K,mode:l}):Ne.createElement(jo,{key:E.id,width:n,ticket:E,isSelected:K})};return Ne.createElement(rr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?M.accent:M.secondary,paddingRight:1,paddingLeft:1,height:r},R,Ne.createElement(rr,{padding:o?1:0},m.length>0&&Ne.createElement(Qt,{selectedIndex:d,height:C,itemHeight:h},m.map(S)),Ne.createElement(le,{isSelected:i&&d===-1})))},Ko=Ne.memo(Qa);import{Box as sr,Text as ld}from"ink";import Ue,{useEffect as ar,useMemo as Xo}from"react";import qe from"chalk";import qo from"string-width";import{decodeTime as ed}from"ulid";var td=(e,t)=>e+" ".repeat(Math.max(0,t-qo(e))),nd=(e,t)=>" ".repeat(Math.max(0,t-qo(e)))+e,rd=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),od=e=>{switch(e.action){case"move.node":{let t=N.getNode(e.payload.parent);return`to ${t?qe.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=f().tags[e.payload.tagId];return t?qe.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=f().tags[e.payload.tagId];return t?qe.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=f().contributors[e.payload.contributor];return t?qe.hex(re(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=f().contributors[e.payload.contributor];return t?qe.hex(re(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},id=e=>{let t=ho(ed(e));return qe.gray(nd(t,8))},sd=12,ad=e=>td(`${e}`,sd),Vo=e=>{let t=id(e.id),n=ad(e.userName),r=rd(e.action),o=od(e),i=qe.dim("\u203A"),d=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${d}`};var D={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=b(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:b(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=f();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=b(n.id),o=r.findIndex(({id:d})=>d===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>zo(1),navigateToPreviousItem:()=>zo(-1),navigateToNextContainer:()=>Go(1),navigateToPreviousContainer:()=>Go(-1),navigate:({currentNode:e=f().currentNode,selectedIndex:t})=>{I({currentNodeId:e.id,selectedIndex:t})}},zo=e=>{let t=f(),n=b(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},Go=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=f();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=b(o.id),d=i.findIndex(h=>h.id===t.id);if(d<0)return;let l=i.at(d+e)??i.at(0);if(!l)return;let u=b(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),x=u.length?p:-1;D.navigate({currentNode:l,selectedIndex:x})};import{Box as rn,Text as dd}from"ink";import Re from"react";var Yo=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=xe(),{title:o}=t,i=b(t.id).map(d=>{let l=typeof d.props?.value=="string"?d.props.value:"";if(o==="Assignees")return N.getContributor(l)?.id;if(o==="Tags")return N.getTag(l)?.id}).filter(d=>!!d);return Re.createElement(rn,{alignItems:"center",paddingTop:1},Re.createElement(rn,{minWidth:12},Re.createElement(le,{isSelected:n}),Re.createElement(dd,{color:n?M.accent:M.secondary2},o,":")),Re.createElement(rn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((d,l)=>{let u=r.id===t.id&&l===e;return Re.createElement(rn,{key:`${o}-${d}`,paddingRight:2,minHeight:1},Re.createElement(le,{isSelected:u}),o==="Assignees"?Re.createElement(en,{isSelected:u,id:d}):o==="Tags"?Re.createElement(tn,{isSelected:u,id:d}):null)})))};import{Box as on,Text as or}from"ink";import Ae,{useEffect as cd}from"react";var ir=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:d,currentNode:l}=xe(),u=h=>String(h).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];cd(()=>{let h=[];return m.forEach((C,R)=>{let S=Ce(BigInt(R+1));if(!ct(S))return;let E=J.text({id:`${e}-${R}`,name:`Line ${R+1}`,parentNodeId:e,rank:S.value,props:{value:C},readonly:!0,isVirtual:!0}),A=N.createNode(E);ct(A)&&h.push(A.value.id)}),()=>h.forEach(N.deleteNode)},[e,n]);let p="\u2029",x=m.map((h,C)=>{let R=l.id===e&&d===C;return Ae.createElement(on,{key:`${e}-${C}`},Ae.createElement(or,{color:R?M.primary:M.secondary2,dimColor:!R},`${C+1} `.padStart(5,"\xA0")),Ae.createElement(or,{backgroundColor:R?"gray":""},u(h.length?Dt(h,i-10):p)))});return Ae.createElement(on,{flexDirection:"column",paddingTop:1},Ae.createElement(on,null,Ae.createElement(le,{isSelected:o}),Ae.createElement(or,{color:o?M.accent:M.secondary2},t)),Ae.createElement(on,{flexDirection:"row",borderStyle:"round",borderColor:M.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Ae.createElement(Qt,{scrollByOne:!0,children:x,height:r-2,selectedIndex:d,itemHeight:1})))};var ud=e=>`${e}::log`,Jo=e=>e==="Assignees"||e==="Tags",Zo=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=xe(),o=process.stdout.columns||120,i=Xo(()=>ud(e.id),[e.id]),d=Xo(()=>[...e.log].reverse().map(Vo).join(`
5
+ `,"utf8"),c("Created project.json",null)}catch(o){return s(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var Kt=()=>{let e=_(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},ro=()=>{let e=Pe(process.cwd());if(a(e))return s("Unable to determine if repository is initialized");let t=ke(e.value);return ct(t)},oo=e=>e===!0?"yes":e===!1?"no":null,io=e=>e==="yes"?!0:e==="no"?!1:null;var J={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:d})};import{ulid as sa}from"ulid";var $e=24n,oa=$e*4n,We=(1n<<oa)-1n,ia=/^[0-9a-f]+$/;function so(e){return!e||!ia.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ce(e,t=$e){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function z(e,t){if(!e&&!t)return Ce(We/2n,$e);let n=e?so(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?so(t):c("Resolved upper bound",We);if(a(r))return r;let o=n.value,i=r.value;if(i<=o)return Ce(We/2n,$e);let d=(o+i)/2n;return d===o||d===i?s("No rank space available between neighbors"):Ce(d,$e)}function ao(){return Ce(We/2n,$e)}function co(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=We*BigInt(r+1)/(t+1n),i=Ce(o,$e);if(a(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var _n=(e,t)=>{let n=$(e),r=co(n.length);if(a(r))return r;let o={};for(let i=0;i<n.length;i++){let d=n[i],l=r.value[i];if(!d||!l)return s("Unable to assign rebalance rank");o[d.id]=l}return c("Created rebalance event",{id:sa(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var G={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var aa=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[te,qt]=aa;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),da={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=J.workspace(t,n,r),i=xt(o);if(a(i))return k(i.message,e);let d=N.createNode(o);return a(d)?k(d.message??"Failed to initialize workspace",e):Mn(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=J.workspace(t,n,r),i=N.createNode(o);return a(i)?k(i.message??"Failed to add workspace",e):Mn(i.value)?c("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(J.board(t,n,r,o));return a(i)?k(i.message??"Unable to create board",e):Or(i.value)?c("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(J.swimlane(t,n,r,o));return a(i)?k(i.message??"Unable to create swimlane",e):kt(i.value)?c("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(J.ticket(t,n,r,o));return a(i)?k(i.message??"Unable to create issue",e):ne(i.value)?c("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,d=N.createNode(J.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(G.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?k(d.message??`Unable to create field: ${n}`,e):Lr(d.value)?c("Added field",{action:e.action,result:d.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?k(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=N.tombstoneNode(t);return a(n)?k(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=N.createTag({id:t,name:n});return a(r)?k(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=N.createContributor({id:t,name:n});return a(r)?k(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=N.tag(n,r,t,o);return a(i)?k(i.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=N.untag(t,n);return a(r)?k(r.message??"Unable to untag ",e):c("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=N.assign(r,n,t,o);return a(i)?k(i.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=N.unassign(t,n);return a(r)?k(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?k(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=N.editValue(t,n);return a(r)?k(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ne(o))return k("Can only close issues",e);let i=N.getNode(te);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let d=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?k(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ne(o))return k("Can only reopen issues",e);let i=N.getNode(te);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return k("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?k(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return a(n)?k(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=N.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let d=N.updateNode({...i,rank:o});if(a(d))return k(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}},ca=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},la=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=f().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function vt(e,t=!1){let n=da[e.action](e);if(a(n))return n;t||([...new Set(la(e))].forEach(d=>ca(d,e)),ce(d=>({...d,eventLog:[...d.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(N.createContributor({name:o,id:r}),n)}var yt=e=>e.map(t=>vt(t));function W(e){let t=vt(e);if(t.status!==Me.Success)return t;let n=jt({event:e});return a(n)?n:t}function Fe(e){return e.map(t=>W(t))}var lo=e=>$n($(e),{at:"end"}),$n=(e,t={at:"end"})=>{let n=r=>a(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(z(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(z(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(z(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=uo(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(z(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=uo(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(z(o.rank,i?.rank)):s("Sibling not found")}}},$=e=>Object.values(f().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),uo=(e,t)=>e.findIndex(n=>n.id===t),mo=(e,t,n={at:"end"})=>$n($(t).filter(r=>r.id!==e),n),ye=(e,t,n,r)=>{let o=mo(t,e,n);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let i=_n(e,r);if(a(i))return i;let d=W(i.value);if(a(d))return d;let l=mo(t,e,n);return a(l)?l:l.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",l.value.rank)},De=(e,t)=>{let n=lo(e);if(a(n))return n;if(!n.value.needsRebalance)return c("Resolved rank",n.value.rank);let r=_n(e,t);if(a(r))return r;let o=W(r.value);if(a(o))return o;let i=lo(e);return a(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",i.value.rank)};var Qe=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},ua=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Wn=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),N={deleteNode(e){ce(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return s("Edit target node not found");let o=Wn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return this.updateNode(i),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Wn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return $(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let d=Wn(o,"move");if(d)return d;if(ua(t,e))return s("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=f(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,d=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of $(m.id))d(p.id)}};d(e);let l={...structuredClone(t)};for(let u of i){if(!l[u])return s("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(I({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ce(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let d=this.getFieldByTitle(i.id,"Assignees");if(!d)return s("Unable to locate assignees field");if($(d.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=J.field({id:n,name:o.name,parentNodeId:d.id,rank:r,props:{value:t}}),m=this.createNode(u);return a(m)?m:c("Assigned contributor",u)},createTag(e){let t=ce(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?s("Could not create tag"):c("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let d=this.getFieldByTitle(i.id,"Tags");if(!d)return s("Unable to locate tags field");if($(d.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=J.field({id:n,name:o.name,parentNodeId:d.id,rank:r,props:{value:t}}),m=this.createNode(u);return a(m)?m:c("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=$(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not tagged with that tag",null);let d={...i,isDeleted:!0};return this.updateNode(d),c("Tag removed",d)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=$(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not assigned to that contributor",null);let d={...i,isDeleted:!0};return this.updateNode(d),c("Assignee removed",d)},createNode(e){let t=ce(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?s("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=ce(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=ce(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return $(e)}};var Z={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},M={accent:Z.cyan,accent2:Z.magenta,primary:Z.white,secondary:Z.grayDark,secondary2:Z.grayLight,gray:Z.gray,green:Z.green,yellow:Z.yellow,red:Z.red};var y={red:Z.red,yellow:Z.yellow,green:Z.green,blue:Z.blue,magenta:Z.magenta,cyan:Z.cyan},et={urgent:y.red,critical:y.red,important:y.red,blocker:y.red,asap:y.red,immediate:y.red,fail:y.red,failure:y.red,broken:y.red,bug:y.red,error:y.red,incident:y.red,outage:y.red,production:y.red,crash:y.red,security:y.red,warning:y.yellow,warn:y.yellow,risky:y.yellow,risk:y.yellow,attention:y.yellow,pending:y.yellow,review:y.yellow,"needs-review":y.yellow,qa:y.yellow,testing:y.yellow,test:y.yellow,validate:y.yellow,verification:y.yellow,staging:y.yellow,check:y.yellow,"follow-up":y.yellow,followup:y.yellow,waiting:y.yellow,blocked:y.yellow,hold:y.yellow,done:y.green,complete:y.green,completed:y.green,success:y.green,ok:y.green,stable:y.green,resolved:y.green,fixed:y.green,closed:y.green,merged:y.green,released:y.green,deployed:y.green,approved:y.green,verified:y.green,working:y.green,healthy:y.green,pass:y.green,passing:y.green,info:y.blue,information:y.blue,note:y.blue,docs:y.blue,documentation:y.blue,doc:y.blue,guide:y.blue,help:y.blue,explanation:y.blue,detail:y.blue,details:y.blue,context:y.blue,design:y.blue,discussion:y.blue,proposal:y.blue,idea:y.blue,feature:y.magenta,enhancement:y.magenta,improvement:y.magenta,refactor:y.magenta,refactoring:y.magenta,cleanup:y.magenta,optimize:y.magenta,optimization:y.magenta,perf:y.magenta,performance:y.magenta,upgrade:y.magenta,migration:y.magenta,modernize:y.magenta,debt:y.magenta,todo:y.cyan,next:y.cyan,planned:y.cyan,plan:y.cyan,future:y.cyan,backlog:y.cyan,investigate:y.cyan,explore:y.cyan,prototype:y.cyan};var po=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r?b(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},jn=e=>po(e,"Tags").map(t=>N.getTag(t)).filter(t=>!!t),Vt=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ne(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",jn(n)??[])},zt=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ne(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Hn(n)??[])},Hn=e=>po(e,"Assignees").map(t=>N.getContributor(t)).filter(t=>!!t);var go=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?Xe(r.props.value):""};var v={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var ma=/^(\d+)(h|d|w|mo|y)$/,pa=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,ga=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},fa=(e,t=new Date)=>{let n=e.match(ma);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-i),d;case"d":return d.setDate(d.getDate()-i),d;case"w":return d.setDate(d.getDate()-i*7),d;case"mo":return d.setMonth(d.getMonth()-i),d;case"y":return d.setFullYear(d.getFullYear()-i),d;default:return null}},va=e=>{let t=e.match(pa);if(!t)return null;let[,n,r,o,i,d]=t,l=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,x=d?Number(d):0;return ga({year:l,month:u,day:m,hour:p,minute:x})?new Date(l,u-1,m,p,x):null},Gt=e=>{let t=e.trim().toLowerCase();return fa(t)??va(t)},fo=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,ya=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],vo=(e=ya)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var xa=["BOARD","TICKET","SWIMLANE"],Y={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},Le={TITLE:"title",DESCRIPTION:"description"},Na=[Y.EDITOR,Y.VIEW,Y.USERNAME,Y.AUTOSYNC,Y.SYNC_DEBOUNCE_MS],ha=[Le.TITLE,Le.DESCRIPTION],qn=[String(Je),"5000","15000","30000","60000"],je=[v.SYNC,v.HELP,v.EXPORT,v.CONFIG],Yt=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Kn=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT],yo=[v.FILTER,v.PEEK],Ia={WORKSPACE:[...je,...Yt],BOARD:[...yo,...je,...Yt],SWIMLANE:[...yo,...je,...Yt],TICKET:[...je,...Yt,...Kn],FIELD:[...je,...Kn],FIELD_LIST:[...je,...Kn],TEXT:[...je]},Ea=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ca=()=>{let{selectedNode:e,readOnly:t,breadCrumb:n}=f(),{isSetupDone:r}=Kt();if(!r)return[v.HELP,v.CONFIG];if(!ro())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.EXPORT,v.CONFIG];let o=e?.context,i=o&&xa.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Ia[l]:[]))].filter(l=>l===v.MOVE?!1:l===v.EDIT||l===v.DELETE?i:!0)},Q=e=>{let{currentNode:t}=f(),n=t.context??"WORKSPACE";return{[v.NONE]:Ca(),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...vo(),"now","prev","next"],[v.EDIT]:[...ha],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","clear"],[v.TAG]:[...new Set([...Object.keys(et),...N.getExistingTags()])],[v.UNTAG]:[...Vt()?.value?.map(({name:o})=>o)??[]],[v.UNASSIGN]:[...zt()?.value?.map(({name:o})=>o)??[]],[v.ASSIGN]:N.getExistingAssignees(),[v.NEW]:Ea(n),[v.CONFIG]:[...Na]}[e]??[]};import tt from"chalk";var xo=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as No}from"ulid";var ho=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"};var Io=e=>{try{return c("Decoded date",new Date(No(e)))}catch(t){return s("Decoding failed + "+t.message)}},Vn=e=>{if(!e?.id)return null;try{return No(e.id)}catch{return null}};var Oe=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):s("Unable to find node in breadcrumb")};import Eo from"chalk";var Gn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ba=(e,t,n)=>Math.max(t,Math.min(n,e)),zn=(e,t,n)=>e+(t-e)*n,Co=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Sa=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,d=e/60,l=i*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=i,m=l):d>=1&&d<2?(u=l,m=i):d>=2&&d<3?(m=i,p=l):d>=3&&d<4?(m=l,p=i):d>=4&&d<5?(u=l,p=i):(u=i,p=l);let x=o-i/2;return[Math.round((u+x)*255),Math.round((m+x)*255),Math.round((p+x)*255)]},Ra=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Aa=(e,t,n)=>[Math.round(zn(e[0],t[0],n)),Math.round(zn(e[1],t[1],n)),Math.round(zn(e[2],t[2],n))],Nt=e=>{let n=Co(e)%360,r=Sa(n,Gn.stringColor.saturation,Gn.stringColor.lightness);return Ra(r)},wa=e=>{let t=Gn.gradient.stops,n=ba(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),d=o-i;return Aa(t[i],t[i+1],d)},Xt=e=>Co(e.toLowerCase().trim())/4294967295,Ta=e=>{let t=Xt(e);return wa(t)},Ma=e=>{let[t,n,r]=Ta(e);return{normal:o=>Eo.bgRgb(t,n,r).black(o),cursor:o=>Eo.bgRgb(t,n,r).white.bold(o)}};var Yn=e=>Ma(e).normal(` ${e} `),re=(e,t=et)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Nt(r)};var He={None:"none",Invalid:"invalid",Valid:"valid"};var Pa=["BOARD","TICKET","SWIMLANE"],Jn=()=>{let e=f().selectedNode;return e?.context?Pa.includes(e.context)?B():O({message:"Command not available in this context"}):O({message:"Missing target context"})},X="<ENTER> to confirm",B=(e="",t=[])=>({message:e,validity:He.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:He.Invalid,message:e,completionWordList:t}),Jt=e=>e.length===0,se=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let d=o.trim();if(d.length<i)return"";let p=[...t.filter(Boolean).filter(x=>x.startsWith(d))].sort((x,h)=>Xt(x)-Xt(h)).slice(0,r).map(Yn).join(" ");return p?`${e}${p}${n}`:""},Xn=({modifier:e})=>{let t="confirm";return e===t?B(X):O({message:Jt(e)?`if you are certain, enter ${Yn(t)}`:"",completionWordList:[t]})},ka=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:n}):B():O({message:Jt(r)?t:"",completionWordList:[...e]}),ht=({hint:e})=>({modifier:t,inputString:n})=>Jt(t)&&Jt(n)?O({message:e,completionWordList:[]}):B(X),Fa=({modifier:e,inputString:t})=>{let n=Q(v.CONFIG);if(!n.includes(e))return O({message:se({prefix:"config... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case Y.EDITOR:{let r=[...xo];return t.trim()?r.includes(t.trim())?B(X):O({message:se({prefix:"known editors... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):O({message:se({prefix:"editor... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case Y.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?B(X):O({message:se({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case Y.USERNAME:return t.trim()?B(X):O({message:`Enter a username. Saved in ${tt.bgBlack("~/.epiq-global/config.json")}`});case Y.AUTOSYNC:{let r=["yes","no"],o=_().autoSync;if(!r.includes(t.trim())){let i=oo(o);return O({message:se({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return B(X)}case Y.SYNC_DEBOUNCE_MS:{let r=_().autoSyncIntervalMs,o=Xr(t);if(!t.trim()||o===null||o<Je){let i=se({prefix:" examples: ",wordList:qn,minLengthForHints:0,inputString:t});return O({message:`provide duration above ${Je}ms. current duration: ${r}ms.`+i,completionWordList:qn})}return B(X)}default:return O({message:"Unknown config option",completionWordList:n})}},Da=({modifier:e})=>{let t=Q(v.EDIT);if(!t.includes(e)){let r=se({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return O({message:r||"Unknown edit option",completionWordList:t})}let n=Jn();if(n.validity==="invalid")return n;switch(e){case Le.TITLE:return B(X);case Le.DESCRIPTION:return B("<ENTER> to edit in "+_().preferredEditor);default:return O({message:"Unknown edit option",completionWordList:t})}},La={[v.EXPORT]:()=>B(X+", and create export markdown file"),[v.PEEK]:e=>{let t=e.modifier;if(t==="now")return B(X);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return B(X);let r=Gt(t);if(!t||!r)return O(n);let o=Oe(f().breadCrumb,"BOARD");if(a(o))return O({message:"Command is not applicable in this context"});let i=Io(o.value.id);return a(i)?O({message:"Unable to peek: board id is not a valid ULID"}):fo({date:r,horizonDate:i.value})?B(X):O({message:tt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[v.EXIT]:()=>B(X+" and exit the application"),[v.INIT]:()=>B(X),[v.FILTER]:e=>{if(e.modifier==="clear")return B();let t=i=>Q(v.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return O({message:se({wordList:Q(v.FILTER),inputString:e.inputString}),completionWordList:Q(v.FILTER)});let n=Object.values(f().tags).map(i=>i.name),r=Object.values(f().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?O({message:se({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):B():O({message:se({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[v.NONE]:e=>{let t=Q(v.NONE);return e.command?B():O({message:se({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>ka({list:Q(v.NEW),hint:se({wordList:Q(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>B(X),[v.EDIT]:Da,[v.CONFIG]:Fa,[v.DELETE]:e=>{let t=Jn();return t.validity==="invalid"?t:Xn(e)},[v.CLOSE_ISSUE]:e=>Xn(e),[v.RE_OPEN_ISSUE]:e=>Xn(e),[v.MOVE]:e=>{let t=Jn();return t.validity==="invalid"?t:ht({hint:se({prefix:"hey hacker! These commands are blocked for you... ",wordList:Q(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=N.getExistingTags().map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10).join("");return ht({hint:n.length?"existing tags ... "+n:"create tag ..."})(e)},[v.UNTAG]:e=>{let t=Vt();if(a(t))return O({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10);return n.length?ht({hint:" ... "+n.join("")})(e):O({message:"Issue has no tags",completionWordList:[]})},[v.ASSIGN]:e=>{let t=N.getExistingAssignees().map(n=>` ${tt.bgHex(re(n))(" "+n+" ")} `).slice(0,10);return ht({hint:"assign to... "+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=zt();if(a(t))return O({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10);return n.length?ht({hint:"remove assignee... "+n.join("")})(e):O({message:"Issue has no assignees",completionWordList:[]})},[v.SYNC]:()=>B(X)},bo=Object.fromEntries(Object.entries(La).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var So=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var w={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Ro=e=>Object.values(v).includes(e),Ao=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:d,validity:l,completionWordList:u}=bo[n].validate(n,r,i),m=o==="command"||o==="modifier"?Q(n):So;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:d??"",autoCompletion:t?Wr(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var wo=e=>{let t=e.trimStart(),n=Ua(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),d=Ba(e),l=Ro(r)?r:null,u=l!==null,m=r!=="",p=l?Q(l)??[]:[],x=l&&p.includes(o)?o:"",h="word";n.length===0||n.length===1&&!i?h="command":(n.length===1&&i||n.length===2&&!i)&&(h="modifier");let C=i?"":d,R=Oa(t,l,x);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:x,target:h,inputToMatch:C,inputString:R}},Oa=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},Ua=e=>e.trim()?e.trim().split(/\s+/):[],Ba=e=>e.trimEnd().split(/\s+/).at(-1)??"";var nt=e=>e===Zn||e===":",Zn=" ",rt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:He.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_a=new Set,To=()=>{for(let e of _a)e()};var be=e=>{let n=e(rt),r=wo(n.value),o=n.cursorPosition===n.value.length;rt={...n,commandMeta:Ao(r,o)},To()},It=({message:e,status:t})=>{let n=structuredClone(rt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,rt=n,To(),c(e,null)},Qn=e=>{be(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},er=e=>{be(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&nt(n[o-1]);)o--;for(;o>0&&!nt(n[o-1]);)o--}else{for(;o<n.length&&!nt(n[o]);)o++;for(;o<n.length&&nt(n[o]);)o++}return{...t,cursorPosition:o}})},Mo=()=>{be(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Po=()=>{be(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&nt(t[r-1]);)r--;for(;r>0&&!nt(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},U=e=>{be(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),d=i+o,l=Math.max(0,Math.min(i.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},ko=()=>{be(e=>({...e,commandIsPending:!0}))},Fo=({addToHistory:e=!0})=>{be(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),$a()},Do=()=>{be(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Lo=()=>{be(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},$a=()=>U(()=>""),ee=()=>rt,Oo=()=>{let[e,...t]=rt.value.split(Zn);return t.join(Zn).trim()};var T={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};var Uo=e=>{let{context:t}=f()?.currentNode;if(!t)return w.None;switch(e){case v.EXIT:return w.Exit;case v.EXPORT:return w.Export;case v.INIT:return w.Init;case v.DELETE:return w.Delete;case v.EDIT:return w.Edit;case v.HELP:return w.ViewHelp;case v.RE_OPEN_ISSUE:return w.ReopenIssue;case v.CLOSE_ISSUE:return w.CloseIssue;case v.TAG:return w.TagTicket;case v.UNTAG:return w.UntagTicket;case v.ASSIGN:return w.AssignUserToTicket;case v.UNASSIGN:return w.UnassignUserFromTicket;case v.NEW:return w.NewItem;case v.FILTER:return w.Filter;case v.MOVE:return w.Move;case v.PEEK:return w.Peek;case v.CONFIG:return w.Config;case v.SYNC:return w.Sync;default:return w.None}};import{ulid as V}from"ulid";import ei from"node:fs";import gd from"node:path";import fd from"react";import{Box as md}from"ink";import sn from"react";import{Box as rr,Text as Za}from"ink";import Ne from"react";import{Text as Bo}from"ink";import _o,{useEffect as $o,useState as Wa}from"react";var Wo={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},le=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=xe(),r=Wo[n]??Wo.default,[o,i]=Wa(0);if($o(()=>{i(0)},[r]),$o(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return _o.createElement(Bo,null,t);let d=r[o]??r[0]??t;return _o.createElement(Bo,{color:M.accent,dimColor:o===1},d)};import{Box as tr,Text as ja}from"ink";import Zt from"react";var Qt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(i/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=o?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),x=p+l,h=e.slice(p,x),C=e.length>l,R=i,S=C?Math.max(1,Math.floor(l/e.length*R)):R,E=Math.max(0,R-S),A=Math.max(1,e.length-l),K=C?Math.floor(p/A*E):0;return Zt.createElement(tr,{flexDirection:"row",height:i,width:"100%"},Zt.createElement(tr,{flexDirection:"column",flexGrow:1,height:i},h),Zt.createElement(tr,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((Te,ie)=>Zt.createElement(ja,{key:ie,color:C&&ie>=K&&ie<K+S?M.accent:M.secondary},C?"\u2502":" "))))};import{Box as nn,Text as Ya}from"ink";import Ke from"react";import{Text as Ha}from"ink";import Ka from"react";var qa=e=>e.toLowerCase().trim(),Va=(e,t=et)=>{let n=qa(e);return t[n]?t[n]:Nt(n)},en=({id:e,isSelected:t})=>{let n=N.getContributor(e);if(n)return Ka.createElement(Ha,{underline:t,color:Va(n.name)},"@"+n.name)};import{Text as za}from"ink";import Ga from"react";var tn=({id:e,isSelected:t})=>{let n=N.getTag(e);if(n)return Ga.createElement(za,{underline:t,backgroundColor:re(n.name),color:M.primary}," "+n.name+" ")};var jo=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Dt(Xe(t.title),r),i=jn(t),d=Hn(t);return Ke.createElement(nn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?M.accent:M.secondary,justifyContent:"space-between"},Ke.createElement(nn,{borderBottom:!0},Ke.createElement(nn,{paddingLeft:1,flexDirection:"column"},Ke.createElement(Ya,{color:M.primary},o))),Ke.createElement(nn,{flexDirection:"row",paddingLeft:1},i.map(l=>Ke.createElement(tn,{key:l.id,id:l.id})),d.map(l=>Ke.createElement(en,{key:l.id,id:l.id}))))};import Xa from"chalk";import{Box as Et,Text as nr}from"ink";import Se from"react";var Ja=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ho=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=b(t.id),d=S=>{let E=i.find(A=>A.title===S);return E?b(E.id).map(A=>typeof A.props?.value=="string"?A.props.value:"").filter(A=>!!A):[]},l=d("Tags").map(S=>N.getTag(S)).filter(S=>!!S),u=d("Assignees").map(S=>N.getContributor(S)).filter(S=>!!S),m=1,p=l.length*(1+m),x=u.length*(2+m),h=l.map(S=>Se.createElement(Et,{key:S.id,paddingRight:m},Se.createElement(nr,{color:re(S.name)},"\u25A0"))),C=u.map(S=>Se.createElement(Et,{key:S.id,paddingRight:m},Se.createElement(nr,{color:Nt(S.name)},"@"+S.name.at(0)))),R=n?M.accent:o===g.MOVE?M.secondary:M.primary;return Se.createElement(Et,{borderBottom:!0,justifyContent:"space-between"},Se.createElement(Et,null,Se.createElement(le,{isSelected:n,placeholder:Xa.dim.gray(r+1+" ")}),Se.createElement(nr,{wrap:"truncate",color:R},Ja(t.title,e-p-x-14))),Se.createElement(Et,null,h,C))};var Qa=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=xe(),m=u[e.id]??[],p=`${e.title} (${m.length})`,x=3,h=o?1:4,C=r-x-(o?2:1),R=Ne.createElement(rr,{borderStyle:"round",borderColor:M.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Ne.createElement(le,{isSelected:t}),Ne.createElement(Za,{bold:!0,color:t?M.accent:M.primary},p," ",e.readonly?"\u{1F512}":"")),S=(E,A)=>{let K=i&&d===A;return o?Ne.createElement(Ho,{key:E.id,index:A,width:n,ticket:E,isSelected:K,mode:l}):Ne.createElement(jo,{key:E.id,width:n,ticket:E,isSelected:K})};return Ne.createElement(rr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?M.accent:M.secondary,paddingRight:1,paddingLeft:1,height:r},R,Ne.createElement(rr,{padding:o?1:0},m.length>0&&Ne.createElement(Qt,{selectedIndex:d,height:C,itemHeight:h},m.map(S)),Ne.createElement(le,{isSelected:i&&d===-1})))},Ko=Ne.memo(Qa);import{Box as sr,Text as ld}from"ink";import Ue,{useEffect as ar,useMemo as Xo}from"react";import qe from"chalk";import qo from"string-width";import{decodeTime as ed}from"ulid";var td=(e,t)=>e+" ".repeat(Math.max(0,t-qo(e))),nd=(e,t)=>" ".repeat(Math.max(0,t-qo(e)))+e,rd=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),od=e=>{switch(e.action){case"move.node":{let t=N.getNode(e.payload.parent);return`to ${t?qe.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=f().tags[e.payload.tagId];return t?qe.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=f().tags[e.payload.tagId];return t?qe.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=f().contributors[e.payload.contributor];return t?qe.hex(re(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=f().contributors[e.payload.contributor];return t?qe.hex(re(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},id=e=>{let t=ho(ed(e));return qe.gray(nd(t,8))},sd=12,ad=e=>td(`${e}`,sd),Vo=e=>{let t=id(e.id),n=ad(e.userName),r=rd(e.action),o=od(e),i=qe.dim("\u203A"),d=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${d}`};var D={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=b(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:b(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=f();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=b(n.id),o=r.findIndex(({id:d})=>d===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>zo(1),navigateToPreviousItem:()=>zo(-1),navigateToNextContainer:()=>Go(1),navigateToPreviousContainer:()=>Go(-1),navigate:({currentNode:e=f().currentNode,selectedIndex:t})=>{I({currentNodeId:e.id,selectedIndex:t})}},zo=e=>{let t=f(),n=b(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},Go=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=f();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=b(o.id),d=i.findIndex(h=>h.id===t.id);if(d<0)return;let l=i.at(d+e)??i.at(0);if(!l)return;let u=b(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),x=u.length?p:-1;D.navigate({currentNode:l,selectedIndex:x})};import{Box as rn,Text as dd}from"ink";import Re from"react";var Yo=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=xe(),{title:o}=t,i=b(t.id).map(d=>{let l=typeof d.props?.value=="string"?d.props.value:"";if(o==="Assignees")return N.getContributor(l)?.id;if(o==="Tags")return N.getTag(l)?.id}).filter(d=>!!d);return Re.createElement(rn,{alignItems:"center",paddingTop:1},Re.createElement(rn,{minWidth:12},Re.createElement(le,{isSelected:n}),Re.createElement(dd,{color:n?M.accent:M.secondary2},o,":")),Re.createElement(rn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((d,l)=>{let u=r.id===t.id&&l===e;return Re.createElement(rn,{key:`${o}-${d}`,paddingRight:2,minHeight:1},Re.createElement(le,{isSelected:u}),o==="Assignees"?Re.createElement(en,{isSelected:u,id:d}):o==="Tags"?Re.createElement(tn,{isSelected:u,id:d}):null)})))};import{Box as on,Text as or}from"ink";import Ae,{useEffect as cd}from"react";var ir=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:d,currentNode:l}=xe(),u=h=>String(h).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];cd(()=>{let h=[];return m.forEach((C,R)=>{let S=Ce(BigInt(R+1));if(!ct(S))return;let E=J.text({id:`${e}-${R}`,name:`Line ${R+1}`,parentNodeId:e,rank:S.value,props:{value:C},readonly:!0,isVirtual:!0}),A=N.createNode(E);ct(A)&&h.push(A.value.id)}),()=>h.forEach(N.deleteNode)},[e,n]);let p="\u2029",x=m.map((h,C)=>{let R=l.id===e&&d===C;return Ae.createElement(on,{key:`${e}-${C}`},Ae.createElement(or,{color:R?M.primary:M.secondary2,dimColor:!R},`${C+1} `.padStart(5,"\xA0")),Ae.createElement(or,{backgroundColor:R?"gray":""},u(h.length?Dt(h,i-10):p)))});return Ae.createElement(on,{flexDirection:"column",paddingTop:1},Ae.createElement(on,null,Ae.createElement(le,{isSelected:o}),Ae.createElement(or,{color:o?M.accent:M.secondary2},t)),Ae.createElement(on,{flexDirection:"row",borderStyle:"round",borderColor:M.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Ae.createElement(Qt,{scrollByOne:!0,children:x,height:r-2,selectedIndex:d,itemHeight:1})))};var ud=e=>`${e}::log`,Jo=e=>e==="Assignees"||e==="Tags",Zo=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=xe(),o=process.stdout.columns||120,i=Xo(()=>ud(e.id),[e.id]),d=Xo(()=>[...e.log].reverse().map(Vo).join(`
6
6
  `),[e.log]);ar(()=>{if(N.getNode(i))return;let A=Ce(We);if(a(A))return;let K={...J.field({id:i,name:G.HISTORY,parentNodeId:e.id,rank:A.value,props:{value:d},isVirtual:!0}),readonly:!0,childRenderAxis:"vertical"};return N.createNode(K),()=>{N.deleteNode(i)}},[i,e.id,d]),ar(()=>{let E=N.getNode(i);E&&E.props.value!==d&&N.updateNode({...E,props:{...E.props,value:d},childRenderAxis:"vertical",readonly:!0})},[i,d]);let l=r.id===e.id,u=r.id===i||r.parentNodeId===i;ar(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=b(e.id);if(u){let E=N.getNode(i),K=t-3;return Ue.createElement(sr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},E?Ue.createElement(ir,{id:E.id,label:"Event log",text:E.props.value??"",selected:!1,maxWidth:o,height:K}):null)}let p=m.reduce((E,A)=>Jo(A.title)||A.id===i?E+1:E,0),x=2,h=p*1,R=t-3-h-x,S=(E,A)=>Jo(E.title)?Ue.createElement(Yo,{key:E.id,parent:E,selected:A,selectedIndex:n}):E.id===i?Ue.createElement(sr,{key:E.id,paddingTop:1},Ue.createElement(le,{isSelected:A}),Ue.createElement(ld,{backgroundColor:M.secondary,color:A?M.accent:M.primary}," History \u203A\u203A ")):E.title===G.DESCRIPTION?Ue.createElement(ir,{label:"Description (press e to edit)",key:E.id,id:E.id,text:E.props.value??"",selected:A,maxWidth:o,height:R}):null;return Ue.createElement(sr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((E,A)=>S(E,l&&n===A)))};var pd=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:d,width:l})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,x=u===P.TICKET?t:r.find(E=>E.context===P.TICKET),h=Math.floor(l/3),C=Math.floor(l/Math.max(e.length,1)),R=Math.min(C,h),S=i==="dense";return sn.createElement(md,{flexDirection:"row",height:d},p&&e.map((E,A)=>{let K=t.id===E.id,Te=K?n:-1,ie=t.context===P.BOARD&&n===A;return sn.createElement(Ko,{key:E.id,height:d,width:R,swimlane:E,isSelected:ie,isDense:S,isFocused:K,listSelectedIndex:Te,mode:o})}),m&&x&&sn.createElement(Zo,{height:d,ticket:x}))},Qo=sn.memo(pd);import{render as vd}from"ink";import{Writable as yd}from"node:stream";var Ct=e=>String(e).padStart(2,"0"),xd=e=>{let t=e.getUTCFullYear(),n=Ct(e.getUTCMonth()+1),r=Ct(e.getUTCDate()),o=Ct(e.getUTCHours()),i=Ct(e.getUTCMinutes()),d=Ct(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${d}`},Nd=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",hd=async(e,{width:t,height:n})=>{let r="",o=new yd({write(d,l,u){let m=Id(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=vd(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),i.unmount(),r},Id=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ti=async()=>{let{viewMode:e}=_(),{currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=f(),d=r.find(A=>A.context==="BOARD");if(!d)return s("No board found to export");let l=120,u=40,m=await hd(fd.createElement(Qo,{height:u,width:l,swimlanes:(i[d.id]??[]).filter(A=>A!==void 0&&kt(A)),currentNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return s("Failed to render board export");let p=fe(process.cwd());if(a(p))return s("Unable to export, epiq root not found");let x=new Date,h=xd(x),C=`board_${Nd(d.title)}_${h}.md`,R=jr(p.value);ei.mkdirSync(R,{recursive:!0});let S=gd.join(R,C),E=`# Board - ${d.title}
7
7
  Date: ${x.toISOString()}
8
8
 
@@ -56,4 +56,4 @@ ${o.message}`):c("Staged state branch event file",void 0)},Ki=async({repoRoot:e,
56
56
  ${i.message}`):c("Pushed state branch",!0)},qi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=st(e);if(a(o))return o;let i=o.value,d=[pn(),await Xd({repoRoot:e,stateBranchName:i}),await xr({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await Qd({stateBranchRoot:t,stateBranchName:i}),await Pi(t),n?await ec({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return s(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import hn from"node:fs";import hr from"node:path";import{decodeTime as tc}from"ulid";var Nr=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Vi=e=>{let[t]=e.id;return tc(t)},nc=e=>{let{userId:t,userName:n,...r}=e;return r},rc=e=>e.length===0?"":e.map(t=>JSON.stringify(nc(t))).join(`
57
57
  `)+`
58
58
  `,oc=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Nr(r),r);return[...n.values()].sort((r,o)=>{let i=Vi(r)-Vi(o);return i!==0?i:Nr(r).localeCompare(Nr(o))})},Ir=({sourceFile:e,targetFile:t})=>{let n=$t(e);if(a(n))return s(n.message);let r=$t(t);if(a(r))return s(r.message);let o=oc(r.value,n.value),i=rc(o);return(hn.existsSync(t)?hn.readFileSync(t,"utf8"):"")===i?c("Event file already merged",!1):(hn.mkdirSync(hr.dirname(t),{recursive:!0}),hn.writeFileSync(t,i,"utf8"),c("Merged event file",!0))},In=({repoRoot:e,stateBranchRoot:t})=>{let n=Ti(t);if(a(n))return s(n.message);let r=Ge(t),o=Ge(e),i=!1;for(let d of n.value){let l=hr.join(r,d),u=hr.join(o,d),m=Ir({sourceFile:l,targetFile:u});if(a(m))return s(m.message);i=i||m.value}return c("Hydrated event files from state branch",i)};var sc=async e=>{let t=await L({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},j=(e,t)=>s(`[${e}] ${t}`),Gi=async()=>{let e=eo(),t=await gn(process.cwd());if(a(t))return j(1,t.message);let n=t.value,r=await wt(n);if(a(r))return j(2,r.message);if(r.value)return j(2,"Cannot initialize Epiq while a git operation is in progress");let o=await sc(n);if(a(o))return j(2.5,o.message);if(o.value)return j(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(kn(n))return j(4,"Epiq project already initialized");let i=Kt();if(!i.isSetupDone||!i.userName)return j(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=_(),l=d.userName,u=d.userId;if(!u||!l)return j(5,"Missing Epiq user id");let m=e.stateBranch,p=await vn({repoRoot:n,branch:m});if(a(p))return j(6,p.message);let x=await xn({repoRoot:n,stateBranchName:e.stateBranch});if(a(x))return j(6,x.message);let h=pn();if(a(h))return j(7,h.message);let C=zi.join(mn(),e.projectId),R=await xr({repoRoot:n,stateBranchRoot:C,stateBranchName:e.stateBranch});if(a(R))return j(8,R.message);let S=zi.join(C,".epiq");ic.mkdirSync(S,{recursive:!0});let E=gi({userId:u,userName:l});if(a(E))return j(9,E.message);for(let Tn of E.value){let Dr=jt({event:Tn,rootDir:C});if(a(Dr))return j(9,Dr.message)}let A=await Nn({stateBranchRoot:C,eventFileName:Ee({userId:u,userName:l})});if(a(A))return j(10,A.message);let K=await it({cwd:C,message:"[epiq:init]"});if(a(K))return j(10,K.message);let Te=await Ci(n);if(a(Te))return j(12,Te.message);let ie=no({repoRoot:n,fileContents:e});if(a(ie))return j(13,ie.message);let wr=await H.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(wr))return j(14,wr.message);let Tr=await H.commit({cwd:n,message:"[epiq:init-project]"});if(a(Tr))return j(14,Tr.message);let Mr=In({repoRoot:n,stateBranchRoot:C});if(a(Mr))return j(15,Mr.message);let wn="Project initialized!",Pr=await Mt({repoRoot:n,stateBranchRoot:C});a(Pr)&&(wn+=` Warn: [init:16] ${Pr.message}`);let kr=await H.push({cwd:n});a(kr)&&(wn+=` Warn: [init:17] ${kr.message}`);let Fr=Fe(E.value).filter(a);if(Fr.length>0)return j(18,Fr.map(Tn=>Tn.message).join(`
59
- `));let{rootNodeId:Ms,nodes:Ps}=f();return D.navigate({currentNode:Ps[Ms],selectedIndex:0}),I({hasProject:!0,mode:g.DEFAULT}),c(wn,null)};import{ulid as dc}from"ulid";import{ulid as ac}from"ulid";var Yi=null,Be=()=>structuredClone(Yi),Pt=e=>Yi=e,Xi=()=>{let{currentNode:e,selectedIndex:t}=f(),r=b(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")};var Ji=({id:e,parentId:t,position:n={at:"end"}})=>{let r=q();if(a(r))return s("Unable to resolve user ID");let o=ye(t,e,n,r.value);return a(o)?o:c("Created pending move state",{id:ac(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},Zi=e=>{Pt(e);let t=vt(e,!0);return a(t)?t:c("Node moved successfully",t.value)};function Er(e){let t=Xi();if(a(t))return t;let{currentNode:n,nodes:r}=f();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=$(o.id),d=i.findIndex(({id:m})=>m===n.id);if(d<0)return s("Current node not found among siblings");let l=i[d+e];if(!l)return s("Missing sibling node");let u=Ji({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Zi(u.value)}function Cr(e){let t=Xi();if(a(t))return t;let{currentNode:n,selectedIndex:r}=f(),i=$(n.id)[r+e];if(!i)return s("Missing sibling node");let d=Ji({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return a(d)?d:Zi(d.value)}var Qi=()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t}=ee().commandMeta,n=()=>{let l=Be();if(!l)return s("No pending move state");let u=l.payload.id;if(!f().nodes[u])return s("Moved node not found");let p=l.payload.parent,x=f().nodes[p];if(!x)return s("Move parent not found");let h=b(p).findIndex(C=>C.id===u);return h===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:x,selectedIndex:h}),c("Synchronized navigation to moved node",null))},r=l=>{if(a(l))return s(l.message);let u=n();return a(u)?s(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:i}=f(),d=b(o.id)[i];if(!d)return I({mode:g.DEFAULT}),s("No move target");if(t==="start"){if(d.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!d.parentNodeId)return s("Target has no parent");let l=$(d.parentNodeId),u=l.findIndex(({id:R})=>R===d.id);if(u===-1)return s("Target not found among siblings");let m=l[u-1],p=l[u+1],x=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},h=ye(d.parentNodeId,d.id,x,e.value);if(a(h))return h;Pt({id:dc(),action:"move.node",payload:{id:d.id,parent:d.parentNodeId,rank:h.value},...e.value}),I({mode:g.MOVE});let C=n();return a(C)?s(C.message):c("Move initialized",null)}if(t==="next")return I({mode:g.MOVE}),r(Cr(1));if(t==="previous")return I({mode:g.MOVE}),r(Cr(-1));if(t==="to-next")return I({mode:g.MOVE}),r(Er(1));if(t==="to-previous")return I({mode:g.MOVE}),r(Er(-1));if(t==="confirm"){I({mode:g.DEFAULT});let l=Be();if(!l)return s("No pending move to confirm");let u=W(l);if(a(u))return u;let m=n();return a(m)?s(m.message):(Pt(null),c("Moved item",null))}return t==="cancel"?(Pt(null),I({mode:g.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")};import cc from"zod";var es=()=>{let e=ee().commandMeta.inputString,t=cc.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return s("Auto sync duration must be a number of at least 3000 ms");let n=ze({autoSyncDebounceMs:t.data});return a(n)?n:(ge({autoSyncIntervalMs:t.data}),I({mode:g.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))};var ts=()=>{let e=ee().commandMeta.modifier;if(e!=="yes"&&e!=="no")return s("Invalid response");let t=io(e),n=ze({autoSync:t});return a(n)?n:(ge({autoSync:t}),I({mode:g.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var ns=e=>Object.values(f().tags).find(t=>t.name===e),rs=e=>Object.values(f().contributors).find(t=>t.name===e),os=[{systemOnly:!0,intent:w.Move,mode:g.COMMAND_LINE,action:Qi},{intent:w.Delete,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];return r?W({id:V(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ee().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>Q(v.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return s("Invalid filter modifier");let d={target:r,operator:"=",value:t.trim()};return ce(l=>({...l,filters:e==="clear"?[]:[...l.filters,d],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:w.ViewHelp,mode:g.COMMAND_LINE,action:()=>(I({mode:g.HELP}),c("Viewing help",null))},{intent:w.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!ne(r))return s("Cannot close in this context");let o=f().nodes[te];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=ye(o.id,r.id,{at:"end"},e.value);if(a(i))return i;let d=W({id:V(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return a(d)?d:c("Issue closed",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Qe(r.id,"TICKET");if(a(o))return s("Cannot reopen in this context");let i=o.value,d=f().nodes[te];if(!d)return s("Unable to locate closed swimlane");if(i.parentNodeId!==d.id)return s("Issue is not closed");if(!ne(i))return s("Target node is not issue");let l=fi(i);if(!l)return s("Unable to resolve previous parent from issue history");if(l===d.id)return s("Previous parent resolves to closed swimlane");let u=f().nodes[l];if(!u)return s("Previous parent no longer exists");let m=ye(u.id,i.id,{at:"end"},e.value);if(a(m))return m;let p=W({id:V(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return a(p)?p:c("Issue reopened",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Init,mode:g.COMMAND_LINE,action:Gi},{intent:w.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=q();if(a(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=f(),d=l=>{let u=W(l);if(a(u))return u;let m=N.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=N.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:N.getSiblings(m.parentNodeId).findIndex(({id:x})=>x===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=f(),u=N.getNode(l);if(!u)return s("Workspace not found");let m=De(u.id,n.value);return a(m)?m:d({id:V(),action:"add.board",payload:{id:V(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let l=Oe(r,"BOARD");if(a(l))return s("Unable to add swimlane in this context");let u=De(l.value.id,n.value);return a(u)?u:d({id:V(),action:"add.swimlane",payload:{id:V(),name:t.inputString,parent:l.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let l=b(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let E=Oe(r,"SWIMLANE");return a(E)?null:E.value})();if(!u)return s("Unable to add issue in this context");let m=De(u.id,n.value);if(a(m))return m;let p=ln({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(a(p))return p;let x=p.value,h=Fe(x);if(h.some(E=>a(E)))return s("Issue create failed: "+h.filter(a).map(E=>E.message).filter(Boolean).join(", "));let C=h[0];if(!C||a(C))return s("Issue creation failed");let S=x.find(E=>E.action==="add.issue")?.payload.id;return S?(D.navigate({currentNode:u,selectedIndex:N.getSiblings(u.id).findIndex(({id:E})=>E===S)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Rename,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Oo();return o?W({id:V(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=ns(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=f();if(!i)return s("Invalid untag target");let d=Qe(i.id,"TICKET");if(a(d))return s("Unable to untag issue in this context");let l=d.value,u=N.getFieldByTitle(l.id,"Tags");if(!u)return s("Unable to locate tags field");let m=b(u.id).find(p=>p.props?.value===o.id);return m?W({id:V(),action:"untag.issue",payload:{id:m.id,target:l.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=f(),d=b(i.id)[o];if(!d)return s("Invalid tag target");let l=Qe(d.id,"TICKET");if(a(l))return s("Unable to tag issue in this context");let u=l.value,m=ns(r),p;if(m)p=m.id;else{let R=V(),S=W({id:V(),action:"create.tag",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(a(S))return S;p=S.value.result.id}let x=N.getFieldByTitle(u.id,"Tags");if(!x)return s("Unable to locate tags field");if(b(x.id).some(R=>R.props?.value===p))return s("Already tagged with that tag");let C=De(x.id,e.value);return a(C)?C:W({id:V(),action:"tag.issue",payload:{id:V(),target:u.id,tagId:p,rank:C.value},...e.value})},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=f(),d=b(i.id)[o];if(!d)return s("Invalid assign target");let l=Qe(d.id,"TICKET");if(a(l))return s("Unable to assign issue in this context");let u=l.value,m=rs(r),p;if(m)p=m.id;else{let R=V(),S=W({id:V(),action:"create.contributor",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(a(S))return S;p=S.value.result.id}let x=N.getFieldByTitle(u.id,"Assignees");if(!x)return s("Unable to locate assignees field");if(b(x.id).some(R=>R.props?.value===p))return s("Assignee already assigned");let C=De(x.id,e.value);return a(C)?C:W({id:V(),action:"assign.issue",payload:{id:V(),target:u.id,contributor:p,rank:C.value},...e.value})},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=rs(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=f();if(!i)return s("Invalid unassign target");let d=Qe(i.id,"TICKET");if(a(d))return s("Unable to unassign in this context");let l=d.value,u=N.getFieldByTitle(l.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=b(u.id).find(p=>p.props?.value===o.id);return m?W({id:V(),action:"unassign.issue",payload:{id:m.id,target:l.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Sync,mode:g.COMMAND_LINE,action:async()=>{if(f().syncStatus.status==="syncing")return s("Sync already in progress");let e=ri();U(()=>""),I({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=_();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=q();if(a(r)||!r.value)return s("Unable to resolve event log path");let o=Ee(r.value),i=await Ze({ownEventFileName:o});if(a(i))return I({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let d=Pe(process.cwd());if(a(d))return d;let l=mt(d.value);if(a(l))return s(`Unable to load events. ${l.message}`);let u=un({eventLog:l.value,hasProject:!0});if(a(u))return s(`Unable to boot synced state. ${u.message}`);I({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let m=oi(e);return a(m)?m:c("Synced",!0)}},{intent:w.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Oe(f().breadCrumb,"BOARD");if(a(e))return e;let t=fe(process.cwd());if(a(t))throw new Error(t.message);let n=mt(t.value);if(a(n))return s(n.message);let r=n.value,{modifier:o}=ee().commandMeta,i;if(o==="now"){let h=br();if(a(h))return h;let C=yt(r);return C.some(a)?s(C.map(R=>R.message).join(", ")):(I({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let h=f().eventLog.at(-2),C=Vn(h);if(C===null)return s("No previous event to peek");i=C}else if(o==="next"){let h=f().unappliedEvents.at(0),C=Vn(h);if(C===null)return s("No next event to peek");i=C}else{let h=Gt(o);if(!h)return s("Invalid peek date");i=h.getTime()}let d=e.value.id,{appliedEvents:l,unappliedEvents:u}=Vr(r,i),m=br();if(a(m))return m;let p=yt(l);if(p.some(a))return s(p.map(h=>h.message).join(", "));let x=f().nodes[d];return x?(D.navigate({currentNode:x,selectedIndex:0}),I({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:w.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await ti();return a(e)?e:(I({mode:g.DEFAULT}),c("Export successful",!0))}},{intent:w.Exit,mode:g.COMMAND_LINE,action:async()=>(D.exit(),c("Exit successful",!0))},{intent:w.Edit,mode:g.COMMAND_LINE,action:(e,t)=>{if(t.modifier===Le.DESCRIPTION)return Ni();if(t.modifier===Le.TITLE){let n=q();if(a(n))return s("Unable to resolve user ID");let{currentNode:r,selectedIndex:o}=f(),i=b(r.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let d=t.inputString.trim();return d?W({id:V(),action:"edit.title",payload:{id:i.id,name:d},...n.value}):s("Provide a new name")}return s("Unknown edit command")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Config,mode:g.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case Y.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=_(),d=n||i,l=r??V();if(!d||!l)return s("Unable to resolve user name or id");let u=ze({userName:d,userId:l,preferredEditor:o??""});return a(u)?u:(ge({userName:d,userId:l}),I({mode:g.DEFAULT}),c(`Username set to "${d}"`,null))}case Y.EDITOR:{if(!n)return s("No editor provided");let r=ze({preferredEditor:n});return a(r)?r:(ge({preferredEditor:n}),I({mode:g.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case Y.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(ge({viewMode:n}),c(`View set to "${n}"`,null));case Y.AUTOSYNC:return ts();case Y.SYNC_DEBOUNCE_MS:return es();default:return s("Unknown config command")}}}];var lc=new Set(["peek","filter","view-help"]),me=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ee();if(!t)return s("No command to confirm");if(!e&&n===He.Invalid)return s("Invalid command");let i=Uo(t);ko();let{readOnly:d}=f();if(d&&!lc.has(i))return It({status:Me.Fail,message:"Command not available in readonly state",value:null});let l=os.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return It({status:Me.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return It({status:Me.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?It(u):(Fo({addToHistory:!e}),l.onSuccess?.(),_().autoSync&&Qr(),u)};var En=[{intent:T.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move cancel"),me({isForceExecutedBySystem:!0}))},{intent:T.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move start"),me({isForceExecutedBySystem:!0}))},{intent:T.ConfirmMove,mode:g.MOVE,action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move confirm"),me({isForceExecutedBySystem:!0}))}],Cn=[{intent:T.MovePreviousItem,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move previous"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveNextItem,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move next"),me({isForceExecutedBySystem:!0})):s("No pending move")}],is=[{intent:T.MoveToNextContainer,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move to-next"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveToPreviousContainer,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move to-previous"),me({isForceExecutedBySystem:!0})):s("No pending move")}];var ss={[P.WORKSPACE]:[...En,...Cn],[P.BOARD]:[...En,...Cn],[P.SWIMLANE]:[...En,...Cn,...is],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var as=[{intent:T.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>`${v.NEW} `),c("Adding new item",null))},{intent:T.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>`${v.DELETE} `),c("Deleting item",null))},{intent:T.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>""),c("Entering command line mode",null))},{intent:T.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=f();if(!$(e?.id??"")?.length){if(e?.title===G.DESCRIPTION)return U(()=>v.EDIT+"description "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(e?.title===G.ASSIGNEES)return U(()=>v.ASSIGN+" "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(e?.title===G.TAGS)return U(()=>v.TAG+" "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(t.title===G.DESCRIPTION&&e?.context==="TEXT")return U(()=>v.EDIT+"description "),I({mode:g.COMMAND_LINE}),c("Propose command",!0)}return D.enterChildNode(),c("Entering context",null)}},{intent:T.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),c("Exiting context",null))},{intent:T.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:T.NavNextItem,mode:g.DEFAULT,action:()=>(D.navigateToNextItem(),c("Navigating to next item",null))},{intent:T.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(D.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:T.NavToNextContainer,mode:g.DEFAULT,action:()=>(D.navigateToNextContainer(),c("Navigating to next container",null))},{intent:T.Edit,mode:g.DEFAULT,action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"edit"),me(),c("Fired command",!0))},{intent:T.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(ge({viewMode:"dense"}),c("View set",null))},{intent:T.SetViewWide,mode:g.DEFAULT,action:()=>(ge({viewMode:"wide"}),c("View set",null))}];var uc=500,mc=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ds=e=>{let t=mc(e);t&&U(n=>(n+t).slice(0,uc))};var cs=[{intent:T.ViewHelp,mode:g.DEFAULT,action:()=>(I({mode:g.HELP}),c("Viewing help",null))},{intent:T.Exit,mode:g.HELP,action:()=>(I({mode:g.DEFAULT}),c("Exiting help",null))},{intent:T.Confirm,mode:g.COMMAND_LINE,action:()=>(me(),c("Executing command",null))},{intent:T.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(Qn(-1),c("Moving cursor left",null))},{intent:T.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(Qn(1),c("Moving cursor right",null))},{intent:T.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(er("left"),c("Moving cursor left of word",null))},{intent:T.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(er("right"),c("Moving cursor right of word",null))},{intent:T.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(I({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:T.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(U((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:T.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(ds(t??""),c("Capturing input",null))},{intent:T.EraseInput,mode:g.COMMAND_LINE,action:()=>(Mo(),c("Erasing input",null))},{intent:T.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Po(),c("Erasing input word",null))},{intent:T.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Do(),c("Getting last command from history",null))},{intent:T.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Lo(),c("Getting next command from history",null))}];import pc from"chalk";var bn=": for command line",ls="q to exit",us=`${pc.hex(M.accent)("m")} to confirm`,Sr={[P.WORKSPACE]:[bn],[P.BOARD]:[bn],[P.BOARD+g.COMMAND_LINE]:[bn],[P.SWIMLANE]:[bn],[P.TICKET+g.HELP]:[ls],[P.SWIMLANE+g.HELP]:[ls],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[us],[P.TICKET+g.MOVE]:[us]};var Sn=e=>e.trim().toLocaleLowerCase(),gc=(e,t)=>{let n=N.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},fc=e=>{let{tags:t}=f(),n=N.getFieldByTitle(e,"Tags");return n?$(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},vc=e=>{let{contributors:t}=f(),n=N.getFieldByTitle(e,"Assignees");return n?$(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},ms=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return Sn(e.title??"").includes(n);case"description":return Sn(gc(e.id,G.DESCRIPTION)).includes(n);case"tag":return fc(e.id).map(Sn).some(l=>l.includes(n));case"assignee":return vc(e.id).map(Sn).some(l=>l.includes(n));default:return!0}};function ps(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var gs=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var Rn,Rr,Ar=new Set,fs=()=>{for(let e of Ar)e()},xc=e=>(Ar.add(e),()=>Ar.delete(e));function vs(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let l=o[t];if(!l)return s("Unable to derive state, currentNode not found");let u=ps(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,x=Sr[p+n]??Sr[p]??[],h=[...as,...ss[p]??[],...cs],C=gs(h),R=Nc(o,i),S=R[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:m,availableHints:x,availableActions:h,actionIndex:C,selectedNode:S,renderedChildrenIndex:R})}var f=()=>(Rn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Rn);function xt(e){Rr=e;let t=Pe(process.cwd()),n=!1;if(!a(t)){let i=ke(t.value);if(a(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:n},o=vs(r);return a(o)?o:(Rn=o.value,fs(),c("State initialized",null))}function ce(e){let t=f(),n=e(t),r=vs(n);return a(r)?s(r.message??"Unable to update state"):(Rn=r.value,fs(),c("State updated",null))}var I=e=>ce(t=>({...t,...e}));var xe=()=>yc(xc,f,f),Nc=(e,t)=>{let n={};for(let r of Object.values(e))ne(r)&&t.length>0&&!t.every(o=>ms(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,i)=>{let d=e[o.id],l=e[i.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},b=e=>f()?.renderedChildrenIndex[e]??[],br=()=>Rr?xt(Rr):s("Cannot reset state: no initial workspace found");var ys=(e="Syncing...")=>{I({syncStatus:{status:"syncing",msg:e}})},xs=(e="Synced")=>{I({syncStatus:{status:"synced",msg:e}})},hc=e=>{I({syncStatus:{status:"outOfSync",msg:e}})},pe=e=>(hc(e),s(e));var Ec=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=pr({root:e,fileName:n}),o=pr({root:t,fileName:n});return Ic.existsSync(r)?Ir({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},Cc=async({cwd:e,ensureUpstream:t})=>{let n=await gn(e);if(a(n))return s(n.message);let r=n.value,o=Ai({repoRoot:r});if(a(o))return s(o.message);let i=o.value,d=await wt(r);if(a(d))return s(d.message);if(d.value)return s("Cannot sync while a git operation is in progress in the current repo");let l=await Hi(r);if(a(l))return s(l.message);let u=await qi({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(a(u))return s(u.message);let m=await wt(i);if(a(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=Mi(r,i);return a(p)?s(p.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},Ns=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Ec({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(a(r))return s(r.message);let o=await $i(t);if(a(o))return s(o.message);if(!r.value&&!o.value)return c("Own event file already up to date in state branch",{createdCommit:!1});let i=await Nn({stateBranchRoot:t,eventFileName:n});if(a(i))return s(i.message);let d=await Ki({repoRoot:e,stateBranchRoot:t});return a(d)?s(d.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:d.value})},Ze=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");ys("Syncing");let n=await Cc({cwd:e,ensureUpstream:!0});if(a(n))return pe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,d=await Wi(r);if(a(d))return pe(d.message);if(d.value)return pe("Cannot run :sync while the repository is in detached HEAD state");let l=!1,u,m=!1,p=!1,x=!1,h=st(r);if(a(h))return pe(h.message);let C=h.value,R=await yr({cwd:o,branch:C});if(a(R))return pe(R.message);m=R.value;let S=In({repoRoot:r,stateBranchRoot:o});if(a(S))return pe(S.message);x=S.value;let E=await Ns({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(a(E))return pe(E.message);if(l=E.value.createdCommit,u=E.value.commitSha,l||i){let A=await Mt({stateBranchRoot:o,repoRoot:r}),K=A;if(a(A)&&_i(A.message)){let Te=await yr({cwd:o,branch:C});if(a(Te))return pe(Te.message);let ie=await Ns({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(a(ie))return pe(ie.message);ie.value.createdCommit&&(l=!0,u=ie.value.commitSha),K=await Mt({stateBranchRoot:o,repoRoot:r})}if(a(K))return pe(K.message);p=K.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(l){let A=await L({args:["rev-parse","HEAD"],cwd:o});if(a(A))return pe(A.message);u=A.value.stdout.trim()}return xs(p?"Synced and pushed":m||x||l?"Synced local state":"Already synced"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,hydrated:x,bootstrapped:i})};var Ye=e=>{let t=fe(e??process.cwd());if(a(t))return t;let n=mt(t.value);if(a(n))return s(n.message);let r=un({eventLog:n.value,hasProject:!0});return a(r)?s(r.message):c("Booted Epiq state",{root:t.value})},An=()=>{let e=pi();return a(e)?s(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):s("Unable to retrieve user name"):s("Unable to retrieve user id")},Is=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r?b(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},bc=e=>Is(e,"Tags").map(t=>N.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),Sc=e=>Is(e,"Assignees").map(t=>N.getContributor(t)).filter(Boolean).map(t=>({id:t.id,name:t.name})),Es=(e={})=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",n)},Cs=(e={})=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===te,readonly:!!r.readonly}));return c("Listed swimlanes",n)},bs=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(ne).filter(r=>e.includeClosed||r.parentNodeId!==te).map(r=>({id:r.id,title:Xe(r.title),description:go(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===te,readonly:!!r.readonly,tags:bc(r),assignees:Sc(r)}));return c("Listed issues",n)},Ss=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=De(e.parentId,n.value);if(a(r))return r;let o=ln({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let i=o.value,l=Fe(i).find(a);if(l)return s(l.message);let u=i.find(m=>m.action==="add.issue")?.payload.id;return u?c("Created issue",{id:u,title:e.title,parentId:e.parentId}):s("Unable to determine created issue id")},Rs=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=ye(te,e.issueId,{at:"end"},n.value);if(a(r))return r;let o={id:hs(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:te,rank:r.value}},d=Fe([o]).find(a);return d?s(d.message):c("Closed issue",{id:e.issueId})},As=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=ye(e.parentId,e.issueId,e.position??{at:"end"},n.value);if(a(r))return r;let o={id:hs(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:r.value}},d=Fe([o]).find(a);return d?s(d.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},ws=async(e={})=>{let t=fe(e.repoRoot??process.cwd());if(a(t))return s("Sync failed");let n=An();if(a(n))return n;let r=await Ze({cwd:t.value,ownEventFileName:Ee(n.value)});return a(r)?r:c("Synced",r.value)},Ts=(e={})=>{let t=Ye(e.repoRoot);return a(t)?t:c("Retrieved Epiq state",{root:t.value.root,nodes:f().nodes,rootNodeId:f().rootNodeId,currentNode:f().currentNode,selectedIndex:f().selectedIndex,eventLog:f().eventLog})};var _e=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),wc=()=>{let e=new Rc({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await Ts(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:F.object({repoRoot:F.string().optional(),includeClosed:F.boolean().optional()})},async t=>_e(await bs(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await Es(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:F.object({repoRoot:F.string().optional(),boardId:F.string().optional()})},async t=>_e(await Cs(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:F.object({title:F.string().min(1),parentId:F.string().min(1),repoRoot:F.string().optional()})},async t=>_e(await Ss(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:F.object({issueId:F.string().min(1),repoRoot:F.string().optional()})},async t=>_e(await Rs(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:F.object({issueId:F.string().min(1),parentId:F.string().min(1),position:F.discriminatedUnion("at",[F.object({at:F.literal("start")}),F.object({at:F.literal("end")}),F.object({at:F.literal("before"),sibling:F.string().min(1)}),F.object({at:F.literal("after"),sibling:F.string().min(1)})]).optional(),repoRoot:F.string().optional()})},async t=>_e(await As(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await ws(t))),e},Tc=async()=>{let e=wc(),t=new Ac;await e.connect(t)};await Tc();export{wc as createMcpServer,_e as resultJson,Tc as startMcpServer};
59
+ `));let{rootNodeId:Ms,nodes:Ps}=f();return D.navigate({currentNode:Ps[Ms],selectedIndex:0}),I({hasProject:!0,mode:g.DEFAULT}),c(wn,null)};import{ulid as dc}from"ulid";import{ulid as ac}from"ulid";var Yi=null,Be=()=>structuredClone(Yi),Pt=e=>Yi=e,Xi=()=>{let{currentNode:e,selectedIndex:t}=f(),r=b(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")};var Ji=({id:e,parentId:t,position:n={at:"end"}})=>{let r=q();if(a(r))return s("Unable to resolve user ID");let o=ye(t,e,n,r.value);return a(o)?o:c("Created pending move state",{id:ac(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},Zi=e=>{Pt(e);let t=vt(e,!0);return a(t)?t:c("Node moved successfully",t.value)};function Er(e){let t=Xi();if(a(t))return t;let{currentNode:n,nodes:r}=f();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=$(o.id),d=i.findIndex(({id:m})=>m===n.id);if(d<0)return s("Current node not found among siblings");let l=i[d+e];if(!l)return s("Missing sibling node");let u=Ji({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Zi(u.value)}function Cr(e){let t=Xi();if(a(t))return t;let{currentNode:n,selectedIndex:r}=f(),i=$(n.id)[r+e];if(!i)return s("Missing sibling node");let d=Ji({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return a(d)?d:Zi(d.value)}var Qi=()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t}=ee().commandMeta,n=()=>{let l=Be();if(!l)return s("No pending move state");let u=l.payload.id;if(!f().nodes[u])return s("Moved node not found");let p=l.payload.parent,x=f().nodes[p];if(!x)return s("Move parent not found");let h=b(p).findIndex(C=>C.id===u);return h===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:x,selectedIndex:h}),c("Synchronized navigation to moved node",null))},r=l=>{if(a(l))return s(l.message);let u=n();return a(u)?s(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:i}=f(),d=b(o.id)[i];if(!d)return I({mode:g.DEFAULT}),s("No move target");if(t==="start"){if(d.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!d.parentNodeId)return s("Target has no parent");let l=$(d.parentNodeId),u=l.findIndex(({id:R})=>R===d.id);if(u===-1)return s("Target not found among siblings");let m=l[u-1],p=l[u+1],x=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},h=ye(d.parentNodeId,d.id,x,e.value);if(a(h))return h;Pt({id:dc(),action:"move.node",payload:{id:d.id,parent:d.parentNodeId,rank:h.value},...e.value}),I({mode:g.MOVE});let C=n();return a(C)?s(C.message):c("Move initialized",null)}if(t==="next")return I({mode:g.MOVE}),r(Cr(1));if(t==="previous")return I({mode:g.MOVE}),r(Cr(-1));if(t==="to-next")return I({mode:g.MOVE}),r(Er(1));if(t==="to-previous")return I({mode:g.MOVE}),r(Er(-1));if(t==="confirm"){I({mode:g.DEFAULT});let l=Be();if(!l)return s("No pending move to confirm");let u=W(l);if(a(u))return u;let m=n();return a(m)?s(m.message):(Pt(null),c("Moved item",null))}return t==="cancel"?(Pt(null),I({mode:g.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")};import cc from"zod";var es=()=>{let e=ee().commandMeta.inputString,t=cc.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return s("Auto sync duration must be a number of at least 3000 ms");let n=ze({autoSyncDebounceMs:t.data});return a(n)?n:(ge({autoSyncIntervalMs:t.data}),I({mode:g.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))};var ts=()=>{let e=ee().commandMeta.inputString.trim();if(e!=="yes"&&e!=="no")return s("Invalid response");let t=io(e),n=ze({autoSync:t});return a(n)?n:(ge({autoSync:t}),I({mode:g.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var ns=e=>Object.values(f().tags).find(t=>t.name===e),rs=e=>Object.values(f().contributors).find(t=>t.name===e),os=[{systemOnly:!0,intent:w.Move,mode:g.COMMAND_LINE,action:Qi},{intent:w.Delete,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];return r?W({id:V(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ee().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>Q(v.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return s("Invalid filter modifier");let d={target:r,operator:"=",value:t.trim()};return ce(l=>({...l,filters:e==="clear"?[]:[...l.filters,d],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:w.ViewHelp,mode:g.COMMAND_LINE,action:()=>(I({mode:g.HELP}),c("Viewing help",null))},{intent:w.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!ne(r))return s("Cannot close in this context");let o=f().nodes[te];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=ye(o.id,r.id,{at:"end"},e.value);if(a(i))return i;let d=W({id:V(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return a(d)?d:c("Issue closed",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Qe(r.id,"TICKET");if(a(o))return s("Cannot reopen in this context");let i=o.value,d=f().nodes[te];if(!d)return s("Unable to locate closed swimlane");if(i.parentNodeId!==d.id)return s("Issue is not closed");if(!ne(i))return s("Target node is not issue");let l=fi(i);if(!l)return s("Unable to resolve previous parent from issue history");if(l===d.id)return s("Previous parent resolves to closed swimlane");let u=f().nodes[l];if(!u)return s("Previous parent no longer exists");let m=ye(u.id,i.id,{at:"end"},e.value);if(a(m))return m;let p=W({id:V(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return a(p)?p:c("Issue reopened",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Init,mode:g.COMMAND_LINE,action:Gi},{intent:w.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=q();if(a(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=f(),d=l=>{let u=W(l);if(a(u))return u;let m=N.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=N.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:N.getSiblings(m.parentNodeId).findIndex(({id:x})=>x===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=f(),u=N.getNode(l);if(!u)return s("Workspace not found");let m=De(u.id,n.value);return a(m)?m:d({id:V(),action:"add.board",payload:{id:V(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let l=Oe(r,"BOARD");if(a(l))return s("Unable to add swimlane in this context");let u=De(l.value.id,n.value);return a(u)?u:d({id:V(),action:"add.swimlane",payload:{id:V(),name:t.inputString,parent:l.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let l=b(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let E=Oe(r,"SWIMLANE");return a(E)?null:E.value})();if(!u)return s("Unable to add issue in this context");let m=De(u.id,n.value);if(a(m))return m;let p=ln({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(a(p))return p;let x=p.value,h=Fe(x);if(h.some(E=>a(E)))return s("Issue create failed: "+h.filter(a).map(E=>E.message).filter(Boolean).join(", "));let C=h[0];if(!C||a(C))return s("Issue creation failed");let S=x.find(E=>E.action==="add.issue")?.payload.id;return S?(D.navigate({currentNode:u,selectedIndex:N.getSiblings(u.id).findIndex(({id:E})=>E===S)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Rename,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Oo();return o?W({id:V(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=ns(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=f();if(!i)return s("Invalid untag target");let d=Qe(i.id,"TICKET");if(a(d))return s("Unable to untag issue in this context");let l=d.value,u=N.getFieldByTitle(l.id,"Tags");if(!u)return s("Unable to locate tags field");let m=b(u.id).find(p=>p.props?.value===o.id);return m?W({id:V(),action:"untag.issue",payload:{id:m.id,target:l.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=f(),d=b(i.id)[o];if(!d)return s("Invalid tag target");let l=Qe(d.id,"TICKET");if(a(l))return s("Unable to tag issue in this context");let u=l.value,m=ns(r),p;if(m)p=m.id;else{let R=V(),S=W({id:V(),action:"create.tag",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(a(S))return S;p=S.value.result.id}let x=N.getFieldByTitle(u.id,"Tags");if(!x)return s("Unable to locate tags field");if(b(x.id).some(R=>R.props?.value===p))return s("Already tagged with that tag");let C=De(x.id,e.value);return a(C)?C:W({id:V(),action:"tag.issue",payload:{id:V(),target:u.id,tagId:p,rank:C.value},...e.value})},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=f(),d=b(i.id)[o];if(!d)return s("Invalid assign target");let l=Qe(d.id,"TICKET");if(a(l))return s("Unable to assign issue in this context");let u=l.value,m=rs(r),p;if(m)p=m.id;else{let R=V(),S=W({id:V(),action:"create.contributor",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(a(S))return S;p=S.value.result.id}let x=N.getFieldByTitle(u.id,"Assignees");if(!x)return s("Unable to locate assignees field");if(b(x.id).some(R=>R.props?.value===p))return s("Assignee already assigned");let C=De(x.id,e.value);return a(C)?C:W({id:V(),action:"assign.issue",payload:{id:V(),target:u.id,contributor:p,rank:C.value},...e.value})},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=rs(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=f();if(!i)return s("Invalid unassign target");let d=Qe(i.id,"TICKET");if(a(d))return s("Unable to unassign in this context");let l=d.value,u=N.getFieldByTitle(l.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=b(u.id).find(p=>p.props?.value===o.id);return m?W({id:V(),action:"unassign.issue",payload:{id:m.id,target:l.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Sync,mode:g.COMMAND_LINE,action:async()=>{if(f().syncStatus.status==="syncing")return s("Sync already in progress");let e=ri();U(()=>""),I({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=_();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=q();if(a(r)||!r.value)return s("Unable to resolve event log path");let o=Ee(r.value),i=await Ze({ownEventFileName:o});if(a(i))return I({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let d=Pe(process.cwd());if(a(d))return d;let l=mt(d.value);if(a(l))return s(`Unable to load events. ${l.message}`);let u=un({eventLog:l.value,hasProject:!0});if(a(u))return s(`Unable to boot synced state. ${u.message}`);I({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let m=oi(e);return a(m)?m:c("Synced",!0)}},{intent:w.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Oe(f().breadCrumb,"BOARD");if(a(e))return e;let t=fe(process.cwd());if(a(t))throw new Error(t.message);let n=mt(t.value);if(a(n))return s(n.message);let r=n.value,{modifier:o}=ee().commandMeta,i;if(o==="now"){let h=br();if(a(h))return h;let C=yt(r);return C.some(a)?s(C.map(R=>R.message).join(", ")):(I({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let h=f().eventLog.at(-2),C=Vn(h);if(C===null)return s("No previous event to peek");i=C}else if(o==="next"){let h=f().unappliedEvents.at(0),C=Vn(h);if(C===null)return s("No next event to peek");i=C}else{let h=Gt(o);if(!h)return s("Invalid peek date");i=h.getTime()}let d=e.value.id,{appliedEvents:l,unappliedEvents:u}=Vr(r,i),m=br();if(a(m))return m;let p=yt(l);if(p.some(a))return s(p.map(h=>h.message).join(", "));let x=f().nodes[d];return x?(D.navigate({currentNode:x,selectedIndex:0}),I({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:w.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await ti();return a(e)?e:(I({mode:g.DEFAULT}),c("Export successful",!0))}},{intent:w.Exit,mode:g.COMMAND_LINE,action:async()=>(D.exit(),c("Exit successful",!0))},{intent:w.Edit,mode:g.COMMAND_LINE,action:(e,t)=>{if(t.modifier===Le.DESCRIPTION)return Ni();if(t.modifier===Le.TITLE){let n=q();if(a(n))return s("Unable to resolve user ID");let{currentNode:r,selectedIndex:o}=f(),i=b(r.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let d=t.inputString.trim();return d?W({id:V(),action:"edit.title",payload:{id:i.id,name:d},...n.value}):s("Provide a new name")}return s("Unknown edit command")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Config,mode:g.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case Y.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=_(),d=n||i,l=r??V();if(!d||!l)return s("Unable to resolve user name or id");let u=ze({userName:d,userId:l,preferredEditor:o??""});return a(u)?u:(ge({userName:d,userId:l}),I({mode:g.DEFAULT}),c(`Username set to "${d}"`,null))}case Y.EDITOR:{if(!n)return s("No editor provided");let r=ze({preferredEditor:n});return a(r)?r:(ge({preferredEditor:n}),I({mode:g.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case Y.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(ge({viewMode:n}),c(`View set to "${n}"`,null));case Y.AUTOSYNC:return ts();case Y.SYNC_DEBOUNCE_MS:return es();default:return s("Unknown config command")}}}];var lc=new Set(["peek","filter","view-help"]),me=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ee();if(!t)return s("No command to confirm");if(!e&&n===He.Invalid)return s("Invalid command");let i=Uo(t);ko();let{readOnly:d}=f();if(d&&!lc.has(i))return It({status:Me.Fail,message:"Command not available in readonly state",value:null});let l=os.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return It({status:Me.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return It({status:Me.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?It(u):(Fo({addToHistory:!e}),l.onSuccess?.(),_().autoSync&&Qr(),u)};var En=[{intent:T.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move cancel"),me({isForceExecutedBySystem:!0}))},{intent:T.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move start"),me({isForceExecutedBySystem:!0}))},{intent:T.ConfirmMove,mode:g.MOVE,action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move confirm"),me({isForceExecutedBySystem:!0}))}],Cn=[{intent:T.MovePreviousItem,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move previous"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveNextItem,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move next"),me({isForceExecutedBySystem:!0})):s("No pending move")}],is=[{intent:T.MoveToNextContainer,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move to-next"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveToPreviousContainer,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move to-previous"),me({isForceExecutedBySystem:!0})):s("No pending move")}];var ss={[P.WORKSPACE]:[...En,...Cn],[P.BOARD]:[...En,...Cn],[P.SWIMLANE]:[...En,...Cn,...is],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var as=[{intent:T.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>`${v.NEW} `),c("Adding new item",null))},{intent:T.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>`${v.DELETE} `),c("Deleting item",null))},{intent:T.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>""),c("Entering command line mode",null))},{intent:T.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=f();if(!$(e?.id??"")?.length){if(e?.title===G.DESCRIPTION)return U(()=>v.EDIT+"description "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(e?.title===G.ASSIGNEES)return U(()=>v.ASSIGN+" "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(e?.title===G.TAGS)return U(()=>v.TAG+" "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(t.title===G.DESCRIPTION&&e?.context==="TEXT")return U(()=>v.EDIT+"description "),I({mode:g.COMMAND_LINE}),c("Propose command",!0)}return D.enterChildNode(),c("Entering context",null)}},{intent:T.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),c("Exiting context",null))},{intent:T.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:T.NavNextItem,mode:g.DEFAULT,action:()=>(D.navigateToNextItem(),c("Navigating to next item",null))},{intent:T.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(D.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:T.NavToNextContainer,mode:g.DEFAULT,action:()=>(D.navigateToNextContainer(),c("Navigating to next container",null))},{intent:T.Edit,mode:g.DEFAULT,action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"edit"),me(),c("Fired command",!0))},{intent:T.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(ge({viewMode:"dense"}),c("View set",null))},{intent:T.SetViewWide,mode:g.DEFAULT,action:()=>(ge({viewMode:"wide"}),c("View set",null))}];var uc=500,mc=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ds=e=>{let t=mc(e);t&&U(n=>(n+t).slice(0,uc))};var cs=[{intent:T.ViewHelp,mode:g.DEFAULT,action:()=>(I({mode:g.HELP}),c("Viewing help",null))},{intent:T.Exit,mode:g.HELP,action:()=>(I({mode:g.DEFAULT}),c("Exiting help",null))},{intent:T.Confirm,mode:g.COMMAND_LINE,action:()=>(me(),c("Executing command",null))},{intent:T.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(Qn(-1),c("Moving cursor left",null))},{intent:T.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(Qn(1),c("Moving cursor right",null))},{intent:T.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(er("left"),c("Moving cursor left of word",null))},{intent:T.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(er("right"),c("Moving cursor right of word",null))},{intent:T.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(I({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:T.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(U((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:T.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(ds(t??""),c("Capturing input",null))},{intent:T.EraseInput,mode:g.COMMAND_LINE,action:()=>(Mo(),c("Erasing input",null))},{intent:T.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Po(),c("Erasing input word",null))},{intent:T.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Do(),c("Getting last command from history",null))},{intent:T.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Lo(),c("Getting next command from history",null))}];import pc from"chalk";var bn=": for command line",ls="q to exit",us=`${pc.hex(M.accent)("m")} to confirm`,Sr={[P.WORKSPACE]:[bn],[P.BOARD]:[bn],[P.BOARD+g.COMMAND_LINE]:[bn],[P.SWIMLANE]:[bn],[P.TICKET+g.HELP]:[ls],[P.SWIMLANE+g.HELP]:[ls],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[us],[P.TICKET+g.MOVE]:[us]};var Sn=e=>e.trim().toLocaleLowerCase(),gc=(e,t)=>{let n=N.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},fc=e=>{let{tags:t}=f(),n=N.getFieldByTitle(e,"Tags");return n?$(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},vc=e=>{let{contributors:t}=f(),n=N.getFieldByTitle(e,"Assignees");return n?$(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},ms=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return Sn(e.title??"").includes(n);case"description":return Sn(gc(e.id,G.DESCRIPTION)).includes(n);case"tag":return fc(e.id).map(Sn).some(l=>l.includes(n));case"assignee":return vc(e.id).map(Sn).some(l=>l.includes(n));default:return!0}};function ps(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var gs=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var Rn,Rr,Ar=new Set,fs=()=>{for(let e of Ar)e()},xc=e=>(Ar.add(e),()=>Ar.delete(e));function vs(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let l=o[t];if(!l)return s("Unable to derive state, currentNode not found");let u=ps(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,x=Sr[p+n]??Sr[p]??[],h=[...as,...ss[p]??[],...cs],C=gs(h),R=Nc(o,i),S=R[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:m,availableHints:x,availableActions:h,actionIndex:C,selectedNode:S,renderedChildrenIndex:R})}var f=()=>(Rn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Rn);function xt(e){Rr=e;let t=Pe(process.cwd()),n=!1;if(!a(t)){let i=ke(t.value);if(a(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:n},o=vs(r);return a(o)?o:(Rn=o.value,fs(),c("State initialized",null))}function ce(e){let t=f(),n=e(t),r=vs(n);return a(r)?s(r.message??"Unable to update state"):(Rn=r.value,fs(),c("State updated",null))}var I=e=>ce(t=>({...t,...e}));var xe=()=>yc(xc,f,f),Nc=(e,t)=>{let n={};for(let r of Object.values(e))ne(r)&&t.length>0&&!t.every(o=>ms(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,i)=>{let d=e[o.id],l=e[i.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},b=e=>f()?.renderedChildrenIndex[e]??[],br=()=>Rr?xt(Rr):s("Cannot reset state: no initial workspace found");var ys=(e="Syncing...")=>{I({syncStatus:{status:"syncing",msg:e}})},xs=(e="Synced")=>{I({syncStatus:{status:"synced",msg:e}})},hc=e=>{I({syncStatus:{status:"outOfSync",msg:e}})},pe=e=>(hc(e),s(e));var Ec=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=pr({root:e,fileName:n}),o=pr({root:t,fileName:n});return Ic.existsSync(r)?Ir({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},Cc=async({cwd:e,ensureUpstream:t})=>{let n=await gn(e);if(a(n))return s(n.message);let r=n.value,o=Ai({repoRoot:r});if(a(o))return s(o.message);let i=o.value,d=await wt(r);if(a(d))return s(d.message);if(d.value)return s("Cannot sync while a git operation is in progress in the current repo");let l=await Hi(r);if(a(l))return s(l.message);let u=await qi({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(a(u))return s(u.message);let m=await wt(i);if(a(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=Mi(r,i);return a(p)?s(p.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},Ns=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Ec({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(a(r))return s(r.message);let o=await $i(t);if(a(o))return s(o.message);if(!r.value&&!o.value)return c("Own event file already up to date in state branch",{createdCommit:!1});let i=await Nn({stateBranchRoot:t,eventFileName:n});if(a(i))return s(i.message);let d=await Ki({repoRoot:e,stateBranchRoot:t});return a(d)?s(d.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:d.value})},Ze=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");ys("Syncing");let n=await Cc({cwd:e,ensureUpstream:!0});if(a(n))return pe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,d=await Wi(r);if(a(d))return pe(d.message);if(d.value)return pe("Cannot run :sync while the repository is in detached HEAD state");let l=!1,u,m=!1,p=!1,x=!1,h=st(r);if(a(h))return pe(h.message);let C=h.value,R=await yr({cwd:o,branch:C});if(a(R))return pe(R.message);m=R.value;let S=In({repoRoot:r,stateBranchRoot:o});if(a(S))return pe(S.message);x=S.value;let E=await Ns({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(a(E))return pe(E.message);if(l=E.value.createdCommit,u=E.value.commitSha,l||i){let A=await Mt({stateBranchRoot:o,repoRoot:r}),K=A;if(a(A)&&_i(A.message)){let Te=await yr({cwd:o,branch:C});if(a(Te))return pe(Te.message);let ie=await Ns({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(a(ie))return pe(ie.message);ie.value.createdCommit&&(l=!0,u=ie.value.commitSha),K=await Mt({stateBranchRoot:o,repoRoot:r})}if(a(K))return pe(K.message);p=K.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(l){let A=await L({args:["rev-parse","HEAD"],cwd:o});if(a(A))return pe(A.message);u=A.value.stdout.trim()}return xs(p?"Synced and pushed":m||x||l?"Synced local state":"Already synced"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,hydrated:x,bootstrapped:i})};var Ye=e=>{let t=fe(e??process.cwd());if(a(t))return t;let n=mt(t.value);if(a(n))return s(n.message);let r=un({eventLog:n.value,hasProject:!0});return a(r)?s(r.message):c("Booted Epiq state",{root:t.value})},An=()=>{let e=pi();return a(e)?s(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):s("Unable to retrieve user name"):s("Unable to retrieve user id")},Is=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r?b(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},bc=e=>Is(e,"Tags").map(t=>N.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),Sc=e=>Is(e,"Assignees").map(t=>N.getContributor(t)).filter(Boolean).map(t=>({id:t.id,name:t.name})),Es=(e={})=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",n)},Cs=(e={})=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===te,readonly:!!r.readonly}));return c("Listed swimlanes",n)},bs=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(ne).filter(r=>e.includeClosed||r.parentNodeId!==te).map(r=>({id:r.id,title:Xe(r.title),description:go(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===te,readonly:!!r.readonly,tags:bc(r),assignees:Sc(r)}));return c("Listed issues",n)},Ss=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=De(e.parentId,n.value);if(a(r))return r;let o=ln({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let i=o.value,l=Fe(i).find(a);if(l)return s(l.message);let u=i.find(m=>m.action==="add.issue")?.payload.id;return u?c("Created issue",{id:u,title:e.title,parentId:e.parentId}):s("Unable to determine created issue id")},Rs=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=ye(te,e.issueId,{at:"end"},n.value);if(a(r))return r;let o={id:hs(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:te,rank:r.value}},d=Fe([o]).find(a);return d?s(d.message):c("Closed issue",{id:e.issueId})},As=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=ye(e.parentId,e.issueId,e.position??{at:"end"},n.value);if(a(r))return r;let o={id:hs(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:r.value}},d=Fe([o]).find(a);return d?s(d.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},ws=async(e={})=>{let t=fe(e.repoRoot??process.cwd());if(a(t))return s("Sync failed");let n=An();if(a(n))return n;let r=await Ze({cwd:t.value,ownEventFileName:Ee(n.value)});return a(r)?r:c("Synced",r.value)},Ts=(e={})=>{let t=Ye(e.repoRoot);return a(t)?t:c("Retrieved Epiq state",{root:t.value.root,nodes:f().nodes,rootNodeId:f().rootNodeId,currentNode:f().currentNode,selectedIndex:f().selectedIndex,eventLog:f().eventLog})};var _e=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),wc=()=>{let e=new Rc({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await Ts(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:F.object({repoRoot:F.string().optional(),includeClosed:F.boolean().optional()})},async t=>_e(await bs(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await Es(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:F.object({repoRoot:F.string().optional(),boardId:F.string().optional()})},async t=>_e(await Cs(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:F.object({title:F.string().min(1),parentId:F.string().min(1),repoRoot:F.string().optional()})},async t=>_e(await Ss(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:F.object({issueId:F.string().min(1),repoRoot:F.string().optional()})},async t=>_e(await Rs(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:F.object({issueId:F.string().min(1),parentId:F.string().min(1),position:F.discriminatedUnion("at",[F.object({at:F.literal("start")}),F.object({at:F.literal("end")}),F.object({at:F.literal("before"),sibling:F.string().min(1)}),F.object({at:F.literal("after"),sibling:F.string().min(1)})]).optional(),repoRoot:F.string().optional()})},async t=>_e(await As(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await ws(t))),e},Tc=async()=>{let e=wc(),t=new Ac;await e.connect(t)};await Tc();export{wc as createMcpServer,_e as resultJson,Tc as startMcpServer};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "epiq",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "EPIQ - CLI based issue tracker",