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