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