epiq 0.4.10 → 0.5.0
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 +55 -54
- package/dist/mcp.js +49 -48
- package/package.json +1 -1
- package/readme.md +1 -1
package/dist/index.js
CHANGED
|
@@ -1,63 +1,64 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),l("Created project.json",null)}catch(o){return s(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var Qt={autoSync:!1,preferredEditor:null,userName:null,userId:null},ce=()=>Qt,Qe=e=>(Qt={...Qt,...e},Qt);var et=()=>{let e=ce(),t=!!e.userName?.trim(),r=!!e.preferredEditor?.trim();return{isSetup:r&&t,hasPreferredEditor:r,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},go=()=>{let e=ye(process.cwd());if(d(e))return s("Unable to determine if repository is initialized");let t=Be(e.value);return xe(t)};var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};var Re=(e,t)=>{let r=e.find(n=>n.context===t);return r!==void 0?l("Found node",r):s("Unable to find node in breadcrumb")};import{useSyncExternalStore as Vc}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function rn(e){return e.context==="WORKSPACE"}function pe(e){return e.context==="TICKET"}function fo(e){return e.context==="FIELD"}var tt=e=>e.context==="SWIMLANE",vo=e=>e.context==="BOARD";function er(e,t){let r=Math.min(e.length,t.length),n=0;for(;n<r&&e[n]===t[n];)n++;return n}var tr=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",nn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var xo=e=>{let t=new Map;for(let r of e)for(let n=1;n<=r.length;n++){let o=r.slice(0,n),i=t.get(o);i?i.push(r):t.set(o,[r])}return t},ho=(e,t)=>t?e.get(t)??[]:[];var yo=new WeakMap,fa=e=>{let t=yo.get(e);return t||(t=xo(e),yo.set(e,t)),t};var Eo=({wordList:e,inputToMatch:t,overlapThreshold:r=1})=>{let n=t.toLowerCase();return ho(fa(e),n).filter(i=>er(n,i)>=r)};var va={hint:"",hints:[],overlap:0,remainder:""},Co=({inputToMatch:e,lastWord:t,isLastWordCompleted:r},n)=>{if(r||e==="")return va;let o=Eo({wordList:n,inputToMatch:e,overlapThreshold:1});return xa(t,o)},xa=(e,t)=>{let r=t[0]??"",n=er(e.toLowerCase(),r.toLowerCase()),[o,i]=r.split(":"),a=n<(o??"").length,c=!!i,p=(c&&a?o:r)+(c&&a?":":" "),v=p.slice(n);return{hint:p,hints:t,overlap:n,remainder:v}};var No=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Z={workspace:(e,t,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,r,n,o=!1)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:r,readonly:o,log:[]}),swimlane:(e,t,r,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:r,readonly:!1,log:[]}),field:(e,t,r,n,o={},i="horizontal")=>({id:e,title:t,rank:n,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:r,readonly:!1,log:[]}),ticket:(e,t,r,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:r,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:r,rank:n,props:o={},readonly:i=!0})=>({id:e,title:t,rank:n,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:r,readonly:i,log:[]})};import{ulid as Ea}from"ulid";var Ve=24n,ha=Ve*4n,Ct=(1n<<ha)-1n,ya=/^[0-9a-f]+$/;function bo(e){return!e||!ya.test(e)?s(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function we(e,t=Ve){if(e<0n)return s("Negative rank not allowed");let r=e.toString(16);return l("Converted bigint to hex rank",r.padStart(Number(t),"0"))}function z(e,t){if(!e&&!t)return we(Ct/2n,Ve);let r=e?bo(e):l("Resolved lower bound",0n);if(d(r))return r;let n=t?bo(t):l("Resolved upper bound",Ct);if(d(n))return n;let o=r.value,i=n.value;if(i<=o)return we(Ct/2n,Ve);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):we(a,Ve)}function Io(){return we(Ct/2n,Ve)}function So(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),r=[];for(let n=0;n<e;n++){let o=Ct*BigInt(n+1)/(t+1n),i=we(o,Ve);if(d(i))return i;r.push(i.value)}return l("Resolved evenly spaced ranks",r)}var on=(e,t)=>{let r=B(e),n=So(r.length);if(d(n))return n;let o={};for(let i=0;i<r.length;i++){let a=r[i],c=n.value[i];if(!a||!c)return s("Unable to assign rebalance rank");o[a.id]=c}return l("Created rebalance event",{id:Ea(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var Ca=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Ae,rr]=Ca;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Na={"init.workspace":e=>{let{id:t,name:r,rank:n}=e.payload,o=Z.workspace(t,r,n),i=It(o);if(d(i))return k(i.message,e);let a=I.createNode(o);return d(a)?k(a.message??"Failed to initialize workspace",e):rn(a.value)?l("Workspace initialized",{action:e.action,result:a.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:r,rank:n}=e.payload,o=Z.workspace(t,r,n),i=I.createNode(o);return d(i)?k(i.message??"Failed to add workspace",e):rn(i.value)?l("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:r,parent:n,rank:o}=e.payload,i=I.createNode(Z.board(t,r,n,o));return d(i)?k(i.message??"Unable to create board",e):vo(i.value)?l("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:r,parent:n,rank:o}=e.payload,i=I.createNode(Z.swimlane(t,r,n,o));return d(i)?k(i.message??"Unable to create swimlane",e):tt(i.value)?l("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:r,parent:n,rank:o}=e.payload,i=I.createNode(Z.ticket(t,r,n,o));return d(i)?k(i.message??"Unable to create issue",e):pe(i.value)?l("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:r,parent:n,val:o,rank:i}=e.payload,a=I.createNode(Z.field(t,r,n,i,{value:o},r.includes("Description")?"vertical":"horizontal"));return d(a)?k(a.message??`Unable to create field: ${r}`,e):fo(a.value)?l("Added field",{action:e.action,result:a.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:r}=e.payload;if(!I.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,r);return d(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,r=I.tombstoneNode(t);return d(r)?k(r.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:r.value})},"create.tag":e=>{let{id:t,name:r}=e.payload,n=I.createTag({id:t,name:r});return d(n)?k(n.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:n.value})},"create.contributor":e=>{let{id:t,name:r}=e.payload,n=I.createContributor({id:t,name:r});return d(n)?k(n.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:n.value})},"tag.issue":e=>{let{id:t,target:r,tagId:n,rank:o}=e.payload,i=I.tag(r,n,t,o);return d(i)?k(i.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:r}=e.payload,n=I.untag(t,r);return d(n)?k(n.message??"Unable to untag ",e):l("Issue untagged",{action:e.action,result:n.value})},"assign.issue":e=>{let{id:t,contributor:r,target:n,rank:o}=e.payload,i=I.assign(n,r,t,o);return d(i)?k(i.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:r}=e.payload,n=I.unassign(t,r);return d(n)?k(n.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:n.value})},"move.node":e=>{let{id:t,parent:r,rank:n}=e.payload,o=I.moveNodeToRank({id:t,parentId:r,rank:n});return d(o)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:r}=e.payload,n=I.editValue(t,r);return d(n)?k(n.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:n.value})},"close.issue":e=>{let{id:t,parent:r,rank:n}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!pe(o))return k("Can only close issues",e);let i=I.getNode(Ae);if(!i)return k("Unable to locate target swimlane",e);if(r!==i.id)return k("Close target must be closed swimlane",e);let a=I.moveNodeToRank({id:t,parentId:r,rank:n});return d(a)?k(a.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:r,rank:n}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!pe(o))return k("Can only reopen issues",e);let i=I.getNode(Ae);if(!i)return k("Unable to locate closed swimlane",e);if(r===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!I.getNode(r))return k("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:r,rank:n});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,r=I.lockNode(t);return d(r)?k(r.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:r.value})},"rebalance.children":e=>{let{parent:t,ranks:r}=e.payload;for(let[n,o]of Object.entries(r)){let i=I.getNode(n);if(!i)return k(`Unable to locate node ${n}`,e);if(i.parentNodeId!==t)return k(`Node ${n} is not child of ${t}`,e);let a=I.updateNode({...i,rank:o});if(d(a))return k(a.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}},ba=(e,t)=>{let r=I.getNode(e);r&&I.updateNode({...r,log:[...r.log??[],t]})},Ia=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],r=x().nodes[e.payload.id]?.parentNodeId;return r&&t.push(r),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 Nt(e,t=!1){let r=Na[e.action](e);if(d(r))return r;t||([...new Set(Ia(e))].forEach(a=>ba(a,e)),le(a=>({...a,eventLog:[...a.eventLog,e]})));let n=e.userId,o=e.userName;return!n?.length||!o?.length?k("Invalid user ID format",e):(I.createContributor({name:o,id:n}),r)}var bt=e=>e.map(t=>Nt(t));import La from"node:fs";import Fa from"node:path";import{decodeTime as Da,monotonicFactory as Ba}from"ulid";import{z as Rt}from"zod";import nr from"node:fs";import an from"node:path";import{decodeTime as Sa}from"ulid";import{z as sn}from"zod";var Ra=sn.object({userId:sn.string().min(1).default("unknown"),userName:sn.string().min(1).default("unknown")}),wa=e=>{let[t,r]=an.basename(e,".jsonl").split("."),n=Ra.safeParse({userId:t,userName:r});return n.success?l("Parsed event file actor",n.data):s(`Invalid event file name ${an.basename(e)}: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Aa=e=>{let t=Object.keys(e).filter(r=>r!=="id"&&r!=="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"):l("Resolved persisted action",t[0])},Ta=(e,t)=>t in e,Ma=({id:e,action:t,payload:r,userId:n,userName:o})=>({id:e,action:t,payload:r,userId:n,userName:o}),Pa=e=>{let{userId:t,userName:r,...n}=e,o=Aa(n);if(d(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?Ta(n,i)?l("Decoded persisted event",Ma({id:a,action:i,payload:n[i],userId:t,userName:r})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},or=e=>{if(!nr.existsSync(e))return l("Event file missing",[]);let t=wa(e);if(d(t))return s(t.message);let r=nr.readFileSync(e,"utf8"),n=[];for(let o of r.split(`
|
|
4
|
-
`)){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 c=
|
|
5
|
-
`,"utf8"),l("Event persisted",{path:o.value,entry:c.value}))}catch(r){let n=r instanceof Error?r.message:"Unknown persist error";return s(`Failed to persist event: ${n}`)}}function V(e){let t=Nt(e);if(t.status!==be.Success)return t;let r=sr({event:e});return d(r)?r:t}function ar(e){return e.map(t=>V(t))}var ko=e=>cn(B(e),{at:"end"}),cn=(e,t={at:"end"})=>{let r=n=>d(n)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:n.value,needsRebalance:!1});if(e.length===0)return r(z(void 0,void 0));switch(t.at){case"start":{let n=e[0];return n?r(z(void 0,n.rank)):s("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?r(z(n.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let n=Lo(e,t.sibling);if(n<0)return s("Sibling not found");let o=n>0?e[n-1]:void 0,i=e[n];return i?r(z(o?.rank,i.rank)):s("Sibling not found")}case"after":{let n=Lo(e,t.sibling);if(n<0)return s("Sibling not found");let o=e[n],i=n<e.length-1?e[n+1]:void 0;return o?r(z(o.rank,i?.rank)):s("Sibling not found")}}},B=e=>Object.values(x().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,r)=>t.rank.localeCompare(r.rank)),Lo=(e,t)=>e.findIndex(r=>r.id===t),Fo=(e,t,r={at:"end"})=>cn(B(t).filter(n=>n.id!==e),r),nt=(e,t,r,n)=>{let o=Fo(t,e,r);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let i=on(e,n);if(d(i))return i;let a=V(i.value);if(d(a))return a;let c=Fo(t,e,r);return d(c)?c:c.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",c.value.rank)},ot=(e,t)=>{let r=ko(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let n=on(e,t);if(d(n))return n;let o=V(n.value);if(d(o))return o;let i=ko(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var Oe=(e,t)=>{let{nodes:r}=x(),n=r[e];if(!n)return s("Node not found");if(n.context===t)return l("Resolved ancestor node",n);let o=n.parentNodeId?r[n.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?r[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},un=(e,t)=>{let{nodes:r}=x(),n=r[e];for(;n?.parentNodeId;){if(n.parentNodeId===t)return!0;n=r[n.parentNodeId]}return!1},ln=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),I={deleteNode(e){le(t=>{let r={...t.nodes};return delete r[e],{...t,nodes:r}})},editValue(e,t){let{nodes:r}=x(),n=r[e];if(!n)return s("Edit target node not found");let o=ln(n,"edit");if(o)return o;let i={...n,props:{...n.props,value:t}};return this.updateNode(i),l("Issue description updated",{md:t})},renameNode(e,t){let r=this.getNode(e);if(!r)return s("Rename target node not found");let n=ln(r,"rename");if(n)return n;let o={...r,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=x();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=x();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return B(e).find(r=>r.title===t)},moveNodeToRank({id:e,parentId:t,rank:r}){let{rootNodeId:n}=x(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(n===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=ln(o,"move");if(a)return a;if(un(t,e))return s("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:r};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,currentNodeId:r,rootNodeId:n}=x(),o=this.getNode(e);if(!o)return s("Node not found");if(n===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 B(m.id))a(p.id)}};a(e);let c={...structuredClone(t)};for(let u of i){if(!c[u])return s("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return r?(A({nodes:c}),l("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=le(r=>({...r,contributors:{...r.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):l("Created contributor",e)},assign(e,t,r,n){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(B(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=Z.field(r,o.name,a.id,n,{value:t}),m=this.createNode(u);return d(m)?m:l("Assigned contributor",u)},createTag(e){let t=le(r=>({...r,tags:{...r.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):l("Tag created",e)},tag(e,t,r,n){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(B(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=Z.field(r,o.name,a.id,n,{value:t}),m=this.createNode(u);return d(m)?m:l("Tag added",u)},untag(e,t){let r=this.getTag(t),n=this.getNode(e);if(!r)return s("Unable to remove tag, missing tag");if(!n)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(n.id,"Tags");if(!o)return s("Unable to locate tags field");let i=B(o.id).find(c=>c.props?.value===t);if(!i)return l("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Tag removed",a)},unassign(e,t){let r=this.getContributor(t),n=this.getNode(e);if(!r)return s("Unable to unassign, missing contributor");if(!n)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(n.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=B(o.id).find(c=>c.props?.value===t);if(!i)return l("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Assignee removed",a)},createNode(e){let t=le(r=>({...r,nodes:{...r.nodes,[e.id]:e}}));return d(t)?s("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let r={...t,readonly:!0},n=le(o=>({...o,nodes:{...o.nodes,[e]:r}}));return d(n)?s(n.message):l("Locked node",r)},updateNode(e){let t=le(r=>({...r,nodes:{...r.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return x().contributors[e]},getTag(e){return x().tags[e]},getNode(e){return x().nodes[e]},getSiblings(e){return B(e)}};var Q={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"},C={accent:Q.cyan,accent2:Q.magenta,primary:Q.white,secondary:Q.grayDark,secondary2:Q.grayLight,gray:Q.gray,green:Q.green,yellow:Q.yellow,red:Q.red};var E={red:Q.red,yellow:Q.yellow,green:Q.green,blue:Q.blue,magenta:Q.magenta,cyan:Q.cyan},it={urgent:E.red,critical:E.red,important:E.red,blocker:E.red,asap:E.red,immediate:E.red,fail:E.red,failure:E.red,broken:E.red,bug:E.red,error:E.red,incident:E.red,outage:E.red,production:E.red,crash:E.red,security:E.red,warning:E.yellow,warn:E.yellow,risky:E.yellow,risk:E.yellow,attention:E.yellow,pending:E.yellow,review:E.yellow,"needs-review":E.yellow,qa:E.yellow,testing:E.yellow,test:E.yellow,validate:E.yellow,verification:E.yellow,staging:E.yellow,check:E.yellow,"follow-up":E.yellow,followup:E.yellow,waiting:E.yellow,blocked:E.yellow,hold:E.yellow,done:E.green,complete:E.green,completed:E.green,success:E.green,ok:E.green,stable:E.green,resolved:E.green,fixed:E.green,closed:E.green,merged:E.green,released:E.green,deployed:E.green,approved:E.green,verified:E.green,working:E.green,healthy:E.green,pass:E.green,passing:E.green,info:E.blue,information:E.blue,note:E.blue,docs:E.blue,documentation:E.blue,doc:E.blue,guide:E.blue,help:E.blue,explanation:E.blue,detail:E.blue,details:E.blue,context:E.blue,design:E.blue,discussion:E.blue,proposal:E.blue,idea:E.blue,feature:E.magenta,enhancement:E.magenta,improvement:E.magenta,refactor:E.magenta,refactoring:E.magenta,cleanup:E.magenta,optimize:E.magenta,optimization:E.magenta,perf:E.magenta,performance:E.magenta,upgrade:E.magenta,migration:E.magenta,modernize:E.magenta,debt:E.magenta,todo:E.cyan,next:E.cyan,planned:E.cyan,plan:E.cyan,future:E.cyan,backlog:E.cyan,investigate:E.cyan,explore:E.cyan,prototype:E.cyan};var Do=(e,t)=>{let n=T(e.id).find(o=>o.title===t);return n?T(n.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},mn=e=>Do(e,"Tags").map(t=>I.getTag(t)).filter(t=>!!t),dr=()=>{let{breadCrumb:e,selectedNode:t}=x(),r=[...e,t].find(n=>n?.context==="TICKET");return!r||!pe(r)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",mn(r)??[])},cr=()=>{let{breadCrumb:e,selectedNode:t}=x(),r=[...e,t].find(n=>n?.context==="TICKET");return!r||!pe(r)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",pn(r)??[])},pn=e=>Do(e,"Assignees").map(t=>I.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 Wa=/^(\d+)(h|d|w|mo|y)$/,_a=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ha=({year:e,month:t,day:r,hour:n=0,minute:o=0})=>{let i=new Date(e,t-1,r,n,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===r&&i.getHours()===n&&i.getMinutes()===o},Ka=(e,t=new Date)=>{let r=e.match(Wa);if(!r)return null;let[,n,o]=r,i=Number(n);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}},Va=e=>{let t=e.match(_a);if(!t)return null;let[,r,n,o,i,a]=t,c=Number(r),u=Number(n),m=Number(o),p=i?Number(i):0,v=a?Number(a):0;return Ha({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},lr=e=>{let t=e.trim().toLowerCase();return Ka(t)??Va(t)},Bo=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,qa=[{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}],Oo=(e=qa)=>{let t=[];for(let{unit:r,from:n,to:o}of e)for(let i=n;i<=o;i++)t.push(`${i}${r}`);return t};var za=["BOARD","TICKET","SWIMLANE"],qe=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],ur=[f.NEW,f.RENAME,f.DELETE,f.MOVE],gn=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],Uo=[f.FILTER,f.PEEK],Ga={WORKSPACE:[...qe,...ur],BOARD:[...Uo,...qe,...ur],SWIMLANE:[...Uo,...qe,...ur],TICKET:[...qe,...ur,...gn],FIELD:[...qe,...gn],FIELD_LIST:[...qe,...gn],TEXT:[...qe]},Ya=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Xa=()=>{let{currentNode:e,selectedNode:t,readOnly:r}=x();if(!et().isSetup)return[f.HELP,f.SET_EDITOR,f.SET_USERNAME];if(!go())return[f.HELP,f.INIT];if(r)return[f.HELP,f.PEEK,f.EXPORT,f.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,a=i&&za.includes(i);return Ga[o].filter(c=>c===f.RENAME||c===f.DELETE||c===f.MOVE?a:!0)},G=e=>{let{currentNode:t}=x(),r=t.context??"WORKSPACE";return{[f.NONE]:Xa(),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...Oo(),"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(it),...I.getExistingTags()])],[f.UNTAG]:[...dr()?.value?.map(({name:o})=>o)??[]],[f.UNASSIGN]:[...cr()?.value?.map(({name:o})=>o)??[]],[f.ASSIGN]:I.getExistingAssignees(),[f.RENAME]:[],[f.NEW]:Ya(r)}[e]??[]};import at from"chalk";import{decodeTime as $o}from"ulid";var jo=e=>{let t=Date.now()-e,r=[{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:n,ms:o}of r){let i=Math.floor(t/o);if(i>=1)return`${i}${n} ago`}return"just now"},Wo=e=>{let t=r=>String(r).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},mr=e=>{try{return l("Decoded date",new Date($o(e)))}catch(t){return s("Decoding failed + "+t.message)}},fn=e=>{if(!e?.id)return null;try{return $o(e.id)}catch{return null}};import st from"chalk";var xn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ja=(e,t,r)=>Math.max(t,Math.min(r,e)),vn=(e,t,r)=>e+(t-e)*r,_o=e=>{let t=0;for(let r=0;r<e.length;r++)t=t*31+e.charCodeAt(r)>>>0;return t},Za=(e,t,r)=>{let n=t/100,o=r/100,i=(1-Math.abs(2*o-1))*n,a=e/60,c=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=c):a>=1&&a<2?(u=c,m=i):a>=2&&a<3?(m=i,p=c):a>=3&&a<4?(m=c,p=i):a>=4&&a<5?(u=c,p=i):(u=i,p=c);let v=o-i/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},Qa=([e,t,r])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`,ed=(e,t,r)=>[Math.round(vn(e[0],t[0],r)),Math.round(vn(e[1],t[1],r)),Math.round(vn(e[2],t[2],r))],wt=e=>{let r=_o(e)%360,n=Za(r,xn.stringColor.saturation,xn.stringColor.lightness);return Qa(n)},td=e=>{let t=xn.gradient.stops,r=Ja(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let n=t.length-1,o=r*n,i=Math.min(Math.floor(o),n-1),a=o-i;return ed(t[i],t[i+1],a)},pr=e=>_o(e.toLowerCase().trim())/4294967295,Ho=e=>{let t=pr(e);return td(t)},rd=e=>{let[t,r,n]=Ho(e);return{normal:o=>st.bgRgb(t,r,n).black(o),cursor:o=>st.bgRgb(t,r,n).white.bold(o)}},hn=e=>{let[t,r,n]=Ho(e);return{fg:o=>st.rgb(t,r,n)(o),fgCursor:o=>st.rgb(t,r,n).inverse(o),bg:o=>st.bgRgb(t,r,n).black(o),bgCursor:o=>st.bgRgb(t,r,n).white.bold(o)}},yn=e=>rd(e).normal(` ${e} `),ee=(e,t=it)=>{let n=(o=>o.toLowerCase().trim())(e);return n&&t[n]?t[n]:wt(n)};var Te={None:"none",Invalid:"invalid",Valid:"valid"};var nd=["BOARD","TICKET","SWIMLANE"],En=()=>{let e=x().selectedNode;return e?.context?nd.includes(e?.context)?j():O({message:"Command not available in this context"}):O({message:"Missing target context"})},oe="<ENTER> to confirm",j=(e="",t=[])=>({message:e,validity:Te.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:Te.Invalid,message:e,completionWordList:t}),Tt=e=>e.length===0,Ue=({prefix:e="",wordList:t,postfix:r="",noOfHints:n=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,v)=>pr(p)-pr(v)).slice(0,n).map(yn),m=u.length>i?u.join(" "):"";return m?`${e}${m}${r}`:""},Cn=({modifier:e})=>{let t="confirm";return e===t?j(oe):O({message:Tt(e)?`if you are certain, enter ${yn(t)}`:"",completionWordList:[t]})},od=({list:e,hint:t})=>({modifier:r})=>e.includes(r)?j(oe):O({message:Tt(r)?t:""}),id=({list:e,hint:t,onValue:r})=>({modifier:n,inputString:o})=>e.includes(n)?o.trim().length<1?O({message:r}):j():O({message:Tt(n)?t:""}),At=({hint:e})=>({modifier:t,inputString:r})=>Tt(t)&&Tt(r)?O({message:e,completionWordList:[]}):j(oe),sd={[f.EXPORT]:()=>j(oe+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return j(oe);let r={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return j(oe);let n=lr(t);if(!t||!n)return O(r);let o=Re(x().breadCrumb,"BOARD");if(d(o))return O({message:"Command is not applicable in this context"});let i=mr(o.value.id);return d(i)?O({message:"Unable to peek: board id is not a valid ULID"}):Bo({date:n,horizonDate:i.value})?j(oe):O({message:at.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>j(oe+" and exit the application"),[f.INIT]:()=>j(oe),[f.FILTER]:e=>{if(e.modifier==="clear")return j();let t=a=>G(f.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return O({message:Ue({wordList:G(f.FILTER),inputString:e.inputString}),completionWordList:G(f.FILTER)});let n=Object.values(x().tags).map(a=>a.name),o=Object.values(x().contributors).map(a=>a.name),i=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?O({message:Ue({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):j():O({message:Ue({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[f.NONE]:e=>{let t=G(f.NONE),r=/^[A-Za-z_]+:/g,n=e.inputString.match(r);return n&&n.length?t=[...t.filter(o=>o.trim().match(r))]:t=[...new Set(t.flatMap(o=>o.match(r)?.join("").replace(":","")??o))],e.command?j():O({message:Ue({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[f.NEW]:e=>id({list:G(f.NEW),hint:Ue({wordList:G(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>j(oe),[f.HELP]:()=>j(oe),[f.RENAME]:()=>{let e=En();return e.validity==="invalid"?e:j(oe)},[f.DELETE]:e=>{let t=En();return t.validity==="invalid"?t:Cn(e)},[f.CLOSE_ISSUE]:e=>Cn(e),[f.RE_OPEN_ISSUE]:e=>Cn(e),[f.MOVE]:e=>{let t=En();return t.validity==="invalid"?t:At({hint:Ue({prefix:"hey hacker! These commands are blocked for you... ",wordList:G(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let t=I.getExistingTags().map(r=>` ${at.bgHex(ee(r))(" "+r+" ")} `).slice(0,10);return At({hint:"tag name like... "+t.join("")})(e)},[f.UNTAG]:e=>{let t=dr();if(d(t))return O({message:"Invalid untag target",completionWordList:[]});let r=t.value.map(({name:n})=>n).map(n=>` ${at.bgHex(ee(n))(" "+n+" ")} `).slice(0,10);return r.length?At({hint:" ... "+r.join("")})(e):O({message:"Issue has not tags",completionWordList:[]})},[f.ASSIGN]:e=>{let t=I.getExistingAssignees().map(r=>` ${at.bgHex(ee(r))(" "+r+" ")} `).slice(0,10);return At({hint:"assign to... "+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=cr();if(d(t))return O({message:"Invalid unassign target",completionWordList:[]});let r=t.value.map(({name:n})=>n).map(n=>` ${at.bgHex(ee(n))(" "+n+" ")} `).slice(0,10);return r.length?At({hint:"remove assignee... "+r.join("")})(e):O({message:"Issue has no assignees",completionWordList:[]})},[f.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=G(f.SET_EDITOR);return e.modifier?j(oe):O({message:Ue({wordList:t,inputString:e.inputString})})},[f.SET_USERNAME]:e=>e.inputString?j():O({message:`Enter a username. Saved in ${at.bgBlack("~/.epiq-global/")}`}),[f.SET_VIEW]:e=>od({list:G(f.SET_VIEW),hint:Ue({wordList:G(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>j(oe)},Ko=Object.fromEntries(Object.entries(sd).map(([e,t])=>[e,{validate:(r,n,o)=>t({modifier:n,command:r,inputString:o})}]));var Vo=["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 qo=e=>Object.values(f).includes(e),zo=(e,t)=>{let r=e.command??"",{modifier:n,target:o,inputString:i}=e,{message:a,validity:c,completionWordList:u}=Ko[r].validate(r,n,i),m=o==="command"?Object.values(f):r&&e.target==="modifier"?G(r):Vo;return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Co(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Go=e=>{let t=e.trimStart(),r=dd(t),n=r[0]??"",o=r[1]??"",i=/\s$/.test(e),a=cd(e),c=qo(n)?n:null,u=c!==null,m=n!=="",p=c?G(c)??[]:[],v=c&&p.includes(o)?o:"",y="word";r.length===0||r.length===1&&!i?y="command":(r.length===1&&i||r.length===2&&!i)&&(y="modifier");let b=i?"":a,R=ad(t,c,v);return{raw:e,trimmedStart:t,words:r,firstWord:n,lastWord:a,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:v,target:y,inputToMatch:b,inputString:R}},ad=(e,t,r)=>{let n=e;return t&&n.startsWith(t)&&(n=n.slice(t.length)),n=n.replace(/^\s+/,""),r&&n.startsWith(r)&&(n=n.slice(r.length),n=n.replace(/^\s+/,"")),n},dd=e=>e.trim()?e.trim().split(/\s+/):[],cd=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Yo=" ",te={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Te.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Nn=new Set,Xo=()=>{for(let e of Nn)e()},Jo=e=>(Nn.add(e),()=>Nn.delete(e)),Me=e=>{let r=e(te),n=Go(r.value),o=r.cursorPosition===r.value.length;te={...r,commandMeta:zo(n,o)},Xo()},Mt=({message:e,status:t})=>{let r=structuredClone(te);return r.commandMeta={...r.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},r.commandIsPending=!0,te=r,Xo(),l(e,null)},bn=e=>{Me(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},In=e=>{Me(t=>{let{value:r,cursorPosition:n}=t,o=n;if(e==="left"){for(;o>0&&r[o-1]===" ";)o--;for(;o>0&&r[o-1]!==" ";)o--}else{for(;o<r.length&&r[o]!==" ";)o++;for(;o<r.length&&r[o]===" ";)o++}return{...t,cursorPosition:o}})},Zo=()=>{Me(e=>{let t=e.value.slice(e.cursorPosition),r=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,r)+t,cursorPosition:r,commandIsPending:!1}})},Qo=()=>{Me(e=>{let{value:t,cursorPosition:r}=e,n=r;for(;n>0&&t[n-1]===" ";)n--;for(;n>0&&t[n-1]!==" ";)n--;let o=t.slice(r);return{...e,value:t.slice(0,n)+o,cursorPosition:n,commandIsPending:!1}})},H=e=>{Me(t=>{let r=Math.max(0,Math.min(t.cursorPosition,t.value.length)),n=t.value.slice(0,r),o=t.value.slice(r),i=e(n,t.commandMeta.autoCompletion),a=i+o,c=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:c,commandIsPending:!1}})},ei=()=>{Me(e=>({...e,commandIsPending:!0}))},ti=({addToHistory:e=!0})=>{Me(r=>({...r,commandHistory:e?[r.value,...r.commandHistory].slice(0,40):r.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ld()},ri=()=>{Me(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),r=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:r,cursorPosition:r.length}})},ni=()=>{Me(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),r=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:r,cursorPosition:r.length}})},ld=()=>H(()=>""),se=()=>te,gr=()=>{let[e,...t]=te.value.split(Yo);return t.join(Yo).trim()};var ud=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",md=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",pd=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",oi=(e,t)=>{if(md(e,e.sequence))return h.MoveCursorLeftOfWord;if(pd(e,e.sequence))return h.MoveCursorRightOfWord;if(ud(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};var h={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function gd(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 fd(e,t,r){let n=x().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?r.prevItem:n?r.prevContainer:null;case"down":return e==="vertical"?r.nextItem:n?r.nextContainer:null;case"left":return e==="horizontal"?r.prevItem:n?r.prevContainer:null;case"right":return e==="horizontal"?r.nextItem:n?r.nextContainer:null}}function ii(e,t){let r=se();if(e.sequence===":"&&r.value==="")return h.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===g.COMMAND_LINE)return oi(e,r.value);let n=gd(e);if(n){let o=t===g.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return fd(x().currentNode.childRenderAxis,n,o)}if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"e":return h.Edit;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return x().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;case"s":return h.Sync;default:return null}}var si=e=>{let{context:t}=x()?.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 Ni from"node:fs";import Hd from"node:path";import Kd from"react";import{Box as Wd}from"ink";import Er from"react";import{Box as wn,Text as wd}from"ink";import Ee from"react";import{Text as ai}from"ink";import di,{useEffect as ci,useState as vd}from"react";var li={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},ae=({isSelected:e,placeholder:t=" "})=>{let{mode:r}=U(),n=li[r]??li.default,[o,i]=vd(0);if(ci(()=>{i(0)},[n]),ci(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%n.length)},500);return()=>clearInterval(c)},[e,n]),!e)return di.createElement(ai,null,t);let a=n[o]??n[0]??t;return di.createElement(ai,{color:C.accent,dimColor:o===1},a)};import{Box as Sn,Text as xd}from"ink";import fr from"react";var vr=({children:e=[],height:t,selectedIndex:r,itemHeight:n=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(n)),c=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(r,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,y=e.slice(p,v),b=e.length>c,R=i,S=b?Math.max(1,Math.floor(c/e.length*R)):R,N=Math.max(0,R-S),w=Math.max(1,e.length-c),D=b?Math.floor(p/w*N):0;return fr.createElement(Sn,{flexDirection:"row",height:i,width:"100%"},fr.createElement(Sn,{flexDirection:"column",flexGrow:1,height:i},y),fr.createElement(Sn,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((ie,X)=>fr.createElement(xd,{key:X,color:b&&X>=D&&X<D+S?C.accent:C.secondary},b?"\u2502":" "))))};import{Box as xr,Text as Id}from"ink";import ze from"react";import{Text as hd}from"ink";import yd from"react";var Ed=e=>e.toLowerCase().trim(),Cd=(e,t=it)=>{let r=Ed(e);return t[r]?t[r]:wt(r)},dt=({id:e,isSelected:t})=>{let r=I.getContributor(e);if(r)return yd.createElement(hd,{underline:t,color:Cd(r.name)},"@"+r.name)};import{Text as Nd}from"ink";import bd from"react";var ct=({id:e,isSelected:t})=>{let r=I.getTag(e);if(r)return bd.createElement(Nd,{underline:t,backgroundColor:ee(r.name),color:C.primary}," "+r.name+" ")};var ui=({width:e,ticket:t,isSelected:r})=>{let n=e-14,o=tr(nn(t.title),n),i=mn(t),a=pn(t);return ze.createElement(xr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?C.accent:C.secondary,justifyContent:"space-between"},ze.createElement(xr,{borderBottom:!0},ze.createElement(xr,{paddingLeft:1,flexDirection:"column"},ze.createElement(Id,{color:C.primary},o))),ze.createElement(xr,{flexDirection:"row",paddingLeft:1},i.map(c=>ze.createElement(ct,{key:c.id,id:c.id})),a.map(c=>ze.createElement(dt,{key:c.id,id:c.id}))))};import Sd from"chalk";import{Box as Pt,Text as Rn}from"ink";import Pe from"react";var Rd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,mi=({width:e,ticket:t,isSelected:r,index:n,mode:o})=>{let i=T(t.id),a=S=>{let N=i.find(w=>w.title===S);return N?T(N.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},c=a("Tags").map(S=>I.getTag(S)).filter(S=>!!S),u=a("Assignees").map(S=>I.getContributor(S)).filter(S=>!!S),m=1,p=c.length*(1+m),v=u.length*(2+m),y=c.map(S=>Pe.createElement(Pt,{key:S.id,paddingRight:m},Pe.createElement(Rn,{color:ee(S.name)},"\u25A0"))),b=u.map(S=>Pe.createElement(Pt,{key:S.id,paddingRight:m},Pe.createElement(Rn,{color:wt(S.name)},"@"+S.name.at(0)))),R=r?C.accent:o===g.MOVE?C.secondary:C.primary;return Pe.createElement(Pt,{borderBottom:!0,justifyContent:"space-between"},Pe.createElement(Pt,null,Pe.createElement(ae,{isSelected:r,placeholder:Sd.dim.gray(n+1+" ")}),Pe.createElement(Rn,{wrap:"truncate",color:R},Rd(t.title,e-p-v-14))),Pe.createElement(Pt,null,y,b))};var Ad=({swimlane:e,isSelected:t,width:r,height:n,isDense:o,isFocused:i,listSelectedIndex:a,mode:c})=>{let{renderedChildrenIndex:u}=U(),m=u[e.id]??[],p=`${e.title} (${m.length})`,v=3,y=o?1:4,b=n-v-(o?2:1),R=Ee.createElement(wn,{borderStyle:"round",borderColor:C.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Ee.createElement(ae,{isSelected:t}),Ee.createElement(wd,{bold:!0,color:t?C.accent:C.primary},p," ",e.readonly?"\u{1F512}":"")),S=(N,w)=>{let D=i&&a===w;return o?Ee.createElement(mi,{key:N.id,index:w,width:r,ticket:N,isSelected:D,mode:c}):Ee.createElement(ui,{key:N.id,width:r,ticket:N,isSelected:D})};return Ee.createElement(wn,{flexDirection:"column",width:r,borderStyle:"round",borderColor:t?C.accent:C.secondary,paddingRight:1,paddingLeft:1,height:n},R,Ee.createElement(wn,{padding:o?1:0},m.length>0&&Ee.createElement(vr,{selectedIndex:a,height:b,itemHeight:y},m.map(S)),Ee.createElement(ae,{isSelected:i&&a===-1})))},pi=Ee.memo(Ad);import{Box as Mn,Text as $d}from"ink";import $e,{useEffect as Pn,useMemo as yi}from"react";import Ge from"chalk";import gi from"string-width";import{decodeTime as Td}from"ulid";var Md=(e,t)=>e+" ".repeat(Math.max(0,t-gi(e))),Pd=(e,t)=>" ".repeat(Math.max(0,t-gi(e)))+e,kd=e=>(()=>{let r={"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=>r[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),Ld=e=>{switch(e.action){case"move.node":{let t=I.getNode(e.payload.parent);return`to ${t?Ge.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=x().tags[e.payload.tagId];return t?Ge.bgHex(ee(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=x().tags[e.payload.tagId];return t?Ge.bgHex(ee(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=x().contributors[e.payload.contributor];return t?Ge.hex(ee(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=x().contributors[e.payload.contributor];return t?Ge.hex(ee(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""}},Fd=e=>{let t=jo(Td(e));return Ge.gray(Pd(t,8))},Dd=12,Bd=e=>Md(`${e}`,Dd),fi=e=>{let t=Fd(e.id),r=Bd(e.userName),n=kd(e.action),o=Ld(e),i=Ge.dim("\u203A"),a=[n,o].filter(Boolean).join(" ");return`${r} ${t} ${i} ${a}`};var L={exit(){process.exit(0)},enterChildNode(){let e=x(),t=e.currentNode,r=Math.max(0,e.selectedIndex),n=T(t.id)[r];!n||t.context==="FIELD"||L.navigate({currentNode:n,selectedIndex:T(n.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=x();if(!e.parentNodeId){logger.info("Missing parent node id");return}let r=t[e.parentNodeId];if(!r){logger.error("Parent not found");return}let n=T(r.id),o=n.findIndex(({id:a})=>a===e.id),i=n.length===0?-1:o>=0?o:0;L.navigate({currentNode:r,selectedIndex:i})},navigateToNextItem:()=>vi(1),navigateToPreviousItem:()=>vi(-1),navigateToNextContainer:()=>xi(1),navigateToPreviousContainer:()=>xi(-1),navigate:({currentNode:e=x().currentNode,selectedIndex:t})=>{A({currentNodeId:e.id,selectedIndex:t})}},vi=e=>{let t=x(),r=T(t.currentNode.id).length;if(r===0)return;let o=(Math.max(0,t.selectedIndex)+e+r)%r;L.navigate({selectedIndex:o})},xi=e=>{let{currentNode:t,nodes:r,selectedIndex:n}=x();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=r[t.parentNodeId];if(!t||!o)return;let i=T(o.id),a=i.findIndex(y=>y.id===t.id);if(a<0)return;let c=i.at(a+e)??i.at(0);if(!c)return;let u=T(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,n),m),v=u.length?p:-1;L.navigate({currentNode:c,selectedIndex:v})};import{Box as hr,Text as Od}from"ink";import ke from"react";var hi=({selectedIndex:e,parent:t,selected:r})=>{let{currentNode:n}=U(),{title:o}=t,i=T(t.id).map(a=>{let c=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return I.getContributor(c)?.id;if(o==="Tags")return I.getTag(c)?.id}).filter(a=>!!a);return ke.createElement(hr,{alignItems:"center",paddingTop:1},ke.createElement(hr,{minWidth:12},ke.createElement(ae,{isSelected:r}),ke.createElement(Od,{color:r?C.accent:C.secondary2},o,":")),ke.createElement(hr,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,c)=>{let u=n.id===t.id&&c===e;return ke.createElement(hr,{key:`${o}-${a}`,paddingRight:2,minHeight:1},ke.createElement(ae,{isSelected:u}),o==="Assignees"?ke.createElement(dt,{isSelected:u,id:a}):o==="Tags"?ke.createElement(ct,{isSelected:u,id:a}):null)})))};import{Box as yr,Text as An}from"ink";import Le,{useEffect as Ud}from"react";var Tn=({id:e,label:t,text:r,height:n,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:c}=U(),u=y=>String(y).replace(/\r?\n/g,""),m=typeof r=="string"?r.split(/\r?\n|\u2028|\u2029/):[];Ud(()=>{let y=[];return m.forEach((b,R)=>{let S=we(BigInt(R+1));if(!xe(S))return;let N=Z.text({id:`${e}-${R}`,name:`Line ${R+1}`,parentNodeId:e,rank:S.value,props:{value:b},readonly:!0}),w=I.createNode(N);xe(w)&&y.push(w.value.id)}),()=>y.forEach(I.deleteNode)},[e,r]);let p="\u2029",v=m.map((y,b)=>{let R=c.id===e&&a===b;return Le.createElement(yr,{key:`${e}-${b}`},Le.createElement(An,{color:R?C.primary:C.secondary2,dimColor:!R},`${b+1} `.padStart(5,"\xA0")),Le.createElement(An,{backgroundColor:R?"gray":""},u(y.length?tr(y,i-10):p)))});return Le.createElement(yr,{flexDirection:"column",paddingTop:1},Le.createElement(yr,null,Le.createElement(ae,{isSelected:o}),Le.createElement(An,{color:o?C.accent:C.secondary2},t)),Le.createElement(yr,{flexDirection:"row",borderStyle:"round",borderColor:C.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Le.createElement(vr,{scrollByOne:!0,children:v,height:n-2,selectedIndex:a,itemHeight:1})))};var jd=e=>`${e}::log`,Ei=e=>e==="Assignees"||e==="Tags",Ci=({ticket:e,height:t})=>{let{selectedIndex:r,currentNode:n}=U(),o=process.stdout.columns||120,i=yi(()=>jd(e.id),[e.id]),a=yi(()=>[...e.log].reverse().map(fi).join(`
|
|
6
|
-
`)
|
|
7
|
-
|
|
2
|
+
import ho from"chalk";import{render as cu}from"ink";import lu from"meow";import uu from"react";import{Box as dt}from"ink";import te from"react";import Tt from"node:fs";import{ulid as Ba}from"ulid";import{z as on}from"zod";var Ue={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Ue.Fail,message:e,value:null}),l=(e,t)=>({status:Ue.Success,message:e,value:t}),d=e=>e.status==="fail",Ee=e=>e.status==="success";import At from"node:fs";import Te from"node:path";var ar=process.env.IS_LOCAL==="true",Me=".epiq",ve=".epiq-global",tn="events",La="project.json",Eo=e=>Te.join(e,Me),nn=e=>Te.join(e,Me),rn=e=>Te.join(nn(e),La),wt=e=>Te.join(nn(e),tn),Oa=e=>{let t=Te.join(e,Me);return At.existsSync(t)&&At.statSync(t).isDirectory()},dr=e=>{let t=rn(e);return At.existsSync(t)&&At.statSync(t).isFile()},$e=e=>{let t=Te.resolve(e);for(;;){if(Oa(t))return l("Resolved closest .epiq root",t);let n=Te.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},be=e=>{let t=Te.resolve(e);for(;;){if(dr(t))return l("Resolved closest epiq project root",t);let n=Te.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},Io=e=>{let t=wt(e);try{return At.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return s(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}};var Ua="epiq/eventlog",$a=on.object({projectId:on.string().min(1),stateBranch:on.string().min(1),createdAt:on.iso.datetime()}),bo=()=>({projectId:Ba(),stateBranch:Ua,createdAt:new Date().toISOString()}),We=e=>{let t=rn(e);if(!Tt.existsSync(t))return s("Missing .epiq/project.json");try{let n=Tt.readFileSync(t,"utf8"),r=JSON.parse(n),o=$a.safeParse(r);return o.success?l("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")}},So=e=>{let t=We(e);return d(t)?s(t.message):l("Read projectId",t.value.projectId)},Ro=({repoRoot:e,fileContents:t})=>{let n=nn(e),r=rn(e);try{if(Tt.mkdirSync(n,{recursive:!0}),Tt.existsSync(r)){let o=We(e);return d(o)?s(o.message):l("Project already initialized",null)}return Tt.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),l("Created project.json",null)}catch(o){return s(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var sn={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},L=()=>sn,pe=e=>(sn={...sn,...e},sn);var _e=()=>{let e=L(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Ao=()=>{let e=be(process.cwd());if(d(e))return s("Unable to determine if repository is initialized");let t=We(e.value);return Ee(t)},wo=e=>e===!0?"yes":e===!1?"no":null,To=e=>e==="yes"?!0:e==="no"?!1:null;var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};var Se=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):s("Unable to find node in breadcrumb")};import{useSyncExternalStore as Sl}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function cr(e){return e.context==="WORKSPACE"}function ye(e){return e.context==="TICKET"}function Mo(e){return e.context==="FIELD"}var lt=e=>e.context==="SWIMLANE",Po=e=>e.context==="BOARD";function an(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var dn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",lr=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var ko=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},Do=(e,t)=>t?e.get(t)??[]:[];var Fo=new WeakMap,Wa=e=>{let t=Fo.get(e);return t||(t=ko(e),Fo.set(e,t)),t};var Lo=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Do(Wa(e),r).filter(i=>an(r,i)>=n)};var _a={hint:"",hints:[],overlap:0,remainder:""},Oo=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return _a;let o=Lo({wordList:r,inputToMatch:e,overlapThreshold:1});return ja(t,o)},ja=(e,t)=>{let n=t[0]??"",r=an(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,c=!!i,p=(c&&a?o:n)+(c&&a?":":" "),g=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:g}};import Ja from"node:fs";import Qa from"node:path";import{decodeTime as Za,monotonicFactory as ed}from"ulid";import{z as Pt}from"zod";import cn from"node:fs";import mr from"node:path";import{decodeTime as Ha}from"ulid";import{z as ur}from"zod";var Ka=ur.object({userId:ur.string().min(1).default("unknown"),userName:ur.string().min(1).default("unknown")}),Va=e=>{let[t,n]=mr.basename(e,".jsonl").split("."),r=Ka.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):s(`Invalid event file name ${mr.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ga=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"):l("Resolved persisted action",t[0])},qa=(e,t)=>t in e,za=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ya=e=>{let{userId:t,userName:n,...r}=e,o=Ga(r);if(d(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?qa(r,i)?l("Decoded persisted event",za({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")},ln=e=>{if(!cn.existsSync(e))return l("Event file missing",[]);let t=Va(e);if(d(t))return s(t.message);let n=cn.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
4
|
+
`)){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 c=pr(a);if(d(c))return s(`${c.message} in ${e}: ${i}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function Bo(e){let t=wt(e);if(!cn.existsSync(t))return l("No events found",[]);let n=cn.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>mr.join(t,o)),r=[];for(let o of n){let i=ln(o);if(d(i))return s(i.message);r.push(...i.value)}return l("All events loaded",Xa(r))}function Mt(e){let t=Bo(e);if(d(t))return s(t.message);let n=[];for(let r of t.value){let o=Ya(r);if(d(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return l("Loaded merged events",n)}function Uo(e=process.cwd()){let t=Bo(e);return d(t)?s(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Xa=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],g=m.id[1]??null;t.set(p,m);let x=n.get(g)??[];x.push(m),n.set(g,x)}for(let m of n.values())m.sort((p,g)=>p.id[0].localeCompare(g.id[0]));let r=[],o=new Set,i=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let g=n.get(p)??[];for(let x of g)i(x)},a=n.get(null)??[];for(let m of a)i(m);let c=e.filter(m=>{let p=m.id[0],g=m.id[1]??null;return!o.has(p)&&g!==null&&!t.has(g)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)i(m);return r},$o=(e,t)=>{let n=e.findIndex(r=>{try{return Ha(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var Wo=e=>({action:e.action,payload:e.payload});var jo=1,_o=ed(),td=Pt.tuple([Pt.string().min(1),Pt.string().min(1).nullable()]),nd=Pt.looseObject({v:Pt.literal(jo),id:td}),pr=e=>{let t=nd.safeParse(e);return t.success?l("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},un=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",K=()=>{let{userName:e,userId:t}=L();return e?t?e.trim()?l("Successfully resolved actor ID",{userId:un(t),userName:un(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Xe=({userId:e,userName:t})=>`${un(e)}.${un(t)}.jsonl`,rd=(e,{userId:t,userName:n})=>{let r=Xe({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Qa.join(wt(e),r);return l("Successfully resolved event log path",i)},od=(e,t)=>{let n={[e.action]:e.payload,v:jo,id:t};return pr(n)};function mn({event:e,rootDir:t=process.cwd()}){try{let n=$e(t);if(d(n))return n;let r=Io(n.value);if(d(r))return r;let o=rd(n.value,{userId:e.userId,userName:e.userName});if(d(o))return o;let i=Uo(n.value);if(d(i))return s(i.message);let a=i.value?_o(Math.max(Date.now(),Za(i.value)+1)):_o(),c=od(Wo(e),[a,i.value]);return d(c)?s(c.message):(Ja.appendFileSync(o.value,`${JSON.stringify(c.value)}
|
|
5
|
+
`,"utf8"),l("Event persisted",{path:o.value,entry:c.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}import Ed from"node:fs";var fr=(e="Syncing...")=>{S({syncStatus:{status:"syncing",msg:e}})},gr=(e="Synced")=>{S({syncStatus:{status:"synced",msg:e}})},id=e=>{S({syncStatus:{status:"outOfSync",msg:e}})},oe=e=>(id(e),s(e));var Je=e=>{let t=be(e);if(d(t))return s("Unable to resolve epiq project root");let n=We(t.value);return d(n)?s("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},xe="origin";import Ft from"node:fs";import ld from"node:os";import Ie from"node:path";var vr=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=r(...i);if(!n.has(a)){let c=e(...i).then(u=>(d(u)&&n.delete(a),u));n.set(a,c)}return n.get(a)});return o.clear=()=>n.clear(),o};import kt from"fs";import Ko from"path";import sd from"util";var Ho=1e3,Vo=()=>{let e=process.cwd(),t=$e(e);if(!d(t))return Ko.join(t.value,Me,"log","epiq.log")};function ad(){if(!ar)return;let e=Vo();if(e===void 0||!kt.existsSync(e))return;let n=kt.readFileSync(e,"utf8").split(`
|
|
6
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=Ho)return;let r=n.slice(-Ho).join(`
|
|
7
|
+
`)+`
|
|
8
|
+
`;kt.writeFileSync(e,r,"utf8")}function yr(e,t,n=!1){if(!ar)return;let r=Vo();if(!r)return;let o=sd.format(...t),i=new Date,c=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
|
|
9
|
+
`;kt.mkdirSync(Ko.dirname(r),{recursive:!0}),kt.appendFileSync(r,c,"utf8"),ad()}var ue={info(...e){yr("[Info]",e,!1)},debug(...e){yr("->",e,!0)},error(...e){yr("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=ue;import{spawn as dd}from"node:child_process";import xr from"node:fs";import zo from"node:path";var H={stage:({cwd:e,pathspec:t})=>F({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>F({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>F({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>F({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>F({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 F({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>F({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>F({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>F({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>F({args:["worktree","prune"],cwd:e})};var Go=15e3,cd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Yo=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!xr.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=dd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:cd}),i=!1,a="",c="",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 ${Go}ms`].join(`
|
|
10
|
+
`);u(n?{stdout:a,stderr:p,exitCode:124}:s(p))},Go);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{a+=p}),o.stderr.on("data",p=>{c+=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(`
|
|
11
|
+
`)))}),o.on("close",p=>{let g=p??1;if(n){u({stdout:a,stderr:c,exitCode:g});return}if(g!==0){u(s([`git ${e.join(" ")}`,c.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
|
|
12
|
+
`)));return}u(l("Git command succeeded",{stdout:a,stderr:c,exitCode:g}))})}),F=({args:e,cwd:t})=>Yo({args:e,cwd:t,allowFail:!1}),ut=({args:e,cwd:t})=>Yo({args:e,cwd:t,allowFail:!0}),mt=async({cwd:e,message:t})=>{let n=await H.commit({cwd:e,message:t});if(d(n))return s(`Failed to create commit
|
|
13
|
+
${n.message}`);let r=await F({args:["rev-parse","HEAD"],cwd:e});return d(r)?s(`Commit created, but failed to read HEAD SHA
|
|
14
|
+
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},Dt=async e=>{let t=await ti(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=>xr.existsSync(zo.join(n,i)));return l("Checked for in-progress Git operation",o.length>0)},hr=async({repoRoot:e})=>{let n=(await ut({args:["remote","get-url",xe],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},pn=async({repoRoot:e,branch:t})=>{let n=await ut({args:["ls-remote","--heads",xe,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${xe}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},fn=async({repoRoot:e,branch:t})=>{let n=await ut({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},qo=e=>{try{return xr.realpathSync.native(e)}catch{return zo.resolve(e)}},Xo=async({repoRoot:e,worktreeRoot:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=qo(t),o=n.value.stdout.split(`
|
|
15
|
+
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(qo).includes(r);return l("Checked worktree registration",o)},Cr=async e=>{let t=await ut({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},gn=async e=>{let t=await F({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?s(t.message):l("Resolved current branch",t.value.stdout.trim())},Jo=async e=>{let t=await F({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?s(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Qo=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),vn=async({cwd:e,branch:t})=>{let n=await pn({repoRoot:e,branch:t});if(d(n))return s(n.message);if(!n.value)return l("Remote branch missing, skipped pull",!1);let r=await H.fetch({cwd:e,remote:xe,branch:t});if(d(r))return s(`Failed to fetch ${t}
|
|
16
|
+
${r.message}`);let o=await H.pullRebase({cwd:e,remote:xe,branch:t});return d(o)?s(`Failed during pull --rebase
|
|
17
|
+
${o.message}`):l("Pulled with rebase",!0)},Zo=async e=>{let t=await F({args:["status","--porcelain"],cwd:e});return d(t)?s(t.message):l("Checked state branch changes",t.value.stdout.trim().length>0)},ei=async e=>{let t=await gn(e);return d(t)?s(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var ni="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ri=e=>Ie.join(Me,tn,e),oi=()=>Ie.join(ld.homedir(),ve),yn=()=>Ie.join(oi(),"worktrees"),ii=({repoRoot:e})=>{let t=So(e);return d(t)?s(t.message):l("Resolved state branch root",Ie.join(yn(),t.value))},ud=e=>Ie.join(e,Me),Qe=e=>Ie.join(ud(e),tn),Nr=({root:e,fileName:t})=>Ie.join(Qe(e),t),Lt=e=>{try{return Ft.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},xn=()=>{let e=Lt(oi());if(d(e))return s(`Ensure epiq home failed.
|
|
18
|
+
`+e.message);let t=Lt(yn());return d(t)?s(`Ensure worktrees dir failed.
|
|
19
|
+
`+t.message):l("Ensured epiq storage",!0)},si=e=>{Ft.existsSync(e)&&(ue.debug("[sync] remove path",e),Ft.rmSync(e,{recursive:!0,force:!0}))},ai=e=>{let t=Qe(e);if(!Ft.existsSync(t))return l("Events dir missing",[]);let n=Ft.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return l("Listed event files",n)},di=(e,t)=>{for(let n of[Qe(e),Qe(t)]){let r=Lt(n);if(d(r))return s(r.message)}return l("Ensured state branch",void 0)},ci=async e=>{let t=await F({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return s(`ensure state branch is storage only failed
|
|
20
|
+
`+t.message);let r=t.value.stdout.trim().split(`
|
|
21
|
+
`).filter(Boolean).filter(a=>a!==Me);if(r.length===0)return l("State branch is storage-only",!1);let o=await F({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return s(`Failed to clean storage branch
|
|
22
|
+
${o.message}`);let i=await mt({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):l("Cleaned storage branch",!0)},hn=vr(async(e=process.cwd())=>{let t=await F({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?s("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>Ie.resolve(e)),ti=vr(async e=>{let t=await F({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return s(t.message);let n=t.value.stdout.trim(),r=Ie.isAbsolute(n)?n:Ie.join(e,n);return l("Resolved git dir",r)},e=>Ie.resolve(e));import pt from"node:fs";import Ot from"node:path";var ui=async e=>{if((await ut({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);ue.info("Creating initial commit");let n=await H.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?s(n.message):l("Created initial commit",!0)},li=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",md=async e=>{let t=await gn(e);if(d(t))return s(t.message);let n=await Jo(e);if(d(n))return s(n.message);let r=`[epiq:sync:${li(t.value)}:${li(n.value)}]`;return l("Built sync commit message",r)},Cn=async({repoRoot:e,stateBranchName:t})=>{ue.info(`Creating ${t}`);let n=await F({args:["commit-tree",ni,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return s(`Failed to create state branch commit
|
|
23
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await F({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?s(`Failed to create ${t}
|
|
24
|
+
${o.message}`):l("Created state branch",!0)},pd=async({repoRoot:e,stateBranchName:t})=>{let n=await fn({repoRoot:e,branch:t});if(d(n))return s(`Ensure local state branch failed
|
|
25
|
+
`+n.message);if(n.value)return l("Local state branch already exists",!1);let r=await hr({repoRoot:e});if(d(r))return s(`Ensure local state branch failed
|
|
26
|
+
`+r.message);if(!r.value)return Cn({repoRoot:e,stateBranchName:t});let o=await pn({repoRoot:e,branch:t});if(d(o))return s(`Ensure local state branch failed
|
|
27
|
+
`+o.message);if(!o.value)return Cn({repoRoot:e,stateBranchName:t});let i=await H.fetch({cwd:e,remote:xe,branch:t});if(d(i))return s(`Failed to fetch ${t} from remote
|
|
28
|
+
${i.message}`);let a=await F({args:["branch","--track",t,`${xe}/${t}`],cwd:e});return d(a)?s(`Failed to create local ${t} from remote
|
|
29
|
+
${a.message}`):l("Created local state branch from remote",!0)},fd=async({repoRoot:e,branch:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=n.value.stdout.split(`
|
|
30
|
+
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},gd=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Lt(Ot.dirname(t));if(d(r))return s(`Failed to create state branch worktree
|
|
31
|
+
`+r.message);pt.existsSync(t)&&!pt.existsSync(Ot.join(t,".git"))&&(ue.info("Removing broken state branch worktree path"),si(t)),ue.info("Creating state branch worktree");let o=await H.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?s(`Failed to create state branch worktree
|
|
32
|
+
${o.message}`):l("Created state branch worktree",!0)},Er=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await fd({repoRoot:e,branch:n});if(d(r))return s(r.message);let o=Ot.resolve(t),i=r.value?Ot.resolve(r.value):null;if(i&&i===o&&pt.existsSync(i))return l("State branch already checked out in expected worktree",!1);if(i&&i!==o){ue.info("Moving state branch worktree to expected location");let u=await H.worktreeRemove({cwd:e,worktreeRoot:i});if(d(u))return s(`Failed to remove existing state branch worktree
|
|
33
|
+
${u.message}`)}if(i&&!pt.existsSync(i)){ue.info("Pruning stale state branch worktree");let u=await H.worktreePrune({cwd:e});if(d(u))return s(`Failed to prune stale worktrees
|
|
34
|
+
${u.message}`)}let a=await Xo({repoRoot:e,worktreeRoot:t});if(d(a))return s(a.message);let c=pt.existsSync(t);if(a.value&&c)return l("State branch worktree already exists",!1);if(a.value&&!c){ue.info("Pruning missing registered state branch worktree");let u=await H.worktreePrune({cwd:e});if(d(u))return s(`Failed to prune stale worktrees
|
|
35
|
+
${u.message}`)}return gd({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},vd=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await gn(e);if(d(n))return s(n.message);if(n.value===t)return l("State branch already checked out",!1);let r=await H.checkout({cwd:e,branch:t});return d(r)?s(`Failed to checkout ${t}
|
|
36
|
+
${r.message}`):l("Checked out state branch",!0)},yd=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Cr(t);if(d(n))return s(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await hr({repoRoot:t});if(d(r))return s(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=Je(e);if(d(o))return o;let i=o.value,a=await pn({repoRoot:t,branch:i});if(d(a))return s(a.message);if(!a.value)return l("Remote state branch missing; upstream will be configured on first push",!1);ue.info(`Configuring ${i} upstream`);let c=await H.fetch({cwd:t,remote:xe,branch:i});if(d(c))return s(`Failed to fetch ${i}
|
|
37
|
+
${c.message}`);let u=await H.setUpstream({cwd:t,branch:i,upstream:`${xe}/${i}`});return d(u)?s(`Failed to set state branch upstream
|
|
38
|
+
${u.message}`):l("Configured state branch upstream",!0)},Nn=async({stateBranchRoot:e,eventFileName:t})=>{let n=ri(t),r=Ot.join(e,n);if(!pt.existsSync(r))return l("No event file to stage",void 0);let o=await H.stage({cwd:e,pathspec:[n]});return d(o)?s(`Failed to stage state branch event file
|
|
39
|
+
${o.message}`):l("Staged state branch event file",void 0)},mi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await md(e);return d(n)?s(`Create state branch sync commit failed
|
|
40
|
+
`+n.message):mt({cwd:t,message:n.value})},Bt=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Cr(t);if(d(n))return s(n.message);let r=Je(e);if(d(r))return r;let o=r.value,i=n.value?await H.push({cwd:t}):await H.push({cwd:t,remote:xe,branch:o,setUpstream:!0});return d(i)?s(`Failed during state branch push
|
|
41
|
+
${i.message}`):l("Pushed state branch",!0)},pi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Je(e);if(d(o))return o;let i=o.value,a=[xn(),await pd({repoRoot:e,stateBranchName:i}),await Er({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await vd({stateBranchRoot:t,stateBranchName:i}),await ci(t),n?await yd({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of a){if(d(c))return s(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import En from"node:fs";import br from"node:path";import{decodeTime as xd}from"ulid";var Ir=e=>{let[t,n]=e.id;return`${t}:${n??""}`},fi=e=>{let[t]=e.id;return xd(t)},hd=e=>{let{userId:t,userName:n,...r}=e;return r},Cd=e=>e.length===0?"":e.map(t=>JSON.stringify(hd(t))).join(`
|
|
42
|
+
`)+`
|
|
43
|
+
`,Nd=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Ir(r),r);return[...n.values()].sort((r,o)=>{let i=fi(r)-fi(o);return i!==0?i:Ir(r).localeCompare(Ir(o))})},Sr=({sourceFile:e,targetFile:t})=>{let n=ln(e);if(d(n))return s(n.message);let r=ln(t);if(d(r))return s(r.message);let o=Nd(r.value,n.value),i=Cd(o);return(En.existsSync(t)?En.readFileSync(t,"utf8"):"")===i?l("Event file already merged",!1):(En.mkdirSync(br.dirname(t),{recursive:!0}),En.writeFileSync(t,i,"utf8"),l("Merged event file",!0))},Ut=({repoRoot:e,stateBranchRoot:t})=>{let n=ai(t);if(d(n))return s(n.message);let r=Qe(t),o=Qe(e),i=!1;for(let a of n.value){let c=br.join(r,a),u=br.join(o,a),m=Sr({sourceFile:c,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return l("Hydrated event files from state branch",i)};var vi=async(e=process.cwd())=>{fr("Syncing from remote");let t=await yi({cwd:e,ensureUpstream:!1});if(d(t))return oe(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=Je(e);if(d(o))return oe(o.message);let i=o.value,a=await vn({cwd:r,branch:i});if(d(a))return oe(a.message);let c=Ut({repoRoot:n,stateBranchRoot:r});return d(c)?oe(c.message):(gr("Synced from remote"),l("Synced state branch",{repoRoot:n,stateBranchRoot:r}))},Id=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Nr({root:e,fileName:n}),o=Nr({root:t,fileName:n});return Ed.existsSync(r)?Sr({sourceFile:r,targetFile:o}):l("Local own event file missing, nothing to merge",!1)},yi=async({cwd:e,ensureUpstream:t})=>{let n=await hn(e);if(d(n))return s(n.message);let r=n.value,o=ii({repoRoot:r});if(d(o))return s(o.message);let i=o.value,a=await Dt(r);if(d(a))return s(a.message);if(a.value)return s("Cannot sync while a git operation is in progress in the current repo");let c=await ui(r);if(d(c))return s(c.message);let u=await pi({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await Dt(i);if(d(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=di(r,i);return d(p)?s(p.message):l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},gi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Id({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(d(r))return s(r.message);let o=await Zo(t);if(d(o))return s(o.message);if(!r.value&&!o.value)return l("Own event file already up to date in state branch",{createdCommit:!1});let i=await Nn({stateBranchRoot:t,eventFileName:n});if(d(i))return s(i.message);let a=await mi({repoRoot:e,stateBranchRoot:t});return d(a)?s(a.message):l("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},In=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");fr("Syncing");let n=await yi({cwd:e,ensureUpstream:!0});if(d(n))return oe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await ei(r);if(d(a))return oe(a.message);if(a.value)return oe("Cannot run :sync while the repository is in detached HEAD state");let c=!1,u,m=!1,p=!1,g=!1,x=Je(r);if(d(x))return oe(x.message);let E=x.value,A=await vn({cwd:o,branch:E});if(d(A))return oe(A.message);m=A.value;let R=Ut({repoRoot:r,stateBranchRoot:o});if(d(R))return oe(R.message);g=R.value;let b=await gi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(b))return oe(b.message);if(c=b.value.createdCommit,u=b.value.commitSha,c||i){let w=await Bt({stateBranchRoot:o,repoRoot:r}),U=w;if(d(w)&&Qo(w.message)){let le=await vn({cwd:o,branch:E});if(d(le))return oe(le.message);let ne=await gi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(ne))return oe(ne.message);ne.value.createdCommit&&(c=!0,u=ne.value.commitSha),U=await Bt({stateBranchRoot:o,repoRoot:r})}if(d(U))return oe(U.message);p=U.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(c){let w=await F({args:["rev-parse","HEAD"],cwd:o});if(d(w))return oe(w.message);u=w.value.stdout.trim()}return gr(p?"Synced and pushed":m||g||c?"Synced local state":"Already synced"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,hydrated:g,bootstrapped:i})};var ft=3e3,xi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<ft?null:t},hi=0,Rr,Ar=!1,$t=!1,wr=()=>Ar||v().syncStatus.status==="syncing",bd=()=>{let e=L().autoSyncIntervalMs??15e3,t=Date.now()-hi;return Math.max(0,e-t)},Ci=()=>{Rr||(Rr=setTimeout(async()=>{if(Rr=void 0,wr()){$t=!0;return}$t=!1,await Sd()},bd()))},Sd=async()=>{if(wr())return $t=!0,s("Sync already in progress");let e=K();if(d(e)||!e.value)return s("Unable to resolve event log path");Ar=!0,hi=Date.now();try{let t=Xe(e.value);return await In({ownEventFileName:t})}finally{Ar=!1,$t&&Ci()}},Ni=()=>{$t=!0,!wr()&&Ci()};var ie={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:a=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:a}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:a=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:a})};import{ulid as wd}from"ulid";var Ze=24n,Rd=Ze*4n,et=(1n<<Rd)-1n,Ad=/^[0-9a-f]+$/;function Ei(e){return!e||!Ad.test(e)?s(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Pe(e,t=Ze){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function z(e,t){if(!e&&!t)return Pe(et/2n,Ze);let n=e?Ei(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Ei(t):l("Resolved upper bound",et);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Pe(et/2n,Ze);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):Pe(a,Ze)}function Ii(){return Pe(et/2n,Ze)}function bi(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=et*BigInt(r+1)/(t+1n),i=Pe(o,Ze);if(d(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var Tr=(e,t)=>{let n=O(e),r=bi(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],c=r.value[i];if(!a||!c)return s("Unable to assign rebalance rank");o[a.id]=c}return l("Created rebalance event",{id:wd(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var Y={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var Td=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ke,bn]=Td;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Md={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ie.workspace(t,n,r),i=jt(o);if(d(i))return k(i.message,e);let a=I.createNode(o);return d(a)?k(a.message??"Failed to initialize workspace",e):cr(a.value)?l("Workspace initialized",{action:e.action,result:a.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ie.workspace(t,n,r),i=I.createNode(o);return d(i)?k(i.message??"Failed to add workspace",e):cr(i.value)?l("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.board(t,n,r,o));return d(i)?k(i.message??"Unable to create board",e):Po(i.value)?l("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.swimlane(t,n,r,o));return d(i)?k(i.message??"Unable to create swimlane",e):lt(i.value)?l("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=I.createNode(ie.ticket(t,n,r,o));return d(i)?k(i.message??"Unable to create issue",e):ye(i.value)?l("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,a=I.createNode(ie.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(Y.DESCRIPTION)?"vertical":"horizontal"}));return d(a)?k(a.message??`Unable to create field: ${n}`,e):Mo(a.value)?l("Added field",{action:e.action,result:a.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=I.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=I.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=I.tag(n,r,t,o);return d(i)?k(i.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=I.untag(t,n);return d(r)?k(r.message??"Unable to untag ",e):l("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=I.assign(r,n,t,o);return d(i)?k(i.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=I.unassign(t,n);return d(r)?k(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=I.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ye(o))return k("Can only close issues",e);let i=I.getNode(ke);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let a=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(a)?k(a.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ye(o))return k("Can only reopen issues",e);let i=I.getNode(ke);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return k("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=I.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let a=I.updateNode({...i,rank:o});if(d(a))return k(a.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}},Pd=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},kd=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function Wt(e,t=!1){let n=Md[e.action](e);if(d(n))return n;t||([...new Set(kd(e))].forEach(a=>Pd(a,e)),he(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(I.createContributor({name:o,id:r}),n)}var _t=e=>e.map(t=>Wt(t));function _(e){let t=Wt(e);if(t.status!==Ue.Success)return t;let n=mn({event:e});return d(n)?n:t}function Sn(e){return e.map(t=>_(t))}var Si=e=>Mr(O(e),{at:"end"}),Mr=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(z(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(z(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(z(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Ri(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(z(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=Ri(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(z(o.rank,i?.rank)):s("Sibling not found")}}},O=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ri=(e,t)=>e.findIndex(n=>n.id===t),Ai=(e,t,n={at:"end"})=>Mr(O(t).filter(r=>r.id!==e),n),tt=(e,t,n,r)=>{let o=Ai(t,e,n);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let i=Tr(e,r);if(d(i))return i;let a=_(i.value);if(d(a))return a;let c=Ai(t,e,n);return d(c)?c:c.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",c.value.rank)},gt=(e,t)=>{let n=Si(e);if(d(n))return n;if(!n.value.needsRebalance)return l("Resolved rank",n.value.rank);let r=Tr(e,t);if(d(r))return r;let o=_(r.value);if(d(o))return o;let i=Si(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var je=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},kr=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Pr=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),I={deleteNode(e){he(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=Pr(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return this.updateNode(i),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Pr(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return O(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=Pr(o,"move");if(a)return a;if(kr(t,e))return s("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of O(m.id))a(p.id)}};a(e);let c={...structuredClone(t)};for(let u of i){if(!c[u])return s("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(S({nodes:c}),l("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=he(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):l("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let a=this.getFieldByTitle(i.id,"Assignees");if(!a)return s("Unable to locate assignees field");if(O(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=ie.field({id:n,name:o.name,parentNodeId:a.id,rank:r,props:{value:t}}),m=this.createNode(u);return d(m)?m:l("Assigned contributor",u)},createTag(e){let t=he(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):l("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let a=this.getFieldByTitle(i.id,"Tags");if(!a)return s("Unable to locate tags field");if(O(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=ie.field({id:n,name:o.name,parentNodeId:a.id,rank:r,props:{value:t}}),m=this.createNode(u);return d(m)?m:l("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=O(o.id).find(c=>c.props?.value===t);if(!i)return l("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Tag removed",a)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=O(o.id).find(c=>c.props?.value===t);if(!i)return l("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Assignee removed",a)},createNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?s("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=he(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):l("Locked node",n)},updateNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return O(e)}};var se={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},N={accent:se.cyan,accent2:se.magenta,primary:se.white,secondary:se.grayDark,secondary2:se.grayLight,gray:se.gray,green:se.green,yellow:se.yellow,red:se.red};var C={red:se.red,yellow:se.yellow,green:se.green,blue:se.blue,magenta:se.magenta,cyan:se.cyan},vt={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan};var wi=(e,t)=>{let r=T(e.id).find(o=>o.title===t);return r?T(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Dr=e=>wi(e,"Tags").map(t=>I.getTag(t)).filter(t=>!!t),Rn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Dr(n)??[])},An=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Fr(n)??[])},Fr=e=>wi(e,"Assignees").map(t=>I.getContributor(t)).filter(t=>!!t);var y={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var Dd=/^(\d+)(h|d|w|mo|y)$/,Fd=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ld=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},Od=(e,t=new Date)=>{let n=e.match(Dd);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},Bd=e=>{let t=e.match(Fd);if(!t)return null;let[,n,r,o,i,a]=t,c=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,g=a?Number(a):0;return Ld({year:c,month:u,day:m,hour:p,minute:g})?new Date(c,u-1,m,p,g):null},wn=e=>{let t=e.trim().toLowerCase();return Od(t)??Bd(t)},Ti=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ud=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Mi=(e=Ud)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var $d=["BOARD","TICKET","SWIMLANE"],X={EDITOR:"editor",VIEW:"view",USERNAME:"userName",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},He={TITLE:"title",DESCRIPTION:"description"},Wd=[X.EDITOR,X.VIEW,X.USERNAME,X.AUTOSYNC,X.SYNC_DEBOUNCE_MS],_d=[He.TITLE,He.DESCRIPTION],Or=[String(ft),"5000","15000","30000","60000"],nt=[y.SYNC,y.HELP,y.EXPORT,y.CONFIG],Tn=[y.NEW,y.EDIT,y.DELETE,y.MOVE],Lr=[y.TAG,y.UNTAG,y.ASSIGN,y.UNASSIGN,y.CLOSE_ISSUE,y.RE_OPEN_ISSUE,y.EDIT],Pi=[y.FILTER,y.PEEK],jd={WORKSPACE:[...nt,...Tn],BOARD:[...Pi,...nt,...Tn],SWIMLANE:[...Pi,...nt,...Tn],TICKET:[...nt,...Tn,...Lr],FIELD:[...nt,...Lr],FIELD_LIST:[...nt,...Lr],TEXT:[...nt]},Hd=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Kd=()=>{let{selectedNode:e,readOnly:t,breadCrumb:n}=v(),{isSetupDone:r}=_e();if(!r)return[y.HELP,y.CONFIG];if(!Ao())return[y.HELP,y.INIT];if(t)return[y.HELP,y.PEEK,y.EXPORT,y.CONFIG];let o=e?.context,i=o&&$d.includes(o);return[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?jd[c]:[]))].filter(c=>c===y.MOVE?!1:c===y.EDIT||c===y.DELETE?i:!0)},ae=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[y.NONE]:Kd(),[y.EXIT]:["confirm"],[y.EXPORT]:[],[y.SYNC]:[],[y.INIT]:[],[y.HELP]:[],[y.PEEK]:[...Mi(),"now","prev","next"],[y.EDIT]:[..._d],[y.DELETE]:["confirm"],[y.RE_OPEN_ISSUE]:["confirm"],[y.CLOSE_ISSUE]:["confirm"],[y.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[y.FILTER]:["tag","assignee","description","title","clear"],[y.TAG]:[...new Set([...Object.keys(vt),...I.getExistingTags()])],[y.UNTAG]:[...Rn()?.value?.map(({name:o})=>o)??[]],[y.UNASSIGN]:[...An()?.value?.map(({name:o})=>o)??[]],[y.ASSIGN]:I.getExistingAssignees(),[y.NEW]:Hd(n),[y.CONFIG]:[...Wd]}[e]??[]};import xt from"chalk";var ki=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Di}from"ulid";var Fi=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},Li=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Mn=e=>{try{return l("Decoded date",new Date(Di(e)))}catch(t){return s("Decoding failed + "+t.message)}},Br=e=>{if(!e?.id)return null;try{return Di(e.id)}catch{return null}};import yt from"chalk";var $r={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Vd=(e,t,n)=>Math.max(t,Math.min(n,e)),Ur=(e,t,n)=>e+(t-e)*n,Oi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Gd=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,c=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=c):a>=1&&a<2?(u=c,m=i):a>=2&&a<3?(m=i,p=c):a>=3&&a<4?(m=c,p=i):a>=4&&a<5?(u=c,p=i):(u=i,p=c);let g=o-i/2;return[Math.round((u+g)*255),Math.round((m+g)*255),Math.round((p+g)*255)]},qd=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,zd=(e,t,n)=>[Math.round(Ur(e[0],t[0],n)),Math.round(Ur(e[1],t[1],n)),Math.round(Ur(e[2],t[2],n))],Ht=e=>{let n=Oi(e)%360,r=Gd(n,$r.stringColor.saturation,$r.stringColor.lightness);return qd(r)},Yd=e=>{let t=$r.gradient.stops,n=Vd(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),a=o-i;return zd(t[i],t[i+1],a)},Pn=e=>Oi(e.toLowerCase().trim())/4294967295,Bi=e=>{let t=Pn(e);return Yd(t)},Xd=e=>{let[t,n,r]=Bi(e);return{normal:o=>yt.bgRgb(t,n,r).black(o),cursor:o=>yt.bgRgb(t,n,r).white.bold(o)}},Wr=e=>{let[t,n,r]=Bi(e);return{fg:o=>yt.rgb(t,n,r)(o),fgCursor:o=>yt.rgb(t,n,r).inverse(o),bg:o=>yt.bgRgb(t,n,r).black(o),bgCursor:o=>yt.bgRgb(t,n,r).white.bold(o)}},_r=e=>Xd(e).normal(` ${e} `),de=(e,t=vt)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Ht(r)};var rt={None:"none",Invalid:"invalid",Valid:"valid"};var Jd=["BOARD","TICKET","SWIMLANE"],Hr=()=>{let e=v().selectedNode;return e?.context?Jd.includes(e.context)?W():B({message:"Command not available in this context"}):B({message:"Missing target context"})},J="<ENTER> to confirm",W=(e="",t=[])=>({message:e,validity:rt.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:rt.Invalid,message:e,completionWordList:t}),kn=e=>e.length===0,fe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let a=o.trim();if(a.length<i)return"";let p=[...t.filter(Boolean).filter(g=>g.startsWith(a))].sort((g,x)=>Pn(g)-Pn(x)).slice(0,r).map(_r).join(" ");return p?`${e}${p}${n}`:""},jr=({modifier:e})=>{let t="confirm";return e===t?W(J):B({message:kn(e)?`if you are certain, enter ${_r(t)}`:"",completionWordList:[t]})},Qd=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?B({message:n}):W():B({message:kn(r)?t:"",completionWordList:[...e]}),Kt=({hint:e})=>({modifier:t,inputString:n})=>kn(t)&&kn(n)?B({message:e,completionWordList:[]}):W(J),Zd=({modifier:e,inputString:t})=>{let n=ae(y.CONFIG);if(!n.includes(e))return B({message:fe({prefix:"config... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case X.EDITOR:{let r=[...ki];return t.trim()?r.includes(t.trim())?W(J):B({message:fe({prefix:"known editors... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):B({message:fe({prefix:"editor... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?W(J):B({message:fe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.USERNAME:return t.trim()?W(J):B({message:`Enter a username. Saved in ${xt.bgBlack("~/.epiq-global/config.json")}`});case X.AUTOSYNC:{let r=["yes","no"],o=L().autoSync;return r.includes(t.trim())?W(J):B({message:fe({prefix:`should auto-sync (recommended), currently: ${wo(o)} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.SYNC_DEBOUNCE_MS:{let r=L().autoSyncIntervalMs,o=xi(t);if(!t.trim()||o===null||o<ft){let i=fe({prefix:" examples: ",wordList:Or,minLengthForHints:0,inputString:t});return B({message:`provide duration above ${ft}ms. current duration: ${r}ms.`+i,completionWordList:Or})}return W(J)}default:return B({message:"Unknown config option",completionWordList:n})}},ec=({modifier:e})=>{let t=ae(y.EDIT);if(!t.includes(e)){let r=fe({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return B({message:r||"Unknown edit option",completionWordList:t})}let n=Hr();if(n.validity==="invalid")return n;switch(e){case He.TITLE:return W(J);case He.DESCRIPTION:return W("<ENTER> to edit in "+L().preferredEditor);default:return B({message:"Unknown edit option",completionWordList:t})}},tc={[y.EXPORT]:()=>W(J+", and create export markdown file"),[y.PEEK]:e=>{let t=e.modifier;if(t==="now")return W(J);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return W(J);let r=wn(t);if(!t||!r)return B(n);let o=Se(v().breadCrumb,"BOARD");if(d(o))return B({message:"Command is not applicable in this context"});let i=Mn(o.value.id);return d(i)?B({message:"Unable to peek: board id is not a valid ULID"}):Ti({date:r,horizonDate:i.value})?W(J):B({message:xt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[y.EXIT]:()=>W(J+" and exit the application"),[y.INIT]:()=>W(J),[y.FILTER]:e=>{if(e.modifier==="clear")return W();let t=i=>ae(y.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return B({message:fe({wordList:ae(y.FILTER),inputString:e.inputString}),completionWordList:ae(y.FILTER)});let n=Object.values(v().tags).map(i=>i.name),r=Object.values(v().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?B({message:fe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):W():B({message:fe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[y.NONE]:e=>{let t=ae(y.NONE);return e.command?W():B({message:fe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[y.NEW]:e=>Qd({list:ae(y.NEW),hint:fe({wordList:ae(y.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[y.HELP]:()=>W(J),[y.EDIT]:ec,[y.CONFIG]:Zd,[y.DELETE]:e=>{let t=Hr();return t.validity==="invalid"?t:jr(e)},[y.CLOSE_ISSUE]:e=>jr(e),[y.RE_OPEN_ISSUE]:e=>jr(e),[y.MOVE]:e=>{let t=Hr();return t.validity==="invalid"?t:Kt({hint:fe({prefix:"hey hacker! These commands are blocked for you... ",wordList:ae(y.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[y.TAG]:e=>{let n=I.getExistingTags().map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10).join("");return Kt({hint:n.length?"existing tags ... "+n:"create tag ..."})(e)},[y.UNTAG]:e=>{let t=Rn();if(d(t))return B({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10);return n.length?Kt({hint:" ... "+n.join("")})(e):B({message:"Issue has no tags",completionWordList:[]})},[y.ASSIGN]:e=>{let t=I.getExistingAssignees().map(n=>` ${xt.bgHex(de(n))(" "+n+" ")} `).slice(0,10);return Kt({hint:"assign to... "+t.join("")})(e)},[y.UNASSIGN]:e=>{let t=An();if(d(t))return B({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${xt.bgHex(de(r))(" "+r+" ")} `).slice(0,10);return n.length?Kt({hint:"remove assignee... "+n.join("")})(e):B({message:"Issue has no assignees",completionWordList:[]})},[y.SYNC]:()=>W(J)},Ui=Object.fromEntries(Object.entries(tc).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var $i=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var M={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Wi=e=>Object.values(y).includes(e),_i=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:c,completionWordList:u}=Ui[n].validate(n,r,i),m=o==="command"||o==="modifier"?ae(n):$i;return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Oo(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var ji=e=>{let t=e.trimStart(),n=rc(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=oc(e),c=Wi(r)?r:null,u=c!==null,m=r!=="",p=c?ae(c)??[]:[],g=c&&p.includes(o)?o:"",x="word";n.length===0||n.length===1&&!i?x="command":(n.length===1&&i||n.length===2&&!i)&&(x="modifier");let E=i?"":a,A=nc(t,c,g);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:g,target:x,inputToMatch:E,inputString:A}},nc=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},rc=e=>e.trim()?e.trim().split(/\s+/):[],oc=e=>e.trimEnd().split(/\s+/).at(-1)??"";var ht=e=>e===Kr||e===":",Kr=" ",ce={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:rt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Vr=new Set,Hi=()=>{for(let e of Vr)e()},Ki=e=>(Vr.add(e),()=>Vr.delete(e)),De=e=>{let n=e(ce),r=ji(n.value),o=n.cursorPosition===n.value.length;ce={...n,commandMeta:_i(r,o)},Hi()},Vt=({message:e,status:t})=>{let n=structuredClone(ce);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ce=n,Hi(),l(e,null)},Gr=e=>{De(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},qr=e=>{De(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&ht(n[o-1]);)o--;for(;o>0&&!ht(n[o-1]);)o--}else{for(;o<n.length&&!ht(n[o]);)o++;for(;o<n.length&&ht(n[o]);)o++}return{...t,cursorPosition:o}})},Vi=()=>{De(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Gi=()=>{De(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&ht(t[r-1]);)r--;for(;r>0&&!ht(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},$=e=>{De(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),a=i+o,c=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:c,commandIsPending:!1}})},qi=()=>{De(e=>({...e,commandIsPending:!0}))},zi=({addToHistory:e=!0})=>{De(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ic()},Yi=()=>{De(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Xi=()=>{De(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ic=()=>$(()=>""),Q=()=>ce,Ji=()=>{let[e,...t]=ce.value.split(Kr);return t.join(Kr).trim()};var sc=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",ac=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",dc=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Qi=(e,t)=>{if(ac(e,e.sequence))return h.MoveCursorLeftOfWord;if(dc(e,e.sequence))return h.MoveCursorRightOfWord;if(sc(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};var h={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function cc(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function lc(e,t,n){let r=v().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Zi(e,t){let n=Q();if(e.sequence===":"&&n.value==="")return h.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===f.COMMAND_LINE)return Qi(e,n.value);let r=cc(e);if(r){let o=t===f.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return lc(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"e":return h.Edit;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return L().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;case"s":return h.Sync;default:return null}}var es=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case y.EXIT:return M.Exit;case y.EXPORT:return M.Export;case y.INIT:return M.Init;case y.DELETE:return M.Delete;case y.EDIT:return M.Edit;case y.HELP:return M.ViewHelp;case y.RE_OPEN_ISSUE:return M.ReopenIssue;case y.CLOSE_ISSUE:return M.CloseIssue;case y.TAG:return M.TagTicket;case y.UNTAG:return M.UntagTicket;case y.ASSIGN:return M.AssignUserToTicket;case y.UNASSIGN:return M.UnassignUserFromTicket;case y.NEW:return M.NewItem;case y.FILTER:return M.Filter;case y.MOVE:return M.Move;case y.PEEK:return M.Peek;case y.CONFIG:return M.Config;case y.SYNC:return M.Sync;default:return M.None}};import{ulid as V}from"ulid";import vs from"node:fs";import Uc from"node:path";import $c from"react";import{Box as Oc}from"ink";import Un from"react";import{Box as Xr,Text as Ec}from"ink";import Re from"react";import{Text as ts}from"ink";import ns,{useEffect as rs,useState as uc}from"react";var os={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},me=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=G(),r=os[n]??os.default,[o,i]=uc(0);if(rs(()=>{i(0)},[r]),rs(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return ns.createElement(ts,null,t);let a=r[o]??r[0]??t;return ns.createElement(ts,{color:N.accent,dimColor:o===1},a)};import{Box as zr,Text as mc}from"ink";import Dn from"react";var Fn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),g=p+c,x=e.slice(p,g),E=e.length>c,A=i,R=E?Math.max(1,Math.floor(c/e.length*A)):A,b=Math.max(0,A-R),w=Math.max(1,e.length-c),U=E?Math.floor(p/w*b):0;return Dn.createElement(zr,{flexDirection:"row",height:i,width:"100%"},Dn.createElement(zr,{flexDirection:"column",flexGrow:1,height:i},x),Dn.createElement(zr,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((le,ne)=>Dn.createElement(mc,{key:ne,color:E&&ne>=U&&ne<U+R?N.accent:N.secondary},E?"\u2502":" "))))};import{Box as Ln,Text as hc}from"ink";import ot from"react";import{Text as pc}from"ink";import fc from"react";var gc=e=>e.toLowerCase().trim(),vc=(e,t=vt)=>{let n=gc(e);return t[n]?t[n]:Ht(n)},Ct=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return fc.createElement(pc,{underline:t,color:vc(n.name)},"@"+n.name)};import{Text as yc}from"ink";import xc from"react";var Nt=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return xc.createElement(yc,{underline:t,backgroundColor:de(n.name),color:N.primary}," "+n.name+" ")};var is=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=dn(lr(t.title),r),i=Dr(t),a=Fr(t);return ot.createElement(Ln,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?N.accent:N.secondary,justifyContent:"space-between"},ot.createElement(Ln,{borderBottom:!0},ot.createElement(Ln,{paddingLeft:1,flexDirection:"column"},ot.createElement(hc,{color:N.primary},o))),ot.createElement(Ln,{flexDirection:"row",paddingLeft:1},i.map(c=>ot.createElement(Nt,{key:c.id,id:c.id})),a.map(c=>ot.createElement(Ct,{key:c.id,id:c.id}))))};import Cc from"chalk";import{Box as Gt,Text as Yr}from"ink";import Fe from"react";var Nc=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ss=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=T(t.id),a=R=>{let b=i.find(w=>w.title===R);return b?T(b.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},c=a("Tags").map(R=>I.getTag(R)).filter(R=>!!R),u=a("Assignees").map(R=>I.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),g=u.length*(2+m),x=c.map(R=>Fe.createElement(Gt,{key:R.id,paddingRight:m},Fe.createElement(Yr,{color:de(R.name)},"\u25A0"))),E=u.map(R=>Fe.createElement(Gt,{key:R.id,paddingRight:m},Fe.createElement(Yr,{color:Ht(R.name)},"@"+R.name.at(0)))),A=n?N.accent:o===f.MOVE?N.secondary:N.primary;return Fe.createElement(Gt,{borderBottom:!0,justifyContent:"space-between"},Fe.createElement(Gt,null,Fe.createElement(me,{isSelected:n,placeholder:Cc.dim.gray(r+1+" ")}),Fe.createElement(Yr,{wrap:"truncate",color:A},Nc(t.title,e-p-g-14))),Fe.createElement(Gt,null,x,E))};var Ic=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:c})=>{let{renderedChildrenIndex:u}=G(),m=u[e.id]??[],p=`${e.title} (${m.length})`,g=3,x=o?1:4,E=r-g-(o?2:1),A=Re.createElement(Xr,{borderStyle:"round",borderColor:N.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Re.createElement(me,{isSelected:t}),Re.createElement(Ec,{bold:!0,color:t?N.accent:N.primary},p," ",e.readonly?"\u{1F512}":"")),R=(b,w)=>{let U=i&&a===w;return o?Re.createElement(ss,{key:b.id,index:w,width:n,ticket:b,isSelected:U,mode:c}):Re.createElement(is,{key:b.id,width:n,ticket:b,isSelected:U})};return Re.createElement(Xr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?N.accent:N.secondary,paddingRight:1,paddingLeft:1,height:r},A,Re.createElement(Xr,{padding:o?1:0},m.length>0&&Re.createElement(Fn,{selectedIndex:a,height:E,itemHeight:x},m.map(R)),Re.createElement(me,{isSelected:i&&a===-1})))},as=Re.memo(Ic);import{Box as Zr,Text as Fc}from"ink";import Ke,{useEffect as eo,useMemo as ps}from"react";import it from"chalk";import ds from"string-width";import{decodeTime as bc}from"ulid";var Sc=(e,t)=>e+" ".repeat(Math.max(0,t-ds(e))),Rc=(e,t)=>" ".repeat(Math.max(0,t-ds(e)))+e,Ac=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),wc=e=>{switch(e.action){case"move.node":{let t=I.getNode(e.payload.parent);return`to ${t?it.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?it.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?it.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?it.hex(de(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?it.hex(de(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Tc=e=>{let t=Fi(bc(e));return it.gray(Rc(t,8))},Mc=12,Pc=e=>Sc(`${e}`,Mc),cs=e=>{let t=Tc(e.id),n=Pc(e.userName),r=Ac(e.action),o=wc(e),i=it.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=T(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:T(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=T(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>ls(1),navigateToPreviousItem:()=>ls(-1),navigateToNextContainer:()=>us(1),navigateToPreviousContainer:()=>us(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{S({currentNodeId:e.id,selectedIndex:t})}},ls=e=>{let t=v(),n=T(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},us=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=T(o.id),a=i.findIndex(x=>x.id===t.id);if(a<0)return;let c=i.at(a+e)??i.at(0);if(!c)return;let u=T(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),g=u.length?p:-1;D.navigate({currentNode:c,selectedIndex:g})};import{Box as On,Text as kc}from"ink";import Le from"react";var ms=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=G(),{title:o}=t,i=T(t.id).map(a=>{let c=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return I.getContributor(c)?.id;if(o==="Tags")return I.getTag(c)?.id}).filter(a=>!!a);return Le.createElement(On,{alignItems:"center",paddingTop:1},Le.createElement(On,{minWidth:12},Le.createElement(me,{isSelected:n}),Le.createElement(kc,{color:n?N.accent:N.secondary2},o,":")),Le.createElement(On,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,c)=>{let u=r.id===t.id&&c===e;return Le.createElement(On,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Le.createElement(me,{isSelected:u}),o==="Assignees"?Le.createElement(Ct,{isSelected:u,id:a}):o==="Tags"?Le.createElement(Nt,{isSelected:u,id:a}):null)})))};import{Box as Bn,Text as Jr}from"ink";import Oe,{useEffect as Dc}from"react";var Qr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:c}=G(),u=x=>String(x).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Dc(()=>{let x=[];return m.forEach((E,A)=>{let R=Pe(BigInt(A+1));if(!Ee(R))return;let b=ie.text({id:`${e}-${A}`,name:`Line ${A+1}`,parentNodeId:e,rank:R.value,props:{value:E},readonly:!0,isVirtual:!0}),w=I.createNode(b);Ee(w)&&x.push(w.value.id)}),()=>x.forEach(I.deleteNode)},[e,n]);let p="\u2029",g=m.map((x,E)=>{let A=c.id===e&&a===E;return Oe.createElement(Bn,{key:`${e}-${E}`},Oe.createElement(Jr,{color:A?N.primary:N.secondary2,dimColor:!A},`${E+1} `.padStart(5,"\xA0")),Oe.createElement(Jr,{backgroundColor:A?"gray":""},u(x.length?dn(x,i-10):p)))});return Oe.createElement(Bn,{flexDirection:"column",paddingTop:1},Oe.createElement(Bn,null,Oe.createElement(me,{isSelected:o}),Oe.createElement(Jr,{color:o?N.accent:N.secondary2},t)),Oe.createElement(Bn,{flexDirection:"row",borderStyle:"round",borderColor:N.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Oe.createElement(Fn,{scrollByOne:!0,children:g,height:r-2,selectedIndex:a,itemHeight:1})))};var Lc=e=>`${e}::log`,fs=e=>e==="Assignees"||e==="Tags",gs=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=G(),o=process.stdout.columns||120,i=ps(()=>Lc(e.id),[e.id]),a=ps(()=>[...e.log].reverse().map(cs).join(`
|
|
44
|
+
`),[e.log]);eo(()=>{if(I.getNode(i))return;let w=Pe(et);if(d(w))return;let U={...ie.field({id:i,name:Y.HISTORY,parentNodeId:e.id,rank:w.value,props:{value:a},isVirtual:!0}),readonly:!0,childRenderAxis:"vertical"};return I.createNode(U),()=>{I.deleteNode(i)}},[i,e.id,a]),eo(()=>{let b=I.getNode(i);b&&b.props.value!==a&&I.updateNode({...b,props:{...b.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let c=r.id===e.id,u=r.id===i||r.parentNodeId===i;eo(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=T(e.id);if(u){let b=I.getNode(i),U=t-3;return Ke.createElement(Zr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},b?Ke.createElement(Qr,{id:b.id,label:"Event log",text:b.props.value??"",selected:!1,maxWidth:o,height:U}):null)}let p=m.reduce((b,w)=>fs(w.title)||w.id===i?b+1:b,0),g=2,x=p*1,A=t-3-x-g,R=(b,w)=>fs(b.title)?Ke.createElement(ms,{key:b.id,parent:b,selected:w,selectedIndex:n}):b.id===i?Ke.createElement(Zr,{key:b.id,paddingTop:1},Ke.createElement(me,{isSelected:w}),Ke.createElement(Fc,{backgroundColor:N.secondary,color:w?N.accent:N.primary}," History \u203A\u203A ")):b.title===Y.DESCRIPTION?Ke.createElement(Qr,{label:"Description (press e to edit)",key:b.id,id:b.id,text:b.props.value??"",selected:w,maxWidth:o,height:A}):null;return Ke.createElement(Zr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((b,w)=>R(b,c&&n===w)))};var Bc=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,g=u===P.TICKET?t:r.find(b=>b.context===P.TICKET),x=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),A=Math.min(E,x),R=i==="dense";return Un.createElement(Oc,{flexDirection:"row",height:a},p&&e.map((b,w)=>{let U=t.id===b.id,le=U?n:-1,ne=t.context===P.BOARD&&n===w;return Un.createElement(as,{key:b.id,height:a,width:A,swimlane:b,isSelected:ne,isDense:R,isFocused:U,listSelectedIndex:le,mode:o})}),m&&g&&Un.createElement(gs,{height:a,ticket:g}))},$n=Un.memo(Bc);import{render as Wc}from"ink";import{Writable as _c}from"node:stream";var qt=e=>String(e).padStart(2,"0"),jc=e=>{let t=e.getUTCFullYear(),n=qt(e.getUTCMonth()+1),r=qt(e.getUTCDate()),o=qt(e.getUTCHours()),i=qt(e.getUTCMinutes()),a=qt(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},Hc=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Kc=async(e,{width:t,height:n})=>{let r="",o=new _c({write(a,c,u){let m=Vc(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Wc(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),r},Vc=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ys=async()=>{let{viewMode:e}=L(),{currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),a=r.find(w=>w.context==="BOARD");if(!a)return s("No board found to export");let c=120,u=40,m=await Kc($c.createElement($n,{height:u,width:c,swimlanes:(i[a.id]??[]).filter(w=>w!==void 0&<(w)),currentNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return s("Failed to render board export");let p=$e(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let g=new Date,x=jc(g),E=`board_${Hc(a.title)}_${x}.md`,A=Eo(p.value);vs.mkdirSync(A,{recursive:!0});let R=Uc.join(A,E),b=`# Board - ${a.title}
|
|
45
|
+
Date: ${g.toISOString()}
|
|
8
46
|
|
|
9
47
|
\`\`\`text
|
|
10
48
|
${m}
|
|
11
49
|
\`\`\`
|
|
12
|
-
`;return
|
|
13
|
-
`);if(r[r.
|
|
14
|
-
`
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
`);
|
|
18
|
-
`)))}),o.on("close",p=>{let v=p??1;if(r){u({stdout:a,stderr:c,exitCode:v});return}if(v!==0){u(s([`git ${e.join(" ")}`,c.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
|
|
19
|
-
`)));return}u(l("Git command succeeded",{stdout:a,stderr:c,exitCode:v}))})}),F=({args:e,cwd:t})=>Mi({args:e,cwd:t,allowFail:!1}),lt=({args:e,cwd:t})=>Mi({args:e,cwd:t,allowFail:!0}),ut=async({cwd:e,message:t})=>{let r=await W.commit({cwd:e,message:t});if(d(r))return s(`Failed to create commit
|
|
20
|
-
${r.message}`);let n=await F({args:["rev-parse","HEAD"],cwd:e});return d(n)?s(`Commit created, but failed to read HEAD SHA
|
|
21
|
-
${n.message}`):l("Created commit and resolved SHA",n.value.stdout.trim())},Ft=async e=>{let t=await Bi(e);if(d(t))return s(t.message);let r=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>Fn.existsSync(Ti.join(r,i)));return l("Checked for in-progress Git operation",o.length>0)},Dn=async({repoRoot:e})=>{let r=(await lt({args:["remote","get-url",ge],cwd:e})).exitCode===0;return l(`Checked remote ${r}`,r)},Nr=async({repoRoot:e,branch:t})=>{let r=await lt({args:["ls-remote","--heads",ge,t],cwd:e});return r.exitCode!==0?s(r.stderr.trim()||`Unable to inspect remote branch ${ge}/${t}`):l("Checked remote branch",r.stdout.trim().length>0)},br=async({repoRoot:e,branch:t})=>{let r=await lt({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return r.exitCode===0?l("Local branch exists",!0):r.exitCode===1?l("Local branch missing",!1):s(r.stderr.trim()||`Unable to inspect branch ${t}`)},Ai=e=>{try{return Fn.realpathSync.native(e)}catch{return Ti.resolve(e)}},Pi=async({repoRoot:e,worktreeRoot:t})=>{let r=await F({args:["worktree","list","--porcelain"],cwd:e});if(d(r))return s(r.message);let n=Ai(t),o=r.value.stdout.split(`
|
|
22
|
-
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Ai).includes(n);return l("Checked worktree registration",o)},Bn=async e=>{let t=await lt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ir=async e=>{let t=await F({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?s(t.message):l("Resolved current branch",t.value.stdout.trim())},ki=async e=>{let t=await F({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?s(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Li=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Sr=async({cwd:e,branch:t})=>{let r=await Nr({repoRoot:e,branch:t});if(d(r))return s(r.message);if(!r.value)return l("Remote branch missing, skipped pull",!1);let n=await W.fetch({cwd:e,remote:ge,branch:t});if(d(n))return s(`Failed to fetch ${t}
|
|
23
|
-
${n.message}`);let o=await W.pullRebase({cwd:e,remote:ge,branch:t});return d(o)?s(`Failed during pull --rebase
|
|
24
|
-
${o.message}`):l("Pulled with rebase",!0)},Fi=async e=>{let t=await F({args:["status","--porcelain"],cwd:e});return d(t)?s(t.message):l("Checked state branch changes",t.value.stdout.trim().length>0)},Di=async e=>{let t=await Ir(e);return d(t)?s(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Oi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ui=e=>he.join(Se,Yt,e),$i=()=>he.join(tc.homedir(),me),Rr=()=>he.join($i(),"worktrees"),ji=({repoRoot:e})=>{let t=mo(e);return d(t)?s(t.message):l("Resolved state branch root",he.join(Rr(),t.value))},rc=e=>he.join(e,Se),Xe=e=>he.join(rc(e),Yt),On=({root:e,fileName:t})=>he.join(Xe(e),t),Bt=e=>{try{return Dt.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},wr=()=>{let e=Bt($i());if(d(e))return s(`Ensure epiq home failed.
|
|
25
|
-
`+e.message);let t=Bt(Rr());return d(t)?s(`Ensure worktrees dir failed.
|
|
26
|
-
`+t.message):l("Ensured epiq storage",!0)},Wi=e=>{Dt.existsSync(e)&&(de.debug("[sync] remove path",e),Dt.rmSync(e,{recursive:!0,force:!0}))},_i=e=>{let t=Xe(e);if(!Dt.existsSync(t))return l("Events dir missing",[]);let r=Dt.readdirSync(t,{withFileTypes:!0}).filter(n=>n.isFile()).map(n=>n.name).filter(n=>n.endsWith(".jsonl")).sort();return l("Listed event files",r)},Hi=(e,t)=>{for(let r of[Xe(e),Xe(t)]){let n=Bt(r);if(d(n))return s(n.message)}return l("Ensured state branch",void 0)},Ki=async e=>{let t=await F({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return s(`ensure state branch is storage only failed
|
|
27
|
-
`+t.message);let n=t.value.stdout.trim().split(`
|
|
28
|
-
`).filter(Boolean).filter(a=>a!==Se);if(n.length===0)return l("State branch is storage-only",!1);let o=await F({args:["rm","-r","--ignore-unmatch","--",...n],cwd:e});if(d(o))return s(`Failed to clean storage branch
|
|
29
|
-
${o.message}`);let i=await ut({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):l("Cleaned storage branch",!0)},Ar=kn(async(e=process.cwd())=>{let t=await F({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?s("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>he.resolve(e)),Bi=kn(async e=>{let t=await F({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return s(t.message);let r=t.value.stdout.trim(),n=he.isAbsolute(r)?r:he.join(e,r);return l("Resolved git dir",n)},e=>he.resolve(e));import mt from"node:fs";import Ot from"node:path";var qi=async e=>{if((await lt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);de.info("Creating initial commit");let r=await W.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(r)?s(r.message):l("Created initial commit",!0)},Vi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",nc=async e=>{let t=await Ir(e);if(d(t))return s(t.message);let r=await ki(e);if(d(r))return s(r.message);let n=`[epiq:sync:${Vi(t.value)}:${Vi(r.value)}]`;return l("Built sync commit message",n)},Tr=async({repoRoot:e,stateBranchName:t})=>{de.info(`Creating ${t}`);let r=await F({args:["commit-tree",Oi,"-m","[epiq:init-state-branch]"],cwd:e});if(d(r))return s(`Failed to create state branch commit
|
|
30
|
-
${r.message}`);let n=r.value.stdout.trim(),o=await F({args:["update-ref",`refs/heads/${t}`,n],cwd:e});return d(o)?s(`Failed to create ${t}
|
|
31
|
-
${o.message}`):l("Created state branch",!0)},oc=async({repoRoot:e,stateBranchName:t})=>{let r=await br({repoRoot:e,branch:t});if(d(r))return s(`Ensure local state branch failed
|
|
32
|
-
`+r.message);if(r.value)return l("Local state branch already exists",!1);let n=await Dn({repoRoot:e});if(d(n))return s(`Ensure local state branch failed
|
|
33
|
-
`+n.message);if(!n.value)return Tr({repoRoot:e,stateBranchName:t});let o=await Nr({repoRoot:e,branch:t});if(d(o))return s(`Ensure local state branch failed
|
|
34
|
-
`+o.message);if(!o.value)return Tr({repoRoot:e,stateBranchName:t});let i=await W.fetch({cwd:e,remote:ge,branch:t});if(d(i))return s(`Failed to fetch ${t} from remote
|
|
35
|
-
${i.message}`);let a=await F({args:["branch","--track",t,`${ge}/${t}`],cwd:e});return d(a)?s(`Failed to create local ${t} from remote
|
|
36
|
-
${a.message}`):l("Created local state branch from remote",!0)},ic=async({repoRoot:e,branch:t})=>{let r=await F({args:["worktree","list","--porcelain"],cwd:e});if(d(r))return s(r.message);let n=r.value.stdout.split(`
|
|
37
|
-
`),o=null;for(let i of n){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},sc=async({repoRoot:e,stateBranchRoot:t,stateBranchName:r})=>{let n=Bt(Ot.dirname(t));if(d(n))return s(`Failed to create state branch worktree
|
|
38
|
-
`+n.message);mt.existsSync(t)&&!mt.existsSync(Ot.join(t,".git"))&&(de.info("Removing broken state branch worktree path"),Wi(t)),de.info("Creating state branch worktree");let o=await W.worktreeAdd({cwd:e,worktreeRoot:t,branch:r});return d(o)?s(`Failed to create state branch worktree
|
|
39
|
-
${o.message}`):l("Created state branch worktree",!0)},Un=async({repoRoot:e,stateBranchRoot:t,stateBranchName:r})=>{let n=await ic({repoRoot:e,branch:r});if(d(n))return s(n.message);let o=Ot.resolve(t),i=n.value?Ot.resolve(n.value):null;if(i&&i===o&&mt.existsSync(i))return l("State branch already checked out in expected worktree",!1);if(i&&i!==o){de.info("Moving state branch worktree to expected location");let u=await W.worktreeRemove({cwd:e,worktreeRoot:i});if(d(u))return s(`Failed to remove existing state branch worktree
|
|
40
|
-
${u.message}`)}if(i&&!mt.existsSync(i)){de.info("Pruning stale state branch worktree");let u=await W.worktreePrune({cwd:e});if(d(u))return s(`Failed to prune stale worktrees
|
|
41
|
-
${u.message}`)}let a=await Pi({repoRoot:e,worktreeRoot:t});if(d(a))return s(a.message);let c=mt.existsSync(t);if(a.value&&c)return l("State branch worktree already exists",!1);if(a.value&&!c){de.info("Pruning missing registered state branch worktree");let u=await W.worktreePrune({cwd:e});if(d(u))return s(`Failed to prune stale worktrees
|
|
42
|
-
${u.message}`)}return sc({repoRoot:e,stateBranchRoot:t,stateBranchName:r})},ac=async({stateBranchRoot:e,stateBranchName:t})=>{let r=await Ir(e);if(d(r))return s(r.message);if(r.value===t)return l("State branch already checked out",!1);let n=await W.checkout({cwd:e,branch:t});return d(n)?s(`Failed to checkout ${t}
|
|
43
|
-
${n.message}`):l("Checked out state branch",!0)},dc=async({repoRoot:e,stateBranchRoot:t})=>{let r=await Bn(t);if(d(r))return s(r.message);if(r.value)return l("State branch upstream already configured",!1);let n=await Dn({repoRoot:t});if(d(n))return s(n.message);if(!n.value)return l("No remote available for state branch upstream",!1);let o=Ye(e);if(d(o))return o;let i=o.value,a=await Nr({repoRoot:t,branch:i});if(d(a))return s(a.message);if(!a.value)return l("Remote state branch missing; upstream will be configured on first push",!1);de.info(`Configuring ${i} upstream`);let c=await W.fetch({cwd:t,remote:ge,branch:i});if(d(c))return s(`Failed to fetch ${i}
|
|
44
|
-
${c.message}`);let u=await W.setUpstream({cwd:t,branch:i,upstream:`${ge}/${i}`});return d(u)?s(`Failed to set state branch upstream
|
|
45
|
-
${u.message}`):l("Configured state branch upstream",!0)},Mr=async({stateBranchRoot:e,eventFileName:t})=>{let r=Ui(t),n=Ot.join(e,r);if(!mt.existsSync(n))return l("No event file to stage",void 0);let o=await W.stage({cwd:e,pathspec:[r]});return d(o)?s(`Failed to stage state branch event file
|
|
46
|
-
${o.message}`):l("Staged state branch event file",void 0)},zi=async({repoRoot:e,stateBranchRoot:t})=>{let r=await nc(e);return d(r)?s(`Create state branch sync commit failed
|
|
47
|
-
`+r.message):ut({cwd:t,message:r.value})},Ut=async({repoRoot:e,stateBranchRoot:t})=>{let r=await Bn(t);if(d(r))return s(r.message);let n=Ye(e);if(d(n))return n;let o=n.value,i=r.value?await W.push({cwd:t}):await W.push({cwd:t,remote:ge,branch:o,setUpstream:!0});return d(i)?s(`Failed during state branch push
|
|
48
|
-
${i.message}`):l("Pushed state branch",!0)},Gi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:r})=>{let n=!1,o=Ye(e);if(d(o))return o;let i=o.value,a=[wr(),await oc({repoRoot:e,stateBranchName:i}),await Un({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await ac({stateBranchRoot:t,stateBranchName:i}),await Ki(t),r?await dc({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of a){if(d(c))return s(c.message);n=n||!!c.value}return l(r?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",n)};import Pr from"node:fs";import jn from"node:path";import{decodeTime as cc}from"ulid";var $n=e=>{let[t,r]=e.id;return`${t}:${r??""}`},Yi=e=>{let[t]=e.id;return cc(t)},lc=e=>{let{userId:t,userName:r,...n}=e;return n},uc=e=>e.length===0?"":e.map(t=>JSON.stringify(lc(t))).join(`
|
|
49
|
-
`)+`
|
|
50
|
-
`,mc=(e,t)=>{let r=new Map;for(let n of[...t,...e])r.set($n(n),n);return[...r.values()].sort((n,o)=>{let i=Yi(n)-Yi(o);return i!==0?i:$n(n).localeCompare($n(o))})},Wn=({sourceFile:e,targetFile:t})=>{let r=or(e);if(d(r))return s(r.message);let n=or(t);if(d(n))return s(n.message);let o=mc(n.value,r.value),i=uc(o);return(Pr.existsSync(t)?Pr.readFileSync(t,"utf8"):"")===i?l("Event file already merged",!1):(Pr.mkdirSync(jn.dirname(t),{recursive:!0}),Pr.writeFileSync(t,i,"utf8"),l("Merged event file",!0))},$t=({repoRoot:e,stateBranchRoot:t})=>{let r=_i(t);if(d(r))return s(r.message);let n=Xe(t),o=Xe(e),i=!1;for(let a of r.value){let c=jn.join(n,a),u=jn.join(o,a),m=Wn({sourceFile:c,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return l("Hydrated event files from state branch",i)};var Ji=async(e=process.cwd())=>{let t=await Zi({cwd:e,ensureUpstream:!1});if(d(t))return t;let{repoRoot:r,stateBranchRoot:n}=t.value,o=Ye(e);if(d(o))return o;let i=o.value,a=await Sr({cwd:n,branch:i});if(d(a))return s(a.message);let c=$t({repoRoot:r,stateBranchRoot:n});return d(c)?s(c.message):l("Synced state branch",{repoRoot:r,stateBranchRoot:n})},gc=({repoRoot:e,stateBranchRoot:t,ownEventFileName:r})=>{let n=On({root:e,fileName:r}),o=On({root:t,fileName:r});return pc.existsSync(n)?Wn({sourceFile:n,targetFile:o}):l("Local own event file missing, nothing to merge",!1)},Zi=async({cwd:e,ensureUpstream:t})=>{let r=await Ar(e);if(d(r))return s(r.message);let n=r.value,o=ji({repoRoot:n});if(d(o))return s(o.message);let i=o.value,a=await Ft(n);if(d(a))return s(a.message);if(a.value)return s("Cannot sync while a git operation is in progress in the current repo");let c=await qi(n);if(d(c))return s(c.message);let u=await Gi({repoRoot:n,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await Ft(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=Hi(n,i);return d(p)?s(p.message):l("Sync preconditions satisfied",{repoRoot:n,stateBranchRoot:i,bootstrapped:u.value})},Xi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:r})=>{let n=gc({repoRoot:e,stateBranchRoot:t,ownEventFileName:r});if(d(n))return s(n.message);let o=await Fi(t);if(d(o))return s(o.message);if(!n.value&&!o.value)return l("Own event file already up to date in state branch",{createdCommit:!1});let i=await Mr({stateBranchRoot:t,eventFileName:r});if(d(i))return s(i.message);let a=await zi({repoRoot:e,stateBranchRoot:t});return d(a)?s(a.message):l("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},Qi=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 r=await Zi({cwd:e,ensureUpstream:!0});if(d(r))return r;let{repoRoot:n,stateBranchRoot:o,bootstrapped:i}=r.value,a=await Di(n);if(d(a))return s(a.message);if(a.value)return s("Cannot run :sync while the repository is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=!1,y=Ye(n);if(d(y))return y;let b=y.value,R=await Sr({cwd:o,branch:b});if(d(R))return s(R.message);m=R.value;let S=$t({repoRoot:n,stateBranchRoot:o});if(d(S))return s(S.message);v=S.value;let N=await Xi({repoRoot:n,stateBranchRoot:o,ownEventFileName:t});if(d(N))return s(N.message);if(c=N.value.createdCommit,u=N.value.commitSha,c||i){let w=await Ut({stateBranchRoot:o,repoRoot:n}),D=w;if(d(w)&&Li(w.message)){let ie=await Sr({cwd:o,branch:b});if(d(ie))return s(ie.message);let X=await Xi({repoRoot:n,stateBranchRoot:o,ownEventFileName:t});if(d(X))return s(X.message);X.value.createdCommit&&(c=!0,u=X.value.commitSha),D=await Ut({stateBranchRoot:o,repoRoot:n})}if(d(D))return s(D.message);p=D.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(c){let w=await F({args:["rev-parse","HEAD"],cwd:o});if(d(w))return s(w.message);u=w.value.stdout.trim()}return l("Synced event logs with state branch",{repoRoot:n,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,hydrated:v,bootstrapped:i})};var ts=()=>{let{currentNode:e,selectedIndex:t}=x(),r=T(e.id)[t];return{currentNodeId:e.id,selectedNodeId:r?.id??null,parentNodeId:r?.parentNodeId??null,selectedIndex:t}},es=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),rs=e=>{let{nodes:t}=x(),r=t[e.currentNodeId];if(r&&!r.isDeleted&&e.selectedNodeId){let i=T(r.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return L.navigate({currentNode:r,selectedIndex:i}),l("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=T(i.id).findIndex(c=>c.id===o.id);if(a>=0)return L.navigate({currentNode:i,selectedIndex:a}),l("Restored navigation to moved node",null)}}}if(r&&!r.isDeleted){let o=T(r.id);return L.navigate({currentNode:r,selectedIndex:es(e.selectedIndex,o.length)}),l("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=T(o.id);return L.navigate({currentNode:o,selectedIndex:es(e.selectedIndex,i.length)}),l("Restored navigation to parent",null)}}let n=t[x().rootNodeId];return!n||n.isDeleted?s("Unable to restore navigation"):(L.navigate({currentNode:n,selectedIndex:0}),l("Restored navigation to root",null))};import{ulid as fc}from"ulid";var ns=null,je=()=>structuredClone(ns),jt=e=>ns=e,os=()=>{let{currentNode:e,selectedIndex:t}=x(),n=T(e.id)[t];return n?l("Resolved selected child",n):s("Target node not found")};var is=({id:e,parentId:t,position:r={at:"end"}})=>{let n=ne();if(d(n))return s("Unable to resolve user ID");let o=nt(t,e,r,n.value);return d(o)?o:l("Created pending move state",{id:fc(),...n.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},ss=e=>{jt(e);let t=Nt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function _n(e){let t=os();if(d(t))return t;let{currentNode:r,nodes:n}=x();if(!r.parentNodeId)return s("Missing parent node id");let o=n[r.parentNodeId];if(!o)return s("Missing parent node");let i=B(o.id),a=i.findIndex(({id:m})=>m===r.id);if(a<0)return s("Current node not found among siblings");let c=i[a+e];if(!c)return s("Missing sibling node");let u=is({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:ss(u.value)}function Hn(e){let t=os();if(d(t))return t;let{currentNode:r,selectedIndex:n}=x(),i=B(r.id)[n+e];if(!i)return s("Missing sibling node");let a=is({id:t.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:ss(a.value)}import bc from"node:os";import ls from"node:path";import{z as Wt}from"zod";import{accessSync as vc,copyFileSync as xc,existsSync as kr,mkdirSync as as,readdirSync as ds,readFileSync as hc,renameSync as yc,rmSync as Ec,statSync as cs,unlinkSync as Cc,writeFileSync as Nc}from"node:fs";import pt from"node:path";var ue={writeToFile:(e,t)=>{try{let r=pt.dirname(e);kr(r)||as(r,{recursive:!0});let n=typeof t=="string"?t:JSON.stringify(t,null,2);Nc(e,n,"utf-8")}catch(r){logger.error(`Failed to write file at ${e}:`,r)}},readFile:e=>{try{return hc(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ue.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 kr(e)&&cs(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await vc(e),!0}catch{return!1}},mkDir:e=>as(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:r}=pt.parse(t);for(;;){let n=pt.join(t,e);try{if(kr(n)&&cs(n).isDirectory())return n}catch{logger.error(`Unable to locate folder ${e}`)}if(t===r)break;t=pt.dirname(t)}return null},readFirstJSON(e){try{if(!ue.dirExists(e))return null;let t=ds(e).filter(n=>n.endsWith(".json")).sort()[0];if(!t)return null;let r=pt.join(e,t);return ue.readFileJSON(r)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ue.dirExists(e)?ds(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Cc(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Ec(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,r){if(this.mkDir(pt.dirname(t)),!r?.overwrite&&kr(t))throw new Error(`moveFile: destination exists: ${t}`);r?.overwrite&&this.rmFile(t);try{yc(e,t)}catch(n){if(n?.code==="EXDEV"){xc(e,t),this.rmFile(e);return}throw n}}};var Ic={userId:"",userName:"",preferredEditor:"",autoSync:!1},us=Wt.object({preferredEditor:Wt.string().optional(),userName:Wt.string().optional(),userId:Wt.string().optional(),autoSync:Wt.boolean().optional()}).strict(),Sc="config.json",ms=()=>ls.join(bc.homedir(),me),Kn=()=>ls.join(ms(),Sc),Vn=()=>{try{return ue.mkDir(ms()),l(`Ensured ~/${me} exists`,null)}catch{return s(`Unable to create ~/${me}`)}},Rc=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${me}/config.json JSON`)}let r=us.safeParse(t??{});return r.success?l("Parsed config",r.data):s(`Invalid ~/${me}/config.json shape: ${r.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ps=()=>{let e=Vn();if(d(e))return s(e.message);let t=Kn(),r=ue.readFile(t);return r==null||r.trim()===""?l("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):Rc(r)},gs=e=>{let t=Vn();if(d(t))return s(t.message);let r=us.safeParse(e);if(!r.success)return s(`Invalid config: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let n=Kn();try{return ue.writeToFile(n,JSON.stringify(r.data,null,2)+`
|
|
51
|
-
`),l("Config written",null)}catch{return s(`Unable to write ~/${me}/config.json`)}},Lr=e=>{let t=ps();if(d(t))return s("Failed to read existing config");let r={...t.value,...e};return gs(r)},fs=()=>{let e=Kn(),t=Vn();if(d(t))return s(`Unable to create ~/${me}`);if(!(ue.readFile(e)!==null)){let u=gs(Ic);if(d(u))throw new Error(`Unable to create ~/${me}/config.json`)}let n=ps();if(d(n))throw new Error(n.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:c}=n.value;return!i||!a?s(`User name or ID not configured in ~/${me}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:c??!1})};import{spawnSync as wc}from"node:child_process";import Ac from"node:os";import vs from"node:path";import{ulid as Tc}from"ulid";function Mc(){let{preferredEditor:e}=ce(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(r=>!!r?.trim());return[...new Set(t)]}function Pc(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function xs(e){let t=vs.join(Ac.tmpdir(),"epiq");ue.mkDir(t);let r=vs.join(t,Tc());ue.writeToFile(r,e??"");let n=Mc();for(let o of n){let i=Pc(o,r),a=wc(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let c=ue.readFile(r);if(c==null)return s("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return s("Unable to open editor")}import{monotonicFactory as kc,ulid as Fr}from"ulid";var Dr=kc(),hs=({name:e,parent:t,rank:r,user:{userId:n,userName:o}})=>{let i=Dr(),a=Dr(),c=Dr(),u=Dr(),m=Io();if(d(m))return m;let p=z(m.value,void 0);if(d(p))return p;let v=z(p.value,void 0);return d(v)?v:l("Created issue events",[{id:Fr(),userId:n,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:r}},{id:Fr(),userId:n,userName:o,action:"add.field",payload:{id:a,parent:i,name:"Description",val:"",rank:m.value}},{id:Fr(),userId:n,userName:o,action:"add.field",payload:{id:c,parent:i,name:"Assignees",rank:p.value}},{id:Fr(),userId:n,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:v.value}}])};import{monotonicFactory as Lc,ulid as Fe}from"ulid";var _t=Lc();function Fc(){let e=Object.values(x().nodes).find(n=>n.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=T(e.id),[r]=t?T(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:r?.id}),r){let n=x().renderedChildrenIndex?.[r.id]??[];return{currentNode:r,selectedIndex:n.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:x().nodes[x().rootNodeId],selectedIndex:0}}function Dc(){let e=Fc();L.navigate(e)}function ys({userId:e,userName:t}){let r=_t(),n=_t(),o=_t(),i=_t(),a=_t(),c=z(void 0,void 0);if(d(c))return c;let u=z(void 0,void 0);if(d(u))return u;let m=z(u.value,void 0);if(d(m))return m;let p=z(void 0,void 0);if(d(p))return p;let v=z(p.value,void 0);if(d(v))return v;let y=z(v.value,void 0);if(d(y))return y;let b=z(void 0,void 0);return d(b)?b:l("Created default events",[{id:Fe(),userId:e,userName:t,action:"init.workspace",payload:{id:r,name:"Workspace",rank:c.value}},{id:Fe(),userId:e,userName:t,action:"add.board",payload:{id:n,name:"Default",parent:r,rank:u.value}},{id:Fe(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:n,rank:p.value}},{id:Fe(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:n,rank:v.value}},{id:Fe(),userId:e,userName:t,action:"add.swimlane",payload:{id:a,name:"Done",parent:n,rank:y.value}},{id:Fe(),userId:e,userName:t,action:"add.board",payload:{id:rr,name:"Closed",parent:r,rank:m.value}},{id:Fe(),userId:e,userName:t,action:"add.swimlane",payload:{id:Ae,name:"Closed",parent:rr,rank:b.value}},{id:Fe(),userId:e,userName:t,action:"lock.node",payload:{id:rr}},{id:Fe(),userId:e,userName:t,action:"lock.node",payload:{id:Ae}}])}function Br({hasProject:e,eventLog:t}){if(!e){let o=Z.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=It(o);return d(i)?i:(A({hasProject:!1,mode:g.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!t.some(o=>o.action==="init.workspace"))return s("Initialized Epiq project has no workspace init event");let n=bt(t).filter(d);return n.length>0?s(n.map(o=>o.message).join(`
|
|
52
|
-
`)):(Dc(),A({hasProject:!0}),l("State booted successfully",null))}var Es=e=>{let t=e.log??[];for(let r=t.length-1;r>=0;r--){let n=t[r];if(n&&n.action==="close.issue"&&n.payload.id===e.id)return n.payload.parent}return null};import Oc from"node:fs";import Ns from"node:path";import qn from"node:fs";import Bc from"node:path";var Cs=async e=>{let t=Bc.join(e,".gitignore"),r=qn.existsSync(t)?qn.readFileSync(t,"utf8"):"",n=[".epiq/events/",".epiq/logs/"],o=r.split(`
|
|
53
|
-
`).map(u=>u.trim()),i=n.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...i].join(`
|
|
54
|
-
`);return r=r.trimEnd()+`
|
|
50
|
+
`;return vs.writeFileSync(R,b,"utf8"),l("Exported board layout",R)};var hs=()=>{let{currentNode:e,selectedIndex:t}=v(),n=T(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},xs=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),Cs=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=T(n.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return D.navigate({currentNode:n,selectedIndex:i}),l("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=T(i.id).findIndex(c=>c.id===o.id);if(a>=0)return D.navigate({currentNode:i,selectedIndex:a}),l("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=T(n.id);return D.navigate({currentNode:n,selectedIndex:xs(e.selectedIndex,o.length)}),l("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=T(o.id);return D.navigate({currentNode:o,selectedIndex:xs(e.selectedIndex,i.length)}),l("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}),l("Restored navigation to root",null))};import Zc from"node:os";import bs from"node:path";import{z as st}from"zod";import{accessSync as Gc,copyFileSync as qc,existsSync as Wn,mkdirSync as Ns,readdirSync as Es,readFileSync as zc,renameSync as Yc,rmSync as Xc,statSync as Is,unlinkSync as Jc,writeFileSync as Qc}from"node:fs";import Et from"node:path";var ge={writeToFile:(e,t)=>{try{let n=Et.dirname(e);Wn(n)||Ns(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Qc(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return zc(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ge.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 Wn(e)&&Is(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Gc(e),!0}catch{return!1}},mkDir:e=>Ns(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Et.parse(t);for(;;){let r=Et.join(t,e);try{if(Wn(r)&&Is(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Et.dirname(t)}return null},readFirstJSON(e){try{if(!ge.dirExists(e))return null;let t=Es(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Et.join(e,t);return ge.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ge.dirExists(e)?Es(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Jc(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Xc(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Et.dirname(t)),!n?.overwrite&&Wn(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Yc(e,t)}catch(r){if(r?.code==="EXDEV"){qc(e,t),this.rmFile(e);return}throw r}}};var el={userId:"",userName:"",preferredEditor:"",autoSync:!1},Ss=st.object({preferredEditor:st.string().optional(),userName:st.string().optional(),userId:st.string().optional(),autoSync:st.boolean().nullable().optional(),autoSyncDebounceMs:st.number().optional(),viewMode:st.enum(["dense","wide"]).optional()}),tl="config.json",Rs=()=>bs.join(Zc.homedir(),ve),to=()=>bs.join(Rs(),tl),no=()=>{try{return ge.mkDir(Rs()),l(`Ensured ~/${ve} exists`,null)}catch{return s(`Unable to create ~/${ve}`)}},nl=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${ve}/config.json JSON`)}let n=Ss.safeParse(t??{});return n.success?l("Parsed config",n.data):s(`Invalid ~/${ve}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},As=()=>{let e=no();if(d(e))return s(e.message);let t=to(),n=ge.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:15e3}):nl(n)},ws=e=>{let t=no();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=to();try{return ge.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
51
|
+
`),l("Config written",null)}catch{return s(`Unable to write ~/${ve}/config.json`)}},at=e=>{let t=As();if(d(t))return s("Failed to read existing config");let n={...t.value,...e};return ws(n)},Ts=()=>{let e=to(),t=no();if(d(t))return s(`Unable to create ~/${ve}`);if(!(ge.readFile(e)!==null)){let m=ws(el);if(d(m))throw new Error(`Unable to create ~/${ve}/config.json`)}let r=As();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:c,autoSyncDebounceMs:u}=r.value;return!i||!a?s(`User name or ID not configured in ~/${ve}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:c??!1,autoSyncIntervalMs:u??15e3,viewMode:"dense"})};import{monotonicFactory as rl,ulid as _n}from"ulid";var jn=rl(),Ms=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=jn(),a=jn(),c=jn(),u=jn(),m=Ii();if(d(m))return m;let p=z(m.value,void 0);if(d(p))return p;let g=z(p.value,void 0);return d(g)?g:l("Created issue events",[{id:_n(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:_n(),userId:r,userName:o,action:"add.field",payload:{id:a,parent:i,name:Y.DESCRIPTION,val:"",rank:m.value}},{id:_n(),userId:r,userName:o,action:"add.field",payload:{id:c,parent:i,name:"Assignees",rank:p.value}},{id:_n(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:g.value}}])};import{monotonicFactory as ol,ulid as Be}from"ulid";var zt=ol();function il(){let e=Object.values(v().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=T(e.id),[n]=t?T(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 sl(){let e=il();D.navigate(e)}function Ps({userId:e,userName:t}){let n=zt(),r=zt(),o=zt(),i=zt(),a=zt(),c=z(void 0,void 0);if(d(c))return c;let u=z(void 0,void 0);if(d(u))return u;let m=z(u.value,void 0);if(d(m))return m;let p=z(void 0,void 0);if(d(p))return p;let g=z(p.value,void 0);if(d(g))return g;let x=z(g.value,void 0);if(d(x))return x;let E=z(void 0,void 0);return d(E)?E:l("Created default events",[{id:Be(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Be(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Be(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Be(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:g.value}},{id:Be(),userId:e,userName:t,action:"add.swimlane",payload:{id:a,name:"Done",parent:r,rank:x.value}},{id:Be(),userId:e,userName:t,action:"add.board",payload:{id:bn,name:"Closed",parent:n,rank:m.value}},{id:Be(),userId:e,userName:t,action:"add.swimlane",payload:{id:ke,name:"Closed",parent:bn,rank:E.value}},{id:Be(),userId:e,userName:t,action:"lock.node",payload:{id:bn}},{id:Be(),userId:e,userName:t,action:"lock.node",payload:{id:ke}}])}function Hn({hasProject:e,eventLog:t}){if(!e){let o=ie.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=jt(o);return d(i)?i:(S({hasProject:!1,mode:f.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!t.some(o=>o.action==="init.workspace"))return s("Initialized Epiq project has no workspace init event");let r=_t(t).filter(d);return r.length>0?s(`Materializing failed:
|
|
52
|
+
${r.map(o=>o.message).join(`
|
|
53
|
+
`)}`):(sl(),S({hasProject:!0}),l("State booted successfully",null))}var ks=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{ulid as Ls}from"ulid";import{spawnSync as al}from"node:child_process";import dl from"node:os";import Ds from"node:path";import{ulid as cl}from"ulid";function ll(){let{preferredEditor:e}=L(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function ul(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Fs(e){let t=Ds.join(dl.tmpdir(),"epiq");ge.mkDir(t);let n=Ds.join(t,cl());ge.writeToFile(n,e??"");let r=ll();for(let o of r){let i=ul(o,n),a=al(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let c=ge.readFile(n);if(c==null)return s("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return s("Unable to open editor")}var Os=()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{breadCrumb:t,selectedNode:n}=v(),r=Se([...t,n],"TICKET");if(d(r))return s("Edit target must be an issue");let o=r.value;if(o.readonly)return s("Cannot edit readonly field");let i=T(o.id).find(m=>m.title===Y.DESCRIPTION);if(!i)return s("No target found");if(i.readonly)return s("Cannot edit readonly field");let a=i.props.value;if(typeof a!="string")return s("Selected field is not editable text");let c=Fs(a);if(d(c))return s("Failed to edit field");let u=c.value;return u===a?l("No changes made",null):i.title===Y.DESCRIPTION?_({id:Ls(),action:"edit.description",payload:{id:i.id,md:u},...e.value}):i.title==="Title"?_({id:Ls(),action:"edit.title",payload:{id:i.id,name:u},...e.value}):s(`Editing not supported for "${i.title}"`)};import pl from"node:fs";import Us from"node:path";import ro from"node:fs";import ml from"node:path";var Bs=async e=>{let t=ml.join(e,".gitignore"),n=ro.existsSync(t)?ro.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
54
|
+
`).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 l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...i].join(`
|
|
55
|
+
`);return n=n.trimEnd()+`
|
|
55
56
|
|
|
56
57
|
${c}
|
|
57
|
-
`,
|
|
58
|
-
`));let{rootNodeId:da,nodes:ca}=x();return L.navigate({currentNode:ca[da],selectedIndex:0}),A({hasProject:!0,mode:g.DEFAULT}),l(q,null)};var Is=e=>Object.values(x().tags).find(t=>t.name===e),Ss=e=>Object.values(x().contributors).find(t=>t.name===e),Rs=[{systemOnly:!0,intent:M.Move,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=se().commandMeta,r=()=>{let c=je();if(!c)return s("No pending move state");let u=c.payload.id;if(!x().nodes[u])return s("Moved node not found");let p=c.payload.parent,v=x().nodes[p];if(!v)return s("Move parent not found");let y=T(p).findIndex(b=>b.id===u);return y===-1?s("Moved node not found among rendered children"):(L.navigate({currentNode:v,selectedIndex:y}),l("Synchronized navigation to moved node",null))},n=c=>{if(d(c))return s(c.message);let u=r();return d(u)?s(u.message):l("Updated move preview",null)},{currentNode:o,selectedIndex:i}=x(),a=T(o.id)[i];if(!a)return A({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 c=B(a.parentNodeId),u=c.findIndex(({id:R})=>R===a.id);if(u===-1)return s("Target not found among siblings");let m=c[u-1],p=c[u+1],v=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},y=nt(a.parentNodeId,a.id,v,e.value);if(d(y))return y;jt({id:$(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:y.value},...e.value}),A({mode:g.MOVE});let b=r();return d(b)?s(b.message):l("Move initialized",null)}if(t==="next")return A({mode:g.MOVE}),n(Hn(1));if(t==="previous")return A({mode:g.MOVE}),n(Hn(-1));if(t==="to-next")return A({mode:g.MOVE}),n(_n(1));if(t==="to-previous")return A({mode:g.MOVE}),n(_n(-1));if(t==="confirm"){A({mode:g.DEFAULT});let c=je();if(!c)return s("No pending move to confirm");let u=V(c);if(d(u))return u;let m=r();return d(m)?s(m.message):(jt(null),l("Moved item",null))}return t==="cancel"?(jt(null),A({mode:g.DEFAULT}),l("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:r}=x(),n=T(t.id)[r];return n?V({id:$(),action:"delete.node",payload:{id:n.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.Edit,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let t=Re(x().breadCrumb,"TICKET");if(d(t))return s("Edit target must be an issue");let r=t.value;if(r.readonly)return s("Cannot edit readonly field");let{currentNode:n,selectedIndex:o}=x();if(!T(r.id)[o])return s("No selected field");let a=T(n.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let c=a.props.value;if(typeof c!="string")return s("Selected field is not editable text");let u=xs(c);if(d(u))return s("Failed to edit field");let m=u.value;return m===c?l("No changes made",null):a.title==="Description"?V({id:$(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?V({id:$(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=se().commandMeta,r=/(!=|=)/,[n,o]=e.split(r);if(!n||!(c=>G(f.FILTER).map(u=>u.split(r)[0]).includes(c))(n))return s("Invalid filter modifier");let a={target:n,operator:"=",value:t.trim()};return le(c=>({...c,filters:e==="clear"?[]:[...c.filters,a],mode:g.DEFAULT})),l("Viewing help",null)}},{intent:M.ViewHelp,mode:g.COMMAND_LINE,action:()=>(A({mode:g.HELP}),l("Viewing help",null))},{intent:M.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:r}=x(),n=T(t.id)[r];if(!n)return s("Unable to close issue, no target found");if(!pe(n))return s("Cannot close in this context");let o=x().nodes[Ae];if(!o)return s("Unable to locate closed swimlane");if(n.parentNodeId===o.id)return s("Issue is already closed");let i=nt(o.id,n.id,{at:"end"},e.value);if(d(i))return i;let a=V({id:$(),action:"close.issue",payload:{id:n.id,parent:o.id,rank:i.value},...e.value});return d(a)?a:l("Issue closed",null)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:r}=x(),n=T(t.id)[r];if(!n)return s("Unable to reopen issue, no target found");let o=n.context==="TICKET"?l("Resolved ticket",n):Oe(n.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=x().nodes[Ae];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!pe(i))return s("Target node is not issue");let c=Es(i);if(!c)return s("Unable to resolve previous parent from issue history");if(c===a.id)return s("Previous parent resolves to closed swimlane");let u=x().nodes[c];if(!u)return s("Previous parent no longer exists");let m=nt(u.id,i.id,{at:"end"},e.value);if(d(m))return m;let p=V({id:$(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return d(p)?p:l("Issue reopened",null)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:r}=ce(),n=gr()?.trim();if(!n)return s("No username provided");let o=n??r,i=e??$();if(!o||!i)return s("Unable to resolve user name or id");let a=Lr({userName:o,userId:i,preferredEditor:t??""});return d(a)?a:(Qe({userName:o,userId:i}),A({mode:g.DEFAULT}),l(`Username set to "${n}"`,null))}},{intent:M.Init,mode:g.COMMAND_LINE,action:bs},{intent:M.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=gr()?.trim();if(!e)return s("No editor provided");let t=Lr({preferredEditor:e});return d(t)?t:(Qe({preferredEditor:e}),A({mode:g.DEFAULT}),l(`Editor configuration set to "${e}"`,null))}},{intent:M.SetAutoSync,mode:g.COMMAND_LINE,action:()=>{let e=se().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",r=Lr({autoSync:t});return d(r)?r:(Qe({autoSync:t}),A({mode:g.DEFAULT}),l(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let r=ne();if(d(r))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:n,currentNode:o,selectedIndex:i}=x(),a=c=>{let u=V(c);if(d(u))return u;let m=I.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=I.getNode(m.parentNodeId);return p?(L.navigate({currentNode:p,selectedIndex:I.getSiblings(m.parentNodeId).findIndex(({id:v})=>v===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:c}=x(),u=I.getNode(c);if(!u)return s("Workspace not found");let m=ot(u.id,r.value);return d(m)?m:a({id:$(),action:"add.board",payload:{id:$(),name:t.inputString,parent:u.id,rank:m.value},...r.value})}if(t.modifier==="swimlane"){let c=Re(n,"BOARD");if(d(c))return s("Unable to add swimlane in this context");let u=ot(c.value.id,r.value);return d(u)?u:a({id:$(),action:"add.swimlane",payload:{id:$(),name:t.inputString,parent:c.value.id,rank:u.value},...r.value})}if(t.modifier==="issue"){let c=T(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&c?.context==="SWIMLANE"?c:(()=>{let N=Re(n,"SWIMLANE");return d(N)?null:N.value})();if(!u)return s("Unable to add issue in this context");let m=ot(u.id,r.value);if(d(m))return m;let p=hs({name:t.inputString,parent:u.id,rank:m.value,user:r.value});if(d(p))return p;let v=p.value,y=ar(v);if(y.some(N=>d(N)))return s("Issue create failed: "+y.filter(d).map(N=>N.message).filter(Boolean).join(", "));let b=y[0];if(!b||d(b))return s("Issue creation failed");let S=v.find(N=>N.action==="add.issue")?.payload.id;return S?(L.navigate({currentNode:u,selectedIndex:I.getSiblings(u.id).findIndex(({id:N})=>N===S)}),l("Issue created",null)):s("Unable to determine ticket id")}return l("Success",null)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=se();return e.validity===Te.Invalid?s("Invalid command "+be):(le(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),l("View set",null))},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.Rename,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:r}=x(),n=T(t.id)[r];if(!n)return s("Missing node");if(n.readonly)return s("Cannot rename readonly node");let o=gr();return o?V({id:$(),action:"edit.title",payload:{id:n.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:r}=se().commandMeta,n=(t||r).trim();if(!n)return s("Provide a tag");let o=Is(n);if(!o)return s(`Tag "${n}" does not exist`);let{selectedNode:i}=x();if(!i)return s("Invalid untag target");let a=Oe(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let c=a.value,u=I.getFieldByTitle(c.id,"Tags");if(!u)return s("Unable to locate tags field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?V({id:$(),action:"untag.issue",payload:{id:m.id,target:c.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:r}=se().commandMeta,n=(t||r).trim();if(!n)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=x(),a=T(i.id)[o];if(!a)return s("Invalid tag target");let c=Oe(a.id,"TICKET");if(d(c))return s("Unable to tag issue in this context");let u=c.value,m=Is(n),p;if(m)p=m.id;else{let R=$(),S=V({id:$(),action:"create.tag",payload:{id:R,name:n},userId:e.value.userId,userName:e.value.userName});if(d(S))return S;p=S.value.result.id}let v=I.getFieldByTitle(u.id,"Tags");if(!v)return s("Unable to locate tags field");if(T(v.id).some(R=>R.props?.value===p))return s("Already tagged with that tag");let b=ot(v.id,e.value);return d(b)?b:V({id:$(),action:"tag.issue",payload:{id:$(),target:u.id,tagId:p,rank:b.value},...e.value})},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:r}=se().commandMeta,n=(t||r).trim();if(!n)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=x(),a=T(i.id)[o];if(!a)return s("Invalid assign target");let c=Oe(a.id,"TICKET");if(d(c))return s("Unable to assign issue in this context");let u=c.value,m=Ss(n),p;if(m)p=m.id;else{let R=$(),S=V({id:$(),action:"create.contributor",payload:{id:R,name:n},userId:e.value.userId,userName:e.value.userName});if(d(S))return S;p=S.value.result.id}let v=I.getFieldByTitle(u.id,"Assignees");if(!v)return s("Unable to locate assignees field");if(T(v.id).some(R=>R.props?.value===p))return s("Assignee already assigned");let b=ot(v.id,e.value);return d(b)?b:V({id:$(),action:"assign.issue",payload:{id:$(),target:u.id,contributor:p,rank:b.value},...e.value})},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=ne();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:r}=se().commandMeta,n=(t||r).trim();if(!n)return s("Provide an assignee to remove");let o=Ss(n);if(!o)return s(`Assignee "${n}" does not exist`);let{selectedNode:i}=x();if(!i)return s("Invalid unassign target");let a=Oe(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let c=a.value,u=I.getFieldByTitle(c.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?V({id:$(),action:"unassign.issue",payload:{id:m.id,target:c.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${n}"`)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=ts();H(()=>""),A({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:r}=ce();if(!t)return s("Unable to resolve userId");if(!r)return s("Unable to resolve userName");let n=ne();if(d(n)||!n.value)return s("Unable to resolve event log path");let o=rt(n.value),i=await Qi({ownEventFileName:o});if(d(i))return A({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let a=ye(process.cwd());if(d(a))return a;let c=St(a.value);if(d(c))return s(`Unable to load events. ${c.message}`);let u=Br({eventLog:c.value,hasProject:!0});if(d(u))return s(`Unable to boot synced state. ${u.message}`);A({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let m=rs(e);return d(m)?m:l("Synced",!0)}},{intent:M.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Re(x().breadCrumb,"BOARD");if(d(e))return e;let t=De(process.cwd());if(d(t))throw new Error(t.message);let r=St(t.value);if(d(r))return s(r.message);let n=r.value,{modifier:o}=se().commandMeta,i;if(o==="now"){let y=zn();if(d(y))return y;let b=bt(n);return b.some(d)?s(b.map(R=>R.message).join(", ")):(A({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let y=x().eventLog.at(-2),b=fn(y);if(b===null)return s("No previous event to peek");i=b}else if(o==="next"){let y=x().unappliedEvents.at(0),b=fn(y);if(b===null)return s("No next event to peek");i=b}else{let y=lr(o);if(!y)return s("Invalid peek date");i=y.getTime()}let a=e.value.id,{appliedEvents:c,unappliedEvents:u}=Ao(n,i),m=zn();if(d(m))return m;let p=bt(c);if(p.some(d))return s(p.map(y=>y.message).join(", "));let v=x().nodes[a];return v?(L.navigate({currentNode:v,selectedIndex:0}),A({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),l("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await bi();return d(e)?e:(A({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,mode:g.COMMAND_LINE,action:async()=>(L.exit(),l("Exit successful",!0))}];var Uc=new Set(["peek","filter","view-help"]),fe=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:r,modifier:n,inputString:o}}=se();if(!t)return s("No command to confirm");if(!e&&r===Te.Invalid)return s("Invalid command");let i=si(t);if(ei(),x().readOnly&&!Uc.has(i))return Mt({status:be.Fail,message:"Command not available in readonly state",value:null});let a=Rs.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return Mt({status:be.Fail,message:"Command not found",value:null});let c=await a.action(a,{command:t,inputString:o,modifier:n});return d(c)?Mt(c):(ti({addToHistory:!e}),a.onSuccess?.(),Mt(c))};var Or=[{intent:h.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(A({mode:g.COMMAND_LINE}),H(()=>"move cancel"),fe({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(A({mode:g.COMMAND_LINE}),H(()=>"move start"),fe({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:g.MOVE,action:()=>(A({mode:g.COMMAND_LINE}),H(()=>"move confirm"),fe({isForceExecutedBySystem:!0}))}],Ur=[{intent:h.MovePreviousItem,mode:g.MOVE,action:()=>je()?(A({mode:g.COMMAND_LINE}),H(()=>"move previous"),fe({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveNextItem,mode:g.MOVE,action:()=>je()?(A({mode:g.COMMAND_LINE}),H(()=>"move next"),fe({isForceExecutedBySystem:!0})):s("No pending move")}],ws=[{intent:h.MoveToNextContainer,mode:g.MOVE,action:()=>je()?(A({mode:g.COMMAND_LINE}),H(()=>"move to-next"),fe({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveToPreviousContainer,mode:g.MOVE,action:()=>je()?(A({mode:g.COMMAND_LINE}),H(()=>"move to-previous"),fe({isForceExecutedBySystem:!0})):s("No pending move")}];var As={[P.WORKSPACE]:[...Or,...Ur],[P.BOARD]:[...Or,...Ur],[P.SWIMLANE]:[...Or,...Ur,...ws],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Ts=[{intent:h.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(A({mode:g.COMMAND_LINE}),H(()=>`${f.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(A({mode:g.COMMAND_LINE}),H(()=>`${f.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(A({mode:g.COMMAND_LINE}),H(()=>""),l("Entering command line mode",null))},{intent:h.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(L.enterChildNode(),l("Entering context",null))},{intent:h.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(L.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.DEFAULT,action:()=>(L.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(L.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.DEFAULT,action:()=>(L.navigateToNextContainer(),l("Navigating to next container",null))},{intent:h.Edit,mode:g.DEFAULT,action:()=>(A({mode:g.COMMAND_LINE}),H(()=>"edit"),fe(),l("Fired command",!0))},{intent:h.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(A({viewMode:"dense"}),l("View set",null))},{intent:h.SetViewWide,mode:g.DEFAULT,action:()=>(A({viewMode:"wide"}),l("View set",null))}];var $c=500,jc=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Ms=e=>{let t=jc(e);t&&H(r=>(r+t).slice(0,$c))};var Ps=[{intent:h.ViewHelp,mode:g.DEFAULT,action:()=>(A({mode:g.HELP}),l("Viewing help",null))},{intent:h.Exit,mode:g.HELP,action:()=>(A({mode:g.DEFAULT}),l("Exiting help",null))},{intent:h.Confirm,mode:g.COMMAND_LINE,action:()=>(fe(),l("Executing command",null))},{intent:h.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(bn(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(bn(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(In("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(In("right"),l("Moving cursor right of word",null))},{intent:h.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(A({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:h.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(H((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(Ms(t??""),l("Capturing input",null))},{intent:h.EraseInput,mode:g.COMMAND_LINE,action:()=>(Zo(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Qo(),l("Erasing input word",null))},{intent:h.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ri(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ni(),l("Getting next command from history",null))}];import Wc from"chalk";var $r=": for command line",ks="q to exit",Ls=`${Wc.hex(C.accent)("m")} to confirm`,Gn={[P.WORKSPACE]:[$r],[P.BOARD]:[$r],[P.BOARD+g.COMMAND_LINE]:[$r],[P.SWIMLANE]:[$r],[P.TICKET+g.HELP]:[ks],[P.SWIMLANE+g.HELP]:[ks],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[Ls],[P.TICKET+g.MOVE]:[Ls]};var jr=e=>e.trim().toLocaleLowerCase(),_c=(e,t)=>{let r=I.getFieldByTitle(e,t);if(!r)return"";let n=r.props?.value;return typeof n=="string"?n:""},Hc=e=>{let{tags:t}=x(),r=I.getFieldByTitle(e,"Tags");return r?B(r.id).map(n=>{let o=n.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(n=>!!n):[]},Kc=e=>{let{contributors:t}=x(),r=I.getFieldByTitle(e,"Assignees");return r?B(r.id).map(n=>{let o=n.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(n=>!!n):[]},Fs=(e,t)=>{let r=t.value;if(!r)return!0;switch(t.target){case"title":return jr(e.title??"").includes(r);case"description":return jr(_c(e.id,"Description")).includes(r);case"tag":return Hc(e.id).map(jr).some(c=>c.includes(r));case"assignee":return Kc(e.id).map(jr).some(c=>c.includes(r));default:return!0}};function Ds(e,t,r){let n=t[e];if(!n)return s("buildBreadCrumb(): current node not found");let o=[],i=n;for(;i&&(o.push(i),!(i.id===r||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==r?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Bs=e=>{let t={};for(let r of e)r.intent&&(t[r.mode]||(t[r.mode]={}),t[r.mode][r.intent]=r);return t};var Wr,Yn,Xn=new Set,Os=()=>{for(let e of Xn)e()},qc=e=>(Xn.add(e),()=>Xn.delete(e));function Us(e){let{currentNodeId:t,mode:r,rootNodeId:n,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!n)return s("derive(): rootNode is missing");if(!o[n])return s("derive(): unable to find root node");let c=o[t];if(!c)return s("Unable to derive state, currentNode not found");let u=Ds(t,o,n);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Gn[p+r]??Gn[p]??[],y=[...Ts,...As[p]??[],...Ps],b=Bs(y),R=zc(o,i),S=R[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:c,breadCrumb:m,availableHints:v,availableActions:y,actionIndex:b,selectedNode:S,renderedChildrenIndex:R})}var x=()=>(Wr||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Wr);function It(e){Yn=e;let t=ye(process.cwd()),r=!1;if(!d(t)){let i=Be(t.value);if(d(i))return s(i.message);r=!0}let n={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:r},o=Us(n);return d(o)?o:(Wr=o.value,Os(),l("State initialized",null))}function le(e){let t=x(),r=e(t),n=Us(r);return d(n)?s(n.message??"Unable to update state"):(Wr=n.value,Os(),l("State updated",null))}var A=e=>le(t=>({...t,...e}));var U=()=>Vc(qc,x,x),zc=(e,t)=>{let r={};for(let n of Object.values(e))pe(n)&&t.length>0&&!t.every(o=>Fs(n,o))||!n.parentNodeId||n.isDeleted||((!n.parentNodeId||!r[n.parentNodeId])&&(r[n.parentNodeId]=[]),r[n.parentNodeId].push(n));for(let n of Object.keys(r))r[n].sort((o,i)=>{let a=e[o.id],c=e[i.id];return!a||!c?0:a.rank.localeCompare(c.rank)});return r},T=e=>x()?.renderedChildrenIndex[e]??[],zn=()=>Yn?It(Yn):s("Cannot reset state: no initial workspace found");import{Box as ul}from"ink";import Qn from"react";import Kt from"chalk";import{Box as Jn,Text as $s}from"ink";import Ht,{useEffect as Gc,useMemo as Yc,useState as Xc}from"react";var js=Kt.gray,Jc=Kt.inverse,Zc=Kt.inverse.gray,Qc={hint:"",hints:[],overlap:0,remainder:""},_s=({value:e,command:t})=>{if(!t)return null;let r=e.trimStart(),o=e.length-r.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},el=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let r=ee(t);return{bg:n=>Kt.bgHex(r).black(n),bgCursor:n=>Kt.bgHex(r).inverse.black(n)}}return hn(t)},tl=({value:e,command:t,modifier:r})=>{if(!t||!r)return null;let n=_s({value:e,command:t});if(!n)return null;let i=e.slice(n.end).match(/^\s*/)?.[0].length??0,a=n.end+i;return e.slice(a,a+r.length)!==r?null:{start:a,end:a+r.length}},Ws=()=>({value:te.value,cursorPosition:te.cursorPosition,commandIsPending:te.commandIsPending,autoCompletion:te.commandMeta.autoCompletion??Qc,infoMessage:te.commandMeta.infoMessage,validationStatus:te.commandMeta.validity,command:te.commandMeta.command,inputString:te.commandMeta.inputString,modifier:te.commandMeta.modifier}),rl=(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,Hs=({width:e})=>{let[t,r]=Xc(Ws());Gc(()=>{let v=()=>{let b=Ws();r(R=>rl(R,b)?R:b)},y=Jo(v);return v(),()=>{y()}},[]);let{value:n,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:c,command:u,modifier:m}=t,p=Yc(()=>{let v=Math.max(0,Math.min(o,n.length)),y=_s({value:n,command:u}),b=tl({value:n,command:u,modifier:m}),R=u?hn(u):null,S=el({command:u,modifier:m}),N=(q,J)=>{let Ze=y&&J>=y.start&&J<y.end,Gt=b&&J>=b.start&&J<b.end;return Ze&&R?R.fg(q):Gt&&S?S.bg(q):q},w=(q,J)=>{let Ze=y&&J>=y.start&&J<y.end,Gt=b&&J>=b.start&&J<b.end;return Ze&&R?R.fgCursor(q):Gt&&S?S.bgCursor(q):Jc(q)},D=n.slice(0,v),ie=n[v]??" ",X=v<n.length?n.slice(v+1):"",zt=Array.from(D).map((q,J)=>N(q,J)).join(""),vt=w(ie,v),xt=Array.from(X).map((q,J)=>N(q,v+1+J)).join("");if(c.hint){let q=c.hint[c.overlap]??ie;vt=Zc(q),xt=js(c.remainder.slice(1)+X)}return js(":")+zt+vt+xt},[n,o,c,u,m]);return Ht.createElement(Jn,{flexDirection:"column",justifyContent:"flex-start"},Ht.createElement(Jn,{flexDirection:"column",paddingX:1,borderColor:C.secondary,borderStyle:"round",width:e},Ht.createElement(Jn,null,Ht.createElement($s,null,p),i&&Ht.createElement($s,{wrap:"truncate",color:a?C.red:C.secondary2},` ${i} `))))};import Ks from"chalk";import{Box as nl,Text as Zn}from"ink";import _r,{useEffect as ol,useState as il}from"react";var sl=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Vs=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)}},al=({r:e,g:t,b:r})=>{let n=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${n(e)}${n(t)}${n(r)}`},dl=(e,t,r)=>{let n=Vs(e),o=Vs(t);return al({r:n.r+(o.r-n.r)*r,g:n.g+(o.g-n.g)*r,b:n.b+(o.b-n.b)*r})},cl=(e,t)=>{if(e.length===1)return e[0];let r=t*(e.length-1),n=Math.floor(r),o=r-n,i=e[n],a=e[Math.min(n+1,e.length-1)];return dl(i,a,o)},ll=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),qs=({width:e,availableHints:t})=>{let{syncStatus:{status:r,msg:n}}=U(),[o,i]=il(0);ol(()=>{if(r!=="syncing"){i(0);return}let N=setInterval(()=>{i(w=>w+1)},50);return()=>clearInterval(N)},[r]);let a=[],c=0;for(let N of t){let D=(a.length>0?" | ":"").length+N.length;if(c+D>e-4)break;a.push(N),c+=D}let u=r!="synced"?n??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),p=r==="syncing"?cl(sl,(Math.sin(o*.12)+1)/2):C.secondary,v=Ks.hex(p??"fff"),y=Ks.hex(C.secondary2),b=v(`\u256D${"\u2500".repeat(m)}\u256E`),R=v(`\u2570${"\u2500".repeat(m)}\u256F`),S=`${v("\u2502")}${y(ll(` ${u} `,m))}${v("\u2502")}`;return _r.createElement(nl,{flexDirection:"column",width:e},_r.createElement(Zn,null,b),_r.createElement(Zn,null,S),_r.createElement(Zn,null,R))};var Hr=({width:e,mode:t,availableHints:r})=>{let n=U(),o=[],i=0;for(let a of r){let u=(o.length>0?" | ":"").length+a.length;if(i+u>e+2)break;o.push(a),i+=u}return Qn.createElement(ul,null,t===g.COMMAND_LINE&&n.syncStatus.status!=="syncing"?Qn.createElement(Hs,{width:e}):Qn.createElement(qs,{width:e,mode:t,availableHints:r}))};import{Box as gt,Text as zs}from"ink";import We from"react";var Gs=({width:e})=>{let t=[...x().availableActions].map(r=>r.description).filter(r=>r!==void 0).map(r=>{let[n,o]=r.split("]"),i=n?.replace("[",""),a=o?.trim();return[i,a]}).filter(r=>r[0]!==void 0&&r[1]!==void 0).sort(([r],[n])=>r.length===1&&n.length!==1?-1:r.length!==1&&n.length===1?1:r.localeCompare(n,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),We.createElement(gt,{flexDirection:"column",marginTop:3,borderColor:C.secondary,borderStyle:"round",width:e,minHeight:19},We.createElement(gt,{flexDirection:"column",width:e},x().mode===g.HELP?t.map(([r,n],o)=>We.createElement(gt,{paddingLeft:1,key:o,flexDirection:"row"},We.createElement(gt,{key:o,flexDirection:"row",paddingBottom:o?0:1},We.createElement(gt,{width:20,justifyContent:"flex-end"},We.createElement(zs,{color:o?C.accent:C.secondary},r)),We.createElement(gt,{flexGrow:1,width:40,paddingLeft:2},We.createElement(zs,{color:o?C.primary:C.secondary},n))))):null))};import ml from"chalk";import{Box as Kr,Text as _e}from"ink";import ve from"react";var Ys=({width:e,height:t})=>ve.createElement(Kr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:C.secondary,rowGap:1},ve.createElement(_e,{color:C.accent,bold:!0},"Initialize project"),ve.createElement(_e,null,`This folder is not an ${ml.hex(C.accent)("epiq")} project yet.`),ve.createElement(_e,{color:C.primary},"To start tracking issues here, we need to initialize a new"," ",ve.createElement(_e,{color:C.primary,backgroundColor:C.secondary}," .epiq/project.json ")," ","file in this repository."),ve.createElement(Kr,{marginTop:1,flexDirection:"column"},ve.createElement(Kr,null,ve.createElement(_e,{color:C.accent}," "),ve.createElement(_e,{color:C.primary},"Type "),ve.createElement(_e,{backgroundColor:C.secondary}," :init "))),ve.createElement(Kr,{marginTop:1},ve.createElement(_e,{color:C.secondary2},"(This will create the local epiq project files)")));import{Box as Vt,Text as Ce}from"ink";import _ from"react";var Vr=({isDone:e,command:t,value:r})=>_.createElement(Vt,null,_.createElement(Ce,{color:C.accent,dimColor:e},e?" \u2714 ":" "),_.createElement(Ce,{dimColor:e},"Type "),_.createElement(Ce,{backgroundColor:C.secondary,dimColor:e}," "+t+" "),r&&_.createElement(_.Fragment,null,_.createElement(Ce,{dimColor:e}," "),_.createElement(Ce,{color:C.secondary,dimColor:e},"<"+r+">")));function eo({width:e,height:t,hasUserName:r,hasPreferredEditor:n,userName:o,preferredEditor:i}){let a=r&&n,c=r?n?null:":config:editor":":config:username";return _.createElement(Vt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:C.secondary,rowGap:1},_.createElement(Ce,{color:C.accent,bold:!0},"Welcome! \u{1F539}"),_.createElement(Ce,null,"Lets get you started - its a breeze."),_.createElement(Ce,{color:C.secondary2},"And remember, you can always get help with"," ",_.createElement(Ce,{color:C.accent},":help"),"."),!a&&_.createElement(Ce,{color:C.secondary2},c===":config:username"?"First, choose your username.":"Nice. One more step."),_.createElement(Vt,{flexDirection:"column"},r&&_.createElement(Vt,{marginBottom:1},_.createElement(Vr,{isDone:!0,command:":config:username",value:o})),!r&&_.createElement(Vr,{isDone:!1,command:":config:username"}),r&&!n&&_.createElement(Vr,{isDone:!1,command:":config:editor"}),a&&_.createElement(Vt,null,_.createElement(Vr,{isDone:!0,command:":config:editor",value:i}))))}import ea from"chalk";import{Box as zr,Text as He}from"ink";import re from"react";import{Box as to,Text as pl}from"ink";import ft from"react";var gl=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Xs=({width:e})=>{let{breadCrumb:t,currentNode:r,selectedIndex:n,viewMode:o}=x(),i=B(r.id)[n],a=Oe(i?.id??r.id,"TICKET"),c=xe(a)?a.value:void 0,u=c?.id?B(c.id):[],m=S=>{let N=u.find(w=>w.title===S);return N?B(N.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},p=m("Tags"),v=m("Assignees"),y=c?.parentNodeId?!un(r.id,c?.parentNodeId)&&o==="dense":!1,b=t.map((S,N)=>{let w=N===t.length-1,D=B(S.id),ie=w?D?.[n]?.title:void 0;return`${N?" / ":""}${S.title??""}${ie?` \u25B8 ${ie}`:""}`}).join(""),R=gl(b,e);return ft.createElement(to,null,ft.createElement(pl,{color:C.secondary2},R),y?p.map(S=>ft.createElement(to,{key:S,paddingLeft:2},ft.createElement(ct,{id:S}))):null,y?v.map(S=>ft.createElement(to,{key:S,paddingLeft:2},ft.createElement(dt,{id:S}))):null)};import{Box as fl,Text as Js}from"ink";import qr from"react";var vl=({filters:e})=>qr.createElement(fl,{columnGap:1},qr.createElement(Js,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:r,operator:n})=>qr.createElement(Js,{backgroundColor:"black",color:"white"},` ${r}${n}"${t}" `))),Zs=qr.memo(vl);var Qs="0.4.10";function Gr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:r,eventLog:n,unappliedEvents:o}=U(),{userName:i,preferredEditor:a}=ce(),c=40,u=process.stdout.columns-c-8,m=n.at(-1)?.id,p=mr(m??""),v=xe(p)?Wo(p.value):"INVALID DATE";return re.createElement(zr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?re.createElement(He,null," "):re.createElement(zr,{paddingLeft:1},e.length>0?re.createElement(Zs,{filters:e}):re.createElement(Xs,{width:u})),r==="live"?re.createElement(zr,{columnGap:1,paddingRight:2,"max-width":c,overflow:"hidden",justifyContent:"flex-end"},re.createElement(He,{dimColor:!0,color:C.secondary2},Qs+" "),re.createElement(ta,{icon:"@",value:i}),re.createElement(ta,{icon:"\u276F",value:a})):"",r==="peek"?re.createElement(zr,{paddingLeft:1},re.createElement(He,{backgroundColor:C.yellow}," Readonly "),re.createElement(He,{color:C.yellow}," "+o.length+" edits ago at "),re.createElement(He,{backgroundColor:C.yellow,color:C.accent}," "+v+" "),re.createElement(He,{color:C.yellow},". Resume with "),re.createElement(He,{backgroundColor:C.yellow}," :peek now ")):"")}function ta({icon:e,value:t}){return re.createElement(He,null,ea.dim(e)+ea.hex(C.accent)(` ${t??"-"} `))}import{Box as xl,Text as hl}from"ink";import qt from"react";import{Box as Yr,Text as ro}from"ink";import Ke from"react";function no(){let e=U(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?T(t?.id):[];return Ke.createElement(Yr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:C.secondary,width:i},Ke.createElement(Yr,{padding:1,paddingTop:0,paddingBottom:0},Ke.createElement(ro,null,"Select a board:")),Ke.createElement(Yr,{padding:1,flexDirection:"column"},a.map((c,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,v=T(c.id).flatMap(({id:y})=>B(y)).length;return Ke.createElement(Yr,{key:c.id??u},Ke.createElement(ro,{color:m?C.accent:C.secondary2},Ke.createElement(ae,{isSelected:m})),Ke.createElement(ro,{color:m?C.accent:C.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var yl=({currentNode:e,selectedIndex:t,breadCrumb:r,mode:n,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:c}=U(),u=r.find(({context:y})=>y==="BOARD"),v=i-1-3;return qt.createElement(xl,{flexDirection:"row"},e.context==="WORKSPACE"?qt.createElement(no,null):u?qt.createElement(Cr,{height:v,width:a,swimlanes:(c[u.id]??[]).filter(y=>y!==void 0&&tt(y)),currentNode:e,selectedIndex:t,breadCrumb:r,viewMode:o,mode:n}):qt.createElement(hl,null))},ra=qt.memo(yl);function oo({width:e,height:t}){let r=U(),n=r.filters;if(r.mode===g.HELP)return Y.createElement(Je,{flexDirection:"column"},Y.createElement(Gs,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:c,preferredEditor:u}=et(),m=!o,p=o&&!r.hasProject;if(m)return Y.createElement(Je,{flexDirection:"column"},Y.createElement(Je,{flexDirection:"column"},Y.createElement(Gr,{hideBreadCrumb:!0,filters:n}),Y.createElement(eo,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:c??"",preferredEditor:u??""})),Y.createElement(Hr,{width:e,mode:r.mode,availableHints:r.availableHints}));if(p)return Y.createElement(Je,{flexDirection:"column"},Y.createElement(Je,{flexDirection:"column"},Y.createElement(Gr,{hideBreadCrumb:!0,filters:n}),Y.createElement(Ys,{height:t,width:e})),Y.createElement(Hr,{width:e,mode:r.mode,availableHints:r.availableHints}));let v=Re(x().breadCrumb??[],"BOARD");if(xe(v)){let y=v.value.id,b=T(y).length,R=3,S=Math.floor(e/R),N=Math.floor(e/Math.max(b,1));e=Math.min(N,S)*Math.max(b,R)}return Y.createElement(Je,{flexDirection:"column"},Y.createElement(Je,{flexDirection:"column"},Y.createElement(Gr,{filters:n}),Y.createElement(ra,{width:e,height:t,currentNode:r.currentNode,selectedIndex:r.selectedIndex,breadCrumb:r.breadCrumb,viewMode:r.viewMode,mode:r.mode})),Y.createElement(Hr,{width:e,mode:r.mode,availableHints:r.availableHints}))}import El from"readline";var Xr,Jr,Ne,Cl=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),na=async e=>{if(e.ctrl&&e.name==="c")return L.exit();let{actionIndex:t,mode:r,readOnly:n}=x(),o=ii(e,r);if(!o||n&&!Cl.has(o))return;let i=t[r]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},Nl=()=>async function(t,r){r.name!=="escape"&&(Ne&&(clearTimeout(Ne),Ne=void 0),await na(r))},bl=()=>async function(t){if(t.length===1&&t[0]===27){Ne&&clearTimeout(Ne),Ne=setTimeout(()=>{na({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ne=void 0},25);return}Ne&&(clearTimeout(Ne),Ne=void 0)};function oa(){Xr&&process.stdin.removeListener("keypress",Xr),Jr&&process.stdin.removeListener("data",Jr),Xr=Nl(),Jr=bl(),El.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Jr),process.stdin.on("keypress",Xr)}Sl(`${io.bold("Epiq CLI")}
|
|
58
|
+
`,ro.writeFileSync(t,n,"utf8"),ue.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var fl=async e=>{let t=await F({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},j=(e,t)=>s(`[${e}] ${t}`),$s=async()=>{let e=bo(),t=await hn(process.cwd());if(d(t))return j(1,t.message);let n=t.value,r=await Dt(n);if(d(r))return j(2,r.message);if(r.value)return j(2,"Cannot initialize Epiq while a git operation is in progress");let o=await fl(n);if(d(o))return j(2.5,o.message);if(o.value)return j(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(dr(n))return j(4,"Epiq project already initialized");let i=_e();if(!i.isSetupDone||!i.userName)return j(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let a=L(),c=a.userName,u=a.userId;if(!u||!c)return j(5,"Missing Epiq user id");let m=e.stateBranch,p=await fn({repoRoot:n,branch:m});if(d(p))return j(6,p.message);let g=await Cn({repoRoot:n,stateBranchName:e.stateBranch});if(d(g))return j(6,g.message);let x=xn();if(d(x))return j(7,x.message);let E=Us.join(yn(),e.projectId),A=await Er({repoRoot:n,stateBranchRoot:E,stateBranchName:e.stateBranch});if(d(A))return j(8,A.message);let R=Us.join(E,".epiq");pl.mkdirSync(R,{recursive:!0});let b=Ps({userId:u,userName:c});if(d(b))return j(9,b.message);for(let sr of b.value){let No=mn({event:sr,rootDir:E});if(d(No))return j(9,No.message)}let w=await Nn({stateBranchRoot:E,eventFileName:Xe({userId:u,userName:c})});if(d(w))return j(10,w.message);let U=await mt({cwd:E,message:"[epiq:init]"});if(d(U))return j(10,U.message);let le=await Bs(n);if(d(le))return j(12,le.message);let ne=Ro({repoRoot:n,fileContents:e});if(d(ne))return j(13,ne.message);let Zt=await H.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(Zt))return j(14,Zt.message);let St=await H.commit({cwd:n,message:"[epiq:init-project]"});if(d(St))return j(14,St.message);let Rt=Ut({repoRoot:n,stateBranchRoot:E});if(d(Rt))return j(15,Rt.message);let q="Project initialized!",re=await Bt({repoRoot:n,stateBranchRoot:E});d(re)&&(q+=` Warn: [init:16] ${re.message}`);let ct=await H.push({cwd:n});d(ct)&&(q+=` Warn: [init:17] ${ct.message}`);let Co=Sn(b.value).filter(d);if(Co.length>0)return j(18,Co.map(sr=>sr.message).join(`
|
|
59
|
+
`));let{rootNodeId:Da,nodes:Fa}=v();return D.navigate({currentNode:Fa[Da],selectedIndex:0}),S({hasProject:!0,mode:f.DEFAULT}),l(q,null)};import{ulid as vl}from"ulid";import{ulid as gl}from"ulid";var Ws=null,Ve=()=>structuredClone(Ws),Yt=e=>Ws=e,_s=()=>{let{currentNode:e,selectedIndex:t}=v(),r=T(e.id)[t];return r?l("Resolved selected child",r):s("Target node not found")};var js=({id:e,parentId:t,position:n={at:"end"}})=>{let r=K();if(d(r))return s("Unable to resolve user ID");let o=tt(t,e,n,r.value);return d(o)?o:l("Created pending move state",{id:gl(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},Hs=e=>{Yt(e);let t=Wt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function oo(e){let t=_s();if(d(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=O(o.id),a=i.findIndex(({id:m})=>m===n.id);if(a<0)return s("Current node not found among siblings");let c=i[a+e];if(!c)return s("Missing sibling node");let u=js({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Hs(u.value)}function io(e){let t=_s();if(d(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=O(n.id)[r+e];if(!i)return s("Missing sibling node");let a=js({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:Hs(a.value)}var Ks=()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=Q().commandMeta,n=()=>{let c=Ve();if(!c)return s("No pending move state");let u=c.payload.id;if(!v().nodes[u])return s("Moved node not found");let p=c.payload.parent,g=v().nodes[p];if(!g)return s("Move parent not found");let x=T(p).findIndex(E=>E.id===u);return x===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:g,selectedIndex:x}),l("Synchronized navigation to moved node",null))},r=c=>{if(d(c))return s(c.message);let u=n();return d(u)?s(u.message):l("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=T(o.id)[i];if(!a)return S({mode:f.DEFAULT}),s("No move target");if(t==="start"){if(a.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!a.parentNodeId)return s("Target has no parent");let c=O(a.parentNodeId),u=c.findIndex(({id:A})=>A===a.id);if(u===-1)return s("Target not found among siblings");let m=c[u-1],p=c[u+1],g=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},x=tt(a.parentNodeId,a.id,g,e.value);if(d(x))return x;Yt({id:vl(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:x.value},...e.value}),S({mode:f.MOVE});let E=n();return d(E)?s(E.message):l("Move initialized",null)}if(t==="next")return S({mode:f.MOVE}),r(io(1));if(t==="previous")return S({mode:f.MOVE}),r(io(-1));if(t==="to-next")return S({mode:f.MOVE}),r(oo(1));if(t==="to-previous")return S({mode:f.MOVE}),r(oo(-1));if(t==="confirm"){S({mode:f.DEFAULT});let c=Ve();if(!c)return s("No pending move to confirm");let u=_(c);if(d(u))return u;let m=n();return d(m)?s(m.message):(Yt(null),l("Moved item",null))}return t==="cancel"?(Yt(null),S({mode:f.DEFAULT}),l("Cancelling move",null)):s("Invalid move modifier")};import yl from"zod";var Vs=()=>{let e=Q().commandMeta.inputString,t=yl.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return s("Auto sync duration must be a number of at least 3000 ms");let n=at({autoSyncDebounceMs:t.data});return d(n)?n:(pe({autoSyncIntervalMs:t.data}),S({mode:f.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Gs=()=>{let e=Q().commandMeta.modifier;if(e!=="yes"&&e!=="no")return s("Invalid response");let t=To(e),n=at({autoSync:t});return d(n)?n:(pe({autoSync:t}),S({mode:f.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var qs=e=>Object.values(v().tags).find(t=>t.name===e),zs=e=>Object.values(v().contributors).find(t=>t.name===e),Ys=[{systemOnly:!0,intent:M.Move,mode:f.COMMAND_LINE,action:Ks},{intent:M.Delete,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];return r?_({id:V(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Filter,mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Q().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(c=>ae(y.FILTER).map(u=>u.split(n)[0]).includes(c))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return he(c=>({...c,filters:e==="clear"?[]:[...c.filters,a],mode:f.DEFAULT})),l("Viewing help",null)}},{intent:M.ViewHelp,mode:f.COMMAND_LINE,action:()=>(S({mode:f.HELP}),l("Viewing help",null))},{intent:M.CloseIssue,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!ye(r))return s("Cannot close in this context");let o=v().nodes[ke];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=tt(o.id,r.id,{at:"end"},e.value);if(d(i))return i;let a=_({id:V(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return d(a)?a:l("Issue closed",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.ReopenIssue,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):je(r.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=v().nodes[ke];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!ye(i))return s("Target node is not issue");let c=ks(i);if(!c)return s("Unable to resolve previous parent from issue history");if(c===a.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[c];if(!u)return s("Previous parent no longer exists");let m=tt(u.id,i.id,{at:"end"},e.value);if(d(m))return m;let p=_({id:V(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return d(p)?p:l("Issue reopened",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Init,mode:f.COMMAND_LINE,action:$s},{intent:M.NewItem,mode:f.COMMAND_LINE,action:(e,t)=>{let n=K();if(d(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=v(),a=c=>{let u=_(c);if(d(u))return u;let m=I.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=I.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:I.getSiblings(m.parentNodeId).findIndex(({id:g})=>g===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:c}=v(),u=I.getNode(c);if(!u)return s("Workspace not found");let m=gt(u.id,n.value);return d(m)?m:a({id:V(),action:"add.board",payload:{id:V(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let c=Se(r,"BOARD");if(d(c))return s("Unable to add swimlane in this context");let u=gt(c.value.id,n.value);return d(u)?u:a({id:V(),action:"add.swimlane",payload:{id:V(),name:t.inputString,parent:c.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let c=T(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&c?.context==="SWIMLANE"?c:(()=>{let b=Se(r,"SWIMLANE");return d(b)?null:b.value})();if(!u)return s("Unable to add issue in this context");let m=gt(u.id,n.value);if(d(m))return m;let p=Ms({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(d(p))return p;let g=p.value,x=Sn(g);if(x.some(b=>d(b)))return s("Issue create failed: "+x.filter(d).map(b=>b.message).filter(Boolean).join(", "));let E=x[0];if(!E||d(E))return s("Issue creation failed");let R=g.find(b=>b.action==="add.issue")?.payload.id;return R?(D.navigate({currentNode:u,selectedIndex:I.getSiblings(u.id).findIndex(({id:b})=>b===R)}),l("Issue created",null)):s("Unable to determine ticket id")}return l("Success",null)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Rename,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=T(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Ji();return o?_({id:V(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.UntagTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=qs(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=je(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let c=a.value,u=I.getFieldByTitle(c.id,"Tags");if(!u)return s("Unable to locate tags field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?_({id:V(),action:"untag.issue",payload:{id:m.id,target:c.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.TagTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=T(i.id)[o];if(!a)return s("Invalid tag target");let c=je(a.id,"TICKET");if(d(c))return s("Unable to tag issue in this context");let u=c.value,m=qs(r),p;if(m)p=m.id;else{let A=V(),R=_({id:V(),action:"create.tag",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(R))return R;p=R.value.result.id}let g=I.getFieldByTitle(u.id,"Tags");if(!g)return s("Unable to locate tags field");if(T(g.id).some(A=>A.props?.value===p))return s("Already tagged with that tag");let E=gt(g.id,e.value);return d(E)?E:_({id:V(),action:"tag.issue",payload:{id:V(),target:u.id,tagId:p,rank:E.value},...e.value})},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.AssignUserToTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=T(i.id)[o];if(!a)return s("Invalid assign target");let c=je(a.id,"TICKET");if(d(c))return s("Unable to assign issue in this context");let u=c.value,m=zs(r),p;if(m)p=m.id;else{let A=V(),R=_({id:V(),action:"create.contributor",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(R))return R;p=R.value.result.id}let g=I.getFieldByTitle(u.id,"Assignees");if(!g)return s("Unable to locate assignees field");if(T(g.id).some(A=>A.props?.value===p))return s("Assignee already assigned");let E=gt(g.id,e.value);return d(E)?E:_({id:V(),action:"assign.issue",payload:{id:V(),target:u.id,contributor:p,rank:E.value},...e.value})},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:f.COMMAND_LINE,action:()=>{let e=K();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=zs(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=je(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let c=a.value,u=I.getFieldByTitle(c.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?_({id:V(),action:"unassign.issue",payload:{id:m.id,target:c.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Sync,mode:f.COMMAND_LINE,action:async()=>{if(v().syncStatus.status==="syncing")return s("Sync already in progress");let e=hs();$(()=>""),S({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=L();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=K();if(d(r)||!r.value)return s("Unable to resolve event log path");let o=Xe(r.value),i=await In({ownEventFileName:o});if(d(i))return S({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let a=be(process.cwd());if(d(a))return a;let c=Mt(a.value);if(d(c))return s(`Unable to load events. ${c.message}`);let u=Hn({eventLog:c.value,hasProject:!0});if(d(u))return s(`Unable to boot synced state. ${u.message}`);S({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:f.DEFAULT});let m=Cs(e);return d(m)?m:l("Synced",!0)}},{intent:M.Peek,mode:f.COMMAND_LINE,action:async()=>{let e=Se(v().breadCrumb,"BOARD");if(d(e))return e;let t=$e(process.cwd());if(d(t))throw new Error(t.message);let n=Mt(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=Q().commandMeta,i;if(o==="now"){let x=so();if(d(x))return x;let E=_t(r);return E.some(d)?s(E.map(A=>A.message).join(", ")):(S({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let x=v().eventLog.at(-2),E=Br(x);if(E===null)return s("No previous event to peek");i=E}else if(o==="next"){let x=v().unappliedEvents.at(0),E=Br(x);if(E===null)return s("No next event to peek");i=E}else{let x=wn(o);if(!x)return s("Invalid peek date");i=x.getTime()}let a=e.value.id,{appliedEvents:c,unappliedEvents:u}=$o(r,i),m=so();if(d(m))return m;let p=_t(c);if(p.some(d))return s(p.map(x=>x.message).join(", "));let g=v().nodes[a];return g?(D.navigate({currentNode:g,selectedIndex:0}),S({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),l("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:f.COMMAND_LINE,action:async()=>{let e=await ys();return d(e)?e:(S({mode:f.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,mode:f.COMMAND_LINE,action:async()=>(D.exit(),l("Exit successful",!0))},{intent:M.Edit,mode:f.COMMAND_LINE,action:(e,t)=>{if(t.modifier===He.DESCRIPTION)return Os();if(t.modifier===He.TITLE){let n=K();if(d(n))return s("Unable to resolve user ID");let{currentNode:r,selectedIndex:o}=v(),i=T(r.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let a=t.inputString.trim();return a?_({id:V(),action:"edit.title",payload:{id:i.id,name:a},...n.value}):s("Provide a new name")}return s("Unknown edit command")},onSuccess:()=>S({mode:f.DEFAULT})},{intent:M.Config,mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case X.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=L(),a=n||i,c=r??V();if(!a||!c)return s("Unable to resolve user name or id");let u=at({userName:a,userId:c,preferredEditor:o??""});return d(u)?u:(pe({userName:a,userId:c}),S({mode:f.DEFAULT}),l(`Username set to "${a}"`,null))}case X.EDITOR:{if(!n)return s("No editor provided");let r=at({preferredEditor:n});return d(r)?r:(pe({preferredEditor:n}),S({mode:f.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case X.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(pe({viewMode:n}),l(`View set to "${n}"`,null));case X.AUTOSYNC:return Gs();case X.SYNC_DEBOUNCE_MS:return Vs();default:return s("Unknown config command")}}}];var xl=new Set(["peek","filter","view-help"]),Ce=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=Q();if(!t)return s("No command to confirm");if(!e&&n===rt.Invalid)return s("Invalid command");let i=es(t);qi();let{readOnly:a}=v();if(a&&!xl.has(i))return Vt({status:Ue.Fail,message:"Command not available in readonly state",value:null});let c=Ys.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!c)return Vt({status:Ue.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return Vt({status:Ue.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Vt(u):(zi({addToHistory:!e}),c.onSuccess?.(),L().autoSync&&Ni(),u)};var Kn=[{intent:h.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move cancel"),Ce({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move start"),Ce({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:f.MOVE,action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"move confirm"),Ce({isForceExecutedBySystem:!0}))}],Vn=[{intent:h.MovePreviousItem,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move previous"),Ce({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveNextItem,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move next"),Ce({isForceExecutedBySystem:!0})):s("No pending move")}],Xs=[{intent:h.MoveToNextContainer,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move to-next"),Ce({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveToPreviousContainer,mode:f.MOVE,action:()=>Ve()?(S({mode:f.COMMAND_LINE}),$(()=>"move to-previous"),Ce({isForceExecutedBySystem:!0})):s("No pending move")}];var Js={[P.WORKSPACE]:[...Kn,...Vn],[P.BOARD]:[...Kn,...Vn],[P.SWIMLANE]:[...Kn,...Vn,...Xs],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Qs=[{intent:h.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>`${y.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>`${y.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(S({mode:f.COMMAND_LINE}),$(()=>""),l("Entering command line mode",null))},{intent:h.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=v();if(!O(e?.id??"")?.length){if(e?.title===Y.DESCRIPTION)return $(()=>y.EDIT+"description "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(e?.title===Y.ASSIGNEES)return $(()=>y.ASSIGN+" "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(e?.title===Y.TAGS)return $(()=>y.TAG+" "),S({mode:f.COMMAND_LINE}),l("Propose command",!0);if(t.title===Y.DESCRIPTION&&e?.context==="TEXT")return $(()=>y.EDIT+"description "),S({mode:f.COMMAND_LINE}),l("Propose command",!0)}return D.enterChildNode(),l("Entering context",null)}},{intent:h.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:f.DEFAULT,action:()=>(D.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(D.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:f.DEFAULT,action:()=>(D.navigateToNextContainer(),l("Navigating to next container",null))},{intent:h.Edit,mode:f.DEFAULT,action:()=>(S({mode:f.COMMAND_LINE}),$(()=>"edit"),Ce(),l("Fired command",!0))},{intent:h.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(pe({viewMode:"dense"}),l("View set",null))},{intent:h.SetViewWide,mode:f.DEFAULT,action:()=>(pe({viewMode:"wide"}),l("View set",null))}];var hl=500,Cl=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Zs=e=>{let t=Cl(e);t&&$(n=>(n+t).slice(0,hl))};var ea=[{intent:h.ViewHelp,mode:f.DEFAULT,action:()=>(S({mode:f.HELP}),l("Viewing help",null))},{intent:h.Exit,mode:f.HELP,action:()=>(S({mode:f.DEFAULT}),l("Exiting help",null))},{intent:h.Confirm,mode:f.COMMAND_LINE,action:()=>(Ce(),l("Executing command",null))},{intent:h.MoveCursorLeft,mode:f.COMMAND_LINE,action:()=>(Gr(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:f.COMMAND_LINE,action:()=>(Gr(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:f.COMMAND_LINE,action:()=>(qr("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:f.COMMAND_LINE,action:()=>(qr("right"),l("Moving cursor right of word",null))},{intent:h.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(S({mode:f.DEFAULT}),l("Exiting command line",null))},{intent:h.AutoCompleteCommand,mode:f.COMMAND_LINE,action:()=>($((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:f.COMMAND_LINE,action:(e,{sequence:t})=>(Zs(t??""),l("Capturing input",null))},{intent:h.EraseInput,mode:f.COMMAND_LINE,action:()=>(Vi(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:f.COMMAND_LINE,action:()=>(Gi(),l("Erasing input word",null))},{intent:h.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Yi(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Xi(),l("Getting next command from history",null))}];import Nl from"chalk";var Gn=": for command line",ta="q to exit",na=`${Nl.hex(N.accent)("m")} to confirm`,ao={[P.WORKSPACE]:[Gn],[P.BOARD]:[Gn],[P.BOARD+f.COMMAND_LINE]:[Gn],[P.SWIMLANE]:[Gn],[P.TICKET+f.HELP]:[ta],[P.SWIMLANE+f.HELP]:[ta],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+f.MOVE]:[na],[P.TICKET+f.MOVE]:[na]};var qn=e=>e.trim().toLocaleLowerCase(),El=(e,t)=>{let n=I.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Il=e=>{let{tags:t}=v(),n=I.getFieldByTitle(e,"Tags");return n?O(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},bl=e=>{let{contributors:t}=v(),n=I.getFieldByTitle(e,"Assignees");return n?O(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},ra=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return qn(e.title??"").includes(n);case"description":return qn(El(e.id,Y.DESCRIPTION)).includes(n);case"tag":return Il(e.id).map(qn).some(c=>c.includes(n));case"assignee":return bl(e.id).map(qn).some(c=>c.includes(n));default:return!0}};function oa(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var ia=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var zn,co,lo=new Set,sa=()=>{for(let e of lo)e()},Rl=e=>(lo.add(e),()=>lo.delete(e));function aa(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let c=o[t];if(!c)return s("Unable to derive state, currentNode not found");let u=oa(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,g=ao[p+n]??ao[p]??[],x=[...Qs,...Js[p]??[],...ea],E=ia(x),A=Al(o,i),R=A[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:c,breadCrumb:m,availableHints:g,availableActions:x,actionIndex:E,selectedNode:R,renderedChildrenIndex:A})}var v=()=>(zn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),zn);function jt(e){co=e;let t=be(process.cwd()),n=!1;if(!d(t)){let i=We(t.value);if(d(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:n},o=aa(r);return d(o)?o:(zn=o.value,sa(),l("State initialized",null))}function he(e){let t=v(),n=e(t),r=aa(n);return d(r)?s(r.message??"Unable to update state"):(zn=r.value,sa(),l("State updated",null))}var S=e=>he(t=>({...t,...e}));var G=()=>Sl(Rl,v,v),Al=(e,t)=>{let n={};for(let r of Object.values(e))ye(r)&&t.length>0&&!t.every(o=>ra(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,i)=>{let a=e[o.id],c=e[i.id];return!a||!c?0:a.rank.localeCompare(c.rank)});return n},T=e=>v()?.renderedChildrenIndex[e]??[],so=()=>co?jt(co):s("Cannot reset state: no initial workspace found");import{Box as Wl}from"ink";import po from"react";import Jt from"chalk";import{Box as uo,Text as da}from"ink";import Xt,{useEffect as wl,useMemo as Tl,useState as Ml}from"react";var ca=Jt.gray,Pl=Jt.inverse,kl=Jt.inverse.gray,Dl={hint:"",hints:[],overlap:0,remainder:""},ua=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},Fl=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=de(t);return{bg:r=>Jt.bgHex(n).black(r),bgCursor:r=>Jt.bgHex(n).inverse.black(r)}}return Wr(t)},Ll=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=ua({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,a=r.end+i;return e.slice(a,a+n.length)!==n?null:{start:a,end:a+n.length}},la=()=>({value:ce.value,cursorPosition:ce.cursorPosition,commandIsPending:ce.commandIsPending,autoCompletion:ce.commandMeta.autoCompletion??Dl,infoMessage:ce.commandMeta.infoMessage,validationStatus:ce.commandMeta.validity,command:ce.commandMeta.command,inputString:ce.commandMeta.inputString,modifier:ce.commandMeta.modifier}),Ol=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,ma=({width:e})=>{let[t,n]=Ml(la());wl(()=>{let g=()=>{let E=la();n(A=>Ol(A,E)?A:E)},x=Ki(g);return g(),()=>{x()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:c,command:u,modifier:m}=t,p=Tl(()=>{let g=Math.max(0,Math.min(o,r.length)),x=ua({value:r,command:u}),E=Ll({value:r,command:u,modifier:m}),A=u?Wr(u):null,R=Fl({command:u,modifier:m}),b=(q,re)=>{let ct=x&&re>=x.start&&re<x.end,en=E&&re>=E.start&&re<E.end;return ct&&A?A.fg(q):en&&R?R.bg(q):q},w=(q,re)=>{let ct=x&&re>=x.start&&re<x.end,en=E&&re>=E.start&&re<E.end;return ct&&A?A.fgCursor(q):en&&R?R.bgCursor(q):Pl(q)},U=r.slice(0,g),le=r[g]??" ",ne=g<r.length?r.slice(g+1):"",Zt=Array.from(U).map((q,re)=>b(q,re)).join(""),St=w(le,g),Rt=Array.from(ne).map((q,re)=>b(q,g+1+re)).join("");if(c.hint){let q=c.hint[c.overlap]??le;St=kl(q),Rt=ca(c.remainder.slice(1)+ne)}return ca(":")+Zt+St+Rt},[r,o,c,u,m]);return Xt.createElement(uo,{flexDirection:"column",justifyContent:"flex-start"},Xt.createElement(uo,{flexDirection:"column",paddingX:1,borderColor:N.secondary,borderStyle:"round",width:e},Xt.createElement(uo,null,Xt.createElement(da,null,p),i&&Xt.createElement(da,{wrap:"truncate",color:a?N.red:N.secondary2},` ${i} `))))};import pa from"chalk";import{Box as Bl,Text as mo}from"ink";import Yn from"react";var Ul=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),$l=(e,t)=>{let n=[],r=0;for(let o of e){let a=(n.length>0?" | ":"").length+o.length;if(r+a>t-4)break;n.push(o),r+=a}return n},fa=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=$l(t,e).join(" | "),o=pa.hex(N.secondary),i=pa.hex(N.secondary2),a=o(`\u256D${"\u2500".repeat(n)}\u256E`),c=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(Ul(` ${r} `,n))}${o("\u2502")}`;return Yn.createElement(Bl,{flexDirection:"column",width:e},Yn.createElement(mo,null,a),Yn.createElement(mo,null,u),Yn.createElement(mo,null,c))};var Xn=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let c=(r.length>0?" | ":"").length+i.length;if(o+c>e+2)break;r.push(i),o+=c}return po.createElement(Wl,null,t===f.COMMAND_LINE?po.createElement(ma,{width:e}):po.createElement(fa,{width:e,mode:t,availableHints:n}))};import{Box as It,Text as ga}from"ink";import Ge from"react";var va=({width:e})=>{let t=[...v().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),Ge.createElement(It,{flexDirection:"column",marginTop:3,borderColor:N.secondary,borderStyle:"round",width:e,minHeight:19},Ge.createElement(It,{flexDirection:"column",width:e},v().mode===f.HELP?t.map(([n,r],o)=>Ge.createElement(It,{paddingLeft:1,key:o,flexDirection:"row"},Ge.createElement(It,{key:o,flexDirection:"row",paddingBottom:o?0:1},Ge.createElement(It,{width:20,justifyContent:"flex-end"},Ge.createElement(ga,{color:o?N.accent:N.secondary},n)),Ge.createElement(It,{flexGrow:1,width:40,paddingLeft:2},Ge.createElement(ga,{color:o?N.primary:N.secondary},r))))):null))};import _l from"chalk";import{Box as Jn,Text as qe}from"ink";import Ne from"react";var ya=({width:e,height:t})=>Ne.createElement(Jn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},Ne.createElement(qe,{color:N.accent,bold:!0},"Initialize project"),Ne.createElement(qe,null,`This folder is not an ${_l.hex(N.accent)("epiq")} project yet.`),Ne.createElement(qe,{color:N.primary},"To start tracking issues here, we need to initialize a new"," ",Ne.createElement(qe,{color:N.primary,backgroundColor:N.secondary}," .epiq/project.json ")," ","file in this repository."),Ne.createElement(Jn,{marginTop:1,flexDirection:"column"},Ne.createElement(Jn,null,Ne.createElement(qe,{color:N.accent}," "),Ne.createElement(qe,{color:N.primary},"Type "),Ne.createElement(qe,{backgroundColor:N.secondary}," :init "))),Ne.createElement(Jn,{marginTop:1},Ne.createElement(qe,{color:N.secondary2},"(This will create the local epiq project files)")));import{Box as Qn,Text as Ae}from"ink";import Z from"react";var jl=({isDone:e,command:t,value:n})=>Z.createElement(Qn,null,Z.createElement(Ae,{color:N.accent,dimColor:e},e?" \u2714 ":" "),Z.createElement(Ae,{dimColor:e},"Type "),Z.createElement(Ae,{backgroundColor:N.secondary,dimColor:e}," "+t+" "),n!==void 0&&Z.createElement(Z.Fragment,null,Z.createElement(Ae,{dimColor:e}," "),Z.createElement(Ae,{color:N.secondary,dimColor:e},"<"+n+">"))),Hl=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function fo({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:a,isSetAutoSync:c}=_e(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:i,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:a,message:"Almost there. Configure auto sync."}],m=u.findIndex(g=>!g.done),p=m===-1?void 0:u[m];return Z.createElement(Qn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},Z.createElement(Ae,{color:N.accent,bold:!0},"Welcome! \u{1F539}"),Z.createElement(Ae,null,"Lets get you started - its a breeze."),Z.createElement(Ae,{color:N.secondary2},"And remember, you can always get help with"," ",Z.createElement(Ae,{color:N.accent},":help"),"."),p&&Z.createElement(Ae,{color:N.secondary2},p.message),Z.createElement(Qn,{flexDirection:"column"},u.map((g,x)=>m===-1||x<=m?Z.createElement(Qn,{key:g.key,marginBottom:1},Z.createElement(jl,{isDone:g.done,command:g.command,value:g.done?Hl(g.value):void 0})):null)))}import Sa from"chalk";import{Box as er,Text as ze}from"ink";import ee from"react";import{Box as go,Text as Kl}from"ink";import bt from"react";var Vl=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",xa=({width:e})=>{let{viewMode:t}=L(),{breadCrumb:n,currentNode:r,selectedIndex:o}=v(),i=O(r.id)[o],a=je(i?.id??r.id,"TICKET"),c=Ee(a)?a.value:void 0,u=c?.id?O(c.id):[],m=R=>{let b=u.find(w=>w.title===R);return b?O(b.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},p=m("Tags"),g=m("Assignees"),x=c?.parentNodeId?!kr(r.id,c?.parentNodeId)&&t==="dense":!1,E=n.map((R,b)=>{let w=b===n.length-1,U=O(R.id),le=w?U?.[o]?.title:void 0;return`${b?" / ":""}${R.title??""}${le?` \u25B8 ${le}`:""}`}).join(""),A=Vl(E,e);return bt.createElement(go,null,bt.createElement(Kl,{color:N.secondary2},A),x?p.map(R=>bt.createElement(go,{key:R,paddingLeft:2},bt.createElement(Nt,{id:R}))):null,x?g.map(R=>bt.createElement(go,{key:R,paddingLeft:2},bt.createElement(Ct,{id:R}))):null)};import{Box as Gl,Text as ha}from"ink";import Zn from"react";var ql=({filters:e})=>Zn.createElement(Gl,{columnGap:1},Zn.createElement(ha,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Zn.createElement(ha,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ca=Zn.memo(ql);var Na="0.5.0";import Ea from"chalk";import{Text as zl}from"ink";import Yl,{useEffect as Xl,useState as Jl}from"react";var Ql=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Ia=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Zl=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},eu=(e,t,n)=>{let r=Ia(e),o=Ia(t);return Zl({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},tu=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],a=e[Math.min(r+1,e.length-1)];return eu(i,a,o)};function ba({syncStatus:e}){let[t,n]=Jl(0);Xl(()=>{if(e.status!=="syncing"){n(0);return}let a=setInterval(()=>{n(c=>c+1)},50);return()=>clearInterval(a)},[e.status]);let r={synced:"synced ",outOfSync:"unsynced",syncing:"syncing "},i={synced:N.secondary2,outOfSync:N.yellow,syncing:tu(Ql,(Math.sin(t*.12)+1)/2)??""}[e.status];return Yl.createElement(zl,null,Ea.hex(i)("\u25CF")+Ea.dim(` ${r[e.status].padEnd(2)} `))}function tr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o,syncStatus:i}=G(),{userName:a,preferredEditor:c}=L(),u=56,m=process.stdout.columns-u-8,p=r.at(-1)?.id,g=Mn(p??""),x=Ee(g)?Li(g.value):"INVALID DATE";return ee.createElement(er,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?ee.createElement(ze,null," "):ee.createElement(er,{paddingLeft:1},e.length>0?ee.createElement(Ca,{filters:e}):ee.createElement(xa,{width:m})),n==="live"?ee.createElement(er,{columnGap:1,paddingRight:2,"max-width":u,overflow:"hidden",justifyContent:"flex-end"},ee.createElement(ba,{syncStatus:i}),ee.createElement(ze,{dimColor:!0,color:N.secondary2},Na+" "),ee.createElement(Ra,{icon:"@",value:a}),ee.createElement(Ra,{icon:"\u276F",value:c})):"",n==="peek"?ee.createElement(er,{paddingLeft:1},ee.createElement(ze,{backgroundColor:N.yellow}," Readonly "),ee.createElement(ze,{color:N.yellow}," "+o.length+" edits ago at "),ee.createElement(ze,{backgroundColor:N.yellow,color:N.accent}," "+x+" "),ee.createElement(ze,{color:N.yellow},". Resume with "),ee.createElement(ze,{backgroundColor:N.yellow}," :peek now ")):"")}function Ra({icon:e,value:t}){return ee.createElement(ze,null,Sa.dim(e)+Sa.hex(N.accent)(` ${t??"-"} `))}import{Box as nu,Text as ru}from"ink";import Qt from"react";import{Box as nr,Text as vo}from"ink";import Ye from"react";function yo(){let e=G(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?T(t?.id):[];return Ye.createElement(nr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:N.secondary,width:i},Ye.createElement(nr,{padding:1,paddingTop:0,paddingBottom:0},Ye.createElement(vo,null,"Select a board:")),Ye.createElement(nr,{padding:1,flexDirection:"column"},a.map((c,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,g=T(c.id).flatMap(({id:x})=>O(x)).length;return Ye.createElement(nr,{key:c.id??u},Ye.createElement(vo,{color:m?N.accent:N.secondary2},Ye.createElement(me,{isSelected:m})),Ye.createElement(vo,{color:m?N.accent:N.secondary2},c.title," (",g," issues)",c.readonly?" \u{1F512}":""))})))}var ou=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:c}=G(),u=n.find(({context:x})=>x==="BOARD"),g=i-1-3;return Qt.createElement(nu,{flexDirection:"row"},e.context==="WORKSPACE"?Qt.createElement(yo,null):u?Qt.createElement($n,{height:g,width:a,swimlanes:(c[u.id]??[]).filter(x=>x!==void 0&<(x)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Qt.createElement(ru,null))},Aa=Qt.memo(ou);function xo({width:e,height:t}){let n=G(),r=n.filters;if(n.mode===f.HELP)return te.createElement(dt,{flexDirection:"column"},te.createElement(va,{width:e}));let{isSetupDone:o}=_e(),i=!o,a=o&&!n.hasProject;if(i)return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{hideBreadCrumb:!0,filters:r}),te.createElement(fo,{height:t,width:e})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(a)return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{hideBreadCrumb:!0,filters:r}),te.createElement(ya,{height:t,width:e})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));let c=Se(v().breadCrumb??[],"BOARD");if(Ee(c)){let u=c.value.id,m=T(u).length,p=3,g=Math.floor(e/p),x=Math.floor(e/Math.max(m,1));e=Math.min(x,g)*Math.max(m,p)}return te.createElement(dt,{flexDirection:"column"},te.createElement(dt,{flexDirection:"column"},te.createElement(tr,{filters:r}),te.createElement(Aa,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:L().viewMode??"dense",mode:n.mode})),te.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import iu from"readline";var rr,or,we,su=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),wa=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Zi(e,n);if(!o||r&&!su.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},au=()=>async function(t,n){n.name!=="escape"&&(we&&(clearTimeout(we),we=void 0),await wa(n))},du=()=>async function(t){if(t.length===1&&t[0]===27){we&&clearTimeout(we),we=setTimeout(()=>{wa({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),we=void 0},25);return}we&&(clearTimeout(we),we=void 0)};function Ta(){rr&&process.stdin.removeListener("keypress",rr),or&&process.stdin.removeListener("data",or),rr=au(),or=du(),iu.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",or),process.stdin.on("keypress",rr)}lu(`${ho.bold("Epiq CLI")}
|
|
59
60
|
|
|
60
|
-
${
|
|
61
|
-
${
|
|
61
|
+
${ho.dim("Boot in directory:")}
|
|
62
|
+
${ho.cyan("$ epiq")}
|
|
62
63
|
|
|
63
|
-
`,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var
|
|
64
|
+
`,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var Ma=process.stdout.columns||120,Pa=process.stdout.rows||20,ir=null,mu=e=>{if(!ir){ir=cu(e);return}ir.rerender(e)},ka=()=>{mu(uu.createElement(xo,{width:Ma,height:Pa}))},pu=()=>{let e=be(process.cwd());return d(e)?{hasProject:!1,epiqRootDir:null,events:[]}:{hasProject:!0,epiqRootDir:e.value,events:[]}};async function fu(){let e=Ts();d(e)||pe(e.value);let t=pu();if(t.hasProject){await vi();let r=Mt(t.epiqRootDir);d(r)||(t.events=r.value)}let n=Hn({hasProject:t.hasProject,eventLog:t.events});d(n)&&logger.info(`Failed to boot state: ${n.message}`),S({hasProject:t.hasProject}),ka(),Ta()}process.stdout.on("resize",()=>{Ma=process.stdout.columns||120,Pa=process.stdout.rows||20,ir&&ka()});(async()=>(console.clear(),await fu()))();
|