epiq 0.4.6 → 0.4.8
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 +50 -49
- package/dist/mcp.js +47 -46
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,68 +1,69 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import zr from"chalk";import{render as hc}from"ink";import Ec from"meow";import Nc from"react";import{Box as Ze}from"ink";import q from"react";import ut from"chalk";import{monotonicFactory as $l,ulid as ke}from"ulid";import{useSyncExternalStore as Ol}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Bn(e){return e.context==="WORKSPACE"}function le(e){return e.context==="TICKET"}function Yr(e){return e.context==="FIELD"}var et=e=>e.context==="SWIMLANE",Xr=e=>e.context==="BOARD";var he={None:"none",Success:"success",Fail:"fail"},s=e=>({status:he.Fail,message:e,value:null}),c=(e,t)=>({status:he.Success,message:e,value:t}),l=e=>e.status==="fail",Ee=e=>e.status==="success";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Bt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Ut=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Un=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Jr=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},Qr=(e,t)=>t?e.get(t)??[]:[];var Zr=new WeakMap,ea=e=>{let t=Zr.get(e);return t||(t=Jr(e),Zr.set(e,t)),t};var eo=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Qr(ea(e),r).filter(i=>Bt(r,i)>=n)};var ta={hint:"",hints:[],overlap:0,remainder:""},to=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ta;let o=eo({wordList:r,inputToMatch:e,overlapThreshold:1});return na(t,o)},na=(e,t)=>{let n=t[0]??"",r=Bt(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,d=!!i,p=(d&&a?o:n)+(d&&a?":":" "),y=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:y}};var no=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var te={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:(e,t,n,r,o={},i="horizontal")=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[]}),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})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[]})};import{ulid as ia}from"ulid";var ze=24n,ra=ze*4n,gt=(1n<<ra)-1n,oa=/^[0-9a-f]+$/;function ro(e){return!e||!oa.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ne(e,t=ze){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 V(e,t){if(!e&&!t)return Ne(gt/2n,ze);let n=e?ro(e):c("Resolved lower bound",0n);if(l(n))return n;let r=t?ro(t):c("Resolved upper bound",gt);if(l(r))return r;let o=n.value,i=r.value;if(i<=o)return Ne(gt/2n,ze);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):Ne(a,ze)}function oo(){return Ne(gt/2n,ze)}function io(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=gt*BigInt(r+1)/(t+1n),i=Ne(o,ze);if(l(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var $n=(e,t)=>{let n=F(e),r=io(n.length);if(l(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],d=r.value[i];if(!a||!d)return s("Unable to assign rebalance rank");o[a.id]=d}return c("Created rebalance event",{id:ia(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var sa=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Ce,$t]=sa;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),aa={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=te.workspace(t,n,r);_n(o);let i=b.createNode(o);return l(i)?k(i.message??"Failed to initialize workspace",e):Bn(i.value)?c("Workspace initialized",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=te.workspace(t,n,r),i=b.createNode(o);return l(i)?k(i.message??"Failed to add workspace",e):Bn(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=b.createNode(te.board(t,n,r,o));return l(i)?k(i.message??"Unable to create board",e):Xr(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=b.createNode(te.swimlane(t,n,r,o));return l(i)?k(i.message??"Unable to create swimlane",e):et(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=b.createNode(te.ticket(t,n,r,o));return l(i)?k(i.message??"Unable to create issue",e):le(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,a=b.createNode(te.field(t,n,r,i,{value:o},n.includes("Description")?"vertical":"horizontal"));return l(a)?k(a.message??`Unable to create field: ${n}`,e):Yr(a.value)?c("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(!b.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return l(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=b.tombstoneNode(t);return l(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=b.createTag({id:t,name:n});return l(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=b.createContributor({id:t,name:n});return l(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=b.tag(n,r,t,o);return l(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=b.untag(t,n);return l(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=b.assign(r,n,t,o);return l(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=b.unassign(t,n);return l(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=b.moveNodeToRank({id:t,parentId:n,rank:r});return l(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=b.editValue(t,n);return l(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=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!le(o))return k("Can only close issues",e);let i=b.getNode(Ce);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=b.moveNodeToRank({id:t,parentId:n,rank:r});return l(a)?k(a.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=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!le(o))return k("Can only reopen issues",e);let i=b.getNode(Ce);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return k("Reopen parent no longer exists",e);let d=b.moveNodeToRank({id:t,parentId:n,rank:r});return l(d)?k(d.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return l(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=b.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=b.updateNode({...i,rank:o});if(l(a))return k(a.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}},da=(e,t)=>{let n=b.getNode(e);n&&b.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=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 ft(e,t=!1){let n=aa[e.action](e);if(l(n))return n;t||([...new Set(la(e))].forEach(a=>da(a,e)),ae(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(b.createContributor({name:o,id:r}),n)}var Ge=e=>e.map(t=>ft(t));import Ca from"node:fs";import ba from"node:path";import{decodeTime as Ia,monotonicFactory as Sa}from"ulid";import{z as ht}from"zod";var _t={autoSync:!1,preferredEditor:null,userName:null,userId:null},fe=()=>_t,tt=e=>(_t={..._t,...e},_t);import vt from"node:fs";import be from"node:path";var Wn=process.env.IS_LOCAL==="true",Ie=".epiq",ce=".epiq-global",Wt="events",ca="project.json",so=e=>be.join(e,Ie),Ht=e=>be.join(e,Ie),ua=e=>be.join(Ht(e),ca),xt=e=>be.join(Ht(e),Wt),ma=e=>{let t=be.join(e,Ie);return vt.existsSync(t)&&vt.statSync(t).isDirectory()},pa=e=>{let t=ua(e);return vt.existsSync(t)&&vt.statSync(t).isFile()},Se=e=>{let t=be.resolve(e);for(;;){if(ma(t))return c("Resolved closest .epiq root",t);let n=be.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},ao=e=>{let t=be.resolve(e);for(;;){if(pa(t))return c("Resolved closest epiq project root",t);let n=be.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},lo=e=>{let t=xt(e);try{return vt.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 jt from"node:fs";import jn from"node:path";import{decodeTime as ga}from"ulid";import{z as Hn}from"zod";var fa=Hn.object({userId:Hn.string().min(1).default("unknown"),userName:Hn.string().min(1).default("unknown")}),va=e=>{let[t,n]=jn.basename(e,".jsonl").split("."),r=fa.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${jn.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},xa=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])},ya=(e,t)=>t in e,ha=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ea=e=>{let{userId:t,userName:n,...r}=e,o=xa(r);if(l(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?ya(r,i)?c("Decoded persisted event",ha({id:a,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},Kt=e=>{if(!jt.existsSync(e))return c("Event file missing",[]);let t=va(e);if(l(t))return s(t.message);let n=jt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
3
|
-
`)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let
|
|
4
|
-
`,"utf8"),c("Event persisted",{path:o.value,entry:d.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}function K(e){let t=ft(e);if(t.status!==he.Success)return t;let n=zt({event:e});return l(n)?n:t}function vo(e){return e.map(t=>K(t))}var xo=e=>zn(F(e),{at:"end"}),zn=(e,t={at:"end"})=>{let n=r=>l(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(V(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(V(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(V(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=yo(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(V(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=yo(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(V(o.rank,i?.rank)):s("Sibling not found")}}},F=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),yo=(e,t)=>e.findIndex(n=>n.id===t),ho=(e,t,n={at:"end"})=>zn(F(t).filter(r=>r.id!==e),n),nt=(e,t,n,r)=>{let o=ho(t,e,n);if(l(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let i=$n(e,r);if(l(i))return i;let a=K(i.value);if(l(a))return a;let d=ho(t,e,n);return l(d)?d:d.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)},rt=(e,t)=>{let n=xo(e);if(l(n))return n;if(!n.value.needsRebalance)return c("Resolved rank",n.value.rank);let r=$n(e,t);if(l(r))return r;let o=K(r.value);if(l(o))return o;let i=xo(e);return l(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",i.value.rank)};var Ue=(e,t)=>{let{nodes:n}=v(),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}`)},qn=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Gn=(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"),b={deleteNode(e){ae(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=Gn(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=Gn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("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 F(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=Gn(o,"move");if(a)return a;if(qn(t,e))return s("Cannot move node into its own descendant");let d={...o,parentNodeId:t,rank:n};return this.updateNode(d),c("Moved node successfully",d)},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 F(m.id))a(p.id)}};a(e);let d={...structuredClone(t)};for(let u of i){if(!d[u])return s("Unable to locate node to delete");d[u]={...d[u],isDeleted:!0}}return n?(T({nodes:d}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ae(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return l(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 a=this.getFieldByTitle(i.id,"Assignees");if(!a)return s("Unable to locate assignees field");if(F(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=te.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return l(m)?m:c("Assigned contributor",u)},createTag(e){let t=ae(n=>({...n,tags:{...n.tags,[e.id]:e}}));return l(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 a=this.getFieldByTitle(i.id,"Tags");if(!a)return s("Unable to locate tags field");if(F(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=te.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return l(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=F(o.id).find(d=>d.props?.value===t);if(!i)return c("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("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=F(o.id).find(d=>d.props?.value===t);if(!i)return c("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("Assignee removed",a)},createNode(e){let t=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return l(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=ae(o=>({...o,nodes:{...o.nodes,[e]:n}}));return l(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return l(t)?t:c("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return F(e)}};var Gt=()=>{let e=fe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},Eo=()=>!qe();var Y={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"},E={accent:Y.cyan,accent2:Y.magenta,primary:Y.white,secondary:Y.grayDark,secondary2:Y.grayLight,gray:Y.gray,green:Y.green,yellow:Y.yellow,red:Y.red};var h={red:Y.red,yellow:Y.yellow,green:Y.green,blue:Y.blue,magenta:Y.magenta,cyan:Y.cyan},ot={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan};var No=(e,t)=>{let r=R(e.id).find(o=>o.title===t);return r?R(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Yn=e=>No(e,"Tags").map(t=>b.getTag(t)).filter(t=>!!t),qt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Yn(n)??[])},Yt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Xn(n)??[])},Xn=e=>No(e,"Assignees").map(t=>b.getContributor(t)).filter(t=>!!t);var f={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",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}))?$/,ka=({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},Da=(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 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}},La=e=>{let t=e.match(Pa);if(!t)return null;let[,n,r,o,i,a]=t,d=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,y=a?Number(a):0;return ka({year:d,month:u,day:m,hour:p,minute:y})?new Date(d,u-1,m,p,y):null},Xt=e=>{let t=e.trim().toLowerCase();return Da(t)??La(t)},Co=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Fa=[{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}],bo=(e=Fa)=>{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 Oa=["BOARD","TICKET","SWIMLANE"],Ye=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],Jt=[f.NEW,f.RENAME,f.DELETE,f.MOVE],Jn=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],Io=[f.FILTER,f.PEEK],Ba={WORKSPACE:[...Ye,...Jt],BOARD:[...Io,...Ye,...Jt],SWIMLANE:[...Io,...Ye,...Jt],TICKET:[...Ye,...Jt,...Jn],FIELD:[...Ye,...Jn],FIELD_LIST:[...Ye,...Jn],TEXT:[...Ye]},Ua=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],$a=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!Gt().isSetup)return[f.HELP,f.SET_EDITOR,f.SET_USERNAME];if(!Eo())return[f.HELP,f.INIT];if(n)return[f.HELP,f.PEEK,f.EXPORT,f.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,a=i&&Oa.includes(i);return Ba[o].filter(d=>d===f.RENAME||d===f.DELETE||d===f.MOVE?a:!0)},z=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[f.NONE]:$a(),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...bo(),"now","prev","next"],[f.SET_USERNAME]:[],[f.SET_DESCRIPTION]:["confirm"],[f.DELETE]:["confirm"],[f.RE_OPEN_ISSUE]:["confirm"],[f.CLOSE_ISSUE]:["confirm"],[f.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[f.FILTER]:["tag","assignee","description","title","clear"],[f.SET_VIEW]:["dense","wide"],[f.SET_EDITOR]:[...no],[f.TAG]:[...new Set([...Object.keys(ot),...b.getExistingTags()])],[f.UNTAG]:[...qt()?.value?.map(({name:o})=>o)??[]],[f.UNASSIGN]:[...Yt()?.value?.map(({name:o})=>o)??[]],[f.ASSIGN]:b.getExistingAssignees(),[f.RENAME]:[],[f.NEW]:Ua(n)}[e]??[]};import st from"chalk";import{decodeTime as So}from"ulid";var Ao=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"},To=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())}`},Qt=e=>{try{return c("Decoded date",new Date(So(e)))}catch(t){return s("Decoding failed + "+t.message)}},Qn=e=>{if(!e?.id)return null;try{return So(e.id)}catch{return null}};var Ae=(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 it from"chalk";var er={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},_a=(e,t,n)=>Math.max(t,Math.min(n,e)),Zn=(e,t,n)=>e+(t-e)*n,wo=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Wa=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,d=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=d):a>=1&&a<2?(u=d,m=i):a>=2&&a<3?(m=i,p=d):a>=3&&a<4?(m=d,p=i):a>=4&&a<5?(u=d,p=i):(u=i,p=d);let y=o-i/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((p+y)*255)]},Ha=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,ja=(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))],Et=e=>{let n=wo(e)%360,r=Wa(n,er.stringColor.saturation,er.stringColor.lightness);return Ha(r)},Ka=e=>{let t=er.gradient.stops,n=_a(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 ja(t[i],t[i+1],a)},Zt=e=>wo(e.toLowerCase().trim())/4294967295,Ro=e=>{let t=Zt(e);return Ka(t)},Va=e=>{let[t,n,r]=Ro(e);return{normal:o=>it.bgRgb(t,n,r).black(o),cursor:o=>it.bgRgb(t,n,r).white.bold(o)}},tr=e=>{let[t,n,r]=Ro(e);return{fg:o=>it.rgb(t,n,r)(o),fgCursor:o=>it.rgb(t,n,r).inverse(o),bg:o=>it.bgRgb(t,n,r).black(o),bgCursor:o=>it.bgRgb(t,n,r).white.bold(o)}},nr=e=>Va(e).normal(` ${e} `),X=(e,t=ot)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Et(r)};var Te={None:"none",Invalid:"invalid",Valid:"valid"};var za=["BOARD","TICKET","SWIMLANE"],rr=()=>{let e=v().selectedNode;return e?.context?za.includes(e?.context)?W():U({message:"Command not available in this context"}):U({message:"Missing target context"})},ee="<ENTER> to confirm",W=(e="",t=[])=>({message:e,validity:Te.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:Te.Invalid,message:e,completionWordList:t}),Ct=e=>e.length===0,$e=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,y)=>Zt(p)-Zt(y)).slice(0,r).map(nr),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},or=({modifier:e})=>{let t="confirm";return e===t?W(ee):U({message:Ct(e)?`if you are certain, enter ${nr(t)}`:"",completionWordList:[t]})},Ga=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?W(ee):U({message:Ct(n)?t:""}),qa=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:n}):W():U({message:Ct(r)?t:""}),Nt=({hint:e})=>({modifier:t,inputString:n})=>Ct(t)&&Ct(n)?U({message:e,completionWordList:[]}):W(ee),Ya={[f.EXPORT]:()=>W(ee+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return W(ee);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(ee);let r=Xt(t);if(!t||!r)return U(n);let o=Ae(v().breadCrumb,"BOARD");if(l(o))return U({message:"Command is not applicable in this context"});let i=Qt(o.value.id);return l(i)?U({message:"Unable to peek: board id is not a valid ULID"}):Co({date:r,horizonDate:i.value})?W(ee):U({message:st.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>W(ee+" and exit the application"),[f.INIT]:()=>W(ee),[f.FILTER]:e=>{if(e.modifier==="clear")return W();let t=a=>z(f.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return U({message:$e({wordList:z(f.FILTER),inputString:e.inputString}),completionWordList:z(f.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?U({message:$e({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):W():U({message:$e({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[f.NONE]:e=>{let t=z(f.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?W():U({message:$e({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[f.NEW]:e=>qa({list:z(f.NEW),hint:$e({wordList:z(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>W(ee),[f.HELP]:()=>W(ee),[f.RENAME]:()=>{let e=rr();return e.validity==="invalid"?e:W(ee)},[f.DELETE]:e=>{let t=rr();return t.validity==="invalid"?t:or(e)},[f.CLOSE_ISSUE]:e=>or(e),[f.RE_OPEN_ISSUE]:e=>or(e),[f.MOVE]:e=>{let t=rr();return t.validity==="invalid"?t:Nt({hint:$e({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let t=b.getExistingTags().map(n=>` ${st.bgHex(X(n))(" "+n+" ")} `).slice(0,10);return Nt({hint:"tag name like... "+t.join("")})(e)},[f.UNTAG]:e=>{let t=qt();if(l(t))return U({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${st.bgHex(X(r))(" "+r+" ")} `).slice(0,10);return n.length?Nt({hint:" ... "+n.join("")})(e):U({message:"Issue has not tags",completionWordList:[]})},[f.ASSIGN]:e=>{let t=b.getExistingAssignees().map(n=>` ${st.bgHex(X(n))(" "+n+" ")} `).slice(0,10);return Nt({hint:"assign to... "+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=Yt();if(l(t))return U({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${st.bgHex(X(r))(" "+r+" ")} `).slice(0,10);return n.length?Nt({hint:"remove assignee... "+n.join("")})(e):U({message:"Issue has no assignees",completionWordList:[]})},[f.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(f.SET_EDITOR);return e.modifier?W(ee):U({message:$e({wordList:t,inputString:e.inputString})})},[f.SET_USERNAME]:e=>e.inputString?W():U({message:`Enter a username. Saved in ${st.bgBlack("~/.epiq-global/")}`}),[f.SET_VIEW]:e=>Ga({list:z(f.SET_VIEW),hint:$e({wordList:z(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>W(ee)},Mo=Object.fromEntries(Object.entries(Ya).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Po=["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",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",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 ko=e=>Object.values(f).includes(e),Do=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:d,completionWordList:u}=Mo[n].validate(n,r,i),m=o==="command"?Object.values(f):n&&e.target==="modifier"?z(n):Po;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?to(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Lo=e=>{let t=e.trimStart(),n=Ja(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=Qa(e),d=ko(r)?r:null,u=d!==null,m=r!=="",p=d?z(d)??[]:[],y=d&&p.includes(o)?o:"",N="word";n.length===0||n.length===1&&!i?N="command":(n.length===1&&i||n.length===2&&!i)&&(N="modifier");let S=i?"":a,A=Xa(t,d,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:d,isCommandKeyword:u,isLastWordCompleted:i,modifier:y,target:N,inputToMatch:S,inputString:A}},Xa=(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},Ja=e=>e.trim()?e.trim().split(/\s+/):[],Qa=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Fo=" ",J={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Te.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ir=new Set,Oo=()=>{for(let e of ir)e()},Bo=e=>(ir.add(e),()=>ir.delete(e)),we=e=>{let n=e(J),r=Lo(n.value),o=n.cursorPosition===n.value.length;J={...n,commandMeta:Do(r,o)},Oo()},bt=({message:e,status:t})=>{let n=structuredClone(J);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,J=n,Oo(),c(e,null)},sr=e=>{we(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},ar=e=>{we(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},Uo=()=>{we(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}})},$o=()=>{we(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},j=e=>{we(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,d=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:d,commandIsPending:!1}})},_o=()=>{we(e=>({...e,commandIsPending:!0}))},Wo=({addToHistory:e=!0})=>{we(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Za()},Ho=()=>{we(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}})},jo=()=>{we(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Za=()=>j(()=>""),ne=()=>J,en=()=>{let[e,...t]=J.value.split(Fo);return t.join(Fo).trim()};var ed=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",td=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",nd=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Ko=(e,t)=>{if(td(e,e.sequence))return x.MoveCursorLeftOfWord;if(nd(e,e.sequence))return x.MoveCursorRightOfWord;if(ed(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};var x={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 rd(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 od(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 Vo(e,t){let n=ne();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===g.COMMAND_LINE)return Ko(e,n.value);let r=rd(e);if(r){let o=t===g.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return od(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var zo=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case f.EXIT:return M.Exit;case f.EXPORT:return M.Export;case f.INIT:return M.Init;case f.DELETE:return M.Delete;case f.SET_DESCRIPTION:return M.Edit;case f.HELP:return M.ViewHelp;case f.RE_OPEN_ISSUE:return M.ReopenIssue;case f.CLOSE_ISSUE:return M.CloseIssue;case f.TAG:return M.TagTicket;case f.UNTAG:return M.UntagTicket;case f.ASSIGN:return M.AssignUserToTicket;case f.UNASSIGN:return M.UnassignUserFromTicket;case f.RENAME:return M.Rename;case f.NEW:return M.NewItem;case f.FILTER:return M.Filter;case f.MOVE:return M.Move;case f.PEEK:return M.Peek;case f.SET_USERNAME:return M.SetUserName;case f.SET_EDITOR:return M.SetEditor;case f.SET_VIEW:return M.SetView;case f.SYNC:return M.Sync;default:return M.None}};import{ulid as _}from"ulid";import si from"node:fs";import kd from"node:path";import Dd from"react";import{Box as Md}from"ink";import an from"react";import{Box as cr,Text as vd}from"ink";import ve from"react";import{Text as Go}from"ink";import qo,{useEffect as Yo,useState as id}from"react";var Xo={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},re=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=Xo[n]??Xo.default,[o,i]=id(0);if(Yo(()=>{i(0)},[r]),Yo(()=>{if(!e)return;let d=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return qo.createElement(Go,null,t);let a=r[o]??r[0]??t;return qo.createElement(Go,{color:E.accent,dimColor:o===1},a)};import{Box as dr,Text as sd}from"ink";import tn from"react";var nn=({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)),d=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-d),p=o?Math.min(m,Math.max(0,u-d+1)):Math.min(m,Math.floor(u/d)*d),y=p+d,N=e.slice(p,y),S=e.length>d,A=i,I=S?Math.max(1,Math.floor(d/e.length*A)):A,C=Math.max(0,A-I),w=Math.max(1,e.length-d),B=S?Math.floor(p/w*C):0;return tn.createElement(dr,{flexDirection:"row",height:i,width:"100%"},tn.createElement(dr,{flexDirection:"column",flexGrow:1,height:i},N),tn.createElement(dr,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((Oe,Be)=>tn.createElement(sd,{key:Be,color:S&&Be>=B&&Be<B+I?E.accent:E.secondary},S?"\u2502":" "))))};import{Box as rn,Text as pd}from"ink";import Xe from"react";import{Text as ad}from"ink";import dd from"react";var ld=e=>e.toLowerCase().trim(),cd=(e,t=ot)=>{let n=ld(e);return t[n]?t[n]:Et(n)},at=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return dd.createElement(ad,{underline:t,color:cd(n.name)},"@"+n.name)};import{Text as ud}from"ink";import md from"react";var dt=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return md.createElement(ud,{underline:t,backgroundColor:X(n.name),color:E.primary}," "+n.name+" ")};var Jo=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Ut(Un(t.title),r),i=Yn(t),a=Xn(t);return Xe.createElement(rn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?E.accent:E.secondary,justifyContent:"space-between"},Xe.createElement(rn,{borderBottom:!0},Xe.createElement(rn,{paddingLeft:1,flexDirection:"column"},Xe.createElement(pd,{color:E.primary},o))),Xe.createElement(rn,{flexDirection:"row",paddingLeft:1},i.map(d=>Xe.createElement(dt,{key:d.id,id:d.id})),a.map(d=>Xe.createElement(at,{key:d.id,id:d.id}))))};import gd from"chalk";import{Box as It,Text as lr}from"ink";import Re from"react";var fd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Qo=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=R(t.id),a=I=>{let C=i.find(w=>w.title===I);return C?R(C.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},d=a("Tags").map(I=>b.getTag(I)).filter(I=>!!I),u=a("Assignees").map(I=>b.getContributor(I)).filter(I=>!!I),m=1,p=d.length*(1+m),y=u.length*(2+m),N=d.map(I=>Re.createElement(It,{key:I.id,paddingRight:m},Re.createElement(lr,{color:X(I.name)},"\u25A0"))),S=u.map(I=>Re.createElement(It,{key:I.id,paddingRight:m},Re.createElement(lr,{color:Et(I.name)},"@"+I.name.at(0)))),A=n?E.accent:o===g.MOVE?E.secondary:E.primary;return Re.createElement(It,{borderBottom:!0,justifyContent:"space-between"},Re.createElement(It,null,Re.createElement(re,{isSelected:n,placeholder:gd.dim.gray(r+1+" ")}),Re.createElement(lr,{wrap:"truncate",color:A},fd(t.title,e-p-y-14))),Re.createElement(It,null,N,S))};var xd=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:d})=>{let{renderedChildrenIndex:u}=$(),m=u[e.id]??[],p=`${e.title} (${m.length})`,y=3,N=o?1:4,S=r-y-(o?2:1),A=ve.createElement(cr,{borderStyle:"round",borderColor:E.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ve.createElement(re,{isSelected:t}),ve.createElement(vd,{bold:!0,color:t?E.accent:E.primary},p," ",e.readonly?"\u{1F512}":"")),I=(C,w)=>{let B=i&&a===w;return o?ve.createElement(Qo,{key:C.id,index:w,width:n,ticket:C,isSelected:B,mode:d}):ve.createElement(Jo,{key:C.id,width:n,ticket:C,isSelected:B})};return ve.createElement(cr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?E.accent:E.secondary,paddingRight:1,paddingLeft:1,height:r},A,ve.createElement(cr,{padding:o?1:0},m.length>0&&ve.createElement(nn,{selectedIndex:a,height:S,itemHeight:N},m.map(I)),ve.createElement(re,{isSelected:i&&a===-1})))},Zo=ve.memo(xd);import{Box as pr,Text as wd}from"ink";import _e,{useEffect as gr,useMemo as ri}from"react";import Je from"chalk";import ei from"string-width";import{decodeTime as yd}from"ulid";var hd=(e,t)=>e+" ".repeat(Math.max(0,t-ei(e))),Ed=(e,t)=>" ".repeat(Math.max(0,t-ei(e)))+e,Nd=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)})(),Cd=e=>{switch(e.action){case"move.node":{let t=b.getNode(e.payload.parent);return`to ${t?Je.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?Je.bgHex(X(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?Je.bgHex(X(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?Je.hex(X(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?Je.hex(X(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""}},bd=e=>{let t=Ao(yd(e));return Je.gray(Ed(t,8))},Id=12,Sd=e=>hd(`${e}`,Id),ti=e=>{let t=bd(e.id),n=Sd(e.userName),r=Nd(e.action),o=Cd(e),i=Je.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as on,Text as Ad}from"ink";import Me from"react";var ni=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=$(),{title:o}=t,i=R(t.id).map(a=>{let d=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return b.getContributor(d)?.id;if(o==="Tags")return b.getTag(d)?.id}).filter(a=>!!a);return Me.createElement(on,{alignItems:"center",paddingTop:1},Me.createElement(on,{minWidth:12},Me.createElement(re,{isSelected:n}),Me.createElement(Ad,{color:n?E.accent:E.secondary2},o,":")),Me.createElement(on,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,d)=>{let u=r.id===t.id&&d===e;return Me.createElement(on,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Me.createElement(re,{isSelected:u}),o==="Assignees"?Me.createElement(at,{isSelected:u,id:a}):o==="Tags"?Me.createElement(dt,{isSelected:u,id:a}):null)})))};import{Box as sn,Text as ur}from"ink";import Pe,{useEffect as Td}from"react";var mr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:d}=$(),u=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Td(()=>{let N=[];return m.forEach((S,A)=>{let I=Ne(BigInt(A+1));if(!Ee(I))return;let C=te.text({id:`${e}-${A}`,name:`Line ${A+1}`,parentNodeId:e,rank:I.value,props:{value:S},readonly:!0}),w=b.createNode(C);Ee(w)&&N.push(w.value.id)}),()=>N.forEach(b.deleteNode)},[e,n]);let p="\u2029",y=m.map((N,S)=>{let A=d.id===e&&a===S;return Pe.createElement(sn,{key:`${e}-${S}`},Pe.createElement(ur,{color:A?E.primary:E.secondary2,dimColor:!A},`${S+1} `.padStart(5,"\xA0")),Pe.createElement(ur,{backgroundColor:A?"gray":""},u(N.length?Ut(N,i-10):p)))});return Pe.createElement(sn,{flexDirection:"column",paddingTop:1},Pe.createElement(sn,null,Pe.createElement(re,{isSelected:o}),Pe.createElement(ur,{color:o?E.accent:E.secondary2},t)),Pe.createElement(sn,{flexDirection:"row",borderStyle:"round",borderColor:E.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Pe.createElement(nn,{scrollByOne:!0,children:y,height:r-2,selectedIndex:a,itemHeight:1})))};var Rd=e=>`${e}::log`,oi=e=>e==="Assignees"||e==="Tags",ii=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=$(),o=process.stdout.columns||120,i=ri(()=>Rd(e.id),[e.id]),a=ri(()=>[...e.log].reverse().map(ti).join(`
|
|
5
|
-
`),[e.log]);
|
|
2
|
+
import Xr from"chalk";import{render as Ec}from"ink";import Nc from"meow";import Cc from"react";import{Box as Ze}from"ink";import G from"react";import ut from"chalk";import{monotonicFactory as _l,ulid as ke}from"ulid";import{useSyncExternalStore as Bl}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Hn(e){return e.context==="WORKSPACE"}function le(e){return e.context==="TICKET"}function Qr(e){return e.context==="FIELD"}var Qe=e=>e.context==="SWIMLANE",eo=e=>e.context==="BOARD";var he={None:"none",Success:"success",Fail:"fail"},s=e=>({status:he.Fail,message:e,value:null}),c=(e,t)=>({status:he.Success,message:e,value:t}),d=e=>e.status==="fail",Ee=e=>e.status==="success";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function $t(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var _t=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",jn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var to=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},no=(e,t)=>t?e.get(t)??[]:[];var ro=new WeakMap,oa=e=>{let t=ro.get(e);return t||(t=to(e),ro.set(e,t)),t};var oo=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return no(oa(e),r).filter(i=>$t(r,i)>=n)};var ia={hint:"",hints:[],overlap:0,remainder:""},io=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ia;let o=oo({wordList:r,inputToMatch:e,overlapThreshold:1});return sa(t,o)},sa=(e,t)=>{let n=t[0]??"",r=$t(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,l=!!i,p=(l&&a?o:n)+(l&&a?":":" "),y=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:y}};var so=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var te={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:(e,t,n,r,o={},i="horizontal")=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[]}),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})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[]})};import{ulid as la}from"ulid";var ze=24n,aa=ze*4n,gt=(1n<<aa)-1n,da=/^[0-9a-f]+$/;function ao(e){return!e||!da.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ne(e,t=ze){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 V(e,t){if(!e&&!t)return Ne(gt/2n,ze);let n=e?ao(e):c("Resolved lower bound",0n);if(d(n))return n;let r=t?ao(t):c("Resolved upper bound",gt);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Ne(gt/2n,ze);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):Ne(a,ze)}function lo(){return Ne(gt/2n,ze)}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=gt*BigInt(r+1)/(t+1n),i=Ne(o,ze);if(d(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var Kn=(e,t)=>{let n=F(e),r=co(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],l=r.value[i];if(!a||!l)return s("Unable to assign rebalance rank");o[a.id]=l}return c("Created rebalance event",{id:la(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var ca=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Ce,Wt]=ca;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ua={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=te.workspace(t,n,r),i=Vn(o);if(d(i))return k(i.message,e);let a=b.createNode(o);return d(a)?k(a.message??"Failed to initialize workspace",e):Hn(a.value)?c("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=te.workspace(t,n,r),i=b.createNode(o);return d(i)?k(i.message??"Failed to add workspace",e):Hn(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=b.createNode(te.board(t,n,r,o));return d(i)?k(i.message??"Unable to create board",e):eo(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=b.createNode(te.swimlane(t,n,r,o));return d(i)?k(i.message??"Unable to create swimlane",e):Qe(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=b.createNode(te.ticket(t,n,r,o));return d(i)?k(i.message??"Unable to create issue",e):le(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,a=b.createNode(te.field(t,n,r,i,{value:o},n.includes("Description")?"vertical":"horizontal"));return d(a)?k(a.message??`Unable to create field: ${n}`,e):Qr(a.value)?c("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(!b.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(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=b.tombstoneNode(t);return d(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=b.createTag({id:t,name:n});return d(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=b.createContributor({id:t,name:n});return d(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=b.tag(n,r,t,o);return d(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=b.untag(t,n);return d(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=b.assign(r,n,t,o);return d(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=b.unassign(t,n);return d(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=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(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=b.editValue(t,n);return d(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=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!le(o))return k("Can only close issues",e);let i=b.getNode(Ce);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=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(a)?k(a.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=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!le(o))return k("Can only reopen issues",e);let i=b.getNode(Ce);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return k("Reopen parent no longer exists",e);let l=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(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=b.lockNode(t);return d(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=b.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=b.updateNode({...i,rank:o});if(d(a))return k(a.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}},ma=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},pa=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 ft(e,t=!1){let n=ua[e.action](e);if(d(n))return n;t||([...new Set(pa(e))].forEach(a=>ma(a,e)),ae(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(b.createContributor({name:o,id:r}),n)}var qe=e=>e.map(t=>ft(t));import Sa from"node:fs";import Aa from"node:path";import{decodeTime as wa,monotonicFactory as Ta}from"ulid";import{z as ht}from"zod";var Ht={autoSync:!1,preferredEditor:null,userName:null,userId:null},ge=()=>Ht,et=e=>(Ht={...Ht,...e},Ht);import vt from"node:fs";import be from"node:path";var zn=process.env.IS_LOCAL==="true",Ie=".epiq",ce=".epiq-global",jt="events",ga="project.json",uo=e=>be.join(e,Ie),Kt=e=>be.join(e,Ie),Vt=e=>be.join(Kt(e),ga),xt=e=>be.join(Kt(e),jt),fa=e=>{let t=be.join(e,Ie);return vt.existsSync(t)&&vt.statSync(t).isDirectory()},va=e=>{let t=Vt(e);return vt.existsSync(t)&&vt.statSync(t).isFile()},Se=e=>{let t=be.resolve(e);for(;;){if(fa(t))return c("Resolved closest .epiq root",t);let n=be.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},zt=e=>{let t=be.resolve(e);for(;;){if(va(t))return c("Resolved closest epiq project root",t);let n=be.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},mo=e=>{let t=xt(e);try{return vt.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 qt from"node:fs";import Gn from"node:path";import{decodeTime as xa}from"ulid";import{z as qn}from"zod";var ya=qn.object({userId:qn.string().min(1).default("unknown"),userName:qn.string().min(1).default("unknown")}),ha=e=>{let[t,n]=Gn.basename(e,".jsonl").split("."),r=ya.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${Gn.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ea=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])},Na=(e,t)=>t in e,Ca=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),ba=e=>{let{userId:t,userName:n,...r}=e,o=Ea(r);if(d(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?Na(r,i)?c("Decoded persisted event",Ca({id:a,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},Gt=e=>{if(!qt.existsSync(e))return c("Event file missing",[]);let t=ha(e);if(d(t))return s(t.message);let n=qt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
3
|
+
`)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let l=Yn(a);if(d(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 po(e){let t=xt(e);if(!qt.existsSync(t))return c("No events found",[]);let n=qt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Gn.join(t,o)),r=[];for(let o of n){let i=Gt(o);if(d(i))return s(i.message);r.push(...i.value)}return c("All events loaded",Ia(r))}function yt(e){let t=po(e);if(d(t))return s(t.message);let n=[];for(let r of t.value){let o=ba(r);if(d(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return c("Loaded merged events",n)}function go(e=process.cwd()){let t=po(e);return d(t)?s(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Ia=e=>{let t=new Map;for(let l of e){let u=l.id[1]??null,m=t.get(u)??[];m.push(l),t.set(u,m)}for(let l of t.values())l.sort((u,m)=>u.id[0].localeCompare(m.id[0]));let n=[],r=new Set;a(t.get(null)??[]);let o=!0;for(;o;){o=!1;for(let l=0;l<n.length;l++){let u=n[l];if(!u)continue;let m=(t.get(u.id[0])??[]).filter(p=>!r.has(p.id[0]));if(m.length!==0){n.splice(l+1,0,...m);for(let p of m)r.add(p.id[0]);o=!0,l+=m.length}}}let i=e.filter(l=>!r.has(l.id[0])).sort((l,u)=>l.id[0].localeCompare(u.id[0]));return n.push(...i),n;function a(l){for(let u of l)r.has(u.id[0])||(n.push(u),r.add(u.id[0]))}},fo=(e,t)=>{let n=e.findIndex(r=>{try{return xa(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var vo=e=>({action:e.action,payload:e.payload});var yo=1,xo=Ta(),Ra=ht.tuple([ht.string().min(1),ht.string().min(1).nullable()]),Ma=ht.looseObject({v:ht.literal(yo),id:Ra}),Yn=e=>{let t=Ma.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(", ")}`)},Yt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Q=()=>{let{userName:e,userId:t}=ge();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Yt(t),userName:Yt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Xn=({userId:e,userName:t})=>`${Yt(e)}.${Yt(t)}.jsonl`,Pa=(e,{userId:t,userName:n})=>{let r=Xn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Aa.join(xt(e),r);return c("Successfully resolved event log path",i)},ka=(e,t)=>{let n={[e.action]:e.payload,v:yo,id:t};return Yn(n)};function Xt({event:e,rootDir:t=process.cwd()}){try{let n=Se(t);if(d(n))return n;let r=mo(n.value);if(d(r))return r;let o=Pa(n.value,{userId:e.userId,userName:e.userName});if(d(o))return o;let i=go(n.value);if(d(i))return s(i.message);let a=i.value?xo(Math.max(Date.now(),wa(i.value)+1)):xo(),l=ka(vo(e),[a,i.value]);return d(l)?s(l.message):(Sa.appendFileSync(o.value,`${JSON.stringify(l.value)}
|
|
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}`)}}function K(e){let t=ft(e);if(t.status!==he.Success)return t;let n=Xt({event:e});return d(n)?n:t}function ho(e){return e.map(t=>K(t))}var Eo=e=>Jn(F(e),{at:"end"}),Jn=(e,t={at:"end"})=>{let n=r=>d(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(V(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(V(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(V(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=No(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(V(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=No(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(V(o.rank,i?.rank)):s("Sibling not found")}}},F=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),No=(e,t)=>e.findIndex(n=>n.id===t),Co=(e,t,n={at:"end"})=>Jn(F(t).filter(r=>r.id!==e),n),tt=(e,t,n,r)=>{let o=Co(t,e,n);if(d(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let i=Kn(e,r);if(d(i))return i;let a=K(i.value);if(d(a))return a;let l=Co(t,e,n);return d(l)?l:l.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",l.value.rank)},nt=(e,t)=>{let n=Eo(e);if(d(n))return n;if(!n.value.needsRebalance)return c("Resolved rank",n.value.rank);let r=Kn(e,t);if(d(r))return r;let o=K(r.value);if(d(o))return o;let i=Eo(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",i.value.rank)};var Ue=(e,t)=>{let{nodes:n}=v(),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}`)},Qn=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Zn=(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"),b={deleteNode(e){ae(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=Zn(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=Zn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("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 F(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=Zn(o,"move");if(a)return a;if(Qn(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}=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 F(m.id))a(p.id)}};a(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?(w({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ae(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(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 a=this.getFieldByTitle(i.id,"Assignees");if(!a)return s("Unable to locate assignees field");if(F(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=te.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return d(m)?m:c("Assigned contributor",u)},createTag(e){let t=ae(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(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 a=this.getFieldByTitle(i.id,"Tags");if(!a)return s("Unable to locate tags field");if(F(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=te.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return d(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=F(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("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=F(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("Assignee removed",a)},createNode(e){let t=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(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=ae(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:c("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return F(e)}};var Y={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"},E={accent:Y.cyan,accent2:Y.magenta,primary:Y.white,secondary:Y.grayDark,secondary2:Y.grayLight,gray:Y.gray,green:Y.green,yellow:Y.yellow,red:Y.red};var h={red:Y.red,yellow:Y.yellow,green:Y.green,blue:Y.blue,magenta:Y.magenta,cyan:Y.cyan},rt={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan};var bo=(e,t)=>{let r=R(e.id).find(o=>o.title===t);return r?R(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},er=e=>bo(e,"Tags").map(t=>b.getTag(t)).filter(t=>!!t),Jt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",er(n)??[])},Zt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",tr(n)??[])},tr=e=>bo(e,"Assignees").map(t=>b.getContributor(t)).filter(t=>!!t);var f={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",EXPORT:"export",NONE:""};var Da=/^(\d+)(h|d|w|mo|y)$/,La=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Fa=({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},Oa=(e,t=new Date)=>{let n=e.match(Da);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}},Ba=e=>{let t=e.match(La);if(!t)return null;let[,n,r,o,i,a]=t,l=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,y=a?Number(a):0;return Fa({year:l,month:u,day:m,hour:p,minute:y})?new Date(l,u-1,m,p,y):null},Qt=e=>{let t=e.trim().toLowerCase();return Oa(t)??Ba(t)},Io=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ua=[{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}],So=(e=Ua)=>{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 $a=["BOARD","TICKET","SWIMLANE"],Ge=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],en=[f.NEW,f.RENAME,f.DELETE,f.MOVE],nr=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],Ao=[f.FILTER,f.PEEK],_a={WORKSPACE:[...Ge,...en],BOARD:[...Ao,...Ge,...en],SWIMLANE:[...Ao,...Ge,...en],TICKET:[...Ge,...en,...nr],FIELD:[...Ge,...nr],FIELD_LIST:[...Ge,...nr],TEXT:[...Ge]},Wa=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ha=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!tn().isSetup)return[f.HELP,f.SET_EDITOR,f.SET_USERNAME];if(!wo())return[f.HELP,f.INIT];if(n)return[f.HELP,f.PEEK,f.EXPORT,f.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,a=i&&$a.includes(i);return _a[o].filter(l=>l===f.RENAME||l===f.DELETE||l===f.MOVE?a:!0)},z=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[f.NONE]:Ha(),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...So(),"now","prev","next"],[f.SET_USERNAME]:[],[f.SET_DESCRIPTION]:["confirm"],[f.DELETE]:["confirm"],[f.RE_OPEN_ISSUE]:["confirm"],[f.CLOSE_ISSUE]:["confirm"],[f.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[f.FILTER]:["tag","assignee","description","title","clear"],[f.SET_VIEW]:["dense","wide"],[f.SET_EDITOR]:[...so],[f.TAG]:[...new Set([...Object.keys(rt),...b.getExistingTags()])],[f.UNTAG]:[...Jt()?.value?.map(({name:o})=>o)??[]],[f.UNASSIGN]:[...Zt()?.value?.map(({name:o})=>o)??[]],[f.ASSIGN]:b.getExistingAssignees(),[f.RENAME]:[],[f.NEW]:Wa(n)}[e]??[]};import it from"chalk";import{decodeTime as To}from"ulid";var Ro=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"},Mo=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())}`},nn=e=>{try{return c("Decoded date",new Date(To(e)))}catch(t){return s("Decoding failed + "+t.message)}},rr=e=>{if(!e?.id)return null;try{return To(e.id)}catch{return null}};var Ae=(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 ot from"chalk";var ir={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ja=(e,t,n)=>Math.max(t,Math.min(n,e)),or=(e,t,n)=>e+(t-e)*n,Po=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Ka=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,l=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=l):a>=1&&a<2?(u=l,m=i):a>=2&&a<3?(m=i,p=l):a>=3&&a<4?(m=l,p=i):a>=4&&a<5?(u=l,p=i):(u=i,p=l);let y=o-i/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((p+y)*255)]},Va=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,za=(e,t,n)=>[Math.round(or(e[0],t[0],n)),Math.round(or(e[1],t[1],n)),Math.round(or(e[2],t[2],n))],Et=e=>{let n=Po(e)%360,r=Ka(n,ir.stringColor.saturation,ir.stringColor.lightness);return Va(r)},qa=e=>{let t=ir.gradient.stops,n=ja(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 za(t[i],t[i+1],a)},rn=e=>Po(e.toLowerCase().trim())/4294967295,ko=e=>{let t=rn(e);return qa(t)},Ga=e=>{let[t,n,r]=ko(e);return{normal:o=>ot.bgRgb(t,n,r).black(o),cursor:o=>ot.bgRgb(t,n,r).white.bold(o)}},sr=e=>{let[t,n,r]=ko(e);return{fg:o=>ot.rgb(t,n,r)(o),fgCursor:o=>ot.rgb(t,n,r).inverse(o),bg:o=>ot.bgRgb(t,n,r).black(o),bgCursor:o=>ot.bgRgb(t,n,r).white.bold(o)}},ar=e=>Ga(e).normal(` ${e} `),X=(e,t=rt)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Et(r)};var we={None:"none",Invalid:"invalid",Valid:"valid"};var Ya=["BOARD","TICKET","SWIMLANE"],dr=()=>{let e=v().selectedNode;return e?.context?Ya.includes(e?.context)?W():U({message:"Command not available in this context"}):U({message:"Missing target context"})},ee="<ENTER> to confirm",W=(e="",t=[])=>({message:e,validity:we.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:we.Invalid,message:e,completionWordList:t}),Ct=e=>e.length===0,$e=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,y)=>rn(p)-rn(y)).slice(0,r).map(ar),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},lr=({modifier:e})=>{let t="confirm";return e===t?W(ee):U({message:Ct(e)?`if you are certain, enter ${ar(t)}`:"",completionWordList:[t]})},Xa=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?W(ee):U({message:Ct(n)?t:""}),Ja=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:n}):W():U({message:Ct(r)?t:""}),Nt=({hint:e})=>({modifier:t,inputString:n})=>Ct(t)&&Ct(n)?U({message:e,completionWordList:[]}):W(ee),Za={[f.EXPORT]:()=>W(ee+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return W(ee);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(ee);let r=Qt(t);if(!t||!r)return U(n);let o=Ae(v().breadCrumb,"BOARD");if(d(o))return U({message:"Command is not applicable in this context"});let i=nn(o.value.id);return d(i)?U({message:"Unable to peek: board id is not a valid ULID"}):Io({date:r,horizonDate:i.value})?W(ee):U({message:it.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>W(ee+" and exit the application"),[f.INIT]:()=>W(ee),[f.FILTER]:e=>{if(e.modifier==="clear")return W();let t=a=>z(f.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return U({message:$e({wordList:z(f.FILTER),inputString:e.inputString}),completionWordList:z(f.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?U({message:$e({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):W():U({message:$e({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[f.NONE]:e=>{let t=z(f.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?W():U({message:$e({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[f.NEW]:e=>Ja({list:z(f.NEW),hint:$e({wordList:z(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>W(ee),[f.HELP]:()=>W(ee),[f.RENAME]:()=>{let e=dr();return e.validity==="invalid"?e:W(ee)},[f.DELETE]:e=>{let t=dr();return t.validity==="invalid"?t:lr(e)},[f.CLOSE_ISSUE]:e=>lr(e),[f.RE_OPEN_ISSUE]:e=>lr(e),[f.MOVE]:e=>{let t=dr();return t.validity==="invalid"?t:Nt({hint:$e({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let t=b.getExistingTags().map(n=>` ${it.bgHex(X(n))(" "+n+" ")} `).slice(0,10);return Nt({hint:"tag name like... "+t.join("")})(e)},[f.UNTAG]:e=>{let t=Jt();if(d(t))return U({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${it.bgHex(X(r))(" "+r+" ")} `).slice(0,10);return n.length?Nt({hint:" ... "+n.join("")})(e):U({message:"Issue has not tags",completionWordList:[]})},[f.ASSIGN]:e=>{let t=b.getExistingAssignees().map(n=>` ${it.bgHex(X(n))(" "+n+" ")} `).slice(0,10);return Nt({hint:"assign to... "+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=Zt();if(d(t))return U({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${it.bgHex(X(r))(" "+r+" ")} `).slice(0,10);return n.length?Nt({hint:"remove assignee... "+n.join("")})(e):U({message:"Issue has no assignees",completionWordList:[]})},[f.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(f.SET_EDITOR);return e.modifier?W(ee):U({message:$e({wordList:t,inputString:e.inputString})})},[f.SET_USERNAME]:e=>e.inputString?W():U({message:`Enter a username. Saved in ${it.bgBlack("~/.epiq-global/")}`}),[f.SET_VIEW]:e=>Xa({list:z(f.SET_VIEW),hint:$e({wordList:z(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>W(ee)},Do=Object.fromEntries(Object.entries(Za).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Lo=["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",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",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 Fo=e=>Object.values(f).includes(e),Oo=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:l,completionWordList:u}=Do[n].validate(n,r,i),m=o==="command"?Object.values(f):n&&e.target==="modifier"?z(n):Lo;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?io(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Bo=e=>{let t=e.trimStart(),n=ed(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=td(e),l=Fo(r)?r:null,u=l!==null,m=r!=="",p=l?z(l)??[]:[],y=l&&p.includes(o)?o:"",N="word";n.length===0||n.length===1&&!i?N="command":(n.length===1&&i||n.length===2&&!i)&&(N="modifier");let S=i?"":a,A=Qa(t,l,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:y,target:N,inputToMatch:S,inputString:A}},Qa=(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},ed=e=>e.trim()?e.trim().split(/\s+/):[],td=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Uo=" ",J={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:we.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},cr=new Set,$o=()=>{for(let e of cr)e()},_o=e=>(cr.add(e),()=>cr.delete(e)),Te=e=>{let n=e(J),r=Bo(n.value),o=n.cursorPosition===n.value.length;J={...n,commandMeta:Oo(r,o)},$o()},bt=({message:e,status:t})=>{let n=structuredClone(J);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,J=n,$o(),c(e,null)},ur=e=>{Te(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},mr=e=>{Te(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},Wo=()=>{Te(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}})},Ho=()=>{Te(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},j=e=>{Te(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,l=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:l,commandIsPending:!1}})},jo=()=>{Te(e=>({...e,commandIsPending:!0}))},Ko=({addToHistory:e=!0})=>{Te(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),nd()},Vo=()=>{Te(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}})},zo=()=>{Te(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},nd=()=>j(()=>""),ne=()=>J,on=()=>{let[e,...t]=J.value.split(Uo);return t.join(Uo).trim()};var rd=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",od=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",id=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",qo=(e,t)=>{if(od(e,e.sequence))return x.MoveCursorLeftOfWord;if(id(e,e.sequence))return x.MoveCursorRightOfWord;if(rd(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};var x={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 sd(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 ad(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 Go(e,t){let n=ne();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===g.COMMAND_LINE)return qo(e,n.value);let r=sd(e);if(r){let o=t===g.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return ad(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var Yo=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case f.EXIT:return M.Exit;case f.EXPORT:return M.Export;case f.INIT:return M.Init;case f.DELETE:return M.Delete;case f.SET_DESCRIPTION:return M.Edit;case f.HELP:return M.ViewHelp;case f.RE_OPEN_ISSUE:return M.ReopenIssue;case f.CLOSE_ISSUE:return M.CloseIssue;case f.TAG:return M.TagTicket;case f.UNTAG:return M.UntagTicket;case f.ASSIGN:return M.AssignUserToTicket;case f.UNASSIGN:return M.UnassignUserFromTicket;case f.RENAME:return M.Rename;case f.NEW:return M.NewItem;case f.FILTER:return M.Filter;case f.MOVE:return M.Move;case f.PEEK:return M.Peek;case f.SET_USERNAME:return M.SetUserName;case f.SET_EDITOR:return M.SetEditor;case f.SET_VIEW:return M.SetView;case f.SYNC:return M.Sync;default:return M.None}};import{ulid as _}from"ulid";import li from"node:fs";import Fd from"node:path";import Od from"react";import{Box as Dd}from"ink";import un from"react";import{Box as fr,Text as hd}from"ink";import ve from"react";import{Text as Xo}from"ink";import Jo,{useEffect as Zo,useState as dd}from"react";var Qo={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},re=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=Qo[n]??Qo.default,[o,i]=dd(0);if(Zo(()=>{i(0)},[r]),Zo(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Jo.createElement(Xo,null,t);let a=r[o]??r[0]??t;return Jo.createElement(Xo,{color:E.accent,dimColor:o===1},a)};import{Box as pr,Text as ld}from"ink";import sn from"react";var an=({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)),l=Math.max(1,Math.floor(i/a)),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),y=p+l,N=e.slice(p,y),S=e.length>l,A=i,I=S?Math.max(1,Math.floor(l/e.length*A)):A,C=Math.max(0,A-I),T=Math.max(1,e.length-l),B=S?Math.floor(p/T*C):0;return sn.createElement(pr,{flexDirection:"row",height:i,width:"100%"},sn.createElement(pr,{flexDirection:"column",flexGrow:1,height:i},N),sn.createElement(pr,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((Oe,Be)=>sn.createElement(ld,{key:Be,color:S&&Be>=B&&Be<B+I?E.accent:E.secondary},S?"\u2502":" "))))};import{Box as dn,Text as vd}from"ink";import Ye from"react";import{Text as cd}from"ink";import ud from"react";var md=e=>e.toLowerCase().trim(),pd=(e,t=rt)=>{let n=md(e);return t[n]?t[n]:Et(n)},st=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return ud.createElement(cd,{underline:t,color:pd(n.name)},"@"+n.name)};import{Text as gd}from"ink";import fd from"react";var at=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return fd.createElement(gd,{underline:t,backgroundColor:X(n.name),color:E.primary}," "+n.name+" ")};var ei=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=_t(jn(t.title),r),i=er(t),a=tr(t);return Ye.createElement(dn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?E.accent:E.secondary,justifyContent:"space-between"},Ye.createElement(dn,{borderBottom:!0},Ye.createElement(dn,{paddingLeft:1,flexDirection:"column"},Ye.createElement(vd,{color:E.primary},o))),Ye.createElement(dn,{flexDirection:"row",paddingLeft:1},i.map(l=>Ye.createElement(at,{key:l.id,id:l.id})),a.map(l=>Ye.createElement(st,{key:l.id,id:l.id}))))};import xd from"chalk";import{Box as It,Text as gr}from"ink";import Re from"react";var yd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ti=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=R(t.id),a=I=>{let C=i.find(T=>T.title===I);return C?R(C.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},l=a("Tags").map(I=>b.getTag(I)).filter(I=>!!I),u=a("Assignees").map(I=>b.getContributor(I)).filter(I=>!!I),m=1,p=l.length*(1+m),y=u.length*(2+m),N=l.map(I=>Re.createElement(It,{key:I.id,paddingRight:m},Re.createElement(gr,{color:X(I.name)},"\u25A0"))),S=u.map(I=>Re.createElement(It,{key:I.id,paddingRight:m},Re.createElement(gr,{color:Et(I.name)},"@"+I.name.at(0)))),A=n?E.accent:o===g.MOVE?E.secondary:E.primary;return Re.createElement(It,{borderBottom:!0,justifyContent:"space-between"},Re.createElement(It,null,Re.createElement(re,{isSelected:n,placeholder:xd.dim.gray(r+1+" ")}),Re.createElement(gr,{wrap:"truncate",color:A},yd(t.title,e-p-y-14))),Re.createElement(It,null,N,S))};var Ed=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:l})=>{let{renderedChildrenIndex:u}=$(),m=u[e.id]??[],p=`${e.title} (${m.length})`,y=3,N=o?1:4,S=r-y-(o?2:1),A=ve.createElement(fr,{borderStyle:"round",borderColor:E.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ve.createElement(re,{isSelected:t}),ve.createElement(hd,{bold:!0,color:t?E.accent:E.primary},p," ",e.readonly?"\u{1F512}":"")),I=(C,T)=>{let B=i&&a===T;return o?ve.createElement(ti,{key:C.id,index:T,width:n,ticket:C,isSelected:B,mode:l}):ve.createElement(ei,{key:C.id,width:n,ticket:C,isSelected:B})};return ve.createElement(fr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?E.accent:E.secondary,paddingRight:1,paddingLeft:1,height:r},A,ve.createElement(fr,{padding:o?1:0},m.length>0&&ve.createElement(an,{selectedIndex:a,height:S,itemHeight:N},m.map(I)),ve.createElement(re,{isSelected:i&&a===-1})))},ni=ve.memo(Ed);import{Box as yr,Text as Pd}from"ink";import _e,{useEffect as hr,useMemo as si}from"react";import Xe from"chalk";import ri from"string-width";import{decodeTime as Nd}from"ulid";var Cd=(e,t)=>e+" ".repeat(Math.max(0,t-ri(e))),bd=(e,t)=>" ".repeat(Math.max(0,t-ri(e)))+e,Id=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)})(),Sd=e=>{switch(e.action){case"move.node":{let t=b.getNode(e.payload.parent);return`to ${t?Xe.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?Xe.bgHex(X(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?Xe.bgHex(X(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?Xe.hex(X(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?Xe.hex(X(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""}},Ad=e=>{let t=Ro(Nd(e));return Xe.gray(bd(t,8))},wd=12,Td=e=>Cd(`${e}`,wd),oi=e=>{let t=Ad(e.id),n=Td(e.userName),r=Id(e.action),o=Sd(e),i=Xe.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as ln,Text as Rd}from"ink";import Me from"react";var ii=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=$(),{title:o}=t,i=R(t.id).map(a=>{let l=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return b.getContributor(l)?.id;if(o==="Tags")return b.getTag(l)?.id}).filter(a=>!!a);return Me.createElement(ln,{alignItems:"center",paddingTop:1},Me.createElement(ln,{minWidth:12},Me.createElement(re,{isSelected:n}),Me.createElement(Rd,{color:n?E.accent:E.secondary2},o,":")),Me.createElement(ln,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,l)=>{let u=r.id===t.id&&l===e;return Me.createElement(ln,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Me.createElement(re,{isSelected:u}),o==="Assignees"?Me.createElement(st,{isSelected:u,id:a}):o==="Tags"?Me.createElement(at,{isSelected:u,id:a}):null)})))};import{Box as cn,Text as vr}from"ink";import Pe,{useEffect as Md}from"react";var xr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:l}=$(),u=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Md(()=>{let N=[];return m.forEach((S,A)=>{let I=Ne(BigInt(A+1));if(!Ee(I))return;let C=te.text({id:`${e}-${A}`,name:`Line ${A+1}`,parentNodeId:e,rank:I.value,props:{value:S},readonly:!0}),T=b.createNode(C);Ee(T)&&N.push(T.value.id)}),()=>N.forEach(b.deleteNode)},[e,n]);let p="\u2029",y=m.map((N,S)=>{let A=l.id===e&&a===S;return Pe.createElement(cn,{key:`${e}-${S}`},Pe.createElement(vr,{color:A?E.primary:E.secondary2,dimColor:!A},`${S+1} `.padStart(5,"\xA0")),Pe.createElement(vr,{backgroundColor:A?"gray":""},u(N.length?_t(N,i-10):p)))});return Pe.createElement(cn,{flexDirection:"column",paddingTop:1},Pe.createElement(cn,null,Pe.createElement(re,{isSelected:o}),Pe.createElement(vr,{color:o?E.accent:E.secondary2},t)),Pe.createElement(cn,{flexDirection:"row",borderStyle:"round",borderColor:E.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Pe.createElement(an,{scrollByOne:!0,children:y,height:r-2,selectedIndex:a,itemHeight:1})))};var kd=e=>`${e}::log`,ai=e=>e==="Assignees"||e==="Tags",di=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=$(),o=process.stdout.columns||120,i=si(()=>kd(e.id),[e.id]),a=si(()=>[...e.log].reverse().map(oi).join(`
|
|
5
|
+
`),[e.log]);hr(()=>{if(b.getNode(i))return;let T=Ne(1n);if(d(T))return;let B={...te.field(i,"Log",e.id,T.value,{value:a}),readonly:!0,childRenderAxis:"vertical"};return b.createNode(B),()=>{b.deleteNode(i)}},[i,e.id,a]),hr(()=>{let C=b.getNode(i);C&&C.props.value!==a&&b.updateNode({...C,props:{...C.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let l=r.id===e.id,u=r.id===i||r.parentNodeId===i;hr(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=R(e.id);if(u){let C=b.getNode(i),B=t-3;return _e.createElement(yr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},C?_e.createElement(xr,{id:C.id,label:"Event log",text:C.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let p=m.reduce((C,T)=>ai(T.title)||T.id===i?C+1:C,0),y=2,N=p*1,A=t-3-N-y,I=(C,T)=>ai(C.title)?_e.createElement(ii,{key:C.id,parent:C,selected:T,selectedIndex:n}):C.id===i?_e.createElement(yr,{key:C.id,paddingTop:1},_e.createElement(re,{isSelected:T}),_e.createElement(Pd,{backgroundColor:E.secondary,color:T?E.accent:E.primary}," History \u203A\u203A ")):C.title==="Description"?_e.createElement(xr,{label:"Description (press e to edit)",key:C.id,id:C.id,text:C.props.value??"",selected:T,maxWidth:o,height:A}):null;return _e.createElement(yr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((C,T)=>I(C,l&&n===T)))};var Ld=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:l})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,y=u===P.TICKET?t:r.find(C=>C.context===P.TICKET),N=Math.floor(l/3),S=Math.floor(l/Math.max(e.length,1)),A=Math.min(S,N),I=i==="dense";return un.createElement(Dd,{flexDirection:"row",height:a},p&&e.map((C,T)=>{let B=t.id===C.id,Oe=B?n:-1,Be=t.context===P.BOARD&&n===T;return un.createElement(ni,{key:C.id,height:a,width:A,swimlane:C,isSelected:Be,isDense:I,isFocused:B,listSelectedIndex:Oe,mode:o})}),m&&y&&un.createElement(di,{height:a,ticket:y}))},mn=un.memo(Ld);import{render as Bd}from"ink";import{Writable as Ud}from"node:stream";var St=e=>String(e).padStart(2,"0"),$d=e=>{let t=e.getUTCFullYear(),n=St(e.getUTCMonth()+1),r=St(e.getUTCDate()),o=St(e.getUTCHours()),i=St(e.getUTCMinutes()),a=St(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},_d=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Wd=async(e,{width:t,height:n})=>{let r="",o=new Ud({write(a,l,u){let m=Hd(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Bd(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),r},Hd=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ci=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o,renderedChildrenIndex:i}=v(),a=n.find(T=>T.context==="BOARD");if(!a)return s("No board found to export");let l=120,u=40,m=await Wd(Od.createElement(mn,{height:u,width:l,swimlanes:(i[a.id]??[]).filter(T=>T!==void 0&&Qe(T)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o}),{width:l,height:u});if(!m)return s("Failed to render board export");let p=Se(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let y=new Date,N=$d(y),S=`board_${_d(a.title)}_${N}.md`,A=uo(p.value);li.mkdirSync(A,{recursive:!0});let I=Fd.join(A,S),C=`# Board - ${a.title}
|
|
6
6
|
Date: ${y.toISOString()}
|
|
7
7
|
|
|
8
8
|
\`\`\`text
|
|
9
9
|
${m}
|
|
10
10
|
\`\`\`
|
|
11
|
-
`;return
|
|
12
|
-
|
|
11
|
+
`;return li.writeFileSync(I,C,"utf8"),c("Exported board layout",I)};import ll from"node:fs";var O="epiq/eventlog",ue="origin";import Tt from"node:fs";import Xd from"node:os";import fe from"node:path";import At from"node:fs";import{ulid as jd}from"ulid";import{z as pn}from"zod";var Kd=pn.object({projectId:pn.string().min(1),stateBranch:pn.string().min(1),createdAt:pn.string().datetime()}),Vd=()=>({projectId:jd(),stateBranch:"epiq/state",createdAt:new Date().toISOString()}),gn=e=>{let t=Vt(e);if(!At.existsSync(t))return s("Missing .epiq/project.json");try{let n=At.readFileSync(t,"utf8"),r=JSON.parse(n),o=Kd.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")}},ui=e=>{let t=gn(e);return d(t)?s(t.message):c("Read projectId",t.value.projectId)},mi=e=>{let t=Kt(e),n=Vt(e);try{if(At.mkdirSync(t,{recursive:!0}),At.existsSync(n)){let o=gn(e);return d(o)?s(o.message):c("Project already initialized",null)}let r=Vd();return At.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
12
|
+
`,"utf8"),c("Created project.json",null)}catch(r){return s(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}};var Er=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=r(...i);if(!n.has(a)){let l=e(...i).then(u=>(d(u)&&n.delete(a),u));n.set(a,l)}return n.get(a)});return o.clear=()=>n.clear(),o};import wt from"fs";import gi from"path";import zd from"util";var pi=1e3,fi=()=>{let e=process.cwd(),t=Se(e);if(!d(t))return gi.join(t.value,Ie,"log","epiq.log")};function qd(){if(!zn)return;let e=fi();if(e===void 0||!wt.existsSync(e))return;let n=wt.readFileSync(e,"utf8").split(`
|
|
13
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=pi)return;let r=n.slice(-pi).join(`
|
|
13
14
|
`)+`
|
|
14
|
-
`;
|
|
15
|
-
`;
|
|
16
|
-
`);u(n?{stdout:a,stderr:p,exitCode:124}:s(p))},
|
|
17
|
-
`)))}),o.on("close",p=>{let y=p??1;if(n){u({stdout:a,stderr:
|
|
18
|
-
`)));return}u(c("Git command succeeded",{stdout:a,stderr:
|
|
19
|
-
${n.message}`);let r=await L({args:["rev-parse","HEAD"],cwd:e});return
|
|
20
|
-
${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},
|
|
21
|
-
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(
|
|
22
|
-
${r.message}`);let o=await
|
|
23
|
-
${o.message}`):c("Pulled with rebase",!0)},
|
|
24
|
-
`+e.message);let t=
|
|
25
|
-
`+t.message):c("Ensured epiq storage",!0)},
|
|
15
|
+
`;wt.writeFileSync(e,r,"utf8")}function Nr(e,t,n=!1){if(!zn)return;let r=fi();if(!r)return;let o=zd.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
|
|
16
|
+
`;wt.mkdirSync(gi.dirname(r),{recursive:!0}),wt.appendFileSync(r,l,"utf8"),qd()}var oe={info(...e){Nr("[Info]",e,!1)},debug(...e){Nr("->",e,!0)},error(...e){Nr("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=oe;import{spawn as Gd}from"node:child_process";import Cr from"node:fs";import yi from"node:path";var q={stage:({cwd:e,pathspec:t})=>L({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>L({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>L({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>L({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>L({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return L({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>L({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>L({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>L({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>L({args:["worktree","prune"],cwd:e})};var vi=15e3,Yd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},hi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Cr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(s(p));return}let o=Gd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Yd}),i=!1,a="",l="",u=p=>{i||(i=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${vi}ms`].join(`
|
|
17
|
+
`);u(n?{stdout:a,stderr:p,exitCode:124}:s(p))},vi);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{a+=p}),o.stderr.on("data",p=>{l+=p}),o.on("error",p=>{if(n){u({stdout:a,stderr:p.message,exitCode:1});return}u(s([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
|
|
18
|
+
`)))}),o.on("close",p=>{let y=p??1;if(n){u({stdout:a,stderr:l,exitCode:y});return}if(y!==0){u(s([`git ${e.join(" ")}`,l.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
|
|
19
|
+
`)));return}u(c("Git command succeeded",{stdout:a,stderr:l,exitCode:y}))})}),L=({args:e,cwd:t})=>hi({args:e,cwd:t,allowFail:!1}),dt=({args:e,cwd:t})=>hi({args:e,cwd:t,allowFail:!0}),fn=async({cwd:e,message:t})=>{let n=await q.commit({cwd:e,message:t});if(d(n))return s(`Failed to create commit
|
|
20
|
+
${n.message}`);let r=await L({args:["rev-parse","HEAD"],cwd:e});return d(r)?s(`Commit created, but failed to read HEAD SHA
|
|
21
|
+
${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},br=async e=>{let t=await Ai(e);if(d(t))return s(t.message);let n=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>Cr.existsSync(yi.join(n,i)));return c("Checked for in-progress Git operation",o.length>0)},Ir=async({repoRoot:e})=>{let n=(await dt({args:["remote","get-url",ue],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},vn=async({repoRoot:e,branch:t})=>{let n=await dt({args:["ls-remote","--heads",ue,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${ue}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Ei=async({repoRoot:e,branch:t})=>{let n=await dt({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},xi=e=>{try{return Cr.realpathSync.native(e)}catch{return yi.resolve(e)}},Ni=async({repoRoot:e,worktreeRoot:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=xi(t),o=n.value.stdout.split(`
|
|
22
|
+
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(xi).includes(r);return c("Checked worktree registration",o)},Sr=async e=>{let t=await dt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},xn=async e=>{let t=await L({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?s(t.message):c("Resolved current branch",t.value.stdout.trim())},Ci=async e=>{let t=await L({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?s(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},bi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),yn=async({cwd:e,branch:t})=>{let n=await vn({repoRoot:e,branch:t});if(d(n))return s(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await q.fetch({cwd:e,remote:ue,branch:t});if(d(r))return s(`Failed to fetch ${t}
|
|
23
|
+
${r.message}`);let o=await q.pullRebase({cwd:e,remote:ue,branch:t});return d(o)?s(`Failed during pull --rebase
|
|
24
|
+
${o.message}`):c("Pulled with rebase",!0)},Ii=async e=>{let t=await L({args:["status","--porcelain"],cwd:e});return d(t)?s(t.message):c("Checked state branch changes",t.value.stdout.trim().length>0)},Si=async e=>{let t=await xn(e);return d(t)?s(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var wi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ti=e=>fe.join(Ie,jt,e),Ri=()=>fe.join(Xd.homedir(),ce),Mi=()=>fe.join(Ri(),"worktrees"),Pi=e=>{let t=ui(e);return d(t)?s(t.message):c("Resolved state branch root",fe.join(Mi(),t.value))},Jd=e=>fe.join(e,Ie),Je=e=>fe.join(Jd(e),jt),Ar=({root:e,fileName:t})=>fe.join(Je(e),t),Rt=e=>{try{return Tt.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},ki=()=>{let e=Rt(Ri());if(d(e))return s(`Ensure epiq home failed.
|
|
25
|
+
`+e.message);let t=Rt(Mi());return d(t)?s(`Ensure worktrees dir failed.
|
|
26
|
+
`+t.message):c("Ensured epiq storage",!0)},Di=e=>{Tt.existsSync(e)&&(oe.debug("[sync] remove path",e),Tt.rmSync(e,{recursive:!0,force:!0}))},Li=e=>{let t=Je(e);if(!Tt.existsSync(t))return c("Events dir missing",[]);let n=Tt.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return c("Listed event files",n)},Fi=(e,t)=>{for(let n of[Je(e),Je(t)]){let r=Rt(n);if(d(r))return s(r.message)}return c("Ensured state branch",void 0)},Oi=async e=>{let t=await L({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return s(`ensure state branch is storage only failed
|
|
26
27
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
27
|
-
`).filter(Boolean).filter(a=>a!==Ie);if(r.length===0)return c("State branch is storage-only",!1);let o=await L({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(
|
|
28
|
-
${o.message}`);let i=await
|
|
29
|
-
${t.message}`);let n=t.value.stdout.trim(),r=await L({args:["update-ref",`refs/heads/${O}`,n],cwd:e});return
|
|
30
|
-
${r.message}`):c("Created state branch",!0)},
|
|
31
|
-
`+t.message);if(t.value)return c("Local state branch already exists",!1);let n=await
|
|
32
|
-
`+n.message);if(!n.value)return
|
|
33
|
-
`+r.message);if(!r.value)return
|
|
34
|
-
${o.message}`);let i=await L({args:["branch","--track",O,`${ue}/${O}`],cwd:e});return
|
|
35
|
-
${i.message}`):c("Created local state branch from remote",!0)},
|
|
36
|
-
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},
|
|
37
|
-
`+n.message);
|
|
38
|
-
${r.message}`):c("Created state branch worktree",!0)},
|
|
39
|
-
${
|
|
40
|
-
${
|
|
41
|
-
${
|
|
42
|
-
${n.message}`):c("Checked out state branch",!0)},
|
|
43
|
-
${o.message}`);let i=await
|
|
44
|
-
${i.message}`):c("Configured state branch upstream",!0)},
|
|
45
|
-
${
|
|
46
|
-
`+n.message):
|
|
47
|
-
${n.message}`):c("Pushed state branch",!0)},
|
|
28
|
+
`).filter(Boolean).filter(a=>a!==Ie);if(r.length===0)return c("State branch is storage-only",!1);let o=await L({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return s(`Failed to clean storage branch
|
|
29
|
+
${o.message}`);let i=await fn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):c("Cleaned storage branch",!0)},Bi=Er(async(e=process.cwd())=>{let t=await L({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?s("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>fe.resolve(e)),Ai=Er(async e=>{let t=await L({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return s(t.message);let n=t.value.stdout.trim(),r=fe.isAbsolute(n)?n:fe.join(e,n);return c("Resolved git dir",r)},e=>fe.resolve(e));import lt from"node:fs";import Mt from"node:path";var _i=async e=>{if((await dt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);oe.info("Creating initial commit");let n=await q.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?s(n.message):c("Created initial commit",!0)},Ui=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Zd=async e=>{let t=await xn(e);if(d(t))return s(t.message);let n=await Ci(e);if(d(n))return s(n.message);let r=`[epiq:sync:${Ui(t.value)}:${Ui(n.value)}]`;return c("Built sync commit message",r)},$i=async e=>{oe.info(`Creating ${O}`);let t=await L({args:["commit-tree",wi,"-m","[epiq:init-state-branch]"],cwd:e});if(d(t))return s(`Failed to create state branch commit
|
|
30
|
+
${t.message}`);let n=t.value.stdout.trim(),r=await L({args:["update-ref",`refs/heads/${O}`,n],cwd:e});return d(r)?s(`Failed to create ${O}
|
|
31
|
+
${r.message}`):c("Created state branch",!0)},Qd=async({repoRoot:e})=>{let t=await Ei({repoRoot:e,branch:O});if(d(t))return s(`Ensure local state branch failed
|
|
32
|
+
`+t.message);if(t.value)return c("Local state branch already exists",!1);let n=await Ir({repoRoot:e});if(d(n))return s(`Ensure local state branch failed
|
|
33
|
+
`+n.message);if(!n.value)return $i(e);let r=await vn({repoRoot:e,branch:O});if(d(r))return s(`Ensure local state branch failed
|
|
34
|
+
`+r.message);if(!r.value)return $i(e);let o=await q.fetch({cwd:e,remote:ue,branch:O});if(d(o))return s(`Failed to fetch ${O} from remote
|
|
35
|
+
${o.message}`);let i=await L({args:["branch","--track",O,`${ue}/${O}`],cwd:e});return d(i)?s(`Failed to create local ${O} from remote
|
|
36
|
+
${i.message}`):c("Created local state branch from remote",!0)},el=async({repoRoot:e,branch:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=n.value.stdout.split(`
|
|
37
|
+
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},tl=async({repoRoot:e,stateBranchRoot:t})=>{let n=Rt(Mt.dirname(t));if(d(n))return s(`Failed to create state branch worktree
|
|
38
|
+
`+n.message);lt.existsSync(t)&&!lt.existsSync(Mt.join(t,".git"))&&(oe.info("Removing broken state branch worktree path"),Di(t)),oe.info("Creating state branch worktree");let r=await q.worktreeAdd({cwd:e,worktreeRoot:t,branch:O});return d(r)?s(`Failed to create state branch worktree
|
|
39
|
+
${r.message}`):c("Created state branch worktree",!0)},nl=async({repoRoot:e,stateBranchRoot:t})=>{let n=await el({repoRoot:e,branch:O});if(d(n))return s(n.message);let r=Mt.resolve(t),o=n.value?Mt.resolve(n.value):null;if(o&&o===r&<.existsSync(o))return c("State branch already checked out in expected worktree",!1);if(o&&o!==r){oe.info("Moving state branch worktree to expected location");let l=await q.worktreeRemove({cwd:e,worktreeRoot:o});if(d(l))return s(`Failed to remove existing state branch worktree
|
|
40
|
+
${l.message}`)}if(o&&!lt.existsSync(o)){oe.info("Pruning stale state branch worktree");let l=await q.worktreePrune({cwd:e});if(d(l))return s(`Failed to prune stale worktrees
|
|
41
|
+
${l.message}`)}let i=await Ni({repoRoot:e,worktreeRoot:t});if(d(i))return s(i.message);let a=lt.existsSync(t);if(i.value&&a)return c("State branch worktree already exists",!1);if(i.value&&!a){oe.info("Pruning missing registered state branch worktree");let l=await q.worktreePrune({cwd:e});if(d(l))return s(`Failed to prune stale worktrees
|
|
42
|
+
${l.message}`)}return tl({repoRoot:e,stateBranchRoot:t})},rl=async e=>{let t=await xn(e);if(d(t))return s(t.message);if(t.value===O)return c("State branch already checked out",!1);let n=await q.checkout({cwd:e,branch:O});return d(n)?s(`Failed to checkout ${O}
|
|
43
|
+
${n.message}`):c("Checked out state branch",!0)},ol=async e=>{let t=await Sr(e);if(d(t))return s(t.message);if(t.value)return c("State branch upstream already configured",!1);let n=await Ir({repoRoot:e});if(d(n))return s(n.message);if(!n.value)return c("No remote available for state branch upstream",!1);let r=await vn({repoRoot:e,branch:O});if(d(r))return s(r.message);if(!r.value)return c("Remote state branch missing; upstream will be configured on first push",!1);oe.info(`Configuring ${O} upstream`);let o=await q.fetch({cwd:e,remote:ue,branch:O});if(d(o))return s(`Failed to fetch ${O}
|
|
44
|
+
${o.message}`);let i=await q.setUpstream({cwd:e,branch:O,upstream:`${ue}/${O}`});return d(i)?s(`Failed to set state branch upstream
|
|
45
|
+
${i.message}`):c("Configured state branch upstream",!0)},Wi=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=Ti(t),r=Mt.join(e,n);if(!lt.existsSync(r))return c("No event file to stage",void 0);let o=await q.stage({cwd:e,pathspec:[n]});return d(o)?s(`Failed to stage state branch event file
|
|
46
|
+
${o.message}`):c("Staged state branch event file",void 0)},Hi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Zd(e);return d(n)?s(`Create state branch sync commit failed
|
|
47
|
+
`+n.message):fn({cwd:t,message:n.value})},wr=async e=>{let t=await Sr(e);if(d(t))return s(t.message);let n=t.value?await q.push({cwd:e}):await q.push({cwd:e,remote:ue,branch:O,setUpstream:!0});return d(n)?s(`Failed during state branch push
|
|
48
|
+
${n.message}`):c("Pushed state branch",!0)},ji=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=[ki(),await Qd({repoRoot:e}),await nl({repoRoot:e,stateBranchRoot:t}),await rl(t),await Oi(t),n?await ol(t):c("Skipped state branch upstream bootstrap",!1)];for(let i of o){if(d(i))return s(i.message);r=r||!!i.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import hn from"node:fs";import Rr from"node:path";import{decodeTime as il}from"ulid";var Tr=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Ki=e=>{let[t]=e.id;return il(t)},sl=e=>{let{userId:t,userName:n,...r}=e;return r},al=e=>e.length===0?"":e.map(t=>JSON.stringify(sl(t))).join(`
|
|
48
49
|
`)+`
|
|
49
|
-
`,
|
|
50
|
-
`),c("Config written",null)}catch{return s(`Unable to write ~/${ce}/config.json`)}},
|
|
51
|
-
`).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return c("Local epiq paths already ignored",!1);let
|
|
50
|
+
`,dl=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Tr(r),r);return[...n.values()].sort((r,o)=>{let i=Ki(r)-Ki(o);return i!==0?i:Tr(r).localeCompare(Tr(o))})},Mr=({sourceFile:e,targetFile:t})=>{let n=Gt(e);if(d(n))return s(n.message);let r=Gt(t);if(d(r))return s(r.message);let o=dl(r.value,n.value),i=al(o);return(hn.existsSync(t)?hn.readFileSync(t,"utf8"):"")===i?c("Event file already merged",!1):(hn.mkdirSync(Rr.dirname(t),{recursive:!0}),hn.writeFileSync(t,i,"utf8"),c("Merged event file",!0))},Pr=({repoRoot:e,stateBranchRoot:t})=>{let n=Li(t);if(d(n))return s(n.message);let r=Je(t),o=Je(e),i=!1;for(let a of n.value){let l=Rr.join(r,a),u=Rr.join(o,a),m=Mr({sourceFile:l,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return c("Hydrated event files from state branch",i)};var zi=async(e=process.cwd())=>{let t=await qi({cwd:e,ensureUpstream:!1});if(d(t))return t;let{repoRoot:n,stateBranchRoot:r}=t.value,o=await yn({cwd:r,branch:O});if(d(o))return s(o.message);let i=Pr({repoRoot:n,stateBranchRoot:r});return d(i)?s(i.message):c("Synced state branch",{repoRoot:n,stateBranchRoot:r})},cl=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Ar({root:e,fileName:n}),o=Ar({root:t,fileName:n});return ll.existsSync(r)?Mr({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},qi=async({cwd:e,ensureUpstream:t})=>{let n=await Bi(e);if(d(n))return s(n.message);let r=n.value,o=Pi(r);if(d(o))return s(o.message);let i=o.value,a=await br(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 l=await _i(r);if(d(l))return s(l.message);let u=await ji({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await br(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=Fi(r,i);return d(p)?s(p.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},Vi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=cl({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(d(r))return s(r.message);let o=await Ii(t);if(d(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 Wi({stateBranchRoot:t,ownEventFileName:n});if(d(i))return s(i.message);let a=await Hi({repoRoot:e,stateBranchRoot:t});return d(a)?s(a.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},Gi=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");let n=await qi({cwd:e,ensureUpstream:!0});if(d(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await Si(r);if(d(a))return s(a.message);if(a.value)return s("Cannot run :sync while the repository is in detached HEAD state");let l=!1,u,m=!1,p=!1,y=!1,N=await yn({cwd:o,branch:O});if(d(N))return s(N.message);m=N.value;let S=Pr({repoRoot:r,stateBranchRoot:o});if(d(S))return s(S.message);y=S.value;let A=await Vi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(A))return s(A.message);if(l=A.value.createdCommit,u=A.value.commitSha,l||i){let I=await wr(o),C=I;if(d(I)&&bi(I.message)){let T=await yn({cwd:o,branch:O});if(d(T))return s(T.message);let B=await Vi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(B))return s(B.message);B.value.createdCommit&&(l=!0,u=B.value.commitSha),C=await wr(o)}if(d(C))return s(C.message);p=C.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(l){let I=await L({args:["rev-parse","HEAD"],cwd:o});if(d(I))return s(I.message);u=I.value.stdout.trim()}return c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,hydrated:y,bootstrapped:i})};var Xi=()=>{let{currentNode:e,selectedIndex:t}=v(),n=R(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},Yi=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),Ji=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=R(n.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return D.navigate({currentNode:n,selectedIndex:i}),c("Restored navigation",null)}if(e.selectedNodeId){let o=t[e.selectedNodeId];if(o&&!o.isDeleted&&o.parentNodeId){let i=t[o.parentNodeId];if(i&&!i.isDeleted){let a=R(i.id).findIndex(l=>l.id===o.id);if(a>=0)return D.navigate({currentNode:i,selectedIndex:a}),c("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=R(n.id);return D.navigate({currentNode:n,selectedIndex:Yi(e.selectedIndex,o.length)}),c("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=R(o.id);return D.navigate({currentNode:o,selectedIndex:Yi(e.selectedIndex,i.length)}),c("Restored navigation to parent",null)}}let r=t[v().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(D.navigate({currentNode:r,selectedIndex:0}),c("Restored navigation to root",null))};import{ulid as ul}from"ulid";var Zi=null,We=()=>structuredClone(Zi),Pt=e=>Zi=e,Qi=()=>{let{currentNode:e,selectedIndex:t}=v(),r=R(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")};var es=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Q();if(d(r))return s("Unable to resolve user ID");let o=tt(t,e,n,r.value);return d(o)?o:c("Created pending move state",{id:ul(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},ts=e=>{Pt(e);let t=ft(e,!0);return d(t)?t:c("Node moved successfully",t.value)};function kr(e){let t=Qi();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=F(o.id),a=i.findIndex(({id:m})=>m===n.id);if(a<0)return s("Current node not found among siblings");let l=i[a+e];if(!l)return s("Missing sibling node");let u=es({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(u)?u:ts(u.value)}function Dr(e){let t=Qi();if(d(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=F(n.id)[r+e];if(!i)return s("Missing sibling node");let a=es({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:ts(a.value)}import hl from"node:os";import is from"node:path";import{z as kt}from"zod";import{accessSync as ml,copyFileSync as pl,existsSync as En,mkdirSync as ns,readdirSync as rs,readFileSync as gl,renameSync as fl,rmSync as vl,statSync as os,unlinkSync as xl,writeFileSync as yl}from"node:fs";import ct from"node:path";var de={writeToFile:(e,t)=>{try{let n=ct.dirname(e);En(n)||ns(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);yl(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return gl(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=de.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return En(e)&&os(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await ml(e),!0}catch{return!1}},mkDir:e=>ns(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ct.parse(t);for(;;){let r=ct.join(t,e);try{if(En(r)&&os(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ct.dirname(t)}return null},readFirstJSON(e){try{if(!de.dirExists(e))return null;let t=rs(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=ct.join(e,t);return de.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return de.dirExists(e)?rs(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{xl(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{vl(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ct.dirname(t)),!n?.overwrite&&En(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{fl(e,t)}catch(r){if(r?.code==="EXDEV"){pl(e,t),this.rmFile(e);return}throw r}}};var El={userId:"",userName:"",preferredEditor:"",autoSync:!1},ss=kt.object({preferredEditor:kt.string().optional(),userName:kt.string().optional(),userId:kt.string().optional(),autoSync:kt.boolean().optional()}).strict(),Nl="config.json",as=()=>is.join(hl.homedir(),ce),Lr=()=>is.join(as(),Nl),Fr=()=>{try{return de.mkDir(as()),c(`Ensured ~/${ce} exists`,null)}catch{return s(`Unable to create ~/${ce}`)}},Cl=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${ce}/config.json JSON`)}let n=ss.safeParse(t??{});return n.success?c("Parsed config",n.data):s(`Invalid ~/${ce}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ds=()=>{let e=Fr();if(d(e))return s(e.message);let t=Lr(),n=de.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):Cl(n)},ls=e=>{let t=Fr();if(d(t))return s(t.message);let n=ss.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Lr();try{return de.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
51
|
+
`),c("Config written",null)}catch{return s(`Unable to write ~/${ce}/config.json`)}},Nn=e=>{let t=ds();if(d(t))return s("Failed to read existing config");let n={...t.value,...e};return ls(n)},cs=()=>{let e=Lr(),t=Fr();if(d(t))return s(`Unable to create ~/${ce}`);if(!(de.readFile(e)!==null)){let u=ls(El);if(d(u))throw new Error(`Unable to create ~/${ce}/config.json`)}let r=ds();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:l}=r.value;return!i||!a?s(`User name or ID not configured in ~/${ce}/config.json`):c("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:l??!1})};import{spawnSync as bl}from"node:child_process";import Il from"node:os";import us from"node:path";import{ulid as Sl}from"ulid";function Al(){let{preferredEditor:e}=ge(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function wl(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function ms(e){let t=us.join(Il.tmpdir(),"epiq");de.mkDir(t);let n=us.join(t,Sl());de.writeToFile(n,e??"");let r=Al();for(let o of r){let i=wl(o,n),a=bl(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let l=de.readFile(n);if(l==null)return s("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return s("Unable to open editor")}import{monotonicFactory as Tl,ulid as Cn}from"ulid";var bn=Tl(),ps=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=bn(),a=bn(),l=bn(),u=bn(),m=lo();if(d(m))return m;let p=V(m.value,void 0);if(d(p))return p;let y=V(p.value,void 0);return d(y)?y:c("Created issue events",[{id:Cn(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:Cn(),userId:r,userName:o,action:"add.field",payload:{id:a,parent:i,name:"Description",val:"",rank:m.value}},{id:Cn(),userId:r,userName:o,action:"add.field",payload:{id:l,parent:i,name:"Assignees",rank:p.value}},{id:Cn(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:y.value}}])};var gs=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id)return r.payload.parent}return null};import Or from"node:fs";import Rl from"node:path";var fs=async e=>{let t=Rl.join(e,".gitignore"),n=Or.existsSync(t)?Or.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/logs/"],o=n.split(`
|
|
52
|
+
`).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...i].join(`
|
|
52
53
|
`);return n=n.trimEnd()+`
|
|
53
54
|
|
|
54
|
-
${
|
|
55
|
-
`,kr.writeFileSync(t,n,"utf8"),oe.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};var ms=e=>Object.values(v().tags).find(t=>t.name===e),ps=e=>Object.values(v().contributors).find(t=>t.name===e),gs=[{systemOnly:!0,intent:M.Move,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{modifier:t}=ne().commandMeta,n=()=>{let d=We();if(!d)return s("No pending move state");let u=d.payload.id;if(!v().nodes[u])return s("Moved node not found");let p=d.payload.parent,y=v().nodes[p];if(!y)return s("Move parent not found");let N=R(p).findIndex(S=>S.id===u);return N===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:y,selectedIndex:N}),c("Synchronized navigation to moved node",null))},r=d=>{if(l(d))return s(d.message);let u=n();return l(u)?s(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=R(o.id)[i];if(!a)return T({mode:g.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 d=F(a.parentNodeId),u=d.findIndex(({id:A})=>A===a.id);if(u===-1)return s("Target not found among siblings");let m=d[u-1],p=d[u+1],y=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},N=nt(a.parentNodeId,a.id,y,e.value);if(l(N))return N;Mt({id:_(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:N.value},...e.value}),T({mode:g.MOVE});let S=n();return l(S)?s(S.message):c("Move initialized",null)}if(t==="next")return T({mode:g.MOVE}),r(wr(1));if(t==="previous")return T({mode:g.MOVE}),r(wr(-1));if(t==="to-next")return T({mode:g.MOVE}),r(Tr(1));if(t==="to-previous")return T({mode:g.MOVE}),r(Tr(-1));if(t==="confirm"){T({mode:g.DEFAULT});let d=We();if(!d)return s("No pending move to confirm");let u=K(d);if(l(u))return u;let m=n();return l(m)?s(m.message):(Mt(null),c("Moved item",null))}return t==="cancel"?(Mt(null),T({mode:g.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];return r?K({id:_(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.Edit,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let t=Ae(v().breadCrumb,"TICKET");if(l(t))return s("Edit target must be an issue");let n=t.value;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();if(!R(n.id)[o])return s("No selected field");let a=R(r.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let d=a.props.value;if(typeof d!="string")return s("Selected field is not editable text");let u=as(d);if(l(u))return s("Failed to edit field");let m=u.value;return m===d?c("No changes made",null):a.title==="Description"?K({id:_(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?K({id:_(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ne().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(d=>z(f.FILTER).map(u=>u.split(n)[0]).includes(d))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return ae(d=>({...d,filters:e==="clear"?[]:[...d.filters,a],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:M.ViewHelp,mode:g.COMMAND_LINE,action:()=>(T({mode:g.HELP}),c("Viewing help",null))},{intent:M.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!le(r))return s("Cannot close in this context");let o=v().nodes[Ce];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=nt(o.id,r.id,{at:"end"},e.value);if(l(i))return i;let a=K({id:_(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return l(a)?a:c("Issue closed",null)},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Ue(r.id,"TICKET");if(l(o))return s("Cannot reopen in this context");let i=o.value,a=v().nodes[Ce];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!le(i))return s("Target node is not issue");let d=ls(i);if(!d)return s("Unable to resolve previous parent from issue history");if(d===a.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[d];if(!u)return s("Previous parent no longer exists");let m=nt(u.id,i.id,{at:"end"},e.value);if(l(m))return m;let p=K({id:_(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return l(p)?p:c("Issue reopened",null)},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=fe(),r=en()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??_();if(!o||!i)return s("Unable to resolve user name or id");let a=vn({userName:o,userId:i,preferredEditor:t??""});return l(a)?a:(tt({userName:o,userId:i}),T({mode:g.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:M.Init,mode:g.COMMAND_LINE,action:async()=>{let e=process.cwd(),t=cs(e);if(l(t))return t;let n=await us(e);if(l(n))return n;let r=Lr();if(l(r))return r;let{rootNodeId:o,nodes:i}=v();return D.navigate({currentNode:i[o],selectedIndex:0}),T({hasProject:!0,mode:g.DEFAULT}),c("Project initialized",null)}},{intent:M.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=en()?.trim();if(!e)return s("No editor provided");let t=vn({preferredEditor:e});return l(t)?t:(tt({preferredEditor:e}),T({mode:g.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:M.SetAutoSync,mode:g.COMMAND_LINE,action:()=>{let e=ne().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=vn({autoSync:t});return l(n)?n:(tt({autoSync:t}),T({mode:g.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=Z();if(l(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=d=>{let u=K(d);if(l(u))return u;let m=b.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=b.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:b.getSiblings(m.parentNodeId).findIndex(({id:y})=>y===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:d}=v(),u=b.getNode(d);if(!u)return s("Workspace not found");let m=rt(u.id,n.value);return l(m)?m:a({id:_(),action:"add.board",payload:{id:_(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let d=Ae(r,"BOARD");if(l(d))return s("Unable to add swimlane in this context");let u=rt(d.value.id,n.value);return l(u)?u:a({id:_(),action:"add.swimlane",payload:{id:_(),name:t.inputString,parent:d.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let d=R(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&d?.context==="SWIMLANE"?d:(()=>{let C=Ae(r,"SWIMLANE");return l(C)?null:C.value})();if(!u)return s("Unable to add issue in this context");let m=rt(u.id,n.value);if(l(m))return m;let p=ds({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(l(p))return p;let y=p.value,N=vo(y);if(N.some(C=>l(C)))return s("Issue create failed: "+N.filter(l).map(C=>C.message).filter(Boolean).join(", "));let S=N[0];if(!S||l(S))return s("Issue creation failed");let I=y.find(C=>C.action==="add.issue")?.payload.id;return I?(D.navigate({currentNode:u,selectedIndex:b.getSiblings(u.id).findIndex(({id:C})=>C===I)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=ne();return e.validity===Te.Invalid?s("Invalid command "+he):(ae(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.Rename,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=en();return o?K({id:_(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=ms(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=Ue(i.id,"TICKET");if(l(a))return s("Unable to untag issue in this context");let d=a.value,u=b.getFieldByTitle(d.id,"Tags");if(!u)return s("Unable to locate tags field");let m=R(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"untag.issue",payload:{id:m.id,target:d.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=R(i.id)[o];if(!a)return s("Invalid tag target");let d=Ue(a.id,"TICKET");if(l(d))return s("Unable to tag issue in this context");let u=d.value,m=ms(r),p;if(m)p=m.id;else{let A=_(),I=K({id:_(),action:"create.tag",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(l(I))return I;p=I.value.result.id}let y=b.getFieldByTitle(u.id,"Tags");if(!y)return s("Unable to locate tags field");if(R(y.id).some(A=>A.props?.value===p))return s("Already tagged with that tag");let S=rt(y.id,e.value);return l(S)?S:K({id:_(),action:"tag.issue",payload:{id:_(),target:u.id,tagId:p,rank:S.value},...e.value})},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=R(i.id)[o];if(!a)return s("Invalid assign target");let d=Ue(a.id,"TICKET");if(l(d))return s("Unable to assign issue in this context");let u=d.value,m=ps(r),p;if(m)p=m.id;else{let A=_(),I=K({id:_(),action:"create.contributor",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(l(I))return I;p=I.value.result.id}let y=b.getFieldByTitle(u.id,"Assignees");if(!y)return s("Unable to locate assignees field");if(R(y.id).some(A=>A.props?.value===p))return s("Assignee already assigned");let S=rt(y.id,e.value);return l(S)?S:K({id:_(),action:"assign.issue",payload:{id:_(),target:u.id,contributor:p,rank:S.value},...e.value})},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=Z();if(l(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=ps(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=Ue(i.id,"TICKET");if(l(a))return s("Unable to unassign in this context");let d=a.value,u=b.getFieldByTitle(d.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=R(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"unassign.issue",payload:{id:m.id,target:d.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>T({mode:g.DEFAULT})},{intent:M.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=Vi();j(()=>""),T({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=fe();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=qe()?Lr():c("No pending default events",null);if(l(r))return s(`Unable to persist default events. ${r.message}`);let o=Z();if(l(o)||!o.value)return s("Unable to resolve event log path");let i=Vn(o.value);logger.debug("[sync-command] pending defaults",qe());let a=await ji({ownEventFileName:i});if(l(a))return T({syncStatus:{msg:a.message,status:"outOfSync"}}),s(`Unable to sync state. ${a.message}`);T({syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let d=Se(process.cwd());if(l(d))throw new Error(d.message);let u=yt(d.value);if(l(u))return s("Unable to load events");Ge(u.value);let m=zi(e);return l(m)?m:c("Synced",!0)}},{intent:M.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Ae(v().breadCrumb,"BOARD");if(l(e))return e;let t=Se(process.cwd());if(l(t))throw new Error(t.message);let n=yt(t.value);if(l(n))return s(n.message);let r=n.value,{modifier:o}=ne().commandMeta,i;if(o==="now"){let N=Dr();if(l(N))return N;let S=Ge(r);return S.some(l)?s(S.map(A=>A.message).join(", ")):(T({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let N=v().eventLog.at(-2),S=Qn(N);if(S===null)return s("No previous event to peek");i=S}else if(o==="next"){let N=v().unappliedEvents.at(0),S=Qn(N);if(S===null)return s("No next event to peek");i=S}else{let N=Xt(o);if(!N)return s("Invalid peek date");i=N.getTime()}let a=e.value.id,{appliedEvents:d,unappliedEvents:u}=mo(r,i),m=Dr();if(l(m))return m;let p=Ge(d);if(p.some(l))return s(p.map(N=>N.message).join(", "));let y=v().nodes[a];return y?(D.navigate({currentNode:y,selectedIndex:0}),T({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await ai();return l(e)?e:(T({mode:g.DEFAULT}),c("Export successful",!0))}},{intent:M.Exit,mode:g.COMMAND_LINE,action:async()=>(D.exit(),c("Exit successful",!0))}];var Rl=new Set(["peek","filter","view-help"]),pe=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ne();if(!t)return s("No command to confirm");if(!e&&n===Te.Invalid)return s("Invalid command");let i=zo(t);if(_o(),v().readOnly&&!Rl.has(i))return bt({status:he.Fail,message:"Command not available in readonly state",value:null});let a=gs.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return bt({status:he.Fail,message:"Command not found",value:null});let d=await a.action(a,{command:t,inputString:o,modifier:r});return l(d)?bt(d):(Wo({addToHistory:!e}),a.onSuccess?.(),bt(d))};var hn=[{intent:x.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(T({mode:g.COMMAND_LINE}),j(()=>"move cancel"),pe({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(T({mode:g.COMMAND_LINE}),j(()=>"move start"),pe({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:g.MOVE,action:()=>(T({mode:g.COMMAND_LINE}),j(()=>"move confirm"),pe({isForceExecutedBySystem:!0}))}],En=[{intent:x.MovePreviousItem,mode:g.MOVE,action:()=>We()?(T({mode:g.COMMAND_LINE}),j(()=>"move previous"),pe({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveNextItem,mode:g.MOVE,action:()=>We()?(T({mode:g.COMMAND_LINE}),j(()=>"move next"),pe({isForceExecutedBySystem:!0})):s("No pending move")}],fs=[{intent:x.MoveToNextContainer,mode:g.MOVE,action:()=>We()?(T({mode:g.COMMAND_LINE}),j(()=>"move to-next"),pe({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveToPreviousContainer,mode:g.MOVE,action:()=>We()?(T({mode:g.COMMAND_LINE}),j(()=>"move to-previous"),pe({isForceExecutedBySystem:!0})):s("No pending move")}];var vs={[P.WORKSPACE]:[...hn,...En],[P.BOARD]:[...hn,...En],[P.SWIMLANE]:[...hn,...En,...fs],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var xs=[{intent:x.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(T({mode:g.COMMAND_LINE}),j(()=>`${f.NEW} `),c("Adding new item",null))},{intent:x.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(T({mode:g.COMMAND_LINE}),j(()=>`${f.DELETE} `),c("Deleting item",null))},{intent:x.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(T({mode:g.COMMAND_LINE}),j(()=>""),c("Entering command line mode",null))},{intent:x.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(D.enterChildNode(),c("Entering context",null))},{intent:x.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),c("Exiting context",null))},{intent:x.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:x.NavNextItem,mode:g.DEFAULT,action:()=>(D.navigateToNextItem(),c("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(D.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:g.DEFAULT,action:()=>(D.navigateToNextContainer(),c("Navigating to next container",null))},{intent:x.Edit,mode:g.DEFAULT,action:()=>(T({mode:g.COMMAND_LINE}),j(()=>"edit"),pe(),c("Fired command",!0))},{intent:x.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(T({viewMode:"dense"}),c("View set",null))},{intent:x.SetViewWide,mode:g.DEFAULT,action:()=>(T({viewMode:"wide"}),c("View set",null))}];var Ml=500,Pl=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ys=e=>{let t=Pl(e);t&&j(n=>(n+t).slice(0,Ml))};var hs=[{intent:x.ViewHelp,mode:g.DEFAULT,action:()=>(T({mode:g.HELP}),c("Viewing help",null))},{intent:x.Exit,mode:g.HELP,action:()=>(T({mode:g.DEFAULT}),c("Exiting help",null))},{intent:x.Confirm,mode:g.COMMAND_LINE,action:()=>(pe(),c("Executing command",null))},{intent:x.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(sr(-1),c("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(sr(1),c("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(ar("left"),c("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(ar("right"),c("Moving cursor right of word",null))},{intent:x.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(T({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:x.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(j((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:x.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(ys(t??""),c("Capturing input",null))},{intent:x.EraseInput,mode:g.COMMAND_LINE,action:()=>(Uo(),c("Erasing input",null))},{intent:x.EraseInputWord,mode:g.COMMAND_LINE,action:()=>($o(),c("Erasing input word",null))},{intent:x.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Ho(),c("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(jo(),c("Getting next command from history",null))}];import kl from"chalk";var Nn=": for command line",Es="q to exit",Ns=`${kl.hex(E.accent)("m")} to confirm`,Fr={[P.WORKSPACE]:[Nn],[P.BOARD]:[Nn],[P.BOARD+g.COMMAND_LINE]:[Nn],[P.SWIMLANE]:[Nn],[P.TICKET+g.HELP]:[Es],[P.SWIMLANE+g.HELP]:[Es],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[Ns],[P.TICKET+g.MOVE]:[Ns]};var Cn=e=>e.trim().toLocaleLowerCase(),Dl=(e,t)=>{let n=b.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Ll=e=>{let{tags:t}=v(),n=b.getFieldByTitle(e,"Tags");return n?F(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Fl=e=>{let{contributors:t}=v(),n=b.getFieldByTitle(e,"Assignees");return n?F(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Cs=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return Cn(e.title??"").includes(n);case"description":return Cn(Dl(e.id,"Description")).includes(n);case"tag":return Ll(e.id).map(Cn).some(d=>d.includes(n));case"assignee":return Fl(e.id).map(Cn).some(d=>d.includes(n));default:return!0}};function bs(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(),c("Breadcrumb built",o))}var Is=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 bn,Or,Br=new Set,Ss=()=>{for(let e of Br)e()},Bl=e=>(Br.add(e),()=>Br.delete(e));function As(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 d=o[t];if(!d)return s("Unable to derive state, currentNode not found");let u=bs(t,o,r);if(l(u))return logger.error(u.message),u;let m=u.value,{context:p}=d,y=Fr[p+n]??Fr[p]??[],N=[...xs,...vs[p]??[],...hs],S=Is(N),A=Ul(o,i),I=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:d,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:S,selectedNode:I,renderedChildrenIndex:A})}var v=()=>(bn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),bn);function _n(e){Or=e;let t={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live"},n=As(t);return l(n)?n:(bn=n.value,Ss(),c("State initialized",null))}function ae(e){let t=v(),n=e(t),r=As(n);return l(r)?s(r.message??"Unable to update state"):(bn=r.value,Ss(),c("State updated",null))}var T=e=>ae(t=>({...t,...e}));var $=()=>Ol(Bl,v,v),Ul=(e,t)=>{let n={};for(let r of Object.values(e))le(r)&&t.length>0&&!t.every(o=>Cs(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],d=e[i.id];return!a||!d?0:a.rank.localeCompare(d.rank)});return n},R=e=>v()?.renderedChildrenIndex[e]??[],Dr=()=>Or?_n(Or):s("Cannot reset state: no initial workspace found");var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=R(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:R(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=R(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:()=>Ts(1),navigateToPreviousItem:()=>Ts(-1),navigateToNextContainer:()=>ws(1),navigateToPreviousContainer:()=>ws(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{T({currentNodeId:e.id,selectedIndex:t})}},Ts=e=>{let t=v(),n=R(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},ws=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=R(o.id),a=i.findIndex(N=>N.id===t.id);if(a<0)return;let d=i.at(a+e)??i.at(0);if(!d)return;let u=R(d.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),y=u.length?p:-1;D.navigate({currentNode:d,selectedIndex:y})};var De="system",Le="ACTOR",kt=$l(),Fe=null;function _l(){let e=Object.values(v().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=R(e.id),[n]=t?R(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=v().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:v().nodes[v().rootNodeId],selectedIndex:0}}function Wl(){let e=_l();D.navigate(e)}function Hl(){let e=kt(),t=kt(),n=kt(),r=kt(),o=kt(),i=V(void 0,void 0);if(l(i))return i;let a=V(void 0,void 0);if(l(a))return a;let d=V(a.value,void 0);if(l(d))return d;let u=V(void 0,void 0);if(l(u))return u;let m=V(u.value,void 0);if(l(m))return m;let p=V(m.value,void 0);if(l(p))return p;let y=V(void 0,void 0);return l(y)?y:c("Created default events",[{id:ke(),userId:De,userName:Le,action:"init.workspace",payload:{id:e,name:"Workspace",rank:i.value}},{id:ke(),userId:De,userName:Le,action:"add.board",payload:{id:t,name:"Default",parent:e,rank:a.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t,rank:u.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t,rank:m.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:o,name:"Done",parent:t,rank:p.value}},{id:ke(),userId:De,userName:Le,action:"add.board",payload:{id:$t,name:"Closed",parent:e,rank:d.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:Ce,name:"Closed",parent:$t,rank:y.value}},{id:ke(),userId:De,userName:Le,action:"lock.node",payload:{id:$t}},{id:ke(),userId:De,userName:Le,action:"lock.node",payload:{id:Ce}}])}function qe(){return Fe!==null}function Lr(){if(!Fe||Fe.length===0)return Fe=null,c("No pending default events to persist",null);let e=Fe.map(t=>zt({event:t})).filter(l);return e.length>0?s([ut.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${ut.dim.gray(`${n+1}.`)} ${ut.dim(t.message)}`),`
|
|
55
|
+
${l}
|
|
56
|
+
`,Or.writeFileSync(t,n,"utf8"),oe.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};var vs=e=>Object.values(v().tags).find(t=>t.name===e),xs=e=>Object.values(v().contributors).find(t=>t.name===e),ys=[{systemOnly:!0,intent:M.Move,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=ne().commandMeta,n=()=>{let l=We();if(!l)return s("No pending move state");let u=l.payload.id;if(!v().nodes[u])return s("Moved node not found");let p=l.payload.parent,y=v().nodes[p];if(!y)return s("Move parent not found");let N=R(p).findIndex(S=>S.id===u);return N===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:y,selectedIndex:N}),c("Synchronized navigation to moved node",null))},r=l=>{if(d(l))return s(l.message);let u=n();return d(u)?s(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=R(o.id)[i];if(!a)return w({mode:g.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 l=F(a.parentNodeId),u=l.findIndex(({id:A})=>A===a.id);if(u===-1)return s("Target not found among siblings");let m=l[u-1],p=l[u+1],y=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},N=tt(a.parentNodeId,a.id,y,e.value);if(d(N))return N;Pt({id:_(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:N.value},...e.value}),w({mode:g.MOVE});let S=n();return d(S)?s(S.message):c("Move initialized",null)}if(t==="next")return w({mode:g.MOVE}),r(Dr(1));if(t==="previous")return w({mode:g.MOVE}),r(Dr(-1));if(t==="to-next")return w({mode:g.MOVE}),r(kr(1));if(t==="to-previous")return w({mode:g.MOVE}),r(kr(-1));if(t==="confirm"){w({mode:g.DEFAULT});let l=We();if(!l)return s("No pending move to confirm");let u=K(l);if(d(u))return u;let m=n();return d(m)?s(m.message):(Pt(null),c("Moved item",null))}return t==="cancel"?(Pt(null),w({mode:g.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];return r?K({id:_(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Edit,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let t=Ae(v().breadCrumb,"TICKET");if(d(t))return s("Edit target must be an issue");let n=t.value;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();if(!R(n.id)[o])return s("No selected field");let a=R(r.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let l=a.props.value;if(typeof l!="string")return s("Selected field is not editable text");let u=ms(l);if(d(u))return s("Failed to edit field");let m=u.value;return m===l?c("No changes made",null):a.title==="Description"?K({id:_(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?K({id:_(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ne().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>z(f.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return ae(l=>({...l,filters:e==="clear"?[]:[...l.filters,a],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:M.ViewHelp,mode:g.COMMAND_LINE,action:()=>(w({mode:g.HELP}),c("Viewing help",null))},{intent:M.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!le(r))return s("Cannot close in this context");let o=v().nodes[Ce];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=K({id:_(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return d(a)?a:c("Issue closed",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Ue(r.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=v().nodes[Ce];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!le(i))return s("Target node is not issue");let l=gs(i);if(!l)return s("Unable to resolve previous parent from issue history");if(l===a.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[l];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=K({id:_(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return d(p)?p:c("Issue reopened",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=ge(),r=on()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??_();if(!o||!i)return s("Unable to resolve user name or id");let a=Nn({userName:o,userId:i,preferredEditor:t??""});return d(a)?a:(et({userName:o,userId:i}),w({mode:g.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:M.Init,mode:g.COMMAND_LINE,action:async()=>{let e=mi(process.cwd());if(d(e))return e;let t=await fs(process.cwd());if(d(t))return t;let n=Ur();if(d(n))return n;let{rootNodeId:r,nodes:o}=v();return D.navigate({currentNode:o[r],selectedIndex:0}),w({hasProject:!0,mode:g.DEFAULT}),c("Project initialized",null)}},{intent:M.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=on()?.trim();if(!e)return s("No editor provided");let t=Nn({preferredEditor:e});return d(t)?t:(et({preferredEditor:e}),w({mode:g.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:M.SetAutoSync,mode:g.COMMAND_LINE,action:()=>{let e=ne().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=Nn({autoSync:t});return d(n)?n:(et({autoSync:t}),w({mode:g.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=Q();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=l=>{let u=K(l);if(d(u))return u;let m=b.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=b.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:b.getSiblings(m.parentNodeId).findIndex(({id:y})=>y===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=v(),u=b.getNode(l);if(!u)return s("Workspace not found");let m=nt(u.id,n.value);return d(m)?m:a({id:_(),action:"add.board",payload:{id:_(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let l=Ae(r,"BOARD");if(d(l))return s("Unable to add swimlane in this context");let u=nt(l.value.id,n.value);return d(u)?u:a({id:_(),action:"add.swimlane",payload:{id:_(),name:t.inputString,parent:l.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let l=R(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let C=Ae(r,"SWIMLANE");return d(C)?null:C.value})();if(!u)return s("Unable to add issue in this context");let m=nt(u.id,n.value);if(d(m))return m;let p=ps({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(d(p))return p;let y=p.value,N=ho(y);if(N.some(C=>d(C)))return s("Issue create failed: "+N.filter(d).map(C=>C.message).filter(Boolean).join(", "));let S=N[0];if(!S||d(S))return s("Issue creation failed");let I=y.find(C=>C.action==="add.issue")?.payload.id;return I?(D.navigate({currentNode:u,selectedIndex:b.getSiblings(u.id).findIndex(({id:C})=>C===I)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=ne();return e.validity===we.Invalid?s("Invalid command "+he):(ae(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Rename,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=on();return o?K({id:_(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=vs(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=Ue(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let l=a.value,u=b.getFieldByTitle(l.id,"Tags");if(!u)return s("Unable to locate tags field");let m=R(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"untag.issue",payload:{id:m.id,target:l.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=R(i.id)[o];if(!a)return s("Invalid tag target");let l=Ue(a.id,"TICKET");if(d(l))return s("Unable to tag issue in this context");let u=l.value,m=vs(r),p;if(m)p=m.id;else{let A=_(),I=K({id:_(),action:"create.tag",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(I))return I;p=I.value.result.id}let y=b.getFieldByTitle(u.id,"Tags");if(!y)return s("Unable to locate tags field");if(R(y.id).some(A=>A.props?.value===p))return s("Already tagged with that tag");let S=nt(y.id,e.value);return d(S)?S:K({id:_(),action:"tag.issue",payload:{id:_(),target:u.id,tagId:p,rank:S.value},...e.value})},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=R(i.id)[o];if(!a)return s("Invalid assign target");let l=Ue(a.id,"TICKET");if(d(l))return s("Unable to assign issue in this context");let u=l.value,m=xs(r),p;if(m)p=m.id;else{let A=_(),I=K({id:_(),action:"create.contributor",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(I))return I;p=I.value.result.id}let y=b.getFieldByTitle(u.id,"Assignees");if(!y)return s("Unable to locate assignees field");if(R(y.id).some(A=>A.props?.value===p))return s("Assignee already assigned");let S=nt(y.id,e.value);return d(S)?S:K({id:_(),action:"assign.issue",payload:{id:_(),target:u.id,contributor:p,rank:S.value},...e.value})},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=xs(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=Ue(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let l=a.value,u=b.getFieldByTitle(l.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=R(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"unassign.issue",payload:{id:m.id,target:l.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=Xi();j(()=>""),w({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=ge();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=Dt()?Ur():c("No pending default events",null);if(d(r))return s(`Unable to persist default events. ${r.message}`);let o=Q();if(d(o)||!o.value)return s("Unable to resolve event log path");let i=Xn(o.value);logger.debug("[sync-command] pending defaults",Dt());let a=await Gi({ownEventFileName:i});if(d(a))return w({syncStatus:{msg:a.message,status:"outOfSync"}}),s(`Unable to sync state. ${a.message}`);w({syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let l=Se(process.cwd());if(d(l))throw new Error(l.message);let u=yt(l.value);if(d(u))return s("Unable to load events");qe(u.value);let m=Ji(e);return d(m)?m:c("Synced",!0)}},{intent:M.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Ae(v().breadCrumb,"BOARD");if(d(e))return e;let t=Se(process.cwd());if(d(t))throw new Error(t.message);let n=yt(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=ne().commandMeta,i;if(o==="now"){let N=Br();if(d(N))return N;let S=qe(r);return S.some(d)?s(S.map(A=>A.message).join(", ")):(w({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let N=v().eventLog.at(-2),S=rr(N);if(S===null)return s("No previous event to peek");i=S}else if(o==="next"){let N=v().unappliedEvents.at(0),S=rr(N);if(S===null)return s("No next event to peek");i=S}else{let N=Qt(o);if(!N)return s("Invalid peek date");i=N.getTime()}let a=e.value.id,{appliedEvents:l,unappliedEvents:u}=fo(r,i),m=Br();if(d(m))return m;let p=qe(l);if(p.some(d))return s(p.map(N=>N.message).join(", "));let y=v().nodes[a];return y?(D.navigate({currentNode:y,selectedIndex:0}),w({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await ci();return d(e)?e:(w({mode:g.DEFAULT}),c("Export successful",!0))}},{intent:M.Exit,mode:g.COMMAND_LINE,action:async()=>(D.exit(),c("Exit successful",!0))}];var Ml=new Set(["peek","filter","view-help"]),me=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ne();if(!t)return s("No command to confirm");if(!e&&n===we.Invalid)return s("Invalid command");let i=Yo(t);if(jo(),v().readOnly&&!Ml.has(i))return bt({status:he.Fail,message:"Command not available in readonly state",value:null});let a=ys.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return bt({status:he.Fail,message:"Command not found",value:null});let l=await a.action(a,{command:t,inputString:o,modifier:r});return d(l)?bt(l):(Ko({addToHistory:!e}),a.onSuccess?.(),bt(l))};var In=[{intent:x.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>"move cancel"),me({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>"move start"),me({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:g.MOVE,action:()=>(w({mode:g.COMMAND_LINE}),j(()=>"move confirm"),me({isForceExecutedBySystem:!0}))}],Sn=[{intent:x.MovePreviousItem,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),j(()=>"move previous"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveNextItem,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),j(()=>"move next"),me({isForceExecutedBySystem:!0})):s("No pending move")}],hs=[{intent:x.MoveToNextContainer,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),j(()=>"move to-next"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveToPreviousContainer,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),j(()=>"move to-previous"),me({isForceExecutedBySystem:!0})):s("No pending move")}];var Es={[P.WORKSPACE]:[...In,...Sn],[P.BOARD]:[...In,...Sn],[P.SWIMLANE]:[...In,...Sn,...hs],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Ns=[{intent:x.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>`${f.NEW} `),c("Adding new item",null))},{intent:x.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>`${f.DELETE} `),c("Deleting item",null))},{intent:x.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>""),c("Entering command line mode",null))},{intent:x.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(D.enterChildNode(),c("Entering context",null))},{intent:x.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),c("Exiting context",null))},{intent:x.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:x.NavNextItem,mode:g.DEFAULT,action:()=>(D.navigateToNextItem(),c("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(D.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:g.DEFAULT,action:()=>(D.navigateToNextContainer(),c("Navigating to next container",null))},{intent:x.Edit,mode:g.DEFAULT,action:()=>(w({mode:g.COMMAND_LINE}),j(()=>"edit"),me(),c("Fired command",!0))},{intent:x.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(w({viewMode:"dense"}),c("View set",null))},{intent:x.SetViewWide,mode:g.DEFAULT,action:()=>(w({viewMode:"wide"}),c("View set",null))}];var Pl=500,kl=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Cs=e=>{let t=kl(e);t&&j(n=>(n+t).slice(0,Pl))};var bs=[{intent:x.ViewHelp,mode:g.DEFAULT,action:()=>(w({mode:g.HELP}),c("Viewing help",null))},{intent:x.Exit,mode:g.HELP,action:()=>(w({mode:g.DEFAULT}),c("Exiting help",null))},{intent:x.Confirm,mode:g.COMMAND_LINE,action:()=>(me(),c("Executing command",null))},{intent:x.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(ur(-1),c("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(ur(1),c("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(mr("left"),c("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(mr("right"),c("Moving cursor right of word",null))},{intent:x.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(w({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:x.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(j((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:x.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(Cs(t??""),c("Capturing input",null))},{intent:x.EraseInput,mode:g.COMMAND_LINE,action:()=>(Wo(),c("Erasing input",null))},{intent:x.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Ho(),c("Erasing input word",null))},{intent:x.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Vo(),c("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(zo(),c("Getting next command from history",null))}];import Dl from"chalk";var An=": for command line",Is="q to exit",Ss=`${Dl.hex(E.accent)("m")} to confirm`,$r={[P.WORKSPACE]:[An],[P.BOARD]:[An],[P.BOARD+g.COMMAND_LINE]:[An],[P.SWIMLANE]:[An],[P.TICKET+g.HELP]:[Is],[P.SWIMLANE+g.HELP]:[Is],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[Ss],[P.TICKET+g.MOVE]:[Ss]};var wn=e=>e.trim().toLocaleLowerCase(),Ll=(e,t)=>{let n=b.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Fl=e=>{let{tags:t}=v(),n=b.getFieldByTitle(e,"Tags");return n?F(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Ol=e=>{let{contributors:t}=v(),n=b.getFieldByTitle(e,"Assignees");return n?F(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},As=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return wn(e.title??"").includes(n);case"description":return wn(Ll(e.id,"Description")).includes(n);case"tag":return Fl(e.id).map(wn).some(l=>l.includes(n));case"assignee":return Ol(e.id).map(wn).some(l=>l.includes(n));default:return!0}};function ws(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(),c("Breadcrumb built",o))}var Ts=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 Tn,_r,Wr=new Set,Rs=()=>{for(let e of Wr)e()},Ul=e=>(Wr.add(e),()=>Wr.delete(e));function Ms(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=ws(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,y=$r[p+n]??$r[p]??[],N=[...Ns,...Es[p]??[],...bs],S=Ts(N),A=$l(o,i),I=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:S,selectedNode:I,renderedChildrenIndex:A})}var v=()=>(Tn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Tn);function Vn(e){_r=e;let t=zt(process.cwd()),n=!1;if(!d(t)){let i=gn(t.value);if(d(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",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=Ms(r);return d(o)?o:(Tn=o.value,Rs(),c("State initialized",null))}function ae(e){let t=v(),n=e(t),r=Ms(n);return d(r)?s(r.message??"Unable to update state"):(Tn=r.value,Rs(),c("State updated",null))}var w=e=>ae(t=>({...t,...e}));var $=()=>Bl(Ul,v,v),$l=(e,t)=>{let n={};for(let r of Object.values(e))le(r)&&t.length>0&&!t.every(o=>As(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],l=e[i.id];return!a||!l?0:a.rank.localeCompare(l.rank)});return n},R=e=>v()?.renderedChildrenIndex[e]??[],Br=()=>_r?Vn(_r):s("Cannot reset state: no initial workspace found");var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=R(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:R(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=R(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:()=>Ps(1),navigateToPreviousItem:()=>Ps(-1),navigateToNextContainer:()=>ks(1),navigateToPreviousContainer:()=>ks(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{w({currentNodeId:e.id,selectedIndex:t})}},Ps=e=>{let t=v(),n=R(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},ks=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=R(o.id),a=i.findIndex(N=>N.id===t.id);if(a<0)return;let l=i.at(a+e)??i.at(0);if(!l)return;let u=R(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),y=u.length?p:-1;D.navigate({currentNode:l,selectedIndex:y})};var De="system",Le="ACTOR",Lt=_l(),Fe=null;function Wl(){let e=Object.values(v().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=R(e.id),[n]=t?R(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=v().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:v().nodes[v().rootNodeId],selectedIndex:0}}function Hl(){let e=Wl();D.navigate(e)}function jl(){let e=Lt(),t=Lt(),n=Lt(),r=Lt(),o=Lt(),i=V(void 0,void 0);if(d(i))return i;let a=V(void 0,void 0);if(d(a))return a;let l=V(a.value,void 0);if(d(l))return l;let u=V(void 0,void 0);if(d(u))return u;let m=V(u.value,void 0);if(d(m))return m;let p=V(m.value,void 0);if(d(p))return p;let y=V(void 0,void 0);return d(y)?y:c("Created default events",[{id:ke(),userId:De,userName:Le,action:"init.workspace",payload:{id:e,name:"Workspace",rank:i.value}},{id:ke(),userId:De,userName:Le,action:"add.board",payload:{id:t,name:"Default",parent:e,rank:a.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t,rank:u.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t,rank:m.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:o,name:"Done",parent:t,rank:p.value}},{id:ke(),userId:De,userName:Le,action:"add.board",payload:{id:Wt,name:"Closed",parent:e,rank:l.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:Ce,name:"Closed",parent:Wt,rank:y.value}},{id:ke(),userId:De,userName:Le,action:"lock.node",payload:{id:Wt}},{id:ke(),userId:De,userName:Le,action:"lock.node",payload:{id:Ce}}])}function Dt(){return Fe!==null}function Ur(){if(!Fe||Fe.length===0)return Fe=null,c("No pending default events to persist",null);let e=Fe.map(t=>Xt({event:t})).filter(d);return e.length>0?s([ut.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${ut.dim.gray(`${n+1}.`)} ${ut.dim(t.message)}`),`
|
|
56
57
|
`].join(`
|
|
57
|
-
`)):(Fe=null,c("Persisted pending default events",null))}function
|
|
58
|
+
`)):(Fe=null,c("Persisted pending default events",null))}function Ds(e){let t;if(e.some(r=>r.action==="init.workspace"))Fe=null,t=qe(e);else{let r=jl();if(d(r))return r;Fe=r.value,t=qe([...Fe])}let n=t.filter(d);return n.length>0?s([ut.bold.red("Materializing failed"),"",...n.map((r,o)=>`${ut.dim.gray(`${o+1}.`)} ${ut.dim(r.message)}`),`
|
|
58
59
|
`].join(`
|
|
59
60
|
|
|
60
61
|
See complete log:
|
|
61
62
|
|
|
62
63
|
`)+e.map(r=>JSON.stringify(r)).join(`
|
|
63
|
-
`)):(Wl(),c("State booted successfully",null))}import{Box as sc}from"ink";import _r from"react";import Lt from"chalk";import{Box as Ur,Text as Ms}from"ink";import Dt,{useEffect as jl,useMemo as Kl,useState as Vl}from"react";var Ps=Lt.gray,zl=Lt.inverse,Gl=Lt.inverse.gray,ql={hint:"",hints:[],overlap:0,remainder:""},Ds=({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}},Yl=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=X(t);return{bg:r=>Lt.bgHex(n).black(r),bgCursor:r=>Lt.bgHex(n).inverse.black(r)}}return tr(t)},Xl=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Ds({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}},ks=()=>({value:J.value,cursorPosition:J.cursorPosition,commandIsPending:J.commandIsPending,autoCompletion:J.commandMeta.autoCompletion??ql,infoMessage:J.commandMeta.infoMessage,validationStatus:J.commandMeta.validity,command:J.commandMeta.command,inputString:J.commandMeta.inputString,modifier:J.commandMeta.modifier}),Jl=(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,Ls=({width:e})=>{let[t,n]=Vl(ks());jl(()=>{let y=()=>{let S=ks();n(A=>Jl(A,S)?A:S)},N=Bo(y);return y(),()=>{N()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:d,command:u,modifier:m}=t,p=Kl(()=>{let y=Math.max(0,Math.min(o,r.length)),N=Ds({value:r,command:u}),S=Xl({value:r,command:u,modifier:m}),A=u?tr(u):null,I=Yl({command:u,modifier:m}),C=(ie,se)=>{let Fn=N&&se>=N.start&&se<N.end,On=S&&se>=S.start&&se<S.end;return Fn&&A?A.fg(ie):On&&I?I.bg(ie):ie},w=(ie,se)=>{let Fn=N&&se>=N.start&&se<N.end,On=S&&se>=S.start&&se<S.end;return Fn&&A?A.fgCursor(ie):On&&I?I.bgCursor(ie):zl(ie)},B=r.slice(0,y),Oe=r[y]??" ",Be=y<r.length?r.slice(y+1):"",Zs=Array.from(B).map((ie,se)=>C(ie,se)).join(""),Gr=w(Oe,y),qr=Array.from(Be).map((ie,se)=>C(ie,y+1+se)).join("");if(d.hint){let ie=d.hint[d.overlap]??Oe;Gr=Gl(ie),qr=Ps(d.remainder.slice(1)+Be)}return Ps(":")+Zs+Gr+qr},[r,o,d,u,m]);return Dt.createElement(Ur,{flexDirection:"column",justifyContent:"flex-start"},Dt.createElement(Ur,{flexDirection:"column",paddingX:1,borderColor:E.secondary,borderStyle:"round",width:e},Dt.createElement(Ur,null,Dt.createElement(Ms,null,p),i&&Dt.createElement(Ms,{wrap:"truncate",color:a?E.red:E.secondary2},` ${i} `))))};import Fs from"chalk";import{Box as Ql,Text as $r}from"ink";import In,{useEffect as Zl,useState as ec}from"react";var tc=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Os=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)}},nc=({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)}`},rc=(e,t,n)=>{let r=Os(e),o=Os(t);return nc({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},oc=(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 rc(i,a,o)},ic=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Bs=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=$(),[o,i]=ec(0);Zl(()=>{if(n!=="syncing"){i(0);return}let C=setInterval(()=>{i(w=>w+1)},50);return()=>clearInterval(C)},[n]);let a=[],d=0;for(let C of t){let B=(a.length>0?" | ":"").length+C.length;if(d+B>e-4)break;a.push(C),d+=B}let u=n!="synced"?r??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),p=n==="syncing"?oc(tc,(Math.sin(o*.12)+1)/2):E.secondary,y=Fs.hex(p??"fff"),N=Fs.hex(E.secondary2),S=y(`\u256D${"\u2500".repeat(m)}\u256E`),A=y(`\u2570${"\u2500".repeat(m)}\u256F`),I=`${y("\u2502")}${N(ic(` ${u} `,m))}${y("\u2502")}`;return In.createElement(Ql,{flexDirection:"column",width:e},In.createElement($r,null,S),In.createElement($r,null,I),In.createElement($r,null,A))};var Sn=({width:e,mode:t,availableHints:n})=>{let r=$(),o=[],i=0;for(let a of n){let u=(o.length>0?" | ":"").length+a.length;if(i+u>e+2)break;o.push(a),i+=u}return _r.createElement(sc,null,t===g.COMMAND_LINE&&r.syncStatus.status!=="syncing"?_r.createElement(Ls,{width:e}):_r.createElement(Bs,{width:e,mode:t,availableHints:n}))};import{Box as mt,Text as Us}from"ink";import He from"react";var $s=({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"]),He.createElement(mt,{flexDirection:"column",marginTop:3,borderColor:E.secondary,borderStyle:"round",width:e,minHeight:19},He.createElement(mt,{flexDirection:"column",width:e},v().mode===g.HELP?t.map(([n,r],o)=>He.createElement(mt,{paddingLeft:1,key:o,flexDirection:"row"},He.createElement(mt,{key:o,flexDirection:"row",paddingBottom:o?0:1},He.createElement(mt,{width:20,justifyContent:"flex-end"},He.createElement(Us,{color:o?E.accent:E.secondary},n)),He.createElement(mt,{flexGrow:1,width:40,paddingLeft:2},He.createElement(Us,{color:o?E.primary:E.secondary},r))))):null))};import ac from"chalk";import{Box as An,Text as je}from"ink";import ge from"react";var _s=({width:e,height:t})=>ge.createElement(An,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},ge.createElement(je,{color:E.accent,bold:!0},"Initialize project"),ge.createElement(je,null,`This folder is not an ${ac.hex(E.accent)("epiq")} project yet.`),ge.createElement(je,{color:E.primary},"To start tracking issues here, we need to initialize a new"," ",ge.createElement(je,{color:E.primary,backgroundColor:E.secondary}," .epiq/project.json ")," ","file in this repository."),ge.createElement(An,{marginTop:1,flexDirection:"column"},ge.createElement(An,null,ge.createElement(je,{color:E.accent}," "),ge.createElement(je,{color:E.primary},"Type "),ge.createElement(je,{backgroundColor:E.secondary}," :init "))),ge.createElement(An,{marginTop:1},ge.createElement(je,{color:E.secondary2},"(This will create the local epiq project files)")));import{Box as Ft,Text as xe}from"ink";import H from"react";var Tn=({isDone:e,command:t,value:n})=>H.createElement(Ft,null,H.createElement(xe,{color:E.accent,dimColor:e},e?" \u2714 ":" "),H.createElement(xe,{dimColor:e},"Type "),H.createElement(xe,{backgroundColor:E.secondary,dimColor:e}," "+t+" "),n&&H.createElement(H.Fragment,null,H.createElement(xe,{dimColor:e}," "),H.createElement(xe,{color:E.secondary,dimColor:e},"<"+n+">")));function Wr({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,d=n?r?null:":config:editor":":config:username";return H.createElement(Ft,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},H.createElement(xe,{color:E.accent,bold:!0},"Welcome! \u{1F539}"),H.createElement(xe,null,"Lets get you started - its a breeze."),H.createElement(xe,{color:E.secondary2},"And remember, you can always get help with"," ",H.createElement(xe,{color:E.accent},":help"),"."),!a&&H.createElement(xe,{color:E.secondary2},d===":config:username"?"First, choose your username.":"Nice. One more step."),H.createElement(Ft,{flexDirection:"column"},n&&H.createElement(Ft,{marginBottom:1},H.createElement(Tn,{isDone:!0,command:":config:username",value:o})),!n&&H.createElement(Tn,{isDone:!1,command:":config:username"}),n&&!r&&H.createElement(Tn,{isDone:!1,command:":config:editor"}),a&&H.createElement(Ft,null,H.createElement(Tn,{isDone:!0,command:":config:editor",value:i}))))}import Vs from"chalk";import{Box as Rn,Text as Ke}from"ink";import Q from"react";import{Box as Hr,Text as dc}from"ink";import pt from"react";var lc=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Ws=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=v(),i=F(n.id)[r],a=Ue(i?.id??n.id,"TICKET"),d=Ee(a)?a.value:void 0,u=d?.id?F(d.id):[],m=I=>{let C=u.find(w=>w.title===I);return C?F(C.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},p=m("Tags"),y=m("Assignees"),N=d?.parentNodeId?!qn(n.id,d?.parentNodeId)&&o==="dense":!1,S=t.map((I,C)=>{let w=C===t.length-1,B=F(I.id),Oe=w?B?.[r]?.title:void 0;return`${C?" / ":""}${I.title??""}${Oe?` \u25B8 ${Oe}`:""}`}).join(""),A=lc(S,e);return pt.createElement(Hr,null,pt.createElement(dc,{color:E.secondary2},A),N?p.map(I=>pt.createElement(Hr,{key:I,paddingLeft:2},pt.createElement(dt,{id:I}))):null,N?y.map(I=>pt.createElement(Hr,{key:I,paddingLeft:2},pt.createElement(at,{id:I}))):null)};import{Box as cc,Text as Hs}from"ink";import wn from"react";var uc=({filters:e})=>wn.createElement(cc,{columnGap:1},wn.createElement(Hs,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>wn.createElement(Hs,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),js=wn.memo(uc);var Ks="0.4.6";function Mn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=$(),{userName:i,preferredEditor:a}=fe(),d=40,u=process.stdout.columns-d-8,m=r.at(-1)?.id,p=Qt(m??""),y=Ee(p)?To(p.value):"INVALID DATE";return Q.createElement(Rn,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Q.createElement(Ke,null," "):Q.createElement(Rn,{paddingLeft:1},e.length>0?Q.createElement(js,{filters:e}):Q.createElement(Ws,{width:u})),n==="live"?Q.createElement(Rn,{columnGap:1,paddingRight:2,"max-width":d,overflow:"hidden",justifyContent:"flex-end"},Q.createElement(Ke,{dimColor:!0,color:E.secondary2},Ks+" "),Q.createElement(zs,{icon:"@",value:i}),Q.createElement(zs,{icon:"\u276F",value:a})):"",n==="peek"?Q.createElement(Rn,{paddingLeft:1},Q.createElement(Ke,{backgroundColor:E.yellow}," Readonly "),Q.createElement(Ke,{color:E.yellow}," "+o.length+" edits ago at "),Q.createElement(Ke,{backgroundColor:E.yellow,color:E.accent}," "+y+" "),Q.createElement(Ke,{color:E.yellow},". Resume with "),Q.createElement(Ke,{backgroundColor:E.yellow}," :peek now ")):"")}function zs({icon:e,value:t}){return Q.createElement(Ke,null,Vs.dim(e)+Vs.hex(E.accent)(` ${t??"-"} `))}import{Box as mc,Text as pc}from"ink";import Ot from"react";import{Box as Pn,Text as jr}from"ink";import Ve from"react";function Kr(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?R(t?.id):[];return Ve.createElement(Pn,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:E.secondary,width:i},Ve.createElement(Pn,{padding:1,paddingTop:0,paddingBottom:0},Ve.createElement(jr,null,"Select a board:")),Ve.createElement(Pn,{padding:1,flexDirection:"column"},a.map((d,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,y=R(d.id).flatMap(({id:N})=>F(N)).length;return Ve.createElement(Pn,{key:d.id??u},Ve.createElement(jr,{color:m?E.accent:E.secondary2},Ve.createElement(re,{isSelected:m})),Ve.createElement(jr,{color:m?E.accent:E.secondary2},d.title," (",y," issues)",d.readonly?" \u{1F512}":""))})))}var gc=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:d}=$(),u=n.find(({context:N})=>N==="BOARD"),y=i-1-3;return Ot.createElement(mc,{flexDirection:"row"},e.context==="WORKSPACE"?Ot.createElement(Kr,null):u?Ot.createElement(dn,{height:y,width:a,swimlanes:(d[u.id]??[]).filter(N=>N!==void 0&&et(N)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Ot.createElement(pc,null))},Gs=Ot.memo(gc);function Vr({width:e,height:t}){let n=$(),r=n.filters;if(n.mode===g.HELP)return q.createElement(Ze,{flexDirection:"column"},q.createElement($s,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:d,preferredEditor:u}=Gt(),m=!o,p=o&&(!n.hasProject||qe());if(m)return q.createElement(Ze,{flexDirection:"column"},q.createElement(Ze,{flexDirection:"column"},q.createElement(Mn,{hideBreadCrumb:!0,filters:r}),q.createElement(Wr,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:d??"",preferredEditor:u??""})),q.createElement(Sn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(p)return q.createElement(Ze,{flexDirection:"column"},q.createElement(Ze,{flexDirection:"column"},q.createElement(Mn,{hideBreadCrumb:!0,filters:r}),q.createElement(_s,{height:t,width:e})),q.createElement(Sn,{width:e,mode:n.mode,availableHints:n.availableHints}));let y=Ae(v().breadCrumb??[],"BOARD");if(Ee(y)){let N=y.value.id,S=R(N).length,A=3,I=Math.floor(e/A),C=Math.floor(e/Math.max(S,1));e=Math.min(C,I)*Math.max(S,A)}return q.createElement(Ze,{flexDirection:"column"},q.createElement(Ze,{flexDirection:"column"},q.createElement(Mn,{filters:r}),q.createElement(Gs,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),q.createElement(Sn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import fc from"readline";var kn,Dn,ye,vc=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.InitCommandLine,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),qs=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Vo(e,n);if(!o||r&&!vc.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},xc=()=>async function(t,n){n.name!=="escape"&&(ye&&(clearTimeout(ye),ye=void 0),await qs(n))},yc=()=>async function(t){if(t.length===1&&t[0]===27){ye&&clearTimeout(ye),ye=setTimeout(()=>{qs({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),ye=void 0},25);return}ye&&(clearTimeout(ye),ye=void 0)};function Ys(){kn&&process.stdin.removeListener("keypress",kn),Dn&&process.stdin.removeListener("data",Dn),kn=xc(),Dn=yc(),fc.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Dn),process.stdin.on("keypress",kn)}Ec(`${zr.bold("Epiq CLI")}
|
|
64
|
+
`)):(Hl(),c("State booted successfully",null))}var tn=()=>{let e=ge(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},wo=()=>!Dt();import{Box as ac}from"ink";import Kr from"react";import Ot from"chalk";import{Box as Hr,Text as Ls}from"ink";import Ft,{useEffect as Kl,useMemo as Vl,useState as zl}from"react";var Fs=Ot.gray,ql=Ot.inverse,Gl=Ot.inverse.gray,Yl={hint:"",hints:[],overlap:0,remainder:""},Bs=({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}},Xl=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=X(t);return{bg:r=>Ot.bgHex(n).black(r),bgCursor:r=>Ot.bgHex(n).inverse.black(r)}}return sr(t)},Jl=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Bs({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}},Os=()=>({value:J.value,cursorPosition:J.cursorPosition,commandIsPending:J.commandIsPending,autoCompletion:J.commandMeta.autoCompletion??Yl,infoMessage:J.commandMeta.infoMessage,validationStatus:J.commandMeta.validity,command:J.commandMeta.command,inputString:J.commandMeta.inputString,modifier:J.commandMeta.modifier}),Zl=(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,Us=({width:e})=>{let[t,n]=zl(Os());Kl(()=>{let y=()=>{let S=Os();n(A=>Zl(A,S)?A:S)},N=_o(y);return y(),()=>{N()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:l,command:u,modifier:m}=t,p=Vl(()=>{let y=Math.max(0,Math.min(o,r.length)),N=Bs({value:r,command:u}),S=Jl({value:r,command:u,modifier:m}),A=u?sr(u):null,I=Xl({command:u,modifier:m}),C=(ie,se)=>{let _n=N&&se>=N.start&&se<N.end,Wn=S&&se>=S.start&&se<S.end;return _n&&A?A.fg(ie):Wn&&I?I.bg(ie):ie},T=(ie,se)=>{let _n=N&&se>=N.start&&se<N.end,Wn=S&&se>=S.start&&se<S.end;return _n&&A?A.fgCursor(ie):Wn&&I?I.bgCursor(ie):ql(ie)},B=r.slice(0,y),Oe=r[y]??" ",Be=y<r.length?r.slice(y+1):"",ra=Array.from(B).map((ie,se)=>C(ie,se)).join(""),Jr=T(Oe,y),Zr=Array.from(Be).map((ie,se)=>C(ie,y+1+se)).join("");if(l.hint){let ie=l.hint[l.overlap]??Oe;Jr=Gl(ie),Zr=Fs(l.remainder.slice(1)+Be)}return Fs(":")+ra+Jr+Zr},[r,o,l,u,m]);return Ft.createElement(Hr,{flexDirection:"column",justifyContent:"flex-start"},Ft.createElement(Hr,{flexDirection:"column",paddingX:1,borderColor:E.secondary,borderStyle:"round",width:e},Ft.createElement(Hr,null,Ft.createElement(Ls,null,p),i&&Ft.createElement(Ls,{wrap:"truncate",color:a?E.red:E.secondary2},` ${i} `))))};import $s from"chalk";import{Box as Ql,Text as jr}from"ink";import Rn,{useEffect as ec,useState as tc}from"react";var nc=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],_s=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)}},rc=({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)}`},oc=(e,t,n)=>{let r=_s(e),o=_s(t);return rc({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},ic=(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 oc(i,a,o)},sc=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Ws=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=$(),[o,i]=tc(0);ec(()=>{if(n!=="syncing"){i(0);return}let C=setInterval(()=>{i(T=>T+1)},50);return()=>clearInterval(C)},[n]);let a=[],l=0;for(let C of t){let B=(a.length>0?" | ":"").length+C.length;if(l+B>e-4)break;a.push(C),l+=B}let u=n!="synced"?r??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),p=n==="syncing"?ic(nc,(Math.sin(o*.12)+1)/2):E.secondary,y=$s.hex(p??"fff"),N=$s.hex(E.secondary2),S=y(`\u256D${"\u2500".repeat(m)}\u256E`),A=y(`\u2570${"\u2500".repeat(m)}\u256F`),I=`${y("\u2502")}${N(sc(` ${u} `,m))}${y("\u2502")}`;return Rn.createElement(Ql,{flexDirection:"column",width:e},Rn.createElement(jr,null,S),Rn.createElement(jr,null,I),Rn.createElement(jr,null,A))};var Mn=({width:e,mode:t,availableHints:n})=>{let r=$(),o=[],i=0;for(let a of n){let u=(o.length>0?" | ":"").length+a.length;if(i+u>e+2)break;o.push(a),i+=u}return Kr.createElement(ac,null,t===g.COMMAND_LINE&&r.syncStatus.status!=="syncing"?Kr.createElement(Us,{width:e}):Kr.createElement(Ws,{width:e,mode:t,availableHints:n}))};import{Box as mt,Text as Hs}from"ink";import He from"react";var js=({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"]),He.createElement(mt,{flexDirection:"column",marginTop:3,borderColor:E.secondary,borderStyle:"round",width:e,minHeight:19},He.createElement(mt,{flexDirection:"column",width:e},v().mode===g.HELP?t.map(([n,r],o)=>He.createElement(mt,{paddingLeft:1,key:o,flexDirection:"row"},He.createElement(mt,{key:o,flexDirection:"row",paddingBottom:o?0:1},He.createElement(mt,{width:20,justifyContent:"flex-end"},He.createElement(Hs,{color:o?E.accent:E.secondary},n)),He.createElement(mt,{flexGrow:1,width:40,paddingLeft:2},He.createElement(Hs,{color:o?E.primary:E.secondary},r))))):null))};import dc from"chalk";import{Box as Pn,Text as je}from"ink";import pe from"react";var Ks=({width:e,height:t})=>pe.createElement(Pn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},pe.createElement(je,{color:E.accent,bold:!0},"Initialize project"),pe.createElement(je,null,`This folder is not an ${dc.hex(E.accent)("epiq")} project yet.`),pe.createElement(je,{color:E.primary},"To start tracking issues here, we need to initialize a new"," ",pe.createElement(je,{color:E.primary,backgroundColor:E.secondary}," .epiq/project.json ")," ","file in this repository."),pe.createElement(Pn,{marginTop:1,flexDirection:"column"},pe.createElement(Pn,null,pe.createElement(je,{color:E.accent}," "),pe.createElement(je,{color:E.primary},"Type "),pe.createElement(je,{backgroundColor:E.secondary}," :init "))),pe.createElement(Pn,{marginTop:1},pe.createElement(je,{color:E.secondary2},"(This will create the local epiq project files)")));import{Box as Bt,Text as xe}from"ink";import H from"react";var kn=({isDone:e,command:t,value:n})=>H.createElement(Bt,null,H.createElement(xe,{color:E.accent,dimColor:e},e?" \u2714 ":" "),H.createElement(xe,{dimColor:e},"Type "),H.createElement(xe,{backgroundColor:E.secondary,dimColor:e}," "+t+" "),n&&H.createElement(H.Fragment,null,H.createElement(xe,{dimColor:e}," "),H.createElement(xe,{color:E.secondary,dimColor:e},"<"+n+">")));function Vr({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,l=n?r?null:":config:editor":":config:username";return H.createElement(Bt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},H.createElement(xe,{color:E.accent,bold:!0},"Welcome! \u{1F539}"),H.createElement(xe,null,"Lets get you started - its a breeze."),H.createElement(xe,{color:E.secondary2},"And remember, you can always get help with"," ",H.createElement(xe,{color:E.accent},":help"),"."),!a&&H.createElement(xe,{color:E.secondary2},l===":config:username"?"First, choose your username.":"Nice. One more step."),H.createElement(Bt,{flexDirection:"column"},n&&H.createElement(Bt,{marginBottom:1},H.createElement(kn,{isDone:!0,command:":config:username",value:o})),!n&&H.createElement(kn,{isDone:!1,command:":config:username"}),n&&!r&&H.createElement(kn,{isDone:!1,command:":config:editor"}),a&&H.createElement(Bt,null,H.createElement(kn,{isDone:!0,command:":config:editor",value:i}))))}import Ys from"chalk";import{Box as Ln,Text as Ke}from"ink";import Z from"react";import{Box as zr,Text as lc}from"ink";import pt from"react";var cc=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Vs=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=v(),i=F(n.id)[r],a=Ue(i?.id??n.id,"TICKET"),l=Ee(a)?a.value:void 0,u=l?.id?F(l.id):[],m=I=>{let C=u.find(T=>T.title===I);return C?F(C.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},p=m("Tags"),y=m("Assignees"),N=l?.parentNodeId?!Qn(n.id,l?.parentNodeId)&&o==="dense":!1,S=t.map((I,C)=>{let T=C===t.length-1,B=F(I.id),Oe=T?B?.[r]?.title:void 0;return`${C?" / ":""}${I.title??""}${Oe?` \u25B8 ${Oe}`:""}`}).join(""),A=cc(S,e);return pt.createElement(zr,null,pt.createElement(lc,{color:E.secondary2},A),N?p.map(I=>pt.createElement(zr,{key:I,paddingLeft:2},pt.createElement(at,{id:I}))):null,N?y.map(I=>pt.createElement(zr,{key:I,paddingLeft:2},pt.createElement(st,{id:I}))):null)};import{Box as uc,Text as zs}from"ink";import Dn from"react";var mc=({filters:e})=>Dn.createElement(uc,{columnGap:1},Dn.createElement(zs,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Dn.createElement(zs,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),qs=Dn.memo(mc);var Gs="0.4.8";function Fn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=$(),{userName:i,preferredEditor:a}=ge(),l=40,u=process.stdout.columns-l-8,m=r.at(-1)?.id,p=nn(m??""),y=Ee(p)?Mo(p.value):"INVALID DATE";return Z.createElement(Ln,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Z.createElement(Ke,null," "):Z.createElement(Ln,{paddingLeft:1},e.length>0?Z.createElement(qs,{filters:e}):Z.createElement(Vs,{width:u})),n==="live"?Z.createElement(Ln,{columnGap:1,paddingRight:2,"max-width":l,overflow:"hidden",justifyContent:"flex-end"},Z.createElement(Ke,{dimColor:!0,color:E.secondary2},Gs+" "),Z.createElement(Xs,{icon:"@",value:i}),Z.createElement(Xs,{icon:"\u276F",value:a})):"",n==="peek"?Z.createElement(Ln,{paddingLeft:1},Z.createElement(Ke,{backgroundColor:E.yellow}," Readonly "),Z.createElement(Ke,{color:E.yellow}," "+o.length+" edits ago at "),Z.createElement(Ke,{backgroundColor:E.yellow,color:E.accent}," "+y+" "),Z.createElement(Ke,{color:E.yellow},". Resume with "),Z.createElement(Ke,{backgroundColor:E.yellow}," :peek now ")):"")}function Xs({icon:e,value:t}){return Z.createElement(Ke,null,Ys.dim(e)+Ys.hex(E.accent)(` ${t??"-"} `))}import{Box as pc,Text as gc}from"ink";import Ut from"react";import{Box as On,Text as qr}from"ink";import Ve from"react";function Gr(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?R(t?.id):[];return Ve.createElement(On,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:E.secondary,width:i},Ve.createElement(On,{padding:1,paddingTop:0,paddingBottom:0},Ve.createElement(qr,null,"Select a board:")),Ve.createElement(On,{padding:1,flexDirection:"column"},a.map((l,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,y=R(l.id).flatMap(({id:N})=>F(N)).length;return Ve.createElement(On,{key:l.id??u},Ve.createElement(qr,{color:m?E.accent:E.secondary2},Ve.createElement(re,{isSelected:m})),Ve.createElement(qr,{color:m?E.accent:E.secondary2},l.title," (",y," issues)",l.readonly?" \u{1F512}":""))})))}var fc=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:l}=$(),u=n.find(({context:N})=>N==="BOARD"),y=i-1-3;return Ut.createElement(pc,{flexDirection:"row"},e.context==="WORKSPACE"?Ut.createElement(Gr,null):u?Ut.createElement(mn,{height:y,width:a,swimlanes:(l[u.id]??[]).filter(N=>N!==void 0&&Qe(N)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Ut.createElement(gc,null))},Js=Ut.memo(fc);function Yr({width:e,height:t}){let n=$(),r=n.filters;if(n.mode===g.HELP)return G.createElement(Ze,{flexDirection:"column"},G.createElement(js,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:l,preferredEditor:u}=tn(),m=!o,p=o&&!n.hasProject;if(m)return G.createElement(Ze,{flexDirection:"column"},G.createElement(Ze,{flexDirection:"column"},G.createElement(Fn,{hideBreadCrumb:!0,filters:r}),G.createElement(Vr,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:l??"",preferredEditor:u??""})),G.createElement(Mn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(p)return G.createElement(Ze,{flexDirection:"column"},G.createElement(Ze,{flexDirection:"column"},G.createElement(Fn,{hideBreadCrumb:!0,filters:r}),G.createElement(Ks,{height:t,width:e})),G.createElement(Mn,{width:e,mode:n.mode,availableHints:n.availableHints}));let y=Ae(v().breadCrumb??[],"BOARD");if(Ee(y)){let N=y.value.id,S=R(N).length,A=3,I=Math.floor(e/A),C=Math.floor(e/Math.max(S,1));e=Math.min(C,I)*Math.max(S,A)}return G.createElement(Ze,{flexDirection:"column"},G.createElement(Ze,{flexDirection:"column"},G.createElement(Fn,{filters:r}),G.createElement(Js,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),G.createElement(Mn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import vc from"readline";var Bn,Un,ye,xc=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.InitCommandLine,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),Zs=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Go(e,n);if(!o||r&&!xc.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},yc=()=>async function(t,n){n.name!=="escape"&&(ye&&(clearTimeout(ye),ye=void 0),await Zs(n))},hc=()=>async function(t){if(t.length===1&&t[0]===27){ye&&clearTimeout(ye),ye=setTimeout(()=>{Zs({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),ye=void 0},25);return}ye&&(clearTimeout(ye),ye=void 0)};function Qs(){Bn&&process.stdin.removeListener("keypress",Bn),Un&&process.stdin.removeListener("data",Un),Bn=yc(),Un=hc(),vc.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Un),process.stdin.on("keypress",Bn)}Nc(`${Xr.bold("Epiq CLI")}
|
|
64
65
|
|
|
65
|
-
${
|
|
66
|
-
${
|
|
66
|
+
${Xr.dim("Boot in directory:")}
|
|
67
|
+
${Xr.cyan("$ epiq")}
|
|
67
68
|
|
|
68
|
-
`,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var
|
|
69
|
+
`,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var ea=process.stdout.columns||120,ta=process.stdout.rows||20,$n=null,bc=e=>{if(!$n){$n=Ec(e);return}$n.rerender(e)},na=()=>{bc(Cc.createElement(Yr,{width:ea,height:ta}))},Ic=()=>{let e=zt(process.cwd());return d(e)?{hasProject:!1,epiqRootDir:null,events:[]}:{hasProject:!0,epiqRootDir:e.value,events:[]}};async function Sc(){let e=cs();d(e)||et(e.value);let t=Ic();if(t.hasProject){let r=await zi();if(d(r))throw new Error(r.message);let o=yt(t.epiqRootDir);d(o)||(t.events=o.value)}let n=Ds(t.events);if(d(n))throw new Error(`Failed to boot state: ${n.message}`);w({hasProject:t.hasProject}),na(),Qs()}process.stdout.on("resize",()=>{ea=process.stdout.columns||120,ta=process.stdout.rows||20,$n&&na()});(async()=>(console.clear(),await Sc()))();
|