epiq 1.2.1 → 1.2.3
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/gui/main.js +210 -167
- package/dist/index.js +52 -52
- package/dist/mcp.js +43 -43
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,66 +1,66 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),l("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var
|
|
4
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
import qt from"chalk";import{render as gv}from"ink";import vv from"meow";import yv from"react";import rg from"chalk";var Rt={Success:"success",Fail:"fail"},a=e=>({status:Rt.Fail,message:e,value:null}),l=(e,t)=>({status:Rt.Success,message:e,value:t}),d=e=>e.status==="fail",oe=e=>e.status==="success";import{spawn as Wl}from"node:child_process";import Yo from"node:process";var hi=e=>{let t=Yo.platform==="darwin"?"open":Yo.platform==="win32"?"cmd":"xdg-open",n=Yo.platform==="win32"?["/c","start","",e]:[e];Wl(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Yf}from"node:fs/promises";import Xf from"node:http";import un from"node:path";import{fileURLToPath as Jf}from"node:url";import{decodeTime as Kf,ulid as Ce}from"ulid";import ss from"node:fs";import tu from"node:os";import tt from"node:path";import Bn from"node:fs";import{ulid as Vl}from"ulid";import{z as br}from"zod";import Dn from"node:fs";import gt from"node:path";var Mv=process.env.IS_LOCAL==="true",vt=".epiq",We=".epiq-global",yr="events",Hl="project.json",hr=e=>gt.join(e,vt),xr=e=>gt.join(hr(e),Hl),Fn=e=>gt.join(hr(e),yr),xi=e=>gt.join(e,vt),jl=e=>{let t=gt.join(e,vt);return Dn.existsSync(t)&&Dn.statSync(t).isDirectory()},Xo=e=>{let t=xr(e);return Dn.existsSync(t)&&Dn.statSync(t).isFile()},Ir=e=>{let t=gt.resolve(e);for(;;){if(jl(t))return l("Resolved closest .epiq root",t);let n=gt.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Je=e=>{let t=gt.resolve(e);for(;;){if(Xo(t))return l("Resolved closest epiq project root",t);let n=gt.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},Ii=e=>{let t=Fn(e);try{return Dn.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Qe=async()=>{let e=await Ze(process.cwd());if(d(e))return e;let t=Pe({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)};var Gl="__epiq_state__",zl=br.object({projectId:br.string().min(1),stateBranch:br.string().min(1),createdAt:br.iso.datetime()}),mn=()=>({projectId:Vl(),stateBranch:Gl,createdAt:new Date().toISOString()}),At=e=>{let t=xr(e);if(!Bn.existsSync(t))return a("Missing .epiq/project.json");try{let n=Bn.readFileSync(t,"utf8"),r=JSON.parse(n),o=zl.safeParse(r);return o.success?l("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},bi=e=>{let t=At(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},Ci=({repoRoot:e,fileContents:t})=>{let n=hr(e),r=xr(e);try{if(Bn.mkdirSync(n,{recursive:!0}),Bn.existsSync(r)){let o=At(e);return d(o)?a(o.message):l("Project already initialized",null)}return Bn.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),l("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var Jo=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(d(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import Un from"fs";import ts from"path";import Kl from"util";var Ei=1e3,ql=50,Qo=0,Si=()=>process.env.EPIQ_MCP==="true",Ni=()=>{let e=process.cwd(),t=Ir(e);return d(t)?Si()?ts.join(process.cwd(),".epiq-mcp.log"):void 0:ts.join(t.value,vt,"log","epiq.log")};function Yl(){let e=Ni();if(!e||!Un.existsSync(e))return;let n=Un.readFileSync(e,"utf8").split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=Ei)return;let r=n.slice(-Ei).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))},
|
|
9
|
-
`)))}),o.on("close",p=>{let
|
|
10
|
-
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:
|
|
11
|
-
${n.message}`);let r=await
|
|
12
|
-
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},
|
|
13
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
14
|
-
${o.message}`);let s=await
|
|
15
|
-
${s.message}`):l("Pulled with rebase",!0)},
|
|
16
|
-
`+e.message);let t
|
|
17
|
-
`+t.message):l("Ensured epiq storage",!0)},
|
|
6
|
+
`;Un.writeFileSync(e,r,"utf8")}function Zo(e,t,n=!1){let r=Ni();if(!r)return;let o=Kl.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
7
|
+
`;Un.mkdirSync(ts.dirname(r),{recursive:!0}),Un.appendFileSync(r,c,"utf8"),Qo++,Qo>=ql&&(Qo=0,Yl())}var es=()=>Si()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ie={info(...e){let t=es();(t==="info"||t==="debug")&&Zo("[Info]",e,!1)},debug(...e){es()==="debug"&&Zo("[Debug]",e,!0)},error(...e){let t=es();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Zo("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ie;import{spawn as Xl}from"node:child_process";import Cr from"node:fs";import On from"node:path";var ae={stage:({cwd:e,pathspec:t})=>O({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>O({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>O({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>O({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>O({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 O({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>O({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>O({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>O({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>O({args:["worktree","prune"],cwd:e})};var pn=e=>{let t=Je(e);if(d(t))return a("Unable to resolve epiq project root");let n=At(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},He="origin";var Ri=1e4,Jl={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ai=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Cr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(a(p));return}let o=Xl("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Jl}),s=!1,i="",c="",u=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Ri}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))},Ri);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{i+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(n){u({stdout:i,stderr:p.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
|
|
9
|
+
`)))}),o.on("close",p=>{let g=p??1;if(n){u({stdout:i,stderr:c,exitCode:g});return}if(g!==0){u(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
10
|
+
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:g}))})}),O=({args:e,cwd:t})=>Ai({args:e,cwd:t,allowFail:!1}),et=({args:e,cwd:t})=>Ai({args:e,cwd:t,allowFail:!0}),fn=async({cwd:e,message:t})=>{let n=await ae.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
|
|
11
|
+
${n.message}`);let r=await O({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
|
|
12
|
+
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},Ql=async e=>{let t=await O({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return l("Resolved git dir",On.isAbsolute(n)?n:On.resolve(e,n))},Zl=async e=>{let t=await Ql(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Cr.existsSync(On.join(n,s)))return l("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(Cr.existsSync(On.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},Er=async e=>{let t=await Zl(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},ns=async({repoRoot:e})=>{let n=(await et({args:["remote","get-url",He],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},Sr=async({repoRoot:e,branch:t})=>{let n=await et({args:["ls-remote","--heads",He,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${He}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},Nr=async({repoRoot:e,branch:t})=>{let n=await et({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},_n=e=>{try{return Cr.realpathSync.native(e)}catch{return On.resolve(e)}},Ti=async({repoRoot:e,worktreeRoot:t})=>{let n=await O({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=_n(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(_n).includes(r);return l("Checked worktree registration",o)},rs=async e=>{let t=await et({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Rr=async e=>{let t=await O({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},wi=async e=>{let t=await O({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Mi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),eu=async e=>(await et({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1);var os=async({cwd:e,branch:t})=>{let n=await Sr({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return l("Remote branch missing, skipped pull",!1);let r=await eu(e);if(d(r))return a(r.message);let o=await ae.fetch({cwd:e,remote:He,branch:t});if(d(o))return a(`Failed to fetch ${t}
|
|
14
|
+
${o.message}`);let s=await ae.pullRebase({cwd:e,remote:He,branch:t});return d(s)?a(`Failed during pull --rebase
|
|
15
|
+
${s.message}`):l("Pulled with rebase",!0)},Pi=async e=>{let t=await et({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?l("No staged changes",!1):t.exitCode===1?l("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var Li=async e=>{let t=await Rr(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Di="4b825dc642cb6eb9a060e54bf8d69288fbee4904",is=e=>tt.join(vt,yr,e),Fi=()=>tt.join(tu.homedir(),We),Ar=()=>tt.join(Fi(),"worktrees"),Pe=({repoRoot:e})=>{let t=bi(e);return d(t)?a(t.message):l("Resolved state branch root",tt.join(Ar(),t.value))},nu=e=>tt.join(e,vt),ki=e=>tt.join(nu(e),yr);var $n=e=>{try{return ss.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Tr=()=>{let e=$n(Fi());if(d(e))return a(`Ensure epiq home failed.
|
|
16
|
+
`+e.message);let t=$n(Ar());return d(t)?a(`Ensure worktrees dir failed.
|
|
17
|
+
`+t.message):l("Ensured epiq storage",!0)},Bi=e=>{ss.existsSync(e)&&(ie.debug("[sync] remove path",e),ss.rmSync(e,{recursive:!0,force:!0}))};var Ui=(e,t)=>{for(let n of[ki(e),ki(t)]){let r=$n(n);if(d(r))return a(r.message)}return l("Ensured state branch",void 0)},Oi=async e=>{let t=await O({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
|
|
18
18
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
19
|
-
`).filter(Boolean).filter(i=>i!==
|
|
20
|
-
${o.message}`);let s=await
|
|
21
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await
|
|
22
|
-
${o.message}`):l("Created state branch",!0)},
|
|
23
|
-
`+n.message);let r=n.value,o=r?await
|
|
24
|
-
`+o.message);let s=o.value;if(r&&s){let c=await
|
|
25
|
-
${c.message}`)}let i=await
|
|
26
|
-
`+i.message);if(i.value)return l("Local state branch already exists",!1);if(s){let c=await
|
|
27
|
-
${c.message}`):l("Created local state branch from remote",!0)}return
|
|
28
|
-
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},
|
|
29
|
-
`+r.message);
|
|
30
|
-
${o.message}`):l("Created state branch worktree",!0)},
|
|
31
|
-
${u.message}`)}if(s&&!
|
|
32
|
-
${u.message}`)}let i=await
|
|
33
|
-
${u.message}`)}return
|
|
34
|
-
${o.message}`):l("Checked out state branch",!0)},
|
|
35
|
-
${c.message}`);let u=await
|
|
36
|
-
${u.message}`):l("Configured state branch upstream",!0)},
|
|
37
|
-
${o.message}`):l("Staged state branch event file",void 0)},
|
|
38
|
-
`+n.message):
|
|
39
|
-
${s.message}`):l("Pushed state branch",!0)},Bi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=cn(e);if(d(o))return o;let s=o.value,i=[Cr(),await Zl({repoRoot:e,stateBranchName:s}),await Gt({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await nu({stateBranchRoot:t,stateBranchName:s}),await Li(t),n?await ru({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as ou}from"ws";var Sr=new Set,Ui=e=>{Sr.add(e),e.on("close",()=>{Sr.delete(e)}),e.on("error",()=>{Sr.delete(e)})},zt=e=>{let t=JSON.stringify(e);for(let n of Sr)n.readyState===ou.OPEN&&n.send(t)};import{useSyncExternalStore as kf}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function rs(e){return e.context===P.WORKSPACE}function w(e){return e.context===P.TICKET}function St(e){return e.context===P.TEXT}function Qe(e){return e.context===P.FIELD}function Bn(e){return e.context===P.FIELD_LIST}var Nt=e=>e.context===P.SWIMLANE,Nr=e=>e.context===P.BOARD,Un=e=>e.context===P.COMMENT;var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Oi=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",_i=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",$i=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Wi=(e,t)=>{if(_i(e,e.sequence))return h.MoveCursorLeftOfWord;if($i(e,e.sequence))return h.MoveCursorRightOfWord;if(Oi(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},Hi=(e,t)=>{if(_i(e,e.sequence))return h.MoveCursorLeftOfWord;if($i(e,e.sequence))return h.MoveCursorRightOfWord;if(Oi(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Rr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var mn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Rt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),ji=e=>e.charAt(0).toUpperCase()+e.slice(1);var Vi=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Gi=(e,t)=>t?e.get(t)??[]:[];var zi=new WeakMap,su=e=>{let t=zi.get(e);return t||(t=Vi(e),zi.set(e,t)),t};var Ki=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Gi(su(e),r).filter(s=>Rr(r,s)>=n)};var iu={hint:"",hints:[],overlap:0,remainder:""},qi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return iu;let o=Ki({wordList:r,inputToMatch:e,overlapThreshold:1});return au(t,o)},au=(e,t)=>{let n=t[0]??"",r=Rr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),v=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:v}};import{useSyncExternalStore as du}from"react";var On={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},os=new Set,cu=()=>{for(let e of os)e()},H=()=>On,Yi=()=>du(e=>(os.add(e),()=>{os.delete(e)}),()=>On),_e=e=>(On={...On,...e},cu(),On);import{ulid as mu}from"ulid";var pn=24n,lu=pn*4n,Ze=(1n<<lu)-1n,uu=/^[0-9a-f]+$/;function Xi(e){return!e||!uu.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function $e(e,t=pn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Se(e,t){if(!e&&!t)return $e(Ze/2n,pn);let n=e?Xi(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Xi(t):l("Resolved upper bound",Ze);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return $e(Ze/2n,pn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):$e(i,pn)}function Ji(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Ze*BigInt(r+1)/(t+1n),s=$e(o,pn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var ss=(e,t)=>{let n=z(e),r=Ji(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:mu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as um}from"ulid";var pt=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},is=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Kt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),b={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){fe(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!w(t))return a("Can only comment on issues");let n=fe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!w(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=fe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=fe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return f().comments?.[e]},getCommentsByIssue(e){return Object.values(f().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return a("Edit target node not found");let o=Kt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=Kt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return z(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=Kt(o,"move");if(i)return i;if(is(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=f(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of z(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(C({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=fe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=fe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=fe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=fe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return z(e)}};var se={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"};var et=e=>e.slice(-7).toUpperCase(),Qi=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?et(e).includes(n):!0};var Q={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:et(e)},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:et(e)},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import qt from"chalk";import sa from"string-width";import{decodeTime as hu}from"ulid";import gn from"chalk";var ge={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:ge.cyan,accent2:ge.magenta,primary:ge.white,secondary:ge.grayDark,secondary2:ge.grayLight,gray:ge.gray,green:ge.green,yellow:ge.yellow,red:ge.red};var E={red:ge.red,yellow:ge.yellow,green:ge.green,blue:ge.blue,magenta:ge.magenta,cyan:ge.cyan},fn={urgent:E.red,critical:E.red,important:E.red,blocker:E.red,asap:E.red,immediate:E.red,fail:E.red,failure:E.red,broken:E.red,bug:E.red,error:E.red,incident:E.red,outage:E.red,production:E.red,crash:E.red,security:E.red,warning:E.yellow,warn:E.yellow,risky:E.yellow,risk:E.yellow,attention:E.yellow,pending:E.yellow,review:E.yellow,"needs-review":E.yellow,qa:E.yellow,testing:E.yellow,test:E.yellow,validate:E.yellow,verification:E.yellow,staging:E.yellow,check:E.yellow,"follow-up":E.yellow,followup:E.yellow,waiting:E.yellow,blocked:E.yellow,hold:E.yellow,done:E.green,complete:E.green,completed:E.green,success:E.green,ok:E.green,stable:E.green,resolved:E.green,fixed:E.green,closed:E.green,merged:E.green,released:E.green,deployed:E.green,approved:E.green,verified:E.green,working:E.green,healthy:E.green,pass:E.green,passing:E.green,info:E.blue,information:E.blue,note:E.blue,docs:E.blue,documentation:E.blue,doc:E.blue,guide:E.blue,help:E.blue,explanation:E.blue,detail:E.blue,details:E.blue,context:E.blue,design:E.blue,discussion:E.blue,proposal:E.blue,idea:E.blue,feature:E.magenta,enhancement:E.magenta,improvement:E.magenta,refactor:E.magenta,refactoring:E.magenta,cleanup:E.magenta,optimize:E.magenta,optimization:E.magenta,perf:E.magenta,performance:E.magenta,upgrade:E.magenta,migration:E.magenta,modernize:E.magenta,debt:E.magenta,todo:E.cyan,next:E.cyan,planned:E.cyan,plan:E.cyan,future:E.cyan,backlog:E.cyan,investigate:E.cyan,explore:E.cyan,prototype:E.cyan};var ds={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Zi=(e,t,n)=>Math.max(t,Math.min(n,e)),as=(e,t,n)=>e+(t-e)*n,ea=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},pu=e=>e.toLowerCase().trim(),fu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let v=o-s/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},ta=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var gu=(e,t,n)=>{let r=Zi(n,0,1);return[Math.round(as(e[0],t[0],r)),Math.round(as(e[1],t[1],r)),Math.round(as(e[2],t[2],r))]};var vu=(e,t,n)=>gu(e,t,n),_n=e=>{let n=ea(e)%360,r=fu(n,ds.stringColor.saturation,ds.stringColor.lightness);return ta(r)},ie=(e,t=fn)=>{let n=pu(e);return n&&t[n]?t[n]:_n(n)};var na=e=>{let t=ds.gradient.stops,n=Zi(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,s=Math.min(Math.floor(o),r-1),i=o-s;return vu(t[s],t[s+1],i)},Ar=e=>ta(na(e)),Tr=e=>ea(e.toLowerCase().trim())/4294967295,ra=e=>{let t=Tr(e);return na(t)},yu=e=>{let[t,n,r]=ra(e);return{normal:o=>gn.bgRgb(t,n,r).black(o),cursor:o=>gn.bgRgb(t,n,r).white.bold(o)}},cs=e=>{let[t,n,r]=ra(e);return{fg:o=>gn.rgb(t,n,r)(o),fgCursor:o=>gn.rgb(t,n,r).inverse(o),bg:o=>gn.bgRgb(t,n,r).black(o),bgCursor:o=>gn.bgRgb(t,n,r).white.bold(o)}},wr=e=>yu(e).normal(` ${e} `);import{decodeTime as oa}from"ulid";var Mr=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 s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Pr=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Lr=e=>{try{return l("Decoded date",new Date(oa(e)))}catch(t){return a("Decoding failed + "+t.message)}},vn=e=>{if(!e?.id)return null;try{return oa(e.id)}catch{return null}};var xu=(e,t)=>e+" ".repeat(Math.max(0,t-sa(e))),Iu=(e,t)=>" ".repeat(Math.max(0,t-sa(e)))+e,ia=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),bu=(e,t)=>t?e<t?"up":e>t?"down":null:null,Cu=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?qt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=bu(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Eu=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?qt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?qt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?qt.hex(ie(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?qt.hex(ie(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""}},Su=e=>{let t=Mr(hu(e));return qt.gray(Iu(t,8))},Nu=12,Ru=e=>xu(`${e}`,Nu),Au=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?t.name:""}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}"`:"";case"move.node":{let t=b.getNode(e.payload.parent);return t?`to ${t.title}`:""}default:return""}},aa=e=>[ia(e.action),Au(e)].filter(Boolean).join(" "),da=(e,t)=>{let n=Su(e.id),r=Ru(e.userName),o=qt.dim("\u203A"),s=e.action==="move.node"?Cu(e,t):[ia(e.action),Eu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as Tu}from"node:crypto";var wu="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Mu=e=>{let t=Tu("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=wu[Number(n>>s&31n)]}return r},Ne=(e,t)=>Mu(`${e}:virtual:${t}`);var Pu=e=>Ne(e,"comments"),Lu=e=>Ne(e,"description"),ku=e=>Ne(e,"assignees"),Du=e=>Ne(e,"tags"),Fu=e=>Ne(e,"history"),ls=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=b.getNode(e);if(!c){let p=b.createNode({...Q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Qe(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=b.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},ca=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=b.getNode(e);if(!i){let m=b.createNode({...Q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Bn(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=b.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},la=e=>{let t=$e(Ze/4n),n=$e(Ze/2n),r=$e(Ze*3n/4n),o=$e(Ze*7n/8n),s=$e(Ze*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;let i=ls({id:Lu(e.id),name:se.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let c=ca({id:ku(e.id),name:se.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let u=ca({id:Du(e.id),name:se.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(u))return u;let m=ls({id:Pu(e.id),name:se.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(m))return m;let p=ls({id:Fu(e.id),name:se.HISTORY,parentNodeId:e.id,rank:s.value,value:Bu(e),readonly:!0,childRenderAxis:"vertical"});return d(p)?p:l("Ticket virtual nodes materialized",void 0)},Bu=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>da(r,n.get(r.action)??[])).join(`
|
|
40
|
-
`)};var
|
|
41
|
-
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=
|
|
42
|
-
`,"utf8"),l("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function
|
|
19
|
+
`).filter(Boolean).filter(i=>i!==vt);if(r.length===0)return l("State branch is storage-only",!1);let o=await O({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
|
|
20
|
+
${o.message}`);let s=await fn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):l("Cleaned storage branch",!0)},Ze=Jo(async(e=process.cwd())=>{let t=await O({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>tt.resolve(e)),xy=Jo(async e=>{let t=await O({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=tt.isAbsolute(n)?n:tt.join(e,n);return l("Resolved git dir",r)},e=>tt.resolve(e));import gn from"node:fs";import as from"node:path";var $i=async e=>{if((await et({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);ie.info("Creating initial commit");let n=await ae.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):l("Created initial commit",!0)},_i=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",ru=async e=>{let t=await Rr(e);if(d(t))return a(t.message);let n=await wi(e);return d(n)?a(n.message):l("Built sync commit message",`[sync|branch:${_i(t.value)}:sha:${_i(n.value)}]`)},ds=async({repoRoot:e,stateBranchName:t})=>{ie.info(`Creating ${t}`);let n=await O({args:["commit-tree",Di,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
21
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await O({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
|
|
22
|
+
${o.message}`):l("Created state branch",!0)},ou=async({repoRoot:e,stateBranchName:t})=>{let n=await ns({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
|
|
23
|
+
`+n.message);let r=n.value,o=r?await Sr({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
|
|
24
|
+
`+o.message);let s=o.value;if(r&&s){let c=await ae.fetch({cwd:e,remote:He,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
|
|
25
|
+
${c.message}`)}let i=await Nr({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
|
|
26
|
+
`+i.message);if(i.value)return l("Local state branch already exists",!1);if(s){let c=await O({args:["branch","--track",t,`${He}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
|
|
27
|
+
${c.message}`):l("Created local state branch from remote",!0)}return ds({repoRoot:e,stateBranchName:t})},su=async({repoRoot:e,branch:t})=>{let n=await O({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
28
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},iu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=$n(as.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
29
|
+
`+r.message);gn.existsSync(t)&&!gn.existsSync(as.join(t,".git"))&&(ie.info("Removing broken state branch worktree path"),Bi(t)),ie.info("Creating state branch worktree");let o=await ae.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
|
|
30
|
+
${o.message}`):l("Created state branch worktree",!0)},Yt=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await su({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=_n(t),s=r.value?_n(r.value):null;if(s&&s===o&&gn.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==o){ie.info("Moving state branch worktree to expected location");let u=await ae.worktreeRemove({cwd:e,worktreeRoot:s});if(d(u))return a(`Failed to remove existing state branch worktree
|
|
31
|
+
${u.message}`)}if(s&&!gn.existsSync(s)){ie.info("Pruning stale state branch worktree");let u=await ae.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
32
|
+
${u.message}`)}let i=await Ti({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=gn.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){ie.info("Pruning missing registered state branch worktree");let u=await ae.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
33
|
+
${u.message}`)}return iu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},au=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Rr(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await et({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ie.info("Aborted stale state branch rebase");let o=await ae.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
|
|
34
|
+
${o.message}`):l("Checked out state branch",!0)},du=async({repoRoot:e,stateBranchRoot:t})=>{let n=await rs(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await ns({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=pn(e);if(d(o))return o;let s=o.value,i=await Sr({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);ie.info(`Configuring ${s} upstream`);let c=await ae.fetch({cwd:t,remote:He,branch:s});if(d(c))return a(`Failed to fetch ${s}
|
|
35
|
+
${c.message}`);let u=await ae.setUpstream({cwd:t,branch:s,upstream:`${He}/${s}`});return d(u)?a(`Failed to set state branch upstream
|
|
36
|
+
${u.message}`):l("Configured state branch upstream",!0)},wr=async({stateBranchRoot:e,eventFileName:t})=>{let n=is(t),r=as.join(e,n);if(!gn.existsSync(r))return l("No event file to stage",void 0);let o=await ae.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
|
|
37
|
+
${o.message}`):l("Staged state branch event file",void 0)},Wi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ru(e);return d(n)?a(`Create state branch sync commit failed
|
|
38
|
+
`+n.message):fn({cwd:t,message:n.value})},Wn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await rs(t);if(d(n))return a(n.message);let r=pn(e);if(d(r))return r;let o=r.value,s=n.value?await ae.push({cwd:t}):await ae.push({cwd:t,remote:He,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
|
|
39
|
+
${s.message}`):l("Pushed state branch",!0)},Hi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=pn(e);if(d(o))return o;let s=o.value,i=[Tr(),await ou({repoRoot:e,stateBranchName:s}),await Yt({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await au({stateBranchRoot:t,stateBranchName:s}),await Oi(t),n?await du({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as cu}from"ws";var Mr=new Set,ji=e=>{Mr.add(e),e.on("close",()=>{Mr.delete(e)}),e.on("error",()=>{Mr.delete(e)})},Xt=e=>{let t=JSON.stringify(e);for(let n of Mr)n.readyState===cu.OPEN&&n.send(t)};import{useSyncExternalStore as Hf}from"react";var L={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function cs(e){return e.context===L.WORKSPACE}function A(e){return e.context===L.TICKET}function Tt(e){return e.context===L.TEXT}function nt(e){return e.context===L.FIELD}function Hn(e){return e.context===L.FIELD_LIST}var wt=e=>e.context===L.SWIMLANE,Pr=e=>e.context===L.BOARD,jn=e=>e.context===L.COMMENT;var v={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Vi=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Gi=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",zi=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Ki=(e,t)=>{if(Gi(e,e.sequence))return h.MoveCursorLeftOfWord;if(zi(e,e.sequence))return h.MoveCursorRightOfWord;if(Vi(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},qi=(e,t)=>{if(Gi(e,e.sequence))return h.MoveCursorLeftOfWord;if(zi(e,e.sequence))return h.MoveCursorRightOfWord;if(Vi(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Lr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Jt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",yt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Yi=e=>e.charAt(0).toUpperCase()+e.slice(1);var Xi=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Ji=(e,t)=>t?e.get(t)??[]:[];var Qi=new WeakMap,lu=e=>{let t=Qi.get(e);return t||(t=Xi(e),Qi.set(e,t)),t};var Zi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ji(lu(e),r).filter(s=>Lr(r,s)>=n)};var uu={hint:"",hints:[],overlap:0,remainder:""},ea=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return uu;let o=Zi({wordList:r,inputToMatch:e,overlapThreshold:1});return mu(t,o)},mu=(e,t)=>{let n=t[0]??"",r=Lr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),g=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:g}};import{useSyncExternalStore as pu}from"react";var Vn={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},ls=new Set,fu=()=>{for(let e of ls)e()},G=()=>Vn,ta=()=>pu(e=>(ls.add(e),()=>{ls.delete(e)}),()=>Vn),je=e=>(Vn={...Vn,...e},fu(),Vn);import{ulid as yu}from"ulid";var vn=24n,gu=vn*4n,rt=(1n<<gu)-1n,vu=/^[0-9a-f]+$/;function na(e){return!e||!vu.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Ve(e,t=vn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ae(e,t){if(!e&&!t)return Ve(rt/2n,vn);let n=e?na(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?na(t):l("Resolved upper bound",rt);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return Ve(rt/2n,vn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):Ve(i,vn)}function ra(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=rt*BigInt(r+1)/(t+1n),s=Ve(o,vn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var us=(e,t)=>{let n=z(e),r=ra(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:yu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as vm}from"ulid";var ht=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},ms=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Qt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),I={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=he(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){he(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!A(t))return a("Can only comment on issues");let n=he(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!A(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=he(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=he(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return f().comments?.[e]},getCommentsByIssue(e){return Object.values(f().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return a("Edit target node not found");let o=Qt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=Qt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return z(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=Qt(o,"move");if(i)return i;if(ms(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=f(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of z(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(b({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=he(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=Qt(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=Qt(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=Qt(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=Qt(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=he(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=he(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return z(e)}};var Q={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"};var Te=e=>e.slice(-7).toUpperCase(),oa=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?Te(e).includes(n):!0};var Z={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:L.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:Te(e)},context:L.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:L.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:Te(e)},context:L.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:L.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Zt from"chalk";import ua from"string-width";import{decodeTime as Eu}from"ulid";import hn from"chalk";var xe={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:xe.cyan,accent2:xe.magenta,primary:xe.white,secondary:xe.grayDark,secondary2:xe.grayLight,gray:xe.gray,green:xe.green,yellow:xe.yellow,red:xe.red};var E={red:xe.red,yellow:xe.yellow,green:xe.green,blue:xe.blue,magenta:xe.magenta,cyan:xe.cyan},yn={urgent:E.red,critical:E.red,important:E.red,blocker:E.red,asap:E.red,immediate:E.red,fail:E.red,failure:E.red,broken:E.red,bug:E.red,error:E.red,incident:E.red,outage:E.red,production:E.red,crash:E.red,security:E.red,warning:E.yellow,warn:E.yellow,risky:E.yellow,risk:E.yellow,attention:E.yellow,pending:E.yellow,review:E.yellow,"needs-review":E.yellow,qa:E.yellow,testing:E.yellow,test:E.yellow,validate:E.yellow,verification:E.yellow,staging:E.yellow,check:E.yellow,"follow-up":E.yellow,followup:E.yellow,waiting:E.yellow,blocked:E.yellow,hold:E.yellow,done:E.green,complete:E.green,completed:E.green,success:E.green,ok:E.green,stable:E.green,resolved:E.green,fixed:E.green,closed:E.green,merged:E.green,released:E.green,deployed:E.green,approved:E.green,verified:E.green,working:E.green,healthy:E.green,pass:E.green,passing:E.green,info:E.blue,information:E.blue,note:E.blue,docs:E.blue,documentation:E.blue,doc:E.blue,guide:E.blue,help:E.blue,explanation:E.blue,detail:E.blue,details:E.blue,context:E.blue,design:E.blue,discussion:E.blue,proposal:E.blue,idea:E.blue,feature:E.magenta,enhancement:E.magenta,improvement:E.magenta,refactor:E.magenta,refactoring:E.magenta,cleanup:E.magenta,optimize:E.magenta,optimization:E.magenta,perf:E.magenta,performance:E.magenta,upgrade:E.magenta,migration:E.magenta,modernize:E.magenta,debt:E.magenta,todo:E.cyan,next:E.cyan,planned:E.cyan,plan:E.cyan,future:E.cyan,backlog:E.cyan,investigate:E.cyan,explore:E.cyan,prototype:E.cyan};var fs={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},sa=(e,t,n)=>Math.max(t,Math.min(n,e)),ps=(e,t,n)=>e+(t-e)*n,ia=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},hu=e=>e.toLowerCase().trim(),xu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let g=o-s/2;return[Math.round((u+g)*255),Math.round((m+g)*255),Math.round((p+g)*255)]},aa=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var Iu=(e,t,n)=>{let r=sa(n,0,1);return[Math.round(ps(e[0],t[0],r)),Math.round(ps(e[1],t[1],r)),Math.round(ps(e[2],t[2],r))]};var bu=(e,t,n)=>Iu(e,t,n),Gn=e=>{let n=ia(e)%360,r=xu(n,fs.stringColor.saturation,fs.stringColor.lightness);return aa(r)},de=(e,t=yn)=>{let n=hu(e);return n&&t[n]?t[n]:Gn(n)};var da=e=>{let t=fs.gradient.stops,n=sa(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,s=Math.min(Math.floor(o),r-1),i=o-s;return bu(t[s],t[s+1],i)},kr=e=>aa(da(e)),Dr=e=>ia(e.toLowerCase().trim())/4294967295,ca=e=>{let t=Dr(e);return da(t)},Cu=e=>{let[t,n,r]=ca(e);return{normal:o=>hn.bgRgb(t,n,r).black(o),cursor:o=>hn.bgRgb(t,n,r).white.bold(o)}},gs=e=>{let[t,n,r]=ca(e);return{fg:o=>hn.rgb(t,n,r)(o),fgCursor:o=>hn.rgb(t,n,r).inverse(o),bg:o=>hn.bgRgb(t,n,r).black(o),bgCursor:o=>hn.bgRgb(t,n,r).white.bold(o)}},Fr=e=>Cu(e).normal(` ${e} `);import{decodeTime as la}from"ulid";var Br=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 s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Ur=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Or=e=>{try{return l("Decoded date",new Date(la(e)))}catch(t){return a("Decoding failed + "+t.message)}},xn=e=>{if(!e?.id)return null;try{return la(e.id)}catch{return null}};var Su=(e,t)=>e+" ".repeat(Math.max(0,t-ua(e))),Nu=(e,t)=>" ".repeat(Math.max(0,t-ua(e)))+e,ma=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Ru=(e,t)=>t?e<t?"up":e>t?"down":null:null,Au=(e,t)=>{let n=I.getNode(e.payload.parent),r=n?Zt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=Ru(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Tu=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?Zt.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?Zt.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?Zt.hex(de(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?Zt.hex(de(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},wu=e=>{let t=Br(Eu(e));return Zt.gray(Nu(t,8))},Mu=12,Pu=e=>Su(`${e}`,Mu),Lu=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?t.name:""}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}"`:"";case"move.node":{let t=I.getNode(e.payload.parent);return t?`to ${t.title}`:""}default:return""}},pa=e=>[ma(e.action),Lu(e)].filter(Boolean).join(" "),fa=(e,t)=>{let n=wu(e.id),r=Pu(e.userName),o=Zt.dim("\u203A"),s=e.action==="move.node"?Au(e,t):[ma(e.action),Tu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as ku}from"node:crypto";var Du="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Fu=e=>{let t=ku("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=Du[Number(n>>s&31n)]}return r},we=(e,t)=>Fu(`${e}:virtual:${t}`);var Bu=e=>we(e,"comments"),Uu=e=>we(e,"description"),Ou=e=>we(e,"assignees"),_u=e=>we(e,"tags"),$u=e=>we(e,"history"),vs=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=I.getNode(e);if(!c){let p=I.createNode({...Z.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!nt(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=I.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},ga=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=I.getNode(e);if(!i){let m=I.createNode({...Z.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Hn(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=I.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},va=e=>{let t=Ve(rt/4n),n=Ve(rt/2n),r=Ve(rt*3n/4n),o=Ve(rt*7n/8n),s=Ve(rt*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;let i=vs({id:Uu(e.id),name:Q.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let c=ga({id:Ou(e.id),name:Q.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let u=ga({id:_u(e.id),name:Q.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(u))return u;let m=vs({id:Bu(e.id),name:Q.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(m))return m;let p=vs({id:$u(e.id),name:Q.HISTORY,parentNodeId:e.id,rank:s.value,value:Wu(e),readonly:!0,childRenderAxis:"vertical"});return d(p)?p:l("Ticket virtual nodes materialized",void 0)},Wu=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>fa(r,n.get(r.action)??[])).join(`
|
|
40
|
+
`)};var Hu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ue,_r]=Hu;var D=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ya=e=>{let t=I.getNode(e);if(!t||!A(t)||t.isDeleted)return null;let n=va(t);return d(n)?n:null},ju=e=>{for(let t of e){let n=ya(t);if(n)return n;let r=f().nodes[t]?.parentNodeId;if(!r)continue;let o=ya(r);if(o)return o}return null},Vu=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Gu=e=>{let t=[e],n=f().nodes[e]?.parentNodeId;return n&&t.push(n),t},ys=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return Gu(e.payload.id);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"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},zu=e=>{he(t=>({...t,eventLog:[...t.eventLog,e]}))},Ku=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):l("Valid user",null)},qu=(e,t)=>{let n=Ku(e);if(d(n))return n;let r=[...new Set(ys(e))];t||(r.forEach(s=>Vu(s,e)),zu(e));let o=ju(r);return o||null},Yu={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Z.workspace(t,n,r),s=zn(o);if(d(s))return D(s.message,e);let i=I.createNode(o);return d(i)?D(i.message??"Failed to initialize workspace",e):cs(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=I.createNode(Z.workspace(t,n,r));return d(o)?D(o.message??"Failed to add workspace",e):cs(o.value)?l("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Z.board(t,n,r,o));return d(s)?D(s.message??"Unable to create board",e):Pr(s.value)?l("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Z.swimlane(t,n,r,o));return d(s)?D(s.message??"Unable to create swimlane",e):wt(s.value)?l("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Z.ticket(t,n,r,o));return d(s)?D(s.message??"Unable to create issue",e):A(s.value)?l("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=I.createNode(Z.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Q.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?D(i.message??`Unable to create field: ${n}`,e):nt(i.value)?l("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,n);return d(o)?D(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return d(n)?D(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=I.createTag({id:t,name:n});return d(r)?D(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=I.createContributor({id:t,name:n});return d(r)?D(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.tag(t,n);return d(r)?D(r.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.untag(t,n);return d(r)?D(r.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=I.assign(t,n);return d(r)?D(r.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=I.unassign(t,n);return d(r)?D(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?D(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=I.editValue(t,n);return d(r)?D(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return D("Unable to locate issue",e);if(!A(o))return D("Can only close issues",e);let s=I.getNode(ue);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let i=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?D(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return D("Unable to locate issue",e);if(!A(o))return D("Can only reopen issues",e);let s=I.getNode(ue);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return D("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?D(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return d(n)?D(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=I.getNode(r);if(!s)return D(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let i=I.updateNode({...s,rank:o});if(d(i))return D(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=I.createComment({id:t,issue:n,authorId:r,authorName:I.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?D(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=I.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let s=I.editComment(t,r);return d(s)?D(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=I.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let o=I.deleteComment(t);return d(o)?D(o.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=I.linkUserId({contributorId:t,userId:e.userId});return d(n)?D(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Mt(e,t=!1){let n=Yu[e.action](e);if(d(n))return n;let r=qu(e,t);return r||n}var Pt=e=>e.map(t=>Mt(t));import im from"node:fs";import am from"node:path";import{decodeTime as dm,monotonicFactory as cm}from"ulid";import{z as Kn}from"zod";import $r from"node:fs";import xs from"node:path";import{decodeTime as Xu}from"ulid";import{z as hs}from"zod";var Ju=hs.object({userId:hs.string().min(1).default("unknown"),userName:hs.string().min(1).default("unknown")}),Qu=e=>{let[t,n]=xs.basename(e,".jsonl").split("."),r=Ju.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${xs.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Zu=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},em=(e,t)=>t in e,tm=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),nm=e=>{let{userId:t,userName:n,...r}=e,o=Zu(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?em(r,s)?l("Decoded persisted event",tm({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},Is=e=>{let t=[];for(let n of e){let r=nm(n);if(d(r))return a(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return l("Decoded reconstructed events",t)},rm=e=>{if(!$r.existsSync(e))return l("Event file missing",[]);let t=Qu(e);if(d(t))return a(t.message);let n=$r.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
41
|
+
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=Cs(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function bs(e){let t=Fn(e);if(!$r.existsSync(t))return l("No events found",[]);let n=$r.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>xs.join(t,o)),r=[];for(let o of n){let s=rm(o);if(d(s))return a(s.message);r.push(...s.value)}return l("All events loaded",om(r))}function xt(e){let t=bs(e);return d(t)?a(t.message):Is(t.value)}function ha(e,t){let n=bs(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=sm(n.value,t),s=Is(r);if(d(s))return a(s.message);let i=Is(o);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function xa(e=process.cwd()){let t=bs(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var om=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],g=m.id[1]??null;t.set(p,m);let C=n.get(g)??[];C.push(m),n.set(g,C)}for(let m of n.values())m.sort((p,g)=>p.id[0].localeCompare(g.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let g=n.get(p)??[];for(let C of g)s(C)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],g=m.id[1]??null;return!o.has(p)&&g!==null&&!t.has(g)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},sm=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],u=!1;try{u=Xu(i)<t}catch{u=!1}!u||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var Ia=e=>({action:e.action,payload:e.payload});var Ea=1,ba=cm(),lm=Kn.tuple([Kn.string().min(1),Kn.string().min(1).nullable()]),um=Kn.looseObject({v:Kn.literal(Ea),id:lm}),Cs=e=>{let t=um.safeParse(e);return t.success?l("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Ca=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",mm=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),pm=e=>e.trim().length>0&&e.length<=80,ee=()=>{let{userName:e,userId:t}=G();return e?t?mm(t)?pm(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},en=({userId:e,userName:t})=>`${Ca(e)}.${Ca(t)}.jsonl`,fm=(e,{userId:t,userName:n})=>{let r=en({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=am.join(Fn(e),r);return l("Successfully resolved event log path",s)},gm=(e,t)=>{let n={[e.action]:e.payload,v:Ea,id:t};return Cs(n)};function Wr({event:e,rootDir:t}){try{let n=Ii(t);if(d(n))return n;let r=fm(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=xa(t);if(d(o))return a(o.message);let s=o.value?ba(Math.max(Date.now(),dm(o.value)+1)):ba(),i=gm(Ia(e),[s,o.value]);return d(i)?a(i.message):(im.appendFileSync(r.value,`${JSON.stringify(i.value)}
|
|
42
|
+
`,"utf8"),l("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function Sa(e,t){let n=Mt(e);if(n.status!==Rt.Success)return n;let r=Wr({event:e,rootDir:t});return d(r)?r:n}function U(e,t){if(e.length===0||!e[0])return a("No events provided");let n=ym(e[0],t);if(d(n))return n;let r=e.map(s=>Sa(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):l("Materialization succeeded",r.map(s=>s.value))}var ym=(e,t)=>{if(e.action==="create.contributor")return l("Contributor already being created",void 0);if(I.getContributor(e.userId))return l("Contributor exists",void 0);let n={id:vm(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=Sa(n,t);return d(r)?a(r.message):l("Contributor created",void 0)};var Na=e=>Hr(z(e),{at:"end"}),Hr=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(Ae(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Ae(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Ae(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=Ra(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,s=e[r];return s?n(Ae(o?.rank,s.rank)):a("Sibling not found")}case"after":{let r=Ra(e,t.sibling);if(r<0)return a("Sibling not found");let o=e[r],s=r<e.length-1?e[r+1]:void 0;return o?n(Ae(o.rank,s?.rank)):a("Sibling not found")}}},z=e=>Object.values(f().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ra=(e,t)=>e.findIndex(n=>n.id===t),Aa=(e,t,n={at:"end"})=>Hr(z(t).filter(r=>r.id!==e),n),tn=(e,t,n,r,o)=>{let s=Aa(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=us(e,r);if(d(i))return i;let c=U([i.value],o);if(d(c))return c;let u=Aa(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},In=(e,t,n)=>{let r=Na(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=us(e,t);if(d(o))return o;let s=U([o.value],n);if(d(s))return s;let i=Na(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var w={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=j(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||w.navigate({contextNode:o,selectedIndex:j(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=f();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=j(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;w.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Ta(1),navigateToPreviousItem:()=>Ta(-1),navigateToNextContainer:()=>wa(1),navigateToPreviousContainer:()=>wa(-1),navigate:({contextNode:e,selectedIndex:t})=>{b({contextNodeId:e.id,selectedIndex:t})}},Ta=e=>{let{selectedIndex:t,contextNode:n}=f(),r=j(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;w.navigate({selectedIndex:s,contextNode:n})},wa=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=f();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=j(o.id),i=s.findIndex(C=>C.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=j(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),g=u.length?p:-1;w.navigate({contextNode:c,selectedIndex:g})};var Pa=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),La=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=f();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},hm=e=>{let t=f().nodes[e];return!!t&&!t.isDeleted&&nt(t)&&t.childRenderAxis==="vertical"},jr=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r||r.isDeleted)return!1;let o=z(r.id);return w.navigate({contextNode:r,selectedIndex:Pa(t,o.length)}),!0},ka=e=>{let{nodes:t}=f(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return jr(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=z(o.id).findIndex(c=>c.id===n.id);return i>=0?(w.navigate({contextNode:o,selectedIndex:i}),!0):ka(o.id)},Ma=e=>{let{nodes:t}=f(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),ka(n))return!0;n=t[n]?.parentNodeId}return!1},xm=e=>{if(!e)return!1;let t=f().nodes[e];return!!t&&!t.isDeleted},Da=e=>{let{nodes:t,rootNodeId:n}=f();if(hm(e.contextNodeId)&&jr(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(xm(e.selectedNodeId)&&e.selectedNodeId&&Ma(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(jr(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&jr(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Ma(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=z(r.id);return w.navigate({contextNode:r,selectedIndex:Pa(e.selectedIndex,o.length)}),l("Restored navigation to root",null)};import{monotonicFactory as Im,ulid as It}from"ulid";var qn=Im();function bm(){let e=Ge();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=j(n.id),[o]=r?j(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?l("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?l("Resolved boot nav target",{contextNode:n,selectedIndex:0}):l("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function Cm(){let e=bm();return d(e)?e:w.navigate(e.value)}function Fa({userId:e,userName:t}){let n=qn(),r=qn(),o=qn(),s=qn(),i=qn(),c=Ae(void 0,void 0);if(d(c))return c;let u=Ae(void 0,void 0);if(d(u))return u;let m=Ae(u.value,void 0);if(d(m))return m;let p=Ae(void 0,void 0);if(d(p))return p;let g=Ae(p.value,void 0);if(d(g))return g;let C=Ae(g.value,void 0);if(d(C))return C;let S=Ae(void 0,void 0);return d(S)?S:l("Created default events",[{id:It(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:It(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:g.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:C.value}},{id:It(),userId:e,userName:t,action:"add.board",payload:{id:_r,name:"Closed",parent:n,rank:m.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:ue,name:"Closed",parent:_r,rank:S.value}},{id:It(),userId:e,userName:t,action:"lock.node",payload:{id:_r}},{id:It(),userId:e,userName:t,action:"lock.node",payload:{id:ue}}])}function nn(e){if(!e.length){let r=Z.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=zn(r);return d(o)?o:(b({hasProjectDefinition:!1,mode:v.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=Pt(e).filter(d);return n.length>0?a(`Materializing failed:
|
|
43
43
|
${n.map(r=>r.message).join(`
|
|
44
|
-
`)}`):(ym(),C({hasProjectDefinition:!0}),l("State booted successfully",null))}var Qt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Or=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},K=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var tt=null,_r=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!tt,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),tt)return logger.debug("[sync] syncAndReloadState joining existing promise"),tt;logger.debug("[sync] syncAndReloadState creating promise"),tt=hm();try{let e=await tt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:f().syncStatus?.status,statusMessageAfterResolve:f().syncStatus?.msg}),d(e)&&f().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),C({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),tt||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),tt=null}},hm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=Ma();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(tt)return tt;logger.debug("[sync] syncAndReloadState:start");let t=K("resolveActorId",Z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");C({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:f().syncStatus});let n=Yt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=K("syncEpiqWithRemote",await $r({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),C({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:f().syncStatus}),He(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=K("loadMergedEvents",ft(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:f().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Ma();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:i.message,syncStatus:f().syncStatus}),i;let c=Ra(),u=f().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id,selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual}),!f().selectedNode?.isVirtual&&!f().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=K("bootStateFromEventLog",Jt(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:f().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),C({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=K("restoreNavigationAnchor",Ta(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:f().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:f().syncStatus}),l("Synced",!0))},Ma=()=>f().mode===g.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:f().mode,syncStatus:f().syncStatus}),C({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var hn=3e3,Pa=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<hn?null:t},La=0,ys,hs=!1,jn=!1,xs=()=>{if(hs)return!0;let e=We();return d(e)?!1:e.value.syncStatus.status==="syncing"},xm=()=>{let e=H().autoSyncIntervalMs??1e4,t=Date.now()-La;return Math.max(0,e-t)},ka=()=>{ys||(ys=setTimeout(async()=>{if(ys=void 0,!!xn()){if(xs()){jn=!0;return}jn=!1,await Im()}},xm()))},Im=async()=>{if(f().readOnly||f().timeMode==="peek"||f().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!xn())return a("Cannot auto-sync before state is initialized");if(xs())return jn=!0,a("Sync already in progress");hs=!0,La=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await _r()}finally{hs=!1,jn&&ka()}},Wr=()=>{xn()&&(jn=!0,!xs()&&ka())};var wt=()=>{let e=H(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Da=()=>{let e=Ke(process.cwd());if(d(e))return!1;let t=Et(e.value);return te(t)},Fa=e=>e===!0?"on":e===!1?"off":null,Ba=e=>e==="on"?!0:e==="off"?!1:null;var bm=e=>e.props.tags??[],Cm=e=>e.props.assignees??[],Vn=e=>bm(e).map(t=>b.getTag(t)).filter(t=>!!t),Gn=e=>Cm(e).map(t=>b.getContributor(t)).filter(t=>!!t),Hr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Vn(n))},jr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Gn(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var Em=/^(\d+)(h|d|w|mo|y)$/,Sm=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Nm=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},Rm=(e,t=new Date)=>{let n=e.match(Em);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Am=e=>{let t=e.match(Sm);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,v=i?Number(i):0;return Nm({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},Zt=e=>{let t=e.trim().toLowerCase();return Rm(t)??Am(t)};var Ua=/^(\d+)(s|m)?$/,Vr=e=>{let t=e.trim().toLowerCase().match(Ua);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Gr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Ua.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Oa=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Tm=[{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}],Is=(e=Tm)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var wm=["BOARD","TICKET","SWIMLANE","COMMENT"],ae={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},we={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Mm=[ae.EDITOR,ae.VIEW,ae.USERNAME,ae.AUTOSYNC,ae.SYNC_DEBOUNCE_MS,ae.LOG_LEVEL],Pm=(e=f().selectedNode?.context)=>{switch(e){case"TICKET":return[we.TITLE,we.DESCRIPTION];case"BOARD":case"SWIMLANE":return[we.TITLE];case"COMMENT":return[we.COMMENT];default:return[]}},Cs=[String(hn),"5000","15000","30000","60000"],Wa=["10s","20s","30s","45s"],en=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],zr=[x.NEW,x.EDIT,x.DELETE,x.MOVE],bs=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],_a=[x.FILTER,x.PEEK,x.REPLAY],Lm={WORKSPACE:[...en,...zr],BOARD:[..._a,...en,...zr],SWIMLANE:[..._a,...en,...zr],TICKET:[...en,...zr,...bs],FIELD:[...en,...bs],FIELD_LIST:[...en,...bs],TEXT:[...en],COMMENT:[x.EDIT,x.DELETE]},km=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ha=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&w(n)),$a=e=>e.parentNodeId===ce,Dm=({selectedNode:e,breadCrumb:t})=>{let n=Pm(e?.context);return Ha({breadCrumb:t,selectedNode:e})?n.includes(we.DESCRIPTION)?n:[...n,we.DESCRIPTION]:n},Fm=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=wt();if(!r)return[x.HELP,x.CONFIG];if(!Da())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG];let o=e?.context,s=o&&wm.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Lm[u]:[]))],c=Ha({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&Vn(c).length>0):u===x.UNASSIGN?!!(c&&Gn(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&$a(c)):u===x.CLOSE_ISSUE?!!(c&&!$a(c)):!0)},le=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:Fm({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Is(),"now","prev","next"],[x.REPLAY]:[...Is()],[x.EDIT]:Dm({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(fn),...b.getExistingTags()])],[x.UNTAG]:[...Hr()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...jr()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:km(s),[x.CONFIG]:[...Mm],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Ka from"chalk";var ja=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var be=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")};import Va from"chalk";var J=e=>Va.dim(e),ve=e=>Va.hex(y.primary)(e),ye=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(i))].sort((v,I)=>Tr(v)-Tr(I)).slice(0,r).map(v=>wr(v)).join(" ");return p?`${J(e)}${p}${J(n)}`:""};var Mt={None:"none",Invalid:"invalid",Valid:"valid"};var In=140,Bm=["BOARD","TICKET","SWIMLANE"],Ga=()=>{let e=f().selectedNode;if(!e?.context)return F({message:J("Missing target context")});if(Bm.includes(e.context))return j();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===Ne(t?.parentNodeId??"","comments"))return j()}return F({message:J("Command not available in this context")})},ne="<ENTER> to confirm",j=(e="",t=[])=>({message:J(e),validity:Mt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:Mt.Invalid,message:e,completionWordList:t}),qr=e=>e.length===0,za=(e,t)=>{let n=be(f().breadCrumb,"BOARD");if(d(n))return F({message:ve("Command is not applicable in this context")});let r=Lr(n.value.id);return d(r)?F({message:ve(`Unable to ${t}: board id is not a valid ULID`)}):Oa({date:e,horizonDate:r.value})?null:F({message:ve(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Kr=e=>` ${Ka.hex("#000").bgHex(ie(e))(` ${e} `)} `,Es=({modifier:e})=>{let t="confirm";return e===t?j(ne):F({message:qr(e)?J("if you are certain, enter ")+wr(t):"",completionWordList:[t]})},Um=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:J(n)}):j():F({message:qr(r)?t:"",completionWordList:[...e]}),tn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>qr(n)&&qr(r)?F({message:e,completionWordList:[]}):j(t??ne),Om=({modifier:e,inputString:t})=>{let n=le(x.CONFIG);if(!n.includes(e))return F({message:ye({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ae.EDITOR:{let r=[...ja];return t.trim()?r.includes(t.trim())?j(ne):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(ne):F({message:ye({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.USERNAME:return t.trim()?j(ne):F({message:ve("Enter a user name. Saved in ")+Ka.bgBlack("~/.epiq-global/config.json")});case ae.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?j(ne):F({message:ye({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ae.AUTOSYNC:{let r=["on","off"],o=H().autoSync;if(!r.includes(t.trim())){let s=Fa(o);return F({message:ye({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(ne)}case ae.SYNC_DEBOUNCE_MS:{let r=H().autoSyncIntervalMs,o=Pa(t);if(!t.trim()||o===null||o<hn){let s=ye({prefix:" examples: ",wordList:Cs,minLengthForHints:0,inputString:t});return F({message:ve(`provide duration above ${hn}ms. current duration: ${r}ms.`)+s,completionWordList:Cs})}return j(ne)}default:return F({message:ve("Unknown config option"),completionWordList:n})}},_m=({modifier:e,inputString:t})=>{let n=le(x.EDIT);if(!n.length)return F({message:ve("Command not available in this context")});if(!n.includes(e)){let r=ye({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||ve("Unknown edit option"),completionWordList:n})}switch(e){case we.COMMENT:return t.trim()?j(ne):F({message:J("write a comment...")});case we.TITLE:return j(ne);case we.DESCRIPTION:{let{preferredEditor:r}=H();return r?j(J("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:ve("Unknown edit option"),completionWordList:n})}},$m={[x.EXPORT]:()=>j(ne+J(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return j(ne);let n={message:J("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Zt(r);if(!r||!o)return F(n);let s=za(o,"peek");return s||j(ne)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Gr(e.modifier,e.inputString),r={message:J("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Zt(t);if(!t||!o)return F(r);let s=za(o,"replay");return s||(n&&Vr(n)===null?F({message:ve("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):j("<ENTER> to replay board history",n?Wa:[]))},[x.EXIT]:()=>j(ne+J(" and exit the application")),[x.INIT]:()=>j(ne),[x.PALETTE]:()=>j(ne),[x.FILTER]:e=>{if(e.modifier==="clear")return j(ne);let t=s=>le(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:ye({wordList:le(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:le(x.FILTER)});let n=Object.values(f().tags).map(s=>s.name),r=Object.values(f().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:ye({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):j():F({message:ye({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=le(x.NONE);return F({message:ye({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Um({list:le(x.NEW),hint:ye({wordList:le(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>j(ne),[x.EDIT]:_m,[x.COMMENT]:e=>{let t=tn({hint:J(`write a comment (max ${In} char)...`),onOk:J(`(${e.inputString.length}/${In})`)})(e);return t.validity===Mt.Invalid?t:e.inputString.length>In?j(ve("max input exceeded")):t},[x.CONFIG]:Om,[x.DELETE]:e=>{let t=Ga();return t.validity==="invalid"?t:Es(e)},[x.CLOSE_ISSUE]:e=>Es(e),[x.RE_OPEN_ISSUE]:e=>Es(e),[x.MOVE]:e=>{let t=Ga();return t.validity==="invalid"?t:tn({hint:ye({prefix:"hey hacker! These commands are blocked for you... ",wordList:le(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(Kr).join("");return tn({hint:n.length?J("create tag or reuse:")+n+J(""):J("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Hr();if(d(t))return F({message:ve("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Kr).slice(0,10);return n.length?tn({hint:J(" ... ")+n.join("")})(e):F({message:ve("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(Kr).slice(0,10);return tn({hint:J("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=jr();if(d(t))return F({message:ve("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Kr).slice(0,10);return n.length?tn({hint:J("remove assignee... ")+n.join("")})(e):F({message:ve("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>j(ne),[x.COFFEE]:e=>{let{modifier:t}=e,n=le(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:J("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):tn({hint:ye({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},qa=Object.fromEntries(Object.entries($m).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Yr=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var Wm=3,Hm=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),jm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Vm=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Wm&&!Hm.has(t)&&!/^\d+$/.test(t)),Gm=e=>{let t=new Map;for(let s of jm(e))for(let i of Vm(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=Yr.filter(s=>!r.has(s));return[...n,...o]},Ya=Yr,Xa=-1,Ja=()=>{let e=We();if(d(e))return Yr;let t=e.value,n=t.eventLog.length;return n!==Xa&&(Ya=Gm(t),Xa=n),Ya};var Qa=e=>Object.values(x).includes(e),Za=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=qa[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?le(n):m?Ja():[],{mode:v}=f(),I=v===g.COMMAND_LINE?i??"":"",S=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?qi(e,S):{hint:"",hints:[],remainder:"",overlap:0}}};var ed=e=>{let t=e.trimStart(),n=Km(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=qm(e),c=Qa(r)?r:null,u=c!==null,m=r!=="",p=c?le(c)??[]:[],v=c&&p.includes(o)?o:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let S=s?"":i,N=zm(t,c,v);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:v,target:I,inputToMatch:S,inputString:N}},zm=(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},Km=e=>e.trim()?e.trim().split(/\s+/):[],qm=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Ym}from"react";var bn=e=>e===Ss||e===":",Ss=" ",he={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Mt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ns=new Set,td=()=>{for(let e of Ns)e()},Rs=e=>(Ns.add(e),()=>Ns.delete(e)),nt=e=>{let n=e(he),r=ed(n.value),o=n.cursorPosition===n.value.length;he={...n,commandMeta:Za(r,o)},td()},zn=({message:e,status:t})=>{let n=structuredClone(he);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,he=n,td(),l(e,null)},As=e=>{nt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ts=e=>{nt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&bn(n[o-1]);)o--;for(;o>0&&!bn(n[o-1]);)o--}else{for(;o<n.length&&!bn(n[o]);)o++;for(;o<n.length&&bn(n[o]);)o++}return{...t,cursorPosition:o}})},nd=()=>{nt(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}})},rd=()=>{nt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&bn(t[r-1]);)r--;for(;r>0&&!bn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Xr=e=>{nt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},od=()=>{nt(e=>({...e,commandIsPending:!0}))},_=e=>{nt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},sd=({addToHistory:e=!0})=>{nt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},id=()=>{nt(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}})},ad=()=>{nt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},q=()=>he,dd=()=>Ym(Rs,q,q),cd=()=>{let[e,...t]=he.value.split(Ss);return t.join(Ss).trim()};var h={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",InitCommandPalette:"initCommandPalette",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",EditTitle:"editTitle",EditDescription:"editDescription",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function Xm(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Jm(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Qm(e,t,n){let r=f().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function ld(e,t){let n=q();if(e.sequence==="?"&&t!==g.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==g.COMMAND_LINE)return h.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===g.COMMAND_LINE)return Wi(e,n.value);if(t===g.PALETTE)return Hi(e,n.value);let r=Xm(e)||Jm(e);if(r)return Zm(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return H().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function Zm(e,t){let n=t===g.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return Qm(f().contextNode.childRenderAxis,e,n)}var Jr=e=>{let{context:t}=f().contextNode;if(!t)return L.None;switch(e){case x.EXIT:return L.Exit;case x.EXPORT:return L.Export;case x.COFFEE:return L.Coffee;case x.INIT:return L.Init;case x.DELETE:return L.Delete;case x.EDIT:return L.Edit;case x.COMMENT:return L.Comment;case x.HELP:return L.ViewHelp;case x.RE_OPEN_ISSUE:return L.ReopenIssue;case x.CLOSE_ISSUE:return L.CloseIssue;case x.TAG:return L.TagTicket;case x.UNTAG:return L.UntagTicket;case x.ASSIGN:return L.AssignUserToTicket;case x.UNASSIGN:return L.UnassignUserFromTicket;case x.NEW:return L.NewItem;case x.FILTER:return L.Filter;case x.MOVE:return L.Move;case x.PEEK:return L.Peek;case x.REPLAY:return L.Replay;case x.CONFIG:return L.Config;case x.SYNC:return L.Sync;default:return L.None}},L={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as xe}from"ulid";import wd from"node:fs";import Dp from"node:path";import Fp from"react";import{Box as Lp}from"ink";import oo from"react";import gp from"chalk";import{Box as Ms,Text as vp}from"ink";import ot from"react";import{Text as ud}from"ink";import md,{useEffect as pd,useState as ep}from"react";var fd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ce=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=fd[n]??fd.default,[o,s]=ep(0);if(pd(()=>{s(0)},[r]),pd(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return md.createElement(ud,null,t);let i=r[o]??r[0]??t;return md.createElement(ud,{color:y.accent,dimColor:o===1},i)};import{Box as ws,Text as tp}from"ink";import Qr from"react";var rt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,I=e.slice(p,v),S=e.length>c,N=s,T=S?Math.max(1,Math.floor(c/e.length*N)):N,k=Math.max(0,N-T),O=Math.max(1,e.length-c),V=S?Math.floor(p/O*k):0;return Qr.createElement(ws,{flexDirection:"row",height:s,width:"100%"},Qr.createElement(ws,{flexDirection:"column",flexGrow:1,height:s},I),Qr.createElement(ws,{flexDirection:"column",width:1,height:N},Array.from({length:N}).map((R,A)=>Qr.createElement(tp,{key:A,color:S&&A>=V&&A<V+T?y.accent:y.secondary},S?"\u2502":" "))))};import{Box as eo,Text as pp}from"ink";import nn from"react";import{Text as np}from"ink";import rp from"react";var op=e=>e.toLowerCase().trim(),sp=(e,t=fn)=>{let n=op(e);return t[n]?t[n]:_n(n)},Pt=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return rp.createElement(np,{underline:t,color:sp(n.name)},"@"+n.name)};import{Text as ip}from"ink";import ap from"react";var Cn=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return ap.createElement(ip,{underline:t,backgroundColor:ie(n.name),color:y.secondary}," "+n.name+" ")};import{useEffect as dp,useState as cp}from"react";var lp=80,gd=1400,Zr=new Set,Kn=null,up=e=>(Zr.add(e),Kn||(Kn=setInterval(()=>{for(let t of Zr)t()},lp)),()=>{Zr.delete(e),Zr.size===0&&Kn&&(clearInterval(Kn),Kn=null)}),mp=()=>{let e=Date.now()%gd/gd;return e<.5?e*2:(1-e)*2},En=e=>{let[,t]=cp(0);return dp(()=>{if(e)return up(()=>t(n=>n+1))},[e]),Ar(mp())};var vd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=En(r),s=e-14,i=mn(Rt(t.title),s),c=Vn(t),u=Gn(t);return nn.createElement(eo,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},nn.createElement(eo,{borderBottom:!0},nn.createElement(eo,{paddingLeft:1,flexDirection:"column"},nn.createElement(pp,{color:y.primary},i))),nn.createElement(eo,{flexDirection:"row",paddingLeft:1},c.map(m=>nn.createElement(Cn,{key:m.id,id:m.id})),u.map(m=>nn.createElement(Pt,{key:m.id,id:m.id}))))};import{Box as rn,Text as qn}from"ink";import Me from"react";var fp=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,yd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=En(r),c=(t.props.tags??[]).map(R=>b.getTag(R)).filter(R=>!!R),u=(t.props.assignees??[]).map(R=>b.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),v=u.length*(2+m),I=c.map(R=>Me.createElement(rn,{key:R.id,paddingRight:m},Me.createElement(qn,{color:ie(R.name)},"\u25A0"))),S=u.map(R=>Me.createElement(rn,{key:R.id,paddingRight:m},Me.createElement(qn,{color:_n(R.name)},"@"+R.name.at(0)))),N=r?i:n?y.accent:s===g.MOVE?y.secondary:y.primary,T=4,k=b.getCommentsByIssue(t.id),O=k.length?String(k.length).length+2+m:0,V=k.length?Me.createElement(rn,{paddingRight:m},Me.createElement(qn,{color:y.accent},"[",k.length,"]")):null;return Me.createElement(rn,{borderBottom:!0,justifyContent:"space-between"},Me.createElement(rn,null,Me.createElement(rn,{width:T},n?Me.createElement(Ce,{isSelected:n}):Me.createElement(qn,{color:"gray",dimColor:!0},o+1)),Me.createElement(qn,{wrap:"truncate",color:N},fp(t.title,e-p-v-O-18))),Me.createElement(rn,null,I,S,V))};var yp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=$(),p=u[e.id]??[],v=m?new Set(m.flashNodeIds):null,I=v?.has(e.id)??!1,S=En(I),N=`${e.title} ${gp.hex(y.secondary2).dim("("+p.length+")")}`,T=3,k=o?1:4,O=r-T-(o?2:1),V=ot.createElement(Ms,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ot.createElement(Ce,{isSelected:t}),ot.createElement(vp,{bold:!0,color:I?S:t?y.accent:y.primary},N," ",e.readonly?"\u{1F512}":"")),R=(A,G)=>{let Re=s&&i===G;if(!w(A))return null;let Ae=v?.has(A.id)??!1;return o?ot.createElement(yd,{key:A.id,index:G,width:n,ticket:A,isSelected:Re,isFlashing:Ae,mode:c}):ot.createElement(vd,{key:A.id,width:n,ticket:A,isSelected:Re,isFlashing:Ae})};return ot.createElement(Ms,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:1,paddingLeft:1,height:r},V,ot.createElement(Ms,{padding:o?1:0},p.length>0&&ot.createElement(rt,{selectedIndex:i,height:O,itemHeight:k},p.map(R)),ot.createElement(Ce,{isSelected:s&&i===-1})))},hd=ot.memo(yp);import{Box as Yn,Text as Ad}from"ink";import Pe,{useMemo as ro}from"react";var xd=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},Id=(e,t,n)=>Q.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as Lt,Text as vt}from"ink";import ue,{useEffect as hp,useMemo as xp,useRef as Ip}from"react";import{decodeTime as Ps}from"ulid";var bp=e=>Ne(e,"comments"),Cp=e=>b.getCommentsByIssue(e.id).sort((t,n)=>Ps(t.id)-Ps(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),bd=e=>{for(let t of e)b.deleteNode(t.id)},Ep=(e,t)=>{let n=b.getNode(bp(e.id));if(!n||!Qe(n))return[];let r=t.map((o,s)=>Id(o,s,n.id)).map(b.createNode).filter(te).map(({value:o})=>o).filter(Un);return t.length>0&&f().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Sp=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Cd({ticket:e,width:t,height:n}){let r=xp(()=>Cp(e),[e]),o=Ip([]);hp(()=>(bd(o.current),o.current=Ep(e,r),()=>{bd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=$(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?ue.createElement(Lt,{flexDirection:"column",width:t,height:n,padding:1},ue.createElement(vt,{color:y.primary},"No comments yet."),ue.createElement(Lt,{paddingTop:1},ue.createElement(vt,{color:y.primary},"Use"),ue.createElement(vt,{color:y.accent}," :comment "),ue.createElement(vt,{color:y.primary},"to add the first one."))):ue.createElement(Lt,{flexDirection:"column",width:t,height:n},ue.createElement(Lt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},ue.createElement(vt,{color:y.secondary2},"Comments (",r.length,") ")),ue.createElement(rt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let v=p===s;return ue.createElement(Lt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},ue.createElement(Lt,{flexDirection:"row",paddingBottom:1},ue.createElement(vt,{color:y.accent},v?"\u276F ":" "),ue.createElement(Lt,{paddingLeft:1},ue.createElement(vt,{color:y.secondary2},`#${p+1} `),ue.createElement(Pt,{id:m.authorId}),ue.createElement(vt,{color:y.secondary2}," "+Mr(Ps(m.id))))),ue.createElement(Lt,{paddingLeft:3,paddingBottom:1},ue.createElement(vt,{color:y.primary},Sp(m.md,u))))})))}import{Box as to,Text as Np}from"ink";import yt from"react";var Ed=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=$(),{title:o}=t,s=t.parentNodeId?b.getNode(t.parentNodeId):void 0,i=s&&w(s)?o===se.ASSIGNEES?s.props.assignees??[]:o===se.TAGS?s.props.tags??[]:[]:[];return yt.createElement(to,{alignItems:"center",paddingTop:1},yt.createElement(to,{minWidth:12},yt.createElement(Ce,{isSelected:n}),yt.createElement(Np,{color:n?y.accent:y.secondary2},o,":")),yt.createElement(to,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return yt.createElement(to,{key:`${o}-${c}`,paddingRight:2,minHeight:1},yt.createElement(Ce,{isSelected:m}),o===se.ASSIGNEES?yt.createElement(Pt,{isSelected:m,id:c}):o===se.TAGS?yt.createElement(Cn,{isSelected:m,id:c}):null)})))};import{Box as no,Text as Ls}from"ink";import ht,{useEffect as Rp,useMemo as Sd}from"react";var Ap="\u2029",Nd=(e,t)=>`${e}::inline-line::${t}`,ks=new Map,Rd=e=>{let t=ks.get(e)??[];ks.delete(e);for(let n of t)b.deleteNode(n)},Tp=(e,t)=>{Rd(e);let n=[];t.forEach((r,o)=>{let s=$e(BigInt(o+1));if(!te(s))return;let i=b.createNode(Q.text({id:Nd(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));te(i)&&n.push(i.value.id)}),ks.set(e,n)},Ds=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=$(),u=Sd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Sd(()=>u.join("\0"),[u]);Rp(()=>(Tp(e,u),()=>{Rd(e)}),[e,m]);let p=I=>String(I).replace(/\r?\n/g,""),v=u.map((I,S)=>{let N=c.id===e&&i===S;return ht.createElement(no,{key:Nd(e,S)},ht.createElement(Ls,{color:N?y.primary:y.secondary2,dimColor:!N},`${S+1} `.padStart(5,"\xA0")),ht.createElement(Ls,{backgroundColor:N?"gray":void 0},p(I.length?mn(I,s-10):Ap)))});return ht.createElement(no,{flexDirection:"column",paddingTop:1},ht.createElement(no,null,ht.createElement(Ce,{isSelected:o}),ht.createElement(Ls,{color:o?y.accent:y.secondary2},t)),ht.createElement(no,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},ht.createElement(rt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},v)))};var wp=e=>Ne(e,"description"),Mp=e=>Ne(e,"comments"),Pp=e=>Ne(e,"history"),Td=({ticket:e,height:t})=>{let n=ro(()=>xd(e),[e]),{selectedIndex:r,contextNode:o}=$(),s=process.stdout.columns||120,i=ro(()=>wp(e.id),[e.id]),c=ro(()=>Mp(e.id),[e.id]),u=ro(()=>Pp(e.id),[e.id]),m=o.id===e.id,p=o.id===c||o.parentNodeId===c,v=o.id===u||o.parentNodeId===u,I=W(e.id);if(p){let A=t-3;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(Cd,{ticket:e,width:s,height:A}))}if(v){let R=b.getNode(u),A=R&&Qe(R)?R.props.value??"":"",Re=t-3;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?Pe.createElement(Ds,{id:R.id,label:"Event log",text:A,selected:!1,maxWidth:s,height:Re}):null)}let S=I.reduce((R,A)=>Bn(A)||A.id===c||A.id===u?R+1:R,0),N=2,T=3,k=S,O=t-T-k-N,V=(R,A)=>R.id===i?Pe.createElement(Ds,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:A,maxWidth:s,height:O}):Bn(R)?Pe.createElement(Ed,{key:R.id,parent:R,selected:A,selectedIndex:r}):R.id===c?Pe.createElement(Yn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Ad,{backgroundColor:y.secondary,color:A?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):R.id===u?Pe.createElement(Yn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Ad,{backgroundColor:y.secondary,color:A?y.accent:y.primary}," History \u203A\u203A ")):null;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},I.map((R,A)=>V(R,m&&r===A)))};var kp=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,v=u===P.TICKET?t:r.find(k=>k.context===P.TICKET),I=Math.floor(c/3),S=Math.floor(c/Math.max(e.length,1)),N=Math.min(S,I),T=s==="dense";return oo.createElement(Lp,{flexDirection:"row",height:i},p&&e.map((k,O)=>{let V=t.id===k.id,R=V?n:-1,A=t.context===P.BOARD&&n===O;return oo.createElement(hd,{key:k.id,height:i,width:N,swimlane:k,isSelected:A,isDense:T,isFocused:V,listSelectedIndex:R,mode:o})}),m&&v&&oo.createElement(Td,{height:i,ticket:v}))},so=oo.memo(kp);import{render as Bp}from"ink";import{Writable as Up}from"node:stream";var Xn=e=>String(e).padStart(2,"0"),Op=e=>{let t=e.getUTCFullYear(),n=Xn(e.getUTCMonth()+1),r=Xn(e.getUTCDate()),o=Xn(e.getUTCHours()),s=Xn(e.getUTCMinutes()),i=Xn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},_p=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",$p=async(e,{width:t,height:n})=>{let r="",o=new Up({write(i,c,u){let m=Wp(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Bp(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},Wp=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Md=async()=>{let{viewMode:e}=H(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),i=r.find(O=>O.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await $p(Fp.createElement(so,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(O=>O!==void 0&&Nt(O)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=fr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let v=new Date,I=Op(v),S=`board_${_p(i.title)}_${I}.md`,N=pi(p.value);wd.mkdirSync(N,{recursive:!0});let T=Dp.join(N,S),k=`# Board - ${i.title}
|
|
45
|
-
Date: ${
|
|
44
|
+
`)}`):(Cm(),b({hasProjectDefinition:!0}),l("State booted successfully",null))}var rn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Vr=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},K=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var ot=null,Gr=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ot,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),ot)return logger.debug("[sync] syncAndReloadState joining existing promise"),ot;logger.debug("[sync] syncAndReloadState creating promise"),ot=Em();try{let e=await ot;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:f().syncStatus?.status,statusMessageAfterResolve:f().syncStatus?.msg}),d(e)&&f().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),b({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),ot||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),ot=null}},Em=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=Ba();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(ot)return ot;logger.debug("[sync] syncAndReloadState:start");let t=K("resolveActorId",ee());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");b({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:f().syncStatus});let n=en(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=K("syncEpiqWithRemote",await zr({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),b({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:f().syncStatus}),ze(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=K("loadMergedEvents",xt(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return b({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:f().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Ba();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:i.message,syncStatus:f().syncStatus}),i;let c=La(),u=f().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id,selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual}),!f().selectedNode?.isVirtual&&!f().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=K("bootStateFromEventLog",nn(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return b({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:f().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),b({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=K("restoreNavigationAnchor",Da(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id}),d(m)?(b({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:f().syncStatus}),m):(b({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:f().syncStatus}),l("Synced",!0))},Ba=()=>f().mode===v.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:f().mode,syncStatus:f().syncStatus}),b({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var bn=3e3,Ua=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<bn?null:t},Oa=0,Es,Ss=!1,Yn=!1,Ns=()=>{if(Ss)return!0;let e=Ge();return d(e)?!1:e.value.syncStatus.status==="syncing"},Sm=()=>{let e=G().autoSyncIntervalMs??1e4,t=Date.now()-Oa;return Math.max(0,e-t)},_a=()=>{Es||(Es=setTimeout(async()=>{if(Es=void 0,!!Cn()){if(Ns()){Yn=!0;return}Yn=!1,await Nm()}},Sm()))},Nm=async()=>{if(f().readOnly||f().timeMode==="peek"||f().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!Cn())return a("Cannot auto-sync before state is initialized");if(Ns())return Yn=!0,a("Sync already in progress");Ss=!0,Oa=Date.now(),b({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Gr()}finally{Ss=!1,Yn&&_a()}},Kr=()=>{Cn()&&(Yn=!0,!Ns()&&_a())};var Lt=()=>{let e=G(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},$a=()=>{let e=Je(process.cwd());if(d(e))return!1;let t=At(e.value);return oe(t)},Wa=e=>e===!0?"on":e===!1?"off":null,Ha=e=>e==="on"?!0:e==="off"?!1:null;var Rm=e=>e.props.tags??[],Am=e=>e.props.assignees??[],kt=e=>Rm(e).map(t=>I.getTag(t)).filter(t=>!!t),Dt=e=>Am(e).map(t=>I.getContributor(t)).filter(t=>!!t),qr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!A(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",kt(n))},Yr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!A(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Dt(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var Tm=/^(\d+)(h|d|w|mo|y)$/,wm=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Mm=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},Pm=(e,t=new Date)=>{let n=e.match(Tm);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Lm=e=>{let t=e.match(wm);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,g=i?Number(i):0;return Mm({year:c,month:u,day:m,hour:p,minute:g})?new Date(c,u-1,m,p,g):null},on=e=>{let t=e.trim().toLowerCase();return Pm(t)??Lm(t)};var ja=/^(\d+)(s|m)?$/,Xr=e=>{let t=e.trim().toLowerCase().match(ja);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Jr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&ja.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Va=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,km=[{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}],Rs=(e=km)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var Dm=["BOARD","TICKET","SWIMLANE","COMMENT"],ce={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},Le={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Fm=[ce.EDITOR,ce.VIEW,ce.USERNAME,ce.AUTOSYNC,ce.SYNC_DEBOUNCE_MS,ce.LOG_LEVEL],Bm=(e=f().selectedNode?.context)=>{switch(e){case"TICKET":return[Le.TITLE,Le.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Le.TITLE];case"COMMENT":return[Le.COMMENT];default:return[]}},Ts=[String(bn),"5000","15000","30000","60000"],Ka=["10s","20s","30s","45s"],sn=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG,x.YANK],Qr=[x.NEW,x.EDIT,x.DELETE,x.MOVE],As=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],Ga=[x.FILTER,x.PEEK,x.REPLAY],Um={WORKSPACE:[...sn,...Qr],BOARD:[...Ga,...sn,...Qr],SWIMLANE:[...Ga,...sn,...Qr],TICKET:[...sn,...Qr,...As],FIELD:[...sn,...As],FIELD_LIST:[...sn,...As],TEXT:[...sn],COMMENT:[x.EDIT,x.DELETE,x.YANK]},Om=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Xn=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&A(n)),za=e=>e.parentNodeId===ue,_m=({selectedNode:e,breadCrumb:t})=>{let n=Bm(e?.context);return Xn({breadCrumb:t,selectedNode:e})?n.includes(Le.DESCRIPTION)?n:[...n,Le.DESCRIPTION]:n},$m=({selectedNode:e,breadCrumb:t})=>{let n=Xn({breadCrumb:t,selectedNode:e});return n?[me.REF,me.TITLE,...n.props?.description?.trim()?[me.DESCRIPTION]:[],...kt(n).length>0?[me.TAGS]:[],...Dt(n).length>0?[me.ASSIGNEES]:[]]:e?[me.REF,me.TITLE]:[]},Wm=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Lt();if(!r)return[x.HELP,x.CONFIG];if(!$a())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG,x.YANK];let o=e?.context,s=o&&Dm.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Um[u]:[]))],c=Xn({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.YANK?!!(c??e):u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&kt(c).length>0):u===x.UNASSIGN?!!(c&&Dt(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&za(c)):u===x.CLOSE_ISSUE?!!(c&&!za(c)):!0)},te=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:Wm({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Rs(),"now","prev","next"],[x.REPLAY]:[...Rs()],[x.EDIT]:_m({selectedNode:n,breadCrumb:o}),[x.YANK]:$m({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(yn),...I.getExistingTags()])],[x.UNTAG]:[...qr()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...Yr()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:I.getExistingAssignees(),[x.NEW]:Om(s),[x.CONFIG]:[...Fm],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Qa from"chalk";var qa=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Ee=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")};import Ya from"chalk";var Y=e=>Ya.dim(e),ge=e=>Ya.hex(y.primary)(e),ve=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(g=>g.startsWith(i))].sort((g,C)=>Dr(g)-Dr(C)).slice(0,r).map(g=>Fr(g)).join(" ");return p?`${Y(e)}${p}${Y(n)}`:""};var st={None:"none",Invalid:"invalid",Valid:"valid"};var En=140,Hm=["BOARD","TICKET","SWIMLANE"],Xa=()=>{let e=f().selectedNode;if(!e?.context)return F({message:Y("Missing target context")});if(Hm.includes(e.context))return V();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===we(t?.parentNodeId??"","comments"))return V()}return F({message:Y("Command not available in this context")})},ne="<ENTER> to confirm",V=(e="",t=[])=>({message:Y(e),validity:st.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:st.Invalid,message:e,completionWordList:t}),eo=e=>e.length===0,Ja=(e,t)=>{let n=Ee(f().breadCrumb,"BOARD");if(d(n))return F({message:ge("Command is not applicable in this context")});let r=Or(n.value.id);return d(r)?F({message:ge(`Unable to ${t}: board id is not a valid ULID`)}):Va({date:e,horizonDate:r.value})?null:F({message:ge(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Zr=e=>` ${Qa.hex("#000").bgHex(de(e))(` ${e} `)} `,ws=({modifier:e})=>{let t="confirm";return e===t?V(ne):F({message:eo(e)?Y("if you are certain, enter ")+Fr(t):"",completionWordList:[t]})},jm=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:Y(n)}):V():F({message:eo(r)?t:"",completionWordList:[...e]}),an=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>eo(n)&&eo(r)?F({message:e,completionWordList:[]}):V(t??ne),Vm=({modifier:e,inputString:t})=>{let n=te(x.CONFIG);if(!n.includes(e))return F({message:ve({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ce.EDITOR:{let r=[...qa];return t.trim()?r.includes(t.trim())?V(ne):F({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ce.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?V(ne):F({message:ve({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ce.USERNAME:return t.trim()?V(ne):F({message:ge("Enter a user name. Saved in ")+Qa.bgBlack("~/.epiq-global/config.json")});case ce.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?V(ne):F({message:ve({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ce.AUTOSYNC:{let r=["on","off"],o=G().autoSync;if(!r.includes(t.trim())){let s=Wa(o);return F({message:ve({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return V(ne)}case ce.SYNC_DEBOUNCE_MS:{let r=G().autoSyncIntervalMs,o=Ua(t);if(!t.trim()||o===null||o<bn){let s=ve({prefix:" examples: ",wordList:Ts,minLengthForHints:0,inputString:t});return F({message:ge(`provide duration above ${bn}ms. current duration: ${r}ms.`)+s,completionWordList:Ts})}return V(ne)}default:return F({message:ge("Unknown config option"),completionWordList:n})}},Gm=({modifier:e,inputString:t})=>{let n=te(x.EDIT);if(!n.length)return F({message:ge("Command not available in this context")});if(!n.includes(e)){let r=ve({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||ge("Unknown edit option"),completionWordList:n})}switch(e){case Le.COMMENT:return t.trim()?V(ne):F({message:Y("write a comment...")});case Le.TITLE:return V(ne);case Le.DESCRIPTION:{let{preferredEditor:r}=G();return r?V(Y("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:ge("Unknown edit option"),completionWordList:n})}},zm=({modifier:e})=>{let t=te(x.YANK);return t.length?t.includes(e)?V(ne+Y(" and copy to clipboard")):F({message:ve({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):F({message:ge("Nothing selected to copy from")})},Km={[x.EXPORT]:()=>V(ne+Y(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return V(ne);let n={message:Y("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=on(r);if(!r||!o)return F(n);let s=Ja(o,"peek");return s||V(ne)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Jr(e.modifier,e.inputString),r={message:Y("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=on(t);if(!t||!o)return F(r);let s=Ja(o,"replay");return s||(n&&Xr(n)===null?F({message:ge("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):V("<ENTER> to replay board history",n?Ka:[]))},[x.EXIT]:()=>V(ne+Y(" and exit the application")),[x.INIT]:()=>V(ne),[x.PALETTE]:()=>V(ne),[x.FILTER]:e=>{if(e.modifier==="clear")return V(ne);let t=s=>te(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:ve({wordList:te(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:te(x.FILTER)});let n=Object.values(f().tags).map(s=>s.name),r=Object.values(f().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:ve({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):V():F({message:ve({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=te(x.NONE);return F({message:ve({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>jm({list:te(x.NEW),hint:ve({wordList:te(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>V(ne),[x.EDIT]:Gm,[x.COMMENT]:e=>{let t=an({hint:Y(`write a comment (max ${En} char)...`),onOk:Y(`(${e.inputString.length}/${En})`)})(e);return t.validity===st.Invalid?t:e.inputString.length>En?V(ge("max input exceeded")):t},[x.CONFIG]:Vm,[x.YANK]:zm,[x.DELETE]:e=>{let t=Xa();return t.validity==="invalid"?t:ws(e)},[x.CLOSE_ISSUE]:e=>ws(e),[x.RE_OPEN_ISSUE]:e=>ws(e),[x.MOVE]:e=>{let t=Xa();return t.validity==="invalid"?t:an({hint:ve({prefix:"hey hacker! These commands are blocked for you... ",wordList:te(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(Zr).join("");return an({hint:n.length?Y("create tag or reuse:")+n+Y(""):Y("create tag ...")})(e)},[x.UNTAG]:e=>{let t=qr();if(d(t))return F({message:ge("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Zr).slice(0,10);return n.length?an({hint:Y(" ... ")+n.join("")})(e):F({message:ge("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=I.getExistingAssignees().map(Zr).slice(0,10);return an({hint:Y("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=Yr();if(d(t))return F({message:ge("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Zr).slice(0,10);return n.length?an({hint:Y("remove assignee... ")+n.join("")})(e):F({message:ge("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>V(ne),[x.COFFEE]:e=>{let{modifier:t}=e,n=te(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:Y("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):an({hint:ve({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Za=Object.fromEntries(Object.entries(Km).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var to=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var qm=3,Ym=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),Xm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Jm=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=qm&&!Ym.has(t)&&!/^\d+$/.test(t)),Qm=e=>{let t=new Map;for(let s of Xm(e))for(let i of Jm(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=to.filter(s=>!r.has(s));return[...n,...o]},ed=to,td=-1,nd=()=>{let e=Ge();if(d(e))return to;let t=e.value,n=t.eventLog.length;return n!==td&&(ed=Qm(t),td=n),ed};var rd=e=>Object.values(x).includes(e),od=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=Za[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?te(n):m?nd():[],{mode:g}=f(),C=g===v.COMMAND_LINE?i??"":"",S=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:C,autoCompletion:t?ea(e,S):{hint:"",hints:[],remainder:"",overlap:0}}};var sd=e=>{let t=e.trimStart(),n=ep(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=tp(e),c=rd(r)?r:null,u=c!==null,m=r!=="",p=c?te(c)??[]:[],g=c&&p.includes(o)?o:"",C="word";n.length===0||n.length===1&&!s?C="command":(n.length===1&&s||n.length===2&&!s)&&(C="modifier");let S=s?"":i,N=Zm(t,c,g);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:g,target:C,inputToMatch:S,inputString:N}},Zm=(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},ep=e=>e.trim()?e.trim().split(/\s+/):[],tp=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as np}from"react";var Sn=e=>e===Ms||e===":",Ms=" ",Ie={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:st.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ps=new Set,id=()=>{for(let e of Ps)e()},Ls=e=>(Ps.add(e),()=>Ps.delete(e)),it=e=>{let n=e(Ie),r=sd(n.value),o=n.cursorPosition===n.value.length;Ie={...n,commandMeta:od(r,o)},id()},Jn=({message:e,status:t})=>{let n=structuredClone(Ie);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ie=n,id(),l(e,null)},ks=e=>{it(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ds=e=>{it(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Sn(n[o-1]);)o--;for(;o>0&&!Sn(n[o-1]);)o--}else{for(;o<n.length&&!Sn(n[o]);)o++;for(;o<n.length&&Sn(n[o]);)o++}return{...t,cursorPosition:o}})},ad=()=>{it(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}})},dd=()=>{it(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Sn(t[r-1]);)r--;for(;r>0&&!Sn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},no=e=>{it(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},cd=()=>{it(e=>({...e,commandIsPending:!0}))},$=e=>{it(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},ld=({addToHistory:e=!0})=>{it(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},ud=()=>{it(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}})},md=()=>{it(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},q=()=>Ie,pd=()=>np(Ls,q,q),fd=()=>{let[e,...t]=Ie.value.split(Ms);return t.join(Ms).trim()};var h={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",InitCommandPalette:"initCommandPalette",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",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function rp(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function op(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function sp(e,t,n){let r=f().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function gd(e,t){let n=q();if(e.sequence==="?"&&t!==v.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==v.COMMAND_LINE)return h.InitCommandLine;if(t===v.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===v.COMMAND_LINE)return Ki(e,n.value);if(t===v.PALETTE)return qi(e,n.value);let r=rp(e)||op(e);if(r)return ip(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"y":return h.Yank;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return G().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function ip(e,t){let n=t===v.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return sp(f().contextNode.childRenderAxis,e,n)}var ro=e=>{let{context:t}=f().contextNode;if(!t)return M.None;switch(e){case x.EXIT:return M.Exit;case x.EXPORT:return M.Export;case x.COFFEE:return M.Coffee;case x.INIT:return M.Init;case x.DELETE:return M.Delete;case x.EDIT:return M.Edit;case x.COMMENT:return M.Comment;case x.HELP:return M.ViewHelp;case x.RE_OPEN_ISSUE:return M.ReopenIssue;case x.CLOSE_ISSUE:return M.CloseIssue;case x.TAG:return M.TagTicket;case x.UNTAG:return M.UntagTicket;case x.ASSIGN:return M.AssignUserToTicket;case x.UNASSIGN:return M.UnassignUserFromTicket;case x.NEW:return M.NewItem;case x.FILTER:return M.Filter;case x.MOVE:return M.Move;case x.PEEK:return M.Peek;case x.REPLAY:return M.Replay;case x.CONFIG:return M.Config;case x.YANK:return M.Yank;case x.SYNC:return M.Sync;default:return M.None}},M={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as be}from"ulid";import Dd from"node:fs";import Wp from"node:path";import Hp from"react";import{Box as _p}from"ink";import uo from"react";import Cp from"chalk";import{Box as Bs,Text as Ep}from"ink";import dt from"react";import{Text as vd}from"ink";import yd,{useEffect as hd,useState as ap}from"react";var xd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Se=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=H(),r=xd[n]??xd.default,[o,s]=ap(0);if(hd(()=>{s(0)},[r]),hd(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return yd.createElement(vd,null,t);let i=r[o]??r[0]??t;return yd.createElement(vd,{color:y.accent,dimColor:o===1},i)};import{Box as Fs,Text as dp}from"ink";import oo from"react";var at=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),g=p+c,C=e.slice(p,g),S=e.length>c,N=s,T=S?Math.max(1,Math.floor(c/e.length*N)):N,P=Math.max(0,N-T),B=Math.max(1,e.length-c),W=S?Math.floor(p/B*P):0;return oo.createElement(Fs,{flexDirection:"row",height:s,width:"100%"},oo.createElement(Fs,{flexDirection:"column",flexGrow:1,height:s},C),oo.createElement(Fs,{flexDirection:"column",width:1,height:N},Array.from({length:N}).map((R,k)=>oo.createElement(dp,{key:k,color:S&&k>=W&&k<W+T?y.accent:y.secondary},S?"\u2502":" "))))};import{Box as An,Text as io}from"ink";import Ke from"react";import{Text as cp}from"ink";import lp from"react";var up=e=>e.toLowerCase().trim(),mp=(e,t=yn)=>{let n=up(e);return t[n]?t[n]:Gn(n)},Ft=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return lp.createElement(cp,{underline:t,color:mp(n.name)},"@"+n.name)};import{Text as pp}from"ink";import fp from"react";var Nn=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return fp.createElement(pp,{underline:t,backgroundColor:de(n.name),color:y.secondary}," "+n.name+" ")};import{useEffect as gp,useState as vp}from"react";var yp=80,Id=1400,so=new Set,Qn=null,hp=e=>(so.add(e),Qn||(Qn=setInterval(()=>{for(let t of so)t()},yp)),()=>{so.delete(e),so.size===0&&Qn&&(clearInterval(Qn),Qn=null)}),xp=()=>{let e=Date.now()%Id/Id;return e<.5?e*2:(1-e)*2},Rn=e=>{let[,t]=vp(0);return gp(()=>{if(e)return hp(()=>t(n=>n+1))},[e]),kr(xp())};var Ip=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),Jt(e.slice(r).trim(),t)]},bd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Rn(r),s=e-4,[i,c]=Ip(yt(t.title),s),u=c?null:Jt(yt(t.props.description),s)||null,m=kt(t),p=Dt(t);return Ke.createElement(An,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},Ke.createElement(An,{paddingLeft:1,flexDirection:"column"},Ke.createElement(io,{color:y.primary},i),c&&Ke.createElement(io,{color:y.primary},c),u&&Ke.createElement(io,{color:y.secondary2,dimColor:!0},u)),Ke.createElement(An,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},Ke.createElement(An,{flexDirection:"row"},m.map(g=>Ke.createElement(An,{paddingRight:1,key:g.id},Ke.createElement(Nn,{key:g.id,id:g.id}))),p.map(g=>Ke.createElement(An,{paddingRight:1,key:g.id},Ke.createElement(Ft,{key:g.id,id:g.id})))),Ke.createElement(io,{wrap:"truncate",color:y.secondary2,dimColor:!0},"#",Te(t.id))))};import{Box as dn,Text as Zn}from"ink";import ke from"react";var bp=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Cd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=Rn(r),c=(t.props.tags??[]).map(R=>I.getTag(R)).filter(R=>!!R),u=(t.props.assignees??[]).map(R=>I.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),g=u.length*(2+m),C=c.map(R=>ke.createElement(dn,{key:R.id,paddingRight:m},ke.createElement(Zn,{color:de(R.name)},"\u25A0"))),S=u.map(R=>ke.createElement(dn,{key:R.id,paddingRight:m},ke.createElement(Zn,{color:Gn(R.name)},"@"+R.name.at(0)))),N=r?i:n?y.accent:s===v.MOVE?y.secondary:y.primary,T=4,P=I.getCommentsByIssue(t.id),B=P.length?String(P.length).length+2+m:0,W=P.length?ke.createElement(dn,{paddingRight:m},ke.createElement(Zn,{color:y.accent},"[",P.length,"]")):null;return ke.createElement(dn,{borderBottom:!0,justifyContent:"space-between"},ke.createElement(dn,null,ke.createElement(dn,{width:T},n?ke.createElement(Se,{isSelected:n}):ke.createElement(Zn,{color:"gray",dimColor:!0},o+1)),ke.createElement(Zn,{wrap:"truncate",color:N},bp(t.title,e-p-g-B-18))),ke.createElement(dn,null,C,S,W))};var Sp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=H(),p=u[e.id]??[],g=m?new Set(m.flashNodeIds):null,C=g?.has(e.id)??!1,S=Rn(C),N=`${e.title} ${Cp.hex(y.secondary2).dim("("+p.length+")")}`,T=3,P=o?1:5,B=s&&i===-1,W=n-(B?7:5),R=r-T-(o?2:1),k=dt.createElement(Bs,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},dt.createElement(Se,{isSelected:t}),dt.createElement(Ep,{bold:!0,color:C?S:t?y.accent:y.primary},N," ",e.readonly?"\u{1F512}":"")),_=(J,Me)=>{let qe=s&&i===Me;if(!A(J))return null;let Re=g?.has(J.id)??!1;return o?dt.createElement(Cd,{key:J.id,index:Me,width:n,ticket:J,isSelected:qe,isFlashing:Re,mode:c}):dt.createElement(bd,{key:J.id,width:W,ticket:J,isSelected:qe,isFlashing:Re})};return dt.createElement(Bs,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:1,paddingLeft:1,height:r},k,dt.createElement(Bs,{padding:o?1:0},p.length>0&&dt.createElement(at,{selectedIndex:i,height:R,itemHeight:P},p.map(_)),B&&dt.createElement(Se,{isSelected:!0})))},Ed=dt.memo(Sp);import{Box as er,Text as Ld}from"ink";import De,{useMemo as lo}from"react";var Sd=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},Nd=(e,t,n)=>Z.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as Bt,Text as bt}from"ink";import pe,{useEffect as Np,useMemo as Rp,useRef as Ap}from"react";import{decodeTime as Us}from"ulid";var Tp=e=>we(e,"comments"),wp=e=>I.getCommentsByIssue(e.id).sort((t,n)=>Us(t.id)-Us(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Rd=e=>{for(let t of e)I.deleteNode(t.id)},Mp=(e,t)=>{let n=I.getNode(Tp(e.id));if(!n||!nt(n))return[];let r=t.map((o,s)=>Nd(o,s,n.id)).map(I.createNode).filter(oe).map(({value:o})=>o).filter(jn);return t.length>0&&f().selectedIndex<0&&w.navigate({contextNode:n,selectedIndex:0}),r},Pp=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Ad({ticket:e,width:t,height:n}){let r=Rp(()=>wp(e),[e]),o=Ap([]);Np(()=>(Rd(o.current),o.current=Mp(e,r),()=>{Rd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=H(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?pe.createElement(Bt,{flexDirection:"column",width:t,height:n,padding:1},pe.createElement(bt,{color:y.primary},"No comments yet."),pe.createElement(Bt,{paddingTop:1},pe.createElement(bt,{color:y.primary},"Use"),pe.createElement(bt,{color:y.accent}," :comment "),pe.createElement(bt,{color:y.primary},"to add the first one."))):pe.createElement(Bt,{flexDirection:"column",width:t,height:n},pe.createElement(Bt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},pe.createElement(bt,{color:y.secondary2},"Comments (",r.length,") ")),pe.createElement(at,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let g=p===s;return pe.createElement(Bt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},pe.createElement(Bt,{flexDirection:"row",paddingBottom:1},pe.createElement(bt,{color:y.accent},g?"\u276F ":" "),pe.createElement(Bt,{paddingLeft:1},pe.createElement(bt,{color:y.secondary2},`#${p+1} `),pe.createElement(Ft,{id:m.authorId}),pe.createElement(bt,{color:y.secondary2}," "+Br(Us(m.id))))),pe.createElement(Bt,{paddingLeft:3,paddingBottom:1},pe.createElement(bt,{color:y.primary},Pp(m.md,u))))})))}import{Box as ao,Text as Lp}from"ink";import Ct from"react";var Td=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=H(),{title:o}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,i=s&&A(s)?o===Q.ASSIGNEES?s.props.assignees??[]:o===Q.TAGS?s.props.tags??[]:[]:[];return Ct.createElement(ao,{alignItems:"center",paddingTop:1},Ct.createElement(ao,{minWidth:12},Ct.createElement(Se,{isSelected:n}),Ct.createElement(Lp,{color:n?y.accent:y.secondary2},o,":")),Ct.createElement(ao,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return Ct.createElement(ao,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Ct.createElement(Se,{isSelected:m}),o===Q.ASSIGNEES?Ct.createElement(Ft,{isSelected:m,id:c}):o===Q.TAGS?Ct.createElement(Nn,{isSelected:m,id:c}):null)})))};import{Box as co,Text as Os}from"ink";import Et,{useEffect as kp,useMemo as wd}from"react";var Dp="\u2029",Md=(e,t)=>`${e}::inline-line::${t}`,_s=new Map,Pd=e=>{let t=_s.get(e)??[];_s.delete(e);for(let n of t)I.deleteNode(n)},Fp=(e,t)=>{Pd(e);let n=[];t.forEach((r,o)=>{let s=Ve(BigInt(o+1));if(!oe(s))return;let i=I.createNode(Z.text({id:Md(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));oe(i)&&n.push(i.value.id)}),_s.set(e,n)},$s=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=H(),u=wd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=wd(()=>u.join("\0"),[u]);kp(()=>(Fp(e,u),()=>{Pd(e)}),[e,m]);let p=C=>String(C).replace(/\r?\n/g,""),g=u.map((C,S)=>{let N=c.id===e&&i===S;return Et.createElement(co,{key:Md(e,S)},Et.createElement(Os,{color:N?y.primary:y.secondary2,dimColor:!N},`${S+1} `.padStart(5,"\xA0")),Et.createElement(Os,{backgroundColor:N?"gray":void 0},p(C.length?Jt(C,s-10):Dp)))});return Et.createElement(co,{flexDirection:"column",paddingTop:1},Et.createElement(co,null,Et.createElement(Se,{isSelected:o}),Et.createElement(Os,{color:o?y.accent:y.secondary2},t)),Et.createElement(co,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},Et.createElement(at,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},g)))};var Bp=e=>we(e,"description"),Up=e=>we(e,"comments"),Op=e=>we(e,"history"),kd=({ticket:e,height:t})=>{let n=lo(()=>Sd(e),[e]),{selectedIndex:r,contextNode:o}=H(),s=process.stdout.columns||120,i=lo(()=>Bp(e.id),[e.id]),c=lo(()=>Up(e.id),[e.id]),u=lo(()=>Op(e.id),[e.id]),m=o.id===e.id,p=o.id===c||o.parentNodeId===c,g=o.id===u||o.parentNodeId===u,C=j(e.id);if(p){let k=t-3;return De.createElement(er,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},De.createElement(Ad,{ticket:e,width:s,height:k}))}if(g){let R=I.getNode(u),k=R&&nt(R)?R.props.value??"":"",J=t-3;return De.createElement(er,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?De.createElement($s,{id:R.id,label:"Event log",text:k,selected:!1,maxWidth:s,height:J}):null)}let S=C.reduce((R,k)=>Hn(k)||k.id===c||k.id===u?R+1:R,0),N=2,T=3,P=S,B=t-T-P-N,W=(R,k)=>R.id===i?De.createElement($s,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:k,maxWidth:s,height:B}):Hn(R)?De.createElement(Td,{key:R.id,parent:R,selected:k,selectedIndex:r}):R.id===c?De.createElement(er,{key:R.id,paddingTop:1},De.createElement(Se,{isSelected:k}),De.createElement(Ld,{backgroundColor:y.secondary,color:k?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):R.id===u?De.createElement(er,{key:R.id,paddingTop:1},De.createElement(Se,{isSelected:k}),De.createElement(Ld,{backgroundColor:y.secondary,color:k?y.accent:y.primary}," History \u203A\u203A ")):null;return De.createElement(er,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},C.map((R,k)=>W(R,m&&r===k)))};var $p=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===L.TICKET||u===L.FIELD_LIST||u===L.FIELD,p=u===L.BOARD||u===L.SWIMLANE,g=u===L.TICKET?t:r.find(P=>P.context===L.TICKET),C=Math.floor(c/3),S=Math.floor(c/Math.max(e.length,1)),N=Math.min(S,C),T=s==="dense";return uo.createElement(_p,{flexDirection:"row",height:i},p&&e.map((P,B)=>{let W=t.id===P.id,R=W?n:-1,k=t.context===L.BOARD&&n===B;return uo.createElement(Ed,{key:P.id,height:i,width:N,swimlane:P,isSelected:k,isDense:T,isFocused:W,listSelectedIndex:R,mode:o})}),m&&g&&uo.createElement(kd,{height:i,ticket:g}))},mo=uo.memo($p);import{render as jp}from"ink";import{Writable as Vp}from"node:stream";var tr=e=>String(e).padStart(2,"0"),Gp=e=>{let t=e.getUTCFullYear(),n=tr(e.getUTCMonth()+1),r=tr(e.getUTCDate()),o=tr(e.getUTCHours()),s=tr(e.getUTCMinutes()),i=tr(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},zp=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Kp=async(e,{width:t,height:n})=>{let r="",o=new Vp({write(i,c,u){let m=qp(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=jp(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},qp=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Fd=async()=>{let{viewMode:e}=G(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),i=r.find(B=>B.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await Kp(Hp.createElement(mo,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(B=>B!==void 0&&wt(B)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=Ir(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let g=new Date,C=Gp(g),S=`board_${zp(i.title)}_${C}.md`,N=xi(p.value);Dd.mkdirSync(N,{recursive:!0});let T=Wp.join(N,S),P=`# Board - ${i.title}
|
|
45
|
+
Date: ${g.toISOString()}
|
|
46
46
|
|
|
47
47
|
\`\`\`text
|
|
48
48
|
${m}
|
|
49
49
|
\`\`\`
|
|
50
|
-
`;return
|
|
51
|
-
`),l("Config written",null)}catch{return a(`Unable to write ~/${
|
|
50
|
+
`;return Dd.writeFileSync(T,P,"utf8"),l("Exported board layout",T)};import nf from"node:os";import _d from"node:path";import{z as Ut}from"zod";import{accessSync as Yp,copyFileSync as Xp,existsSync as po,mkdirSync as Bd,readdirSync as Ud,readFileSync as Jp,renameSync as Qp,rmSync as Zp,statSync as Od,unlinkSync as ef,writeFileSync as tf}from"node:fs";import Tn from"node:path";var Ws=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Fe={writeToFile:(e,t)=>{try{let n=Tn.dirname(e);po(n)||Bd(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);tf(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Jp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Fe.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 po(e)&&Od(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Yp(e),!0}catch{return!1}},mkDir:e=>Bd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Tn.parse(t);for(;;){let r=Tn.join(t,e);try{if(po(r)&&Od(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Tn.dirname(t)}return null},readFirstJSON(e){try{if(!Fe.dirExists(e))return null;let t=Ud(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Tn.join(e,t);return Fe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Fe.dirExists(e)?Ud(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{ef(e)}catch(t){(!Ws(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Zp(e,{recursive:!0,force:!0})}catch(t){(!Ws(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Tn.dirname(t)),!n?.overwrite&&po(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Qp(e,t)}catch(r){if(Ws(r)&&r.code==="EXDEV"){Xp(e,t),this.rmFile(e);return}throw r}}};var rf={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},$d=Ut.object({logLevel:Ut.enum(["info","error","debug"]),preferredEditor:Ut.string().optional(),userName:Ut.string().optional(),userId:Ut.string().optional(),autoSync:Ut.boolean().nullable().optional(),autoSyncDebounceMs:Ut.number().optional(),viewMode:Ut.enum(["dense","wide"]).optional()}).partial(),of="config.json",Wd=()=>_d.join(nf.homedir(),We),Hs=()=>_d.join(Wd(),of),js=()=>{try{return Fe.mkDir(Wd()),l(`Ensured ~/${We} exists`,null)}catch{return a(`Unable to create ~/${We}`)}},sf=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${We}/config.json JSON`)}let n=$d.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${We}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},nr=()=>{let e=js();if(d(e))return a(e.message);let t=Hs(),n=Fe.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):sf(n)},Hd=e=>{let t=js();if(d(t))return a(t.message);let n=$d.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Hs();try{return Fe.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
51
|
+
`),l("Config written",null)}catch{return a(`Unable to write ~/${We}/config.json`)}},ct=e=>{let t=nr();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Hd(n)},rr=()=>{let e=Hs(),t=js();if(d(t))return a(`Unable to create ~/${We}`);if(!(Fe.readFile(e)!==null)){let g=Hd(rf);if(d(g))throw new Error(`Unable to create ~/${We}/config.json`)}let r=nr();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,logLevel:m,viewMode:p}=r.value;return!s||!i?a(`User name or ID not configured in ~/${We}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,l("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:u??1e4,viewMode:p??"dense"}))};var fo=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){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};import{useSyncExternalStore as fN}from"react";var go,af=new Set,jd=()=>{for(let e of af)e()};var Ot=()=>{if(!go)throw new Error("Ui state not initialized. Call initUiState() first.");return go};var Vd=(e={})=>(go=e,jd(),l("UX state initialized",null)),df=e=>{let t=Ot();return go=e(t),jd(),l("UX state updated",null)},_t=e=>df(t=>({...t,...e}));import{spawn as cf}from"node:child_process";function Vs(e){let t=process.platform,o=cf(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}import{ulid as Gs}from"ulid";import{spawnSync as lf}from"node:child_process";import uf from"node:os";import Gd from"node:path";import{ulid as mf}from"ulid";function pf(){let{preferredEditor:e}=G(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function ff(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function zd(e){let t=Gd.join(uf.tmpdir(),"epiq");Fe.mkDir(t);let n=Gd.join(t,mf());Fe.writeToFile(n,e??"");let r=pf();for(let o of r){let s=ff(o,n),i=lf(s,{stdio:"inherit",shell:!0});if(!i.error&&i.status===0){let c=Fe.readFile(n);if(c==null)return a("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return a("Unable to open editor")}var Kd=async e=>{let{contextNode:t,selectedIndex:n}=f(),r=j(t.id)[n];if(e.modifier===Le.DESCRIPTION)return vf();if(r&&jn(r))return gf(e);if(e.modifier===Le.TITLE){let o=ee();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await Qe();return d(c)?c:U([{id:Gs(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},gf=async e=>{let t=ee();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=f(),o=j(n.id)[r];if(!o||!jn(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=f().nodes[s];if(!i||!A(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=I.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await Qe();if(d(p))return p;let g=p.value;return U([{id:Gs(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],g)},vf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let t=await Qe();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=f(),s=Ee([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!A(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=j(i.id).find(g=>g.title===Q.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=zd(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):U([{id:Gs(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import hf from"node:fs";import Yd from"node:path";import zs from"node:fs";import yf from"node:path";var qd=async e=>{let t=yf.join(e,".gitignore"),n=zs.existsSync(t)?zs.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
52
52
|
`).map(u=>u.trim()),s=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
53
53
|
`);return n=n.trimEnd()+`
|
|
54
54
|
|
|
55
55
|
${c}
|
|
56
|
-
|
|
57
|
-
`));let ze=We();if(d(ze))return Y(16,ze.message);let{rootNodeId:Dl,nodes:Fl}=ze.value,li=Fl[Dl];return li?(M.navigate({contextNode:li,selectedIndex:0}),C({hasProjectDefinition:!0,mode:g.DEFAULT}),l(Ae,null)):Y(16,"Unable to resolve initialized root node")};import{ulid as ff}from"ulid";import{ulid as pf}from"ulid";var zd=null,Bt=()=>structuredClone(zd),Zn=e=>{zd=e},Kd=()=>{let{contextNode:e,selectedIndex:t}=f(),r=z(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},Ws=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z(t).filter(o=>o.id!==e);return Br(r,n)},qd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Z();if(d(r))return a("Unable to resolve user ID");let o=Ws({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:pf(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Yd=e=>{Zn(e);let t=At(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function Hs(e){let t=Kd();if(d(t))return t;let{contextNode:n,nodes:r}=f();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=z(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=qd({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Yd(u.value)}function js(e){let t=Kd();if(d(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=z(n.id)[r+e];if(!s)return a("Missing sibling node");let i=qd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Yd(i.value)}var Xd=()=>{let e=Bt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=f().nodes[n];if(!r)return a("Move parent not found");let o=z(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},lo=(e,t="Moved preview")=>{if(d(e))return e;let n=Xd();return d(n)?n:(C({mode:g.MOVE}),l(t,null))},Jd=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=q().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=z(n.id)[r];if(!o)return C({mode:g.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=z(o.parentNodeId),i=s.findIndex(({id:v})=>v===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Ws({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Zn({id:ff(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:g.MOVE}),l("Move initialized",null))}if(t==="next")return lo(js(1));if(t==="previous")return lo(js(-1));if(t==="to-next")return lo(Hs(1));if(t==="to-previous")return lo(Hs(-1));if(t==="confirm"){let s=Bt();if(!s)return a("No pending move to confirm");let i=await qe();if(d(i))return i;let c=B([s],i.value);if(d(c))return c;let u=Xd();return d(u)?u:(Zn(null),C({mode:g.DEFAULT}),l("Moved item",null))}return t==="cancel"?(Zn(null),C({mode:g.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as mo}from"ulid";import{monotonicFactory as gf,ulid as vf}from"ulid";var yf=gf(),uo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=yf();return l("Created issue events",[{id:vf(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Qd=async(e,t)=>{let n=Z();if(d(n))return a("Unable to resolve user ID");let r=await qe();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=f(),u=m=>{let p=B([m],o);if(d(p))return p;let v=b.getNode(p.value[0].result.id);if(!v)return a("Created node not found");if(!v.parentNodeId)return p;let I=b.getNode(v.parentNodeId);return I?(M.navigate({contextNode:I,selectedIndex:b.getSiblings(v.parentNodeId).findIndex(({id:S})=>S===v.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=b.getNode(m);if(!p)return a("Workspace not found");let v=yn(p.id,n.value,o);return d(v)?v:u({id:mo(),action:"add.board",payload:{id:mo(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=be(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=yn(m.value.id,n.value,o);return d(p)?p:u({id:mo(),action:"add.swimlane",payload:{id:mo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=W(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let V=be(s,"SWIMLANE");return d(V)?null:V.value})();if(!p)return a("Unable to add issue in this context");let v=yn(p.id,n.value,o);if(d(v))return v;let I=uo({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(d(I))return I;let S=I.value,N=B([...S],o);if(d(N))return N;if(!N.value[0])return a("Issue creation failed");let O=S.find(V=>V.action==="add.issue")?.payload.id;return O?(M.navigate({contextNode:p,selectedIndex:b.getSiblings(p.id).findIndex(({id:V})=>V===O)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var po=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=ma(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Ut();if(d(u))return u;let p=Tt(i).filter(d);if(p.length>0)return Ut(),C(o),a(p.map(I=>I.message).join(", "));let v=f().nodes[e];return v?(M.navigate({contextNode:v,selectedIndex:r}),l("",{unappliedEvents:c})):(Ut(),C(o),a("Board did not exist at that date"))};var hf=20,xf=16,If=150,fo=null,go=null;var on=()=>{fo!==null&&(clearInterval(fo),fo=null),go!==null&&(clearTimeout(go),go=null)},Zd=()=>{on(),C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},bf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},ec=({events:e,startTime:t,durationMs:n})=>{on();let r=e.length,o=e.map(v=>vn(v)??t),s=o[r-1]??Date.now(),i=bf(o),c=Math.max(1,Math.round(n*hf/1e3)),u=Math.max(Math.round(n/c),xf),m=0,p=0;C({mode:g.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),fo=setInterval(()=>{m++;let v=m/c,I=[],S;for(;p<r&&i[p]<=v;){let T=e[p],k=At(T);if(d(k)){Zd();return}I.push(...us(T)),S=T,p++}if(p>=r||m>=c){for(;p<r;p++){let k=At(e[p]);if(d(k))break}let T=f().replay;C({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),on(),go=setTimeout(Zd,If);return}let N=f().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,v),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:S?vn(S)??N?.currentTime??t:N?.currentTime??t,currentLabel:S?aa(S):N?.currentLabel??"",flashNodeIds:S?[...new Set(I)]:N?.flashNodeIds??[]}})},u)};var tc=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta;if(on(),r==="now"){let c=ft(n.value);if(d(c))return a(c.message);let u=Ut();if(d(u))return u;let p=Tt(c.value).filter(d);return p.length>0?a(p.map(v=>v.message).join(", ")):(C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=f().eventLog.at(-1),u=vn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=f().unappliedEvents.at(0),u=vn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=Zt(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=po({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var nc=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta,{dateInput:s,durationInput:i}=Gr(r,o);if(on(),f().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=Zt(s);if(!c)return a("Invalid replay date");let u=i?Vr(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=f(),v=po({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(v))return v;let{unappliedEvents:I}=v.value;return I.length===0?(Ut(),C(p),l("Nothing to replay from that point",!0)):(ec({events:I,startTime:m,durationMs:u}),l("Replaying board history",!0))};import Ef from"zod";var rc=()=>{let e=q().commandMeta.inputString,t=Ef.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=xt({autoSyncDebounceMs:t.data});return d(n)?n:(_e({autoSyncIntervalMs:t.data}),C({mode:g.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var oc=()=>{let e=q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Ba(e),n=xt({autoSync:t});return d(n)?n:(_e({autoSync:t}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var sc=()=>{let e=q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=xt({logLevel:e});return d(n)?n:(_e({logLevel:e}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var ic=async()=>{_(""),C({mode:g.DEFAULT});let e=We();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");C({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await _r();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:g.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Sf=e=>e.action==="add.issue.comment",ac=e=>Object.values(f().tags).find(t=>t.name===e),dc=e=>Object.values(f().contributors).find(t=>t.name===e),It=async()=>{let e=await qe();return d(e)?e:l("Resolved persist root",e.value)},vo=[{systemOnly:!0,intent:L.Move,description:"Internal move-state command",mode:g.COMMAND_LINE,action:Jd},{intent:L.Delete,description:"Delete the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await It();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=w(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=f().nodes[i];if(!c||!w(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Sf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:xe(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:xe(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=q().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>le(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return fe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:g.DEFAULT})),l("Filter updated",null)}},{intent:L.ViewHelp,description:"Open the help screen",mode:g.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Ft({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:g.HELP}),l("Viewing help",null)}},{intent:L.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!w(r))return a("Cannot close in this context");let o=f().nodes[ce];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await It();if(d(s))return s;let i=s.value,c=Xt(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=B([{id:xe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):pt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=f().nodes[ce];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!w(s))return a("Target node is not issue");let c=ao(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=f().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await It();if(d(m))return m;let p=m.value,v=Xt(u.id,s.id,{at:"end"},e.value,p);if(d(v))return v;let I=B([{id:xe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return d(I)?I:l("Issue reopened",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Init,description:"Initialize Epiq in the current git repository",mode:g.COMMAND_LINE,action:Gd},{intent:L.NewItem,description:"Create a new board, swimlane, or issue",mode:g.COMMAND_LINE,action:Qd,onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Rename,description:"itle] Rename the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=cd();if(!o)return a("Provide a title");let s=await It();return d(s)?s:B([{id:xe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UntagTicket,description:"Remove a tag from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=ac(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid untag target");let i=pt(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await It();return d(m)?m:B([{id:xe(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.TagTicket,description:"Add or create a tag on the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=f();if(!o)return a("Invalid tag target");let s=pt(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!w(i))return a("Target node is not issue");let c=await It();if(d(c))return c;let u=ac(r),m=u?.id??xe();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...u?[]:[{id:xe(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:xe(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.AssignUserToTicket,description:"Assign a user to the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=f(),i=W(s.id)[o];if(!i)return a("Invalid assign target");let c=pt(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!w(u))return a("Target node is not issue");let m=await It();if(d(m))return m;let p=dc(r),v=p?.id??xe();return(u.props.assignees??[]).includes(v)?a("Assignee already assigned"):B([...p?[]:[{id:xe(),action:"create.contributor",payload:{id:v,name:r},...e.value}],{id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:v},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=dc(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid unassign target");let i=pt(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await It();return d(m)?m:B([{id:xe(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Comment,description:"Add a comment to the selected issue",mode:g.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>In)return a(`Cannot exceed ${In} characters`);let r=Z();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=f(),i=be([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):pt(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!w(m))return a("Target node is not issue");let p=await It();return d(p)?p:B([{id:xe(),action:"add.issue.comment",payload:{id:xe(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Sync,description:"Pull, commit, and push Epiq state",mode:g.COMMAND_LINE,action:ic},{intent:L.Peek,description:"View board state at another point in time",mode:g.COMMAND_LINE,action:tc},{intent:L.Replay,description:"Replay board history forward from a point in time",mode:g.COMMAND_LINE,action:nc},{intent:L.Export,description:"Export the current board layout to markdown",mode:g.COMMAND_LINE,action:async()=>{let e=await Md();return d(e)?e:(C({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:L.Exit,description:"Exit the application",mode:g.COMMAND_LINE,action:async()=>(M.exit(),l("Exit successful",!0))},{intent:L.Edit,description:"Edit title or description",mode:g.COMMAND_LINE,action:async(e,t)=>Hd(t),onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:g.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ae.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=H(),i=n||s,c=r??xe();if(!i||!c)return a("Unable to resolve user name or id");let u=xt({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(_e({userName:i,userId:c}),C({mode:g.DEFAULT}),l(`Username set to "${i}"`,null))}case ae.EDITOR:{if(!n)return a("No editor provided");let r=xt({preferredEditor:n});return d(r)?r:(_e({preferredEditor:n}),C({mode:g.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ae.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(_e({viewMode:n}),l(`View set to "${n}"`,null));case ae.AUTOSYNC:return oc();case ae.LOG_LEVEL:return sc();case ae.SYNC_DEBOUNCE_MS:return rc();default:return a("Unknown config command")}}},{intent:L.Coffee,description:"Sponsor the development of Epiq!",mode:g.COMMAND_LINE,action:()=>{let e=q().commandMeta.modifier;return e==="custom"?Os("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Os(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),_(""),l("Thanks you!",null)}}];var Nf=new Set(["peek","replay","filter","view-help"]),st=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=q();if(!t)return a("No command to confirm");if(!e&&n===Mt.Invalid)return a("Invalid command");let s=Jr(t);od();let{readOnly:i}=f();if(i&&!Nf.has(s))return zn({status:Ct.Fail,message:"Command not available in readonly state",value:null});let c=vo.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return zn({status:Ct.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return zn({status:Ct.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?zn(u):(sd({addToHistory:!e}),c.onSuccess?.(),H().autoSync&&Wr(),u)};var yo=[{intent:h.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:g.COMMAND_LINE}),_("move cancel"),st({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:g.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:g.COMMAND_LINE}),_("move start"),st({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:g.MOVE,action:()=>(C({mode:g.COMMAND_LINE}),_("move confirm"),st({isForceExecutedBySystem:!0}))}],ho=[{intent:h.MovePreviousItem,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move previous"),st({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move next"),st({isForceExecutedBySystem:!0})):a("No pending move")}],cc=[{intent:h.MoveToNextContainer,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move to-next"),st({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move to-previous"),st({isForceExecutedBySystem:!0})):a("No pending move")}];var lc={[P.WORKSPACE]:[...yo,...ho],[P.BOARD]:[...yo,...ho],[P.SWIMLANE]:[...yo,...ho,...cc],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[],[P.COMMENT]:[]};var uc=()=>{_("");let{pendingNavTarget:e}=Dt();C({mode:g.DEFAULT}),e&&M.navigate(e),Ft({pendingNavTarget:void 0})},mc=[{intent:h.ExitCommandLine,mode:g.HELP,action:()=>(uc(),l("Exiting help",null))},{intent:h.Exit,mode:g.HELP,action:()=>(uc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:g.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:g.HELP,action:()=>(M.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:g.HELP,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:g.HELP,action:()=>(M.navigateToNextContainer(),l("Navigating to next help container",null))}];var Rf=e=>{C({mode:g.COMMAND_LINE});let{pendingNavTarget:t}=Dt();t&&M.navigate(t),Ft({pendingNavTarget:void 0}),_(`${e} `)},pc=()=>{_("");let{pendingNavTarget:e}=Dt();e&&M.navigate(e),Ft({pendingNavTarget:void 0}),C({mode:g.DEFAULT})},fc=[{intent:h.InitCommandPalette,mode:g.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{_("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Ft({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:g.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:g.PALETTE,action:()=>{let{selectedNode:e}=f();if(!e||!St(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(Rf(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:g.PALETTE,action:()=>(pc(),l("Exiting palette",null))},{intent:h.Exit,mode:g.PALETTE,action:()=>(pc(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:g.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.PALETTE,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.PALETTE,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.PALETTE,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var gc=[...mc,...fc,{intent:h.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:g.COMMAND_LINE}),_(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!z(e?.id??"")?.length){if(e?.title===se.DESCRIPTION)return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===se.ASSIGNEES)return C({mode:g.COMMAND_LINE}),_(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===se.TAGS)return C({mode:g.COMMAND_LINE}),_(`${x.TAG} `),l("Propose command",!0);if(t.title===se.DESCRIPTION&&e?.context==="TEXT")return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0)}return M.enterChildNode(),l("Entering context",null)}},{intent:h.EditTitle,mode:g.DEFAULT,description:"[r] rename title",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} title ${f().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:g.DEFAULT,description:"[e] edit description",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.DEFAULT,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.DEFAULT,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var Af=500,Tf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),vc=e=>{let t=Tf(e);t&&Xr(n=>(n+t).slice(0,Af))};var wf=[g.COMMAND_LINE,g.PALETTE],Mf=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(As(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(As(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Ts("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Ts("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(Xr((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=f().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(vc(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>(nd(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(rd(),l("Erasing input word",null))}],yc=[{intent:h.Confirm,mode:g.COMMAND_LINE,action:()=>(st(),l("Executing command",null))},{intent:h.ViewHelp,mode:g.DEFAULT,action:()=>(C({mode:g.HELP}),l("Viewing help",null))},...wf.flatMap(Mf),{intent:h.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(C({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(id(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ad(),l("Getting next command from history",null))}];import Ic from"chalk";var xo=Ic.dim.hex(y.secondary2)(": for command line"),hc="q to exit",xc=`${Ic.hex(y.accent)("m")} to confirm`,Vs={[P.WORKSPACE]:[xo],[P.BOARD]:[xo],[P.BOARD+g.COMMAND_LINE]:[xo],[P.SWIMLANE]:[xo],[P.TICKET+g.HELP]:[hc],[P.SWIMLANE+g.HELP]:[hc],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[xc],[P.TICKET+g.MOVE]:[xc]};var er=e=>e.trim().toLocaleLowerCase(),Pf=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Lf=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},bc=(e,t)=>{let n=er(t.value);if(!n)return!0;switch(t.target){case"title":return er(e.title??"").includes(n);case"description":return er(e.props.description??"").includes(n);case"tag":return Pf(e).map(er).some(o=>o.includes(n));case"assignee":return Lf(e).map(er).some(o=>o.includes(n));case"ref":return Qi(e.id,t.value);default:return!0}};function Cc(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Ec=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 sn,Gs,zs=new Set,Sc=()=>{for(let e of zs)e()},Df=e=>(zs.add(e),()=>zs.delete(e));function Nc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let u=Cc(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Vs[p+n]??Vs[p]??[],I=[...gc,...lc[p]??[],...yc],S=Ec(I),N=Ff(o,s),T=N[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:v,availableActions:I,actionIndex:S,selectedNode:T,renderedChildrenIndex:N})}var f=()=>{if(!sn)throw new Error("State not initialized. Call initWorkspaceState() first.");return sn},We=()=>sn?l("Retrieved state",sn):a("State not initialized. Call initWorkspaceState() first.");function $n(e){Gs=e;let t=Ke(process.cwd()),n=!1;if(!d(t)){let s=Et(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},o=Nc(r);return d(o)?o:(sn=o.value,Sc(),l("State initialized",null))}function fe(e){let t=f(),n=e(t),r=Nc(n);return d(r)?a(r.message??"Unable to update state"):(sn=r.value,Sc(),l("State updated",null))}var C=e=>fe(t=>({...t,...e}));var $=()=>kf(Df,f,f),Ff=(e,t)=>{let n={};for(let r of Object.values(e))w(r)&&t.length>0&&!t.every(o=>bc(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,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},W=e=>f()?.renderedChildrenIndex[e]??[],Ut=()=>Gs?$n(Gs):a("Cannot reset state: no initial workspace found"),xn=()=>sn!==void 0;var Ks=e=>{xn()&&(C({syncStatus:e}),zt({type:"sync-status",payload:e}))},Io=(e="Syncing...")=>{Ks({status:"syncing",msg:e})},bo=(e="Synced")=>{Ks({status:"synced",msg:e})},qs=e=>{Ks({status:"failed",msg:e})},He=e=>(qs(e),a(e));import{decodeTime as PM}from"ulid";var Bf=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=K("getRepoRootDir",await Ye(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=K("getStateBranchRoot",Te({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=K("ensureInitialCommit",await Di(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=K("bootstrapStateBranchStorage",await Bi({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=K("hasInProgressGitOperation(stateBranchRoot)",await yr(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=K("ensureStateBranchLayout",Pi(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},Uf=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=K("stageStateBranchOwnEventFile",await Er({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=K("hasStagedChanges(after stage)",await Ni(t));if(d(o))return a(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=K("createStateBranchSyncCommit",await Fi({repoRoot:e,stateBranchRoot:t}));return d(s)?a(s.message):(logger.debug("[sync] created sync commit",s.value),l("Committed own event file",{createdCommit:!0,commitSha:s.value}))},$r=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Io();let n=K("ensureSyncReady",await Bf({cwd:e,ensureUpstream:!0}));if(d(n))return He(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=K("isDetachedHead(stateBranchRoot)",await Ri(o));if(d(i))return He(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return He("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=K("getStateBranch",cn(r));if(d(v))return He(v.message);let I=v.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let S=K("commitOwnEventFileToStateBranch",await Uf({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(S))return He(S.message);c=S.value.createdCommit,u=S.value.commitSha;let N=K("pullBranchRebaseIfPresent",await Qo({cwd:o,branch:I}));if(d(N))return He(N.message);if(m=N.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let T=K("pushStateBranch",await Fn({stateBranchRoot:o,repoRoot:r}));if(d(T)&&Si(T.message)){let k=K("pullBranchRebaseIfPresent(retry)",await Qo({cwd:o,branch:I}));if(d(k))return He(k.message);m=m||k.value,T=K("pushStateBranch(retry)",await Fn({stateBranchRoot:o,repoRoot:r}))}if(d(T))return He(T.message);p=T.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=K("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:o}));if(d(T))return He(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return bo(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var Ys=e=>{let t=Ke(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},ke=async e=>{let t=Ys(e);if(d(t))return t;let n=Te({repoRoot:t.value});if(d(n))return a(n.message);let r=dn(),o=await Gt({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await U({cwd:n.value,args:["pull","--ff-only"]});d(s)&&re.info(3,s.message);let i=ft(n.value);if(d(i))return a(i.message);let c=Jt(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},De=()=>{let e=Qn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},je=()=>{let e=We();return d(e)?a(e.message):e},Rc=e=>(e.props.tags??[]).map(t=>b.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)})),Ac=e=>(e.props.assignees??[]).map(t=>b.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)}));var Tc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes).filter(w).filter(o=>e.includeClosed||o.parentNodeId!==ce).map(o=>({id:o.id,ref:et(o.id),title:Rt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===ce,readonly:!!o.readonly,tags:Rc(o),assignees:Ac(o)}));return l("Listed issues",r)},wc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=yn(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=uo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=B([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},Mc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Xt(ce,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:Ie(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ce,rank:r.value}},s=B([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},Pc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Target node is not issue");if(o.parentNodeId!==ce)return a("Issue is not closed");let s=ao(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ce)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=Xt(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:Ie(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},Lc=async e=>{let t=Ys(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Te({repoRoot:t.value});if(d(r))return r;let o=ft(r.value);if(d(o))return o;let s=Jt(o.value);if(d(s))return s;let i=Xt(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:Ie(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=B([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},Co=async(e={})=>{Io();let t=Ys(e.repoRoot);if(d(t))return a("Sync failed");let n=De();if(d(n))return n;let r=await $r({cwd:t.value,ownEventFileName:Yt(n.value)});return d(r)?(qs(r.message),r):(bo(),l("Synced",r.value))};var Ot=async(e={})=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(m=>Nr(m)&&!m.isDeleted),s=new Map,i=new Map;for(let m of r)if(!m.isDeleted){if(Nt(m)&&m.parentNodeId){let p=s.get(m.parentNodeId)??[];p.push(m),s.set(m.parentNodeId,p)}if(w(m)&&m.parentNodeId){let p=i.get(m.parentNodeId)??[];p.push(m),i.set(m.parentNodeId,p)}}let c=Qn();if(d(c))return c;let u={};for(let m of r.filter(w))m.isDeleted||(u[m.id]=b.getCommentsByIssue(m.id).map(p=>{let v=b.getContributor(p.authorId);return{id:p.id,issueId:p.issue,body:p.md,author:{id:p.authorId,name:v?.name??"Unknown",color:ie(v?.name??p.authorId)},createdAt:Of(p.id)}}));return l("Retrieved Epiq GUI state",{boards:o.sort((m,p)=>m.rank.localeCompare(p.rank)).map(m=>({id:m.id,ref:et(m.id),title:m.title,swimlanes:(s.get(m.id)??[]).sort((p,v)=>p.rank.localeCompare(v.rank)).map(p=>({id:p.id,title:p.title,readonly:!!p.readonly,issues:(i.get(p.id)??[]).sort((v,I)=>v.rank.localeCompare(I.rank)).map(v=>({id:v.id,ref:et(v.id),title:Rt(v.title),description:v.props.description??"",readonly:!!v.readonly,tags:Rc(v),assignees:Ac(v),parentNodeId:v.parentNodeId,isClosed:v.parentNodeId===ce})),parentNodeId:p.parentNodeId}))})),tags:Object.values(n.value.tags).map(m=>({...m,color:ie(m.name)})),contributors:Object.values(n.value.contributors).map(m=>({...m,color:ie(m.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:ie(c.value.userName??"")},commentsByIssueId:u})},kc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:Ie(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},Dc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Rt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:Ie(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},Fc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Rt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},Bc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:Ie(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Uc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=Rt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},Oc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:Ie(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Eo=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=Ie(),c={id:Ie(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},So=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!w(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:Ie(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})};var _c=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=Jn();if(d(p))return re.error(p.message);let{autoSync:v,userName:I,preferredEditor:S}=p.value;return!!(v&&I&&S)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await Co({repoRoot:e.repoRoot}),zt({type:"state",payload:await Ot({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=Jn();if(d(p))return re.error(p.message);let{autoSyncDebounceMs:v}=p.value;i()&&(t=setTimeout(()=>{c(),m()},v??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as _f}from"ws";var Fe=(e,t)=>{e.send(JSON.stringify(t))},tr=async(e,t)=>Fe(e,{type:"state",payload:await Ot({repoRoot:t})}),it=async(e,t,n,r,o)=>{if(Fe(e,{type:r,payload:o}),d(o))return Fe(e,{type:"failed",payload:o.message});n(),tr(e,t)},$c=(e,t,{onStateChanged:n})=>{new _f({server:e,path:"/ws"}).on("connection",o=>{Ui(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return tr(o,t);if(c==="sync"){let u=await Co({repoRoot:t});return Fe(o,{type:"sync:result",payload:u}),n(),tr(o,t)}if(c==="issue:comment:add"){let u=await Eo({repoRoot:t,...i.payload});return it(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await So({repoRoot:t,...i.payload});return Fe(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Fe(o,{type:"failed",payload:u.message}):(n(),tr(o,t))}if(c==="issue:edit:description"){let u=await kc({repoRoot:t,...i.payload});return it(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await Dc({repoRoot:t,...i.payload});return it(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await Fc({repoRoot:t,...i.payload});return it(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await Bc({repoRoot:t,...i.payload});return it(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await Uc({repoRoot:t,...i.payload});return it(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await Oc({repoRoot:t,...i.payload});return it(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Fe(o,{type:"issues",payload:await Tc({repoRoot:t})});if(c==="issues:create"){let u=await wc({...i.payload,repoRoot:t});return Fe(o,{type:"issues:create:result",payload:u}),d(u)?zt({type:"failed",payload:u.message}):(zt({type:"issue:created",payload:u.value}),n(),tr(o,t))}if(c==="issues:move"){if(!i.payload.position)return Fe(o,{type:"error",message:"Missing move position"});let u=await Lc({...i.payload,repoRoot:t});return it(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await Mc({repoRoot:t,issueId:i.payload.issueId});return it(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await Pc({repoRoot:t,issueId:i.payload.issueId});return it(o,t,n,"issue:reopen:result",u)}return Fe(o,{type:"error",message:"Unknown message type"})}catch(i){return Fe(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var jf=an.dirname(Hf(import.meta.url)),Vf=process.env.IS_LOCAL==="true"?an.resolve(process.cwd(),"dist/gui"):an.join(jf,"gui"),at=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},Gf=async e=>new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o}),e.on("end",()=>{try{t(r?JSON.parse(r):{})}catch{n(new Error("Invalid JSON body"))}}),e.on("error",n)}),zf=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",Wc=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=an.resolve(Vf),o=an.resolve(r,n),s=an.relative(r,o);if(s.startsWith("..")||an.isAbsolute(s))return at(t,403,{isError:!0,message:"Forbidden"});try{let i=await $f(o);return t.writeHead(200,{"content-type":zf(o)}),t.end(i)}catch{return at(t,404,{isError:!0,message:`Not found: ${n}`})}},Kf=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),Hc=async e=>{let t=Wf.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return at(s,200,await Ot({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await Gf(o);if(!c.issueId||!c.body?.trim())return at(s,400,{isError:!0,message:"Missing issueId or body"});let u=await Eo({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?at(s,400,u):at(s,200,await Ot({repoRoot:e.repoRoot}))}catch(c){return at(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return at(s,400,{isError:!0,message:"Missing comment id"});let u=await So({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?at(s,400,u):at(s,200,await Ot({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?Wc("/",s):Wc(i.pathname,s)});try{await Kf(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=_c({repoRoot:e.repoRoot});$c(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var jc=async e=>{let t=await Hc({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${qf.cyan(n)}`),mi(n),l("Started GUI",{url:n})};import{Box as jt}from"ink";import ee from"react";import{Box as Xs,Text as nr}from"ink";import Ve,{useEffect as Yf,useMemo as Xf}from"react";import{ulid as Jf}from"ulid";var Vc=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ve.createElement(nr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?Ve.createElement(nr,{color:n,dimColor:o},e):Ve.createElement(nr,{color:n,dimColor:o},e.slice(0,c),Ve.createElement(nr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Gc=Jf(),Qf=e=>`${e}`,Zf=e=>{let{pendingNavTarget:t}=Dt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(le(x.NONE,{breadCrumb:n,contextNode:r,readOnly:f().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=Jr(i),u=vo.find(m=>m.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},eg=e=>Q.text({id:Gc,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),tg=(e,t,n)=>Q.text({id:Qf(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Js=[],ng=e=>{zc();let t=b.createNode(eg(f().rootNodeId));d(t)||!St(t.value)||(Js=[t.value,...e.map((n,r)=>tg(n,r,Gc)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0}))},zc=()=>{let e=Js.map(t=>t.id);Js=[];for(let t of e)b.deleteNode(t)};function Kc({width:e,height:t}){let r=dd().value.trim().toLowerCase(),o=Xf(()=>Zf(r),[r]);Yf(()=>(ng(o),()=>{zc()}),[o]);let s=f().selectedIndex;return Ve.createElement(Xs,{flexDirection:"column",width:e,height:t-2},Ve.createElement(rt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ve.createElement(Xs,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ve.createElement(nr,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",Ve.createElement(Vc,{text:ji(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ve.createElement(Xs,{paddingLeft:2},Ve.createElement(Vc,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as xg}from"ink";import Ao from"react";import or from"chalk";import{Box as Qs,Text as qc}from"ink";import rr,{useEffect as rg,useMemo as og,useState as sg}from"react";var Yc=or.hex(y.secondary),ig=or.inverse,ag=or.inverse.hex(y.secondary2),dg={hint:"",hints:[],overlap:0,remainder:""},Jc=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},cg=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ie(t);return{bg:r=>or.bgHex(n).black(r),bgCursor:r=>or.bgHex(n).inverse.black(r)}}return cs(t)},lg=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Jc({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},Xc=()=>({value:he.value,cursorPosition:he.cursorPosition,commandIsPending:he.commandIsPending,autoCompletion:he.commandMeta.autoCompletion??dg,infoMessage:he.commandMeta.infoMessage,validationStatus:he.commandMeta.validity,command:he.commandMeta.command,inputString:he.commandMeta.inputString,modifier:he.commandMeta.modifier}),ug=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,Qc=({width:e,mode:t})=>{let[n,r]=sg(Xc());rg(()=>{let I=()=>{let N=Xc();r(T=>ug(T,N)?T:N)},S=Rs(I);return I(),()=>{S()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p}=n,v=og(()=>{let I=Math.max(0,Math.min(s,o.length)),S=Jc({value:o,command:m}),N=lg({value:o,command:m,modifier:p}),T=m?cs(m):null,k=cg({command:m,modifier:p}),O=(de,X)=>{let lt=S&&X>=S.start&&X<S.end,ze=N&&X>=N.start&&X<N.end;return lt&&T?T.fg(de):ze&&k?k.bg(de):de},V=(de,X)=>{let lt=S&&X>=S.start&&X<S.end,ze=N&&X>=N.start&&X<N.end;return lt&&T?T.fgCursor(de):ze&&k?k.bgCursor(de):ig(de)},R=o.slice(0,I),A=o[I]??" ",G=I<o.length?o.slice(I+1):"",Re=Array.from(R).map((de,X)=>O(de,X)).join(""),Ae=V(A,I),Ge=Array.from(G).map((de,X)=>O(de,I+1+X)).join("");if(u.hint){let de=u.hint[u.overlap]??A;Ae=ag(de),Ge=Yc(u.remainder.slice(1)+G)}return Yc(t===g.PALETTE?"?":":")+Re+Ae+Ge},[o,s,u,m,p]);return rr.createElement(Qs,{flexDirection:"column",justifyContent:"flex-start"},rr.createElement(Qs,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},rr.createElement(Qs,null,rr.createElement(qc,null,v),i&&rr.createElement(qc,{wrap:"truncate",color:c?y.red:y.secondary2},` ${i} `))))};import{Box as mg,Text as pg}from"ink";import Zc from"react";var fg=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},el=({width:e,availableHints:t})=>{let n=fg(t,e).join(" | ");return Zc.createElement(mg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},Zc.createElement(pg,{color:y.secondary2},n.length?n:"\xA0"))};import{Box as gg,Text as No}from"ink";import sr,{useEffect as vg,useRef as Nn,useState as yg}from"react";var hg=40,Ro=.3,Zs="\u2500",tl=1,nl=16,rl=({width:e})=>{let{replay:t}=$(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*tl,[c,u]=yg(0),m=Nn(r);m.current=r;let p=Nn(0),v=Nn(0),I=Nn(0),S=Nn(0),N=Nn(0);if(vg(()=>{if(!n){p.current=0,I.current=0,S.current=0,N.current=0,u(0);return}p.current=m.current,v.current=Date.now(),I.current=m.current;let R=setInterval(()=>{let A=Date.now(),G=m.current;if(G!==I.current){let X=G-I.current,lt=A-v.current;if(X<0)S.current=0,N.current=0;else if(X>0&<>0){let ze=X/lt;S.current=S.current===0?ze:S.current*(1-Ro)+ze*Ro,N.current=N.current===0?X:N.current*(1-Ro)+X*Ro}p.current=G,v.current=A,I.current=G}let Re=A-v.current,Ae=Math.min(N.current,S.current*Re),Ge=Math.min(1,p.current+Ae),de=Math.round(Ge*i);u(X=>X===de?X:de)},hg);return()=>clearInterval(R)},[n,i]),!t)return null;let T=R=>{let A=s>1?R/(s-1):0,G=Math.round(A*(nl-1))/(nl-1);return Ar(G)},k=Math.min(s,Math.floor(c/tl)),O=[];for(let R=0;R<k;R++){let A=T(R),G=O[O.length-1];G&&G.color===A?G.text+=Zs:O.push({text:Zs,color:A})}let V=Zs.repeat(Math.max(0,s-k));return sr.createElement(gg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},sr.createElement(No,{color:y.secondary2},"\u25B6"),sr.createElement(No,null,O.map((R,A)=>sr.createElement(No,{key:A,color:R.color},R.text)),sr.createElement(No,{color:y.secondary,dimColor:!0},V)))};var ir=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=$(),o=t===g.COMMAND_LINE||t===g.PALETTE;return Ao.createElement(xg,null,o?Ao.createElement(Qc,{width:e,mode:t}):r==="replay"?Ao.createElement(rl,{width:e}):Ao.createElement(el,{width:e,mode:t,availableHints:n}))};import{Box as _t,Text as Rn}from"ink";import Ee,{useEffect as Ig,useMemo as bg}from"react";import{ulid as ol}from"ulid";var wo=ol(),Cg=()=>[...new Set([...f().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),Eg=e=>Q.text({id:wo,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Sg=(e,t,n)=>Q.text({id:ol(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),To=[],sl=()=>{let e=To.filter(n=>n.id!==wo).map(n=>n.id),t=To.filter(n=>n.id===wo).map(n=>n.id);To=[];for(let n of[...e,...t])b.deleteNode(n)},Ng=e=>{sl();let t=b.createNode(Eg(f().rootNodeId));if(d(t)||!St(t.value))return logger.error("Could not attach help nodes");To=[t.value,...e.map((n,r)=>Sg(n,r,wo)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0})},il=({width:e,height:t})=>{let n=bg(()=>Cg(),[]);Ig(()=>(Ng(n),()=>{sl()}),[n]);let r=f().selectedIndex;return Ee.createElement(_t,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},Ee.createElement(_t,{paddingX:1,justifyContent:"center"},Ee.createElement(Rn,{color:y.accent},"Help"),Ee.createElement(Rn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),Ee.createElement(_t,{paddingX:1,marginTop:1},Ee.createElement(_t,{width:20,justifyContent:"flex-end"},Ee.createElement(Rn,{color:y.secondary},"Key(s)")),Ee.createElement(_t,{flexGrow:1,width:40,paddingLeft:2},Ee.createElement(Rn,{color:y.secondary},"Action"))),Ee.createElement(rt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return Ee.createElement(_t,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},Ee.createElement(_t,{width:20,justifyContent:"flex-end"},Ee.createElement(Rn,{color:y.accent},o)),Ee.createElement(_t,{flexGrow:1,width:40,paddingLeft:2},Ee.createElement(Rn,{color:c?y.primary:y.secondary2},s)))})))};import Rg from"chalk";import{Box as Mo,Text as bt}from"ink";import Be from"react";var al=({width:e,height:t})=>Be.createElement(Mo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Be.createElement(bt,{color:y.accent,bold:!0},"Initialize project"),Be.createElement(bt,null,`This folder is not an ${Rg.hex(y.accent)("epiq")} project yet.`),Be.createElement(bt,{color:y.primary},"To start tracking issues here, we need to initialize a new",Be.createElement(bt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Be.createElement(Mo,{marginTop:1,flexDirection:"column"},Be.createElement(Mo,null,Be.createElement(bt,{color:y.accent}," "),Be.createElement(bt,{color:y.primary},"Type "),Be.createElement(bt,{backgroundColor:y.secondary}," :init "))),Be.createElement(Mo,{marginTop:1},Be.createElement(bt,{color:y.secondary2},"This will create, commit and push "),Be.createElement(bt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as Po,Text as dt}from"ink";import pe from"react";var Ag=({isDone:e,command:t,value:n})=>pe.createElement(Po,null,pe.createElement(dt,{color:y.accent,dimColor:e},e?" \u2714 ":" "),pe.createElement(dt,{dimColor:e},"Type "),pe.createElement(dt,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&pe.createElement(pe.Fragment,null,pe.createElement(dt,{dimColor:e}," "),pe.createElement(dt,{color:y.secondary,dimColor:e},"<"+n+">"))),Tg=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function ei({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=wt(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(v=>!v.done),p=m===-1?void 0:u[m];return pe.createElement(Po,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},pe.createElement(dt,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),pe.createElement(dt,null,"Let's get you started - it's a breeze."),pe.createElement(dt,{color:y.secondary2},"Remember - you can always search available commands by typing:",pe.createElement(dt,{color:y.accent}," ? ")),p&&pe.createElement(dt,{color:y.secondary2},p.message),pe.createElement(Po,{flexDirection:"column"},u.map((v,I)=>m===-1||I<=m?pe.createElement(Po,{key:v.key,marginBottom:1},pe.createElement(Ag,{isDone:v.done,command:v.command,value:v.done?Tg(v.value):void 0})):null)))}import Bo from"chalk";import{Box as dr,Text as An}from"ink";import me from"react";import{Box as Lo,Text as dl}from"ink";import $t from"react";import wg from"chalk";var Mg=e=>(b.getTag(e)?.name??"").length+3,Pg=e=>(b.getContributor(e)?.name??"").length+3,cl=({width:e})=>{let{viewMode:t}=H(),n=$(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=pt(c?.id??o.id,"TICKET"),m=te(u)?u.value:void 0,p=m?.props.tags??[],v=m?.props.assignees??[],I=m?.parentNodeId?!is(o.id,m.parentNodeId)&&t==="dense":!1,S=r.map((A,G)=>{let Re=G===r.length-1,Ae=z(A.id),Ge=Re?Ae?.[s]?.title:void 0;return`${G?" / ":""}${A.title??""}${Ge?` \u25B8 ${Ge}`:""}`}).join(""),N=m?b.getCommentsByIssue(m.id):[],T=N.length?String(N.length).length+11:0,k=I?p.reduce((A,G)=>A+Mg(G),0)+v.reduce((A,G)=>A+Pg(G),0)+T:0,O=Math.max(0,e-k),V=S.substring(0,O)+(c?.id?wg.hex(y.secondary2).dim(` #${et(c.id)}`):""),R=I?[...p.map(A=>$t.createElement(Lo,{key:`tag-${A}`,paddingLeft:1},$t.createElement(Cn,{id:A}))),...v.map(A=>$t.createElement(Lo,{key:`assignee-${A}`,paddingLeft:1},$t.createElement(Pt,{id:A}))),N.length?$t.createElement(Lo,{key:"comments",paddingLeft:1},$t.createElement(dl,{color:y.accent},"[",N.length," comment",N.length===1?"":"s","]")):null]:[];return $t.createElement(Lo,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},$t.createElement(dl,{color:y.secondary2},V),R)};import{Box as Lg,Text as ll}from"ink";import ko from"react";var kg=({filters:e})=>ko.createElement(Lg,{columnGap:1},ko.createElement(ll,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>ko.createElement(ll,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),ul=ko.memo(kg);import{Box as Dg,Text as Do}from"ink";import ar from"react";function ml(){let{eventLog:e,unappliedEvents:t}=$(),n=e.at(-1)?.id,r=Lr(n??""),o=te(r)?Pr(r.value):"INVALID DATE";return ar.createElement(Dg,{paddingLeft:1},ar.createElement(Do,{backgroundColor:y.accent,color:y.secondary}," Readonly "),ar.createElement(Do,{color:y.accent}," "+t.length+" edits ago at "+o+"."),ar.createElement(Do,{color:y.accent}," Resume with "),ar.createElement(Do,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as Fg,Text as ti}from"ink";import Fo from"react";function pl(){let{replay:e}=$();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Fo.createElement(Fg,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Fo.createElement(ti,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Fo.createElement(ti,{color:y.secondary2},Pr(new Date(r))),Fo.createElement(ti,{color:y.accent},`${t}/${n} edits`))}import ni from"chalk";import{Box as Bg,Text as fl}from"ink";import ri,{useEffect as Ug,useState as Og}from"react";var _g=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],$g=150,gl=12,Wg=.36,vl=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Hg=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},jg=(e,t,n)=>{let r=vl(e),o=vl(t);return Hg({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Vg=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return jg(s,i,o)};function yl({syncStatus:e,autoSync:t}){let[n,r]=Og(0);Ug(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*Wg)+1)/2,p=Math.round(m*(gl-1));r(v=>v===p?v:p)},$g);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:Vg(_g,n/(gl-1))??""}[e.status];return ri.createElement(Bg,null,ri.createElement(fl,null,ni.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),ri.createElement(fl,null,ni.hex(i)("\u25CF")+ni.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Cl from"chalk";import{Text as El}from"ink";import Sl,{useEffect as qg,useState as Yg}from"react";var Wt="1.2.1";import oi from"chalk";var Gg="https://registry.npmjs.org/epiq/latest",si=null,hl=0,zg=1e3*60*60*24,xl=e=>e.replace(/^v/,""),Kg=(e,t)=>{let n=xl(e).split(".").map(Number),r=xl(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},Il=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(si&&Date.now()-hl<zg)return si;try{let t=await fetch(Gg);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?Kg(r,e)>0:!1};return si=o,hl=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},bl=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?oi.hex(y.accent).dim(s):oi.hex(y.secondary).dim(s)).join(oi.hex(y.secondary2).dim("."))};function Nl(){let[e,t]=Yg({current:Wt,latest:null,updateAvailable:!1});return qg(()=>{let n=!0;return Il(Wt).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Sl.createElement(El,{dimColor:!0,color:y.secondary2},Wt+" "):Sl.createElement(El,null,Cl.hex(y.secondary2).dim(Wt),Cl.hex(y.accent).dim(" \u2197 "),bl(Wt,e.latest))}function cr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=$(),{userName:i,preferredEditor:c,autoSync:u}=H(),m=64,p=process.stdout.columns-m-8,v=t||n==="replay",I=s?mn(s.currentLabel,Math.max(0,p)):"";return me.createElement(dr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?me.createElement(dr,{paddingLeft:1},me.createElement(An,{color:y.secondary2},I)):v?me.createElement(An,null," "):o===g.PALETTE?me.createElement(dr,null,me.createElement(An,{color:y.accent},"Command Palette"),me.createElement(An,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):me.createElement(dr,{paddingLeft:1},e.length>0?me.createElement(ul,{filters:e}):me.createElement(cl,{width:p})),n==="live"?me.createElement(dr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},me.createElement(yl,{autoSync:!!u,syncStatus:r}),me.createElement(An,null,Bo.hex(y.secondary2).dim("Mode: ")+Bo.hex(y.secondary2).dim(o.padEnd(8," "))," "),me.createElement(Rl,{icon:"@",value:i}),me.createElement(Rl,{icon:"\u276F",value:c}),me.createElement(Nl,null)):"",n==="peek"?me.createElement(ml,null):"",n==="replay"?me.createElement(pl,null):"")}function Rl({icon:e,value:t}){return me.createElement(An,null,Bo.dim(e)+Bo.hex(y.accent)(` ${t??"-"} `))}import{Box as Xg,Text as Jg}from"ink";import lr from"react";import{Box as Uo,Text as ii}from"ink";import Ht from"react";function ai(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?W(t?.id):[];return Ht.createElement(Uo,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},Ht.createElement(Uo,{padding:1,paddingTop:0,paddingBottom:0},Ht.createElement(ii,null,"Select a board:")),Ht.createElement(Uo,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,v=W(c.id).flatMap(({id:I})=>z(I)).length;return Ht.createElement(Uo,{key:c.id??u},Ht.createElement(ii,{color:m?y.accent:y.secondary2},Ht.createElement(Ce,{isSelected:m})),Ht.createElement(ii,{color:m?y.accent:y.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var Qg=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=$(),u=n.find(({context:I})=>I==="BOARD"),v=s-1-3;return lr.createElement(Xg,{flexDirection:"row"},e.context==="WORKSPACE"?lr.createElement(ai,null):u?lr.createElement(so,{height:v,width:i,swimlanes:(c[u.id]??[]).filter(I=>I!==void 0&&Nt(I)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):lr.createElement(Jg,null))},Al=lr.memo(Qg);import{useEffect as Zg}from"react";var ev=e=>{Zg(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=H();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=f();u==="default"&&!c&&Wr(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Tl=({autoSync:e})=>(ev(e),null);function di({width:e,height:t}){let n=$(),{autoSync:r,viewMode:o}=Yi(),s=n.filters;if(n.mode===g.HELP)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(il,{width:e,height:t}));if(n.mode===g.PALETTE)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{filters:s}),ee.createElement(Kc,{width:e,height:t-2}),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=wt(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{hideBreadCrumb:!0,filters:s}),ee.createElement(ei,{height:t,width:e})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{hideBreadCrumb:!0,filters:s}),ee.createElement(al,{height:t,width:e})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=be(n.breadCrumb??[],"BOARD");if(te(m)){let p=m.value.id,v=W(p).length,I=3,S=Math.floor(e/I),N=Math.floor(e/Math.max(v,1));e=Math.min(N,S)*Math.max(v,I)}return ee.createElement(jt,{flexDirection:"column"},ee.createElement(Tl,{autoSync:r}),ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{filters:s}),ee.createElement(Al,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}))}import tv from"readline";var Oo,_o,ct,nv=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),rv=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp]),wl=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=f(),s=ld(e,n);if(!s||r&&!nv.has(s)||o==="replay"&&n===g.DEFAULT&&rv.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},ov=()=>async function(t,n){n.name!=="escape"&&(ct&&(clearTimeout(ct),ct=void 0),await wl(n))},sv=()=>async function(t){if(t.length===1&&t[0]===27){ct&&clearTimeout(ct),ct=setTimeout(()=>{wl({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),ct=void 0},25);return}ct&&(clearTimeout(ct),ct=void 0)};function Ml(){Oo&&process.stdin.removeListener("keypress",Oo),_o&&process.stdin.removeListener("data",_o),Oo=ov(),_o=sv(),tv.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",_o),process.stdin.on("keypress",Oo)}async function Pl(){try{let e=Qn();te(e)&&_e(e.value);let t=Ke(process.cwd()),n=[];if(te(t)){let s=Te({repoRoot:t.value});if(d(s))return Qt(3,s.message);let i=dn(),c=await Gt({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return Qt(3,c.message);let u=await U({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=ft(s.value);if(d(m))return Qt(3,m.message);n=m.value}let r=Jt(n);if(d(r))return Qt(4,r.message);C({hasProjectDefinition:te(t),hasInitializingEvents:!!n.length});let o=ci();return d(o)?Qt(6,o.message):(Ml(),l("Booted Epiq",void 0))}catch(e){return Qt(0,Or(e))}}_d();var cv=`${Vt.bold("Epiq CLI")}
|
|
56
|
+
`,zs.writeFileSync(t,n,"utf8"),ie.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var xf=async e=>{let t=await O({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},X=(e,t)=>a(`[${e}] ${t}`),Xd=async()=>{$("");let e=mn(),t=await Ze(process.cwd());if(d(t))return X(1,t.message);let n=t.value,r=await Er(n);if(d(r))return X(2,r.message);if(r.value)return X(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await xf(n);if(d(o))return X(2.5,o.message);if(o.value)return X(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Xo(n))return X(4,"Epiq project already initialized");let s=Lt();if(!s.isSetupDone||!s.userName)return X(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=G(),c=i.userName,u=i.userId;if(!u||!c)return X(5,"Missing Epiq user id");let m=e.stateBranch,p=await Nr({repoRoot:n,branch:m});if(d(p))return X(6,p.message);if(p.value)return X(6,`State branch already exists: ${m}`);let g=await ds({repoRoot:n,stateBranchName:m});if(d(g))return X(6,g.message);let C=Tr();if(d(C))return X(7,C.message);let S=Yd.join(Ar(),e.projectId),N=await Yt({repoRoot:n,stateBranchRoot:S,stateBranchName:m});if(d(N))return X(8,N.message);let T=Yd.join(S,".epiq");hf.mkdirSync(T,{recursive:!0});let P=Fa({userId:u,userName:c});if(d(P))return X(9,P.message);for(let qo of P.value){let yi=Wr({event:qo,rootDir:S});if(d(yi))return X(9,yi.message)}let B=await wr({stateBranchRoot:S,eventFileName:en({userId:u,userName:c})});if(d(B))return X(10,B.message);let W=await fn({cwd:S,message:"[epiq:init]"});if(d(W))return X(10,W.message);let R=await qd(n);if(d(R))return X(11,R.message);let k=Ci({repoRoot:n,fileContents:e});if(d(k))return X(12,k.message);let _=await ae.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(_))return X(13,_.message);let J=await ae.commit({cwd:n,message:"[epiq:init-project]"});if(d(J))return X(13,J.message);let Me="Project initialized!",qe=await O({cwd:n,args:["push","-u","origin","HEAD"]});d(qe)&&(Me+=` Warn: [init:14] ${qe.message}`);let Re=await Wn({repoRoot:n,stateBranchRoot:S});d(Re)&&(Me+=` Warn: [init:15] ${Re.message}`);let le=Pt(P.value).filter(d);if(le.length>0)return X(16,le.map(qo=>qo.message).join(`
|
|
57
|
+
`));let se=Ge();if(d(se))return X(16,se.message);let{rootNodeId:Ln,nodes:kn}=se.value,vi=kn[Ln];return vi?(w.navigate({contextNode:vi,selectedIndex:0}),b({hasProjectDefinition:!0,mode:v.DEFAULT}),l(Me,null)):X(16,"Unable to resolve initialized root node")};import{ulid as bf}from"ulid";import{ulid as If}from"ulid";var Jd=null,$t=()=>structuredClone(Jd),or=e=>{Jd=e},Qd=()=>{let{contextNode:e,selectedIndex:t}=f(),r=z(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},Ks=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z(t).filter(o=>o.id!==e);return Hr(r,n)},Zd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ee();if(d(r))return a("Unable to resolve user ID");let o=Ks({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:If(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},ec=e=>{or(e);let t=Mt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function qs(e){let t=Qd();if(d(t))return t;let{contextNode:n,nodes:r}=f();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=z(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=Zd({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:ec(u.value)}function Ys(e){let t=Qd();if(d(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=z(n.id)[r+e];if(!s)return a("Missing sibling node");let i=Zd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:ec(i.value)}var tc=()=>{let e=$t();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=f().nodes[n];if(!r)return a("Move parent not found");let o=z(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(w.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},vo=(e,t="Moved preview")=>{if(d(e))return e;let n=tc();return d(n)?n:(b({mode:v.MOVE}),l(t,null))},nc=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=q().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=z(n.id)[r];if(!o)return b({mode:v.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=z(o.parentNodeId),i=s.findIndex(({id:g})=>g===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Ks({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(or({id:bf(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),b({mode:v.MOVE}),l("Move initialized",null))}if(t==="next")return vo(Ys(1));if(t==="previous")return vo(Ys(-1));if(t==="to-next")return vo(qs(1));if(t==="to-previous")return vo(qs(-1));if(t==="confirm"){let s=$t();if(!s)return a("No pending move to confirm");let i=await Qe();if(d(i))return i;let c=U([s],i.value);if(d(c))return c;let u=tc();return d(u)?u:(or(null),b({mode:v.DEFAULT}),l("Moved item",null))}return t==="cancel"?(or(null),b({mode:v.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as ho}from"ulid";import{monotonicFactory as Cf,ulid as Ef}from"ulid";var Sf=Cf(),yo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Sf();return l("Created issue events",[{id:Ef(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var rc=async(e,t)=>{let n=ee();if(d(n))return a("Unable to resolve user ID");let r=await Qe();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=f(),u=m=>{let p=U([m],o);if(d(p))return p;let g=I.getNode(p.value[0].result.id);if(!g)return a("Created node not found");if(!g.parentNodeId)return p;let C=I.getNode(g.parentNodeId);return C?(w.navigate({contextNode:C,selectedIndex:I.getSiblings(g.parentNodeId).findIndex(({id:S})=>S===g.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=I.getNode(m);if(!p)return a("Workspace not found");let g=In(p.id,n.value,o);return d(g)?g:u({id:ho(),action:"add.board",payload:{id:ho(),name:t.inputString,parent:p.id,rank:g.value},...n.value})}if(t.modifier==="swimlane"){let m=Ee(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=In(m.value.id,n.value,o);return d(p)?p:u({id:ho(),action:"add.swimlane",payload:{id:ho(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=j(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let W=Ee(s,"SWIMLANE");return d(W)?null:W.value})();if(!p)return a("Unable to add issue in this context");let g=In(p.id,n.value,o);if(d(g))return g;let C=yo({name:t.inputString,parent:p.id,rank:g.value,user:n.value});if(d(C))return C;let S=C.value,N=U([...S],o);if(d(N))return N;if(!N.value[0])return a("Issue creation failed");let B=S.find(W=>W.action==="add.issue")?.payload.id;return B?(w.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:W})=>W===B)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var xo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=ha(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Wt();if(d(u))return u;let p=Pt(i).filter(d);if(p.length>0)return Wt(),b(o),a(p.map(C=>C.message).join(", "));let g=f().nodes[e];return g?(w.navigate({contextNode:g,selectedIndex:r}),l("",{unappliedEvents:c})):(Wt(),b(o),a("Board did not exist at that date"))};var Nf=20,Rf=16,Af=150,Io=null,bo=null;var cn=()=>{Io!==null&&(clearInterval(Io),Io=null),bo!==null&&(clearTimeout(bo),bo=null)},oc=()=>{cn(),b({mode:v.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Tf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},sc=({events:e,startTime:t,durationMs:n})=>{cn();let r=e.length,o=e.map(g=>xn(g)??t),s=o[r-1]??Date.now(),i=Tf(o),c=Math.max(1,Math.round(n*Nf/1e3)),u=Math.max(Math.round(n/c),Rf),m=0,p=0;b({mode:v.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Io=setInterval(()=>{m++;let g=m/c,C=[],S;for(;p<r&&i[p]<=g;){let T=e[p],P=Mt(T);if(d(P)){oc();return}C.push(...ys(T)),S=T,p++}if(p>=r||m>=c){for(;p<r;p++){let P=Mt(e[p]);if(d(P))break}let T=f().replay;b({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),cn(),bo=setTimeout(oc,Af);return}let N=f().replay;b({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,g),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:S?xn(S)??N?.currentTime??t:N?.currentTime??t,currentLabel:S?pa(S):N?.currentLabel??"",flashNodeIds:S?[...new Set(C)]:N?.flashNodeIds??[]}})},u)};var ic=async()=>{let e=Ee(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ze(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta;if(cn(),r==="now"){let c=xt(n.value);if(d(c))return a(c.message);let u=Wt();if(d(u))return u;let p=Pt(c.value).filter(d);return p.length>0?a(p.map(g=>g.message).join(", ")):(b({mode:v.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=f().eventLog.at(-1),u=xn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=f().unappliedEvents.at(0),u=xn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=on(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=xo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(b({mode:v.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var ac=async()=>{let e=Ee(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ze(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta,{dateInput:s,durationInput:i}=Jr(r,o);if(cn(),f().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=on(s);if(!c)return a("Invalid replay date");let u=i?Xr(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=f(),g=xo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(g))return g;let{unappliedEvents:C}=g.value;return C.length===0?(Wt(),b(p),l("Nothing to replay from that point",!0)):(sc({events:C,startTime:m,durationMs:u}),l("Replaying board history",!0))};import Mf from"zod";var dc=()=>{let e=q().commandMeta.inputString,t=Mf.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=ct({autoSyncDebounceMs:t.data});return d(n)?n:(je({autoSyncIntervalMs:t.data}),b({mode:v.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var cc=()=>{let e=q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Ha(e),n=ct({autoSync:t});return d(n)?n:(je({autoSync:t}),b({mode:v.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var lc=()=>{let e=q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=ct({logLevel:e});return d(n)?n:(je({logLevel:e}),b({mode:v.DEFAULT}),l(`Auto sync set to "${e}"`,null))};import{spawn as Pf}from"node:child_process";var Lf=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},uc=async e=>new Promise(t=>{let{command:n,args:r}=Lf();try{let o=Pf(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?l("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}});var sr=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await uc(e);return d(n)?n:l(`Copied ${t} to clipboard`,null)},mc=async e=>{let{breadCrumb:t,selectedNode:n}=f(),r=Xn({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case me.REF:return sr(Te(o.id),"ref");case me.TITLE:return sr(o.title,"title");case me.DESCRIPTION:return r?sr(r.props?.description??"","description"):a("No issue in scope");case me.TAGS:{if(!r)return a("No issue in scope");let s=kt(r).map(({name:i})=>i);return sr(s.join(", "),"tags")}case me.ASSIGNEES:{if(!r)return a("No issue in scope");let s=Dt(r).map(({name:i})=>i);return sr(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var pc=async()=>{$(""),b({mode:v.DEFAULT});let e=Ge();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");b({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Gr();return d(t)?(b({syncStatus:{msg:t.message,status:"failed"}}),t):(b({mode:v.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var kf=e=>e.action==="add.issue.comment",fc=e=>Object.values(f().tags).find(t=>t.name===e),gc=e=>Object.values(f().contributors).find(t=>t.name===e),St=async()=>{let e=await Qe();return d(e)?e:l("Resolved persist root",e.value)},Co=[{systemOnly:!0,intent:M.Move,description:"Internal move-state command",mode:v.COMMAND_LINE,action:nc},{intent:M.Delete,description:"Delete the currently selected node",mode:v.COMMAND_LINE,action:async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=j(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await St();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=A(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=f().nodes[i];if(!c||!A(c))return a("Unable to resolve comment issue");let u=c.log?.filter(kf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):U([{id:be(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return U([{id:be(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:v.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=q().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>te(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return he(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:v.DEFAULT})),l("Filter updated",null)}},{intent:M.ViewHelp,description:"Open the help screen",mode:v.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return _t({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),b({mode:v.HELP}),l("Viewing help",null)}},{intent:M.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:v.COMMAND_LINE,action:async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=j(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!A(r))return a("Cannot close in this context");let o=f().nodes[ue];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await St();if(d(s))return s;let i=s.value,c=tn(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=U([{id:be(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:v.COMMAND_LINE,action:async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=j(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):ht(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=f().nodes[ue];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!A(s))return a("Target node is not issue");let c=fo(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=f().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await St();if(d(m))return m;let p=m.value,g=tn(u.id,s.id,{at:"end"},e.value,p);if(d(g))return g;let C=U([{id:be(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:g.value},...e.value}],p);return d(C)?C:l("Issue reopened",null)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.Init,description:"Initialize Epiq in the current git repository",mode:v.COMMAND_LINE,action:Xd},{intent:M.NewItem,description:"Create a new board, swimlane, or issue",mode:v.COMMAND_LINE,action:rc,onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.Rename,description:"Rename the currently selected node",mode:v.COMMAND_LINE,action:async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=j(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=fd();if(!o)return a("Provide a title");let s=await St();return d(s)?s:U([{id:be(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.UntagTicket,description:"Remove a tag from the selected issue",mode:v.COMMAND_LINE,action:async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=fc(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid untag target");let i=ht(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!A(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await St();return d(m)?m:U([{id:be(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.TagTicket,description:"Add or create a tag on the selected issue",mode:v.COMMAND_LINE,action:async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=f();if(!o)return a("Invalid tag target");let s=ht(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!A(i))return a("Target node is not issue");let c=await St();if(d(c))return c;let u=fc(r),m=u?.id??be();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):U([...u?[]:[{id:be(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:be(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.AssignUserToTicket,description:"Assign a user to the selected issue",mode:v.COMMAND_LINE,action:async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=f(),i=j(s.id)[o];if(!i)return a("Invalid assign target");let c=ht(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!A(u))return a("Target node is not issue");let m=await St();if(d(m))return m;let p=gc(r),g=p?.id??be();return(u.props.assignees??[]).includes(g)?a("Assignee already assigned"):U([...p?[]:[{id:be(),action:"create.contributor",payload:{id:g,name:r},...e.value}],{id:be(),action:"add.issue.assignee",payload:{id:u.id,assignee:g},...e.value}],m.value)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:v.COMMAND_LINE,action:async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=gc(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid unassign target");let i=ht(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!A(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await St();return d(m)?m:U([{id:be(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.Comment,description:"Add a comment to the selected issue",mode:v.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>En)return a(`Cannot exceed ${En} characters`);let r=ee();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=f(),i=Ee([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):ht(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!A(m))return a("Target node is not issue");let p=await St();return d(p)?p:U([{id:be(),action:"add.issue.comment",payload:{id:be(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.Sync,description:"Pull, commit, and push Epiq state",mode:v.COMMAND_LINE,action:pc},{intent:M.Peek,description:"View board state at another point in time",mode:v.COMMAND_LINE,action:ic},{intent:M.Replay,description:"Replay board history forward from a point in time",mode:v.COMMAND_LINE,action:ac},{intent:M.Export,description:"Export the current board layout to markdown",mode:v.COMMAND_LINE,action:async()=>{let e=await Fd();return d(e)?e:(b({mode:v.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,description:"Exit the application",mode:v.COMMAND_LINE,action:async()=>(w.exit(),l("Exit successful",!0))},{intent:M.Edit,description:"Edit title or description",mode:v.COMMAND_LINE,action:async(e,t)=>Kd(t),onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:v.COMMAND_LINE,action:async(e,t)=>mc(t),onSuccess:()=>b({mode:v.DEFAULT})},{intent:M.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:v.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ce.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=G(),i=n||s,c=r??be();if(!i||!c)return a("Unable to resolve user name or id");let u=ct({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(je({userName:i,userId:c}),b({mode:v.DEFAULT}),l(`Username set to "${i}"`,null))}case ce.EDITOR:{if(!n)return a("No editor provided");let r=ct({preferredEditor:n});return d(r)?r:(je({preferredEditor:n}),b({mode:v.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ce.VIEW:{if(n!=="wide"&&n!=="dense")return a("Invalid view mode");let r=ct({viewMode:n});return d(r)?r:(je({viewMode:n}),b({mode:v.DEFAULT}),l(`View set to "${n}"`,null))}case ce.AUTOSYNC:return cc();case ce.LOG_LEVEL:return lc();case ce.SYNC_DEBOUNCE_MS:return dc();default:return a("Unknown config command")}}},{intent:M.Coffee,description:"Sponsor the development of Epiq!",mode:v.COMMAND_LINE,action:()=>{let e=q().commandMeta.modifier;return e==="custom"?Vs("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Vs(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),$(""),l("Thanks you!",null)}}];var Df=new Set(["peek","replay","filter","view-help","yank"]),lt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=q();if(!t)return a("No command to confirm");if(!e&&n===st.Invalid)return a("Invalid command");let s=ro(t);cd();let{readOnly:i}=f();if(i&&!Df.has(s))return Jn({status:Rt.Fail,message:"Command not available in readonly state",value:null});let c=Co.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Jn({status:Rt.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return Jn({status:Rt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Jn(u):(ld({addToHistory:!e}),c.onSuccess?.(),G().autoSync&&Kr(),u)};var Eo=[{intent:h.Exit,mode:v.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(b({mode:v.COMMAND_LINE}),$("move cancel"),lt({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:v.DEFAULT,description:"[m] move (init/confirm)",action:()=>(b({mode:v.COMMAND_LINE}),$("move start"),lt({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:v.MOVE,action:()=>(b({mode:v.COMMAND_LINE}),$("move confirm"),lt({isForceExecutedBySystem:!0}))}],So=[{intent:h.MovePreviousItem,mode:v.MOVE,action:()=>$t()?(b({mode:v.COMMAND_LINE}),$("move previous"),lt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:v.MOVE,action:()=>$t()?(b({mode:v.COMMAND_LINE}),$("move next"),lt({isForceExecutedBySystem:!0})):a("No pending move")}],vc=[{intent:h.MoveToNextContainer,mode:v.MOVE,action:()=>$t()?(b({mode:v.COMMAND_LINE}),$("move to-next"),lt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:v.MOVE,action:()=>$t()?(b({mode:v.COMMAND_LINE}),$("move to-previous"),lt({isForceExecutedBySystem:!0})):a("No pending move")}];var yc={[L.WORKSPACE]:[...Eo,...So],[L.BOARD]:[...Eo,...So],[L.SWIMLANE]:[...Eo,...So,...vc],[L.TICKET]:[],[L.FIELD]:[],[L.FIELD_LIST]:[],[L.TEXT]:[],[L.COMMENT]:[]};var hc=()=>{$("");let{pendingNavTarget:e}=Ot();b({mode:v.DEFAULT}),e&&w.navigate(e),_t({pendingNavTarget:void 0})},xc=[{intent:h.ExitCommandLine,mode:v.HELP,action:()=>(hc(),l("Exiting help",null))},{intent:h.Exit,mode:v.HELP,action:()=>(hc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:v.HELP,description:"[arrows/hjkl] navigate",action:()=>(w.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:v.HELP,action:()=>(w.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:v.HELP,action:()=>(w.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:v.HELP,action:()=>(w.navigateToNextContainer(),l("Navigating to next help container",null))}];var Ff=e=>{b({mode:v.COMMAND_LINE});let{pendingNavTarget:t}=Ot();t&&w.navigate(t),_t({pendingNavTarget:void 0}),$(`${e} `)},Ic=()=>{$("");let{pendingNavTarget:e}=Ot();e&&w.navigate(e),_t({pendingNavTarget:void 0}),b({mode:v.DEFAULT})},bc=[{intent:h.InitCommandPalette,mode:v.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{$("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return _t({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),b({mode:v.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:v.PALETTE,action:()=>{let{selectedNode:e}=f();if(!e||!Tt(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(Ff(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:v.PALETTE,action:()=>(Ic(),l("Exiting palette",null))},{intent:h.Exit,mode:v.PALETTE,action:()=>(Ic(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:v.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(w.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:v.PALETTE,action:()=>(w.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:v.PALETTE,action:()=>(w.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:v.PALETTE,action:()=>(w.navigateToNextContainer(),l("Navigating to next container",null))}];var Cc=[...xc,...bc,{intent:h.AddItem,mode:v.DEFAULT,description:"[n] new...",action:()=>(b({mode:v.COMMAND_LINE}),$(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:v.DEFAULT,description:"[d] delete",action:()=>(b({mode:v.COMMAND_LINE}),$(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:v.DEFAULT,description:"[:] focus command line",action:()=>(b({mode:v.COMMAND_LINE}),$(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:v.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!z(e?.id??"")?.length){if(e?.title===Q.DESCRIPTION)return b({mode:v.COMMAND_LINE}),$(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===Q.ASSIGNEES)return b({mode:v.COMMAND_LINE}),$(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===Q.TAGS)return b({mode:v.COMMAND_LINE}),$(`${x.TAG} `),l("Propose command",!0);if(t.title===Q.DESCRIPTION&&e?.context==="TEXT")return b({mode:v.COMMAND_LINE}),$(`${x.EDIT} description `),l("Propose command",!0)}return w.enterChildNode(),l("Entering context",null)}},{intent:h.Yank,mode:v.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=f(),t=e?.title===Q.DESCRIPTION?me.DESCRIPTION:e?.title===Q.TAGS?me.TAGS:e?.title===Q.ASSIGNEES?me.ASSIGNEES:me.REF,r=te(x.YANK).includes(t)?t:me.REF;return b({mode:v.COMMAND_LINE}),$(`${x.YANK} ${r}`),l("Propose command",!0)}},{intent:h.EditTitle,mode:v.DEFAULT,description:"[r] rename title",action:()=>(b({mode:v.COMMAND_LINE}),$(`${x.EDIT} title ${f().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:v.DEFAULT,description:"[e] edit description",action:()=>(b({mode:v.COMMAND_LINE}),$(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:v.DEFAULT,description:"[q] exit context",action:()=>(w.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:v.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(w.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:v.DEFAULT,action:()=>(w.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:v.DEFAULT,action:()=>(w.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:v.DEFAULT,action:()=>(w.navigateToNextContainer(),l("Navigating to next container",null))}];var Bf=500,Uf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Ec=e=>{let t=Uf(e);t&&no(n=>(n+t).slice(0,Bf))};var Of=[v.COMMAND_LINE,v.PALETTE],_f=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(ks(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(ks(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Ds("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Ds("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(no((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=f().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(Ec(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>(ad(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(dd(),l("Erasing input word",null))}],Sc=[{intent:h.Confirm,mode:v.COMMAND_LINE,action:()=>(lt(),l("Executing command",null))},{intent:h.ViewHelp,mode:v.DEFAULT,action:()=>(b({mode:v.HELP}),l("Viewing help",null))},...Of.flatMap(_f),{intent:h.ExitCommandLine,mode:v.COMMAND_LINE,action:()=>(b({mode:v.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:v.COMMAND_LINE,action:()=>(ud(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:v.COMMAND_LINE,action:()=>(md(),l("Getting next command from history",null))}];import Ac from"chalk";var No=Ac.dim.hex(y.secondary2)(": for command line"),Nc="q to exit",Rc=`${Ac.hex(y.accent)("m")} to confirm`,Xs={[L.WORKSPACE]:[No],[L.BOARD]:[No],[L.BOARD+v.COMMAND_LINE]:[No],[L.SWIMLANE]:[No],[L.TICKET+v.HELP]:[Nc],[L.SWIMLANE+v.HELP]:[Nc],[L.TICKET]:[],[L.FIELD]:[],[L.SWIMLANE+v.MOVE]:[Rc],[L.TICKET+v.MOVE]:[Rc]};var ir=e=>e.trim().toLocaleLowerCase(),$f=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Wf=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Tc=(e,t)=>{let n=ir(t.value);if(!n)return!0;switch(t.target){case"title":return ir(e.title??"").includes(n);case"description":return ir(e.props.description??"").includes(n);case"tag":return $f(e).map(ir).some(o=>o.includes(n));case"assignee":return Wf(e).map(ir).some(o=>o.includes(n));case"ref":return oa(e.id,t.value);default:return!0}};function wc(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Mc=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 ln,Js,Qs=new Set,Pc=()=>{for(let e of Qs)e()},jf=e=>(Qs.add(e),()=>Qs.delete(e));function Lc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let u=wc(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,g=Xs[p+n]??Xs[p]??[],C=[...Cc,...yc[p]??[],...Sc],S=Mc(C),N=Vf(o,s),T=N[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:g,availableActions:C,actionIndex:S,selectedNode:T,renderedChildrenIndex:N})}var f=()=>{if(!ln)throw new Error("State not initialized. Call initWorkspaceState() first.");return ln},Ge=()=>ln?l("Retrieved state",ln):a("State not initialized. Call initWorkspaceState() first.");function zn(e){Js=e;let t=Je(process.cwd()),n=!1;if(!d(t)){let s=At(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:v.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},o=Lc(r);return d(o)?o:(ln=o.value,Pc(),l("State initialized",null))}function he(e){let t=f(),n=e(t),r=Lc(n);return d(r)?a(r.message??"Unable to update state"):(ln=r.value,Pc(),l("State updated",null))}var b=e=>he(t=>({...t,...e}));var H=()=>Hf(jf,f,f),Vf=(e,t)=>{let n={};for(let r of Object.values(e))A(r)&&t.length>0&&!t.every(o=>Tc(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,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},j=e=>f()?.renderedChildrenIndex[e]??[],Wt=()=>Js?zn(Js):a("Cannot reset state: no initial workspace found"),Cn=()=>ln!==void 0;var Zs=e=>{Cn()&&(b({syncStatus:e}),Xt({type:"sync-status",payload:e}))},Ro=(e="Syncing...")=>{Zs({status:"syncing",msg:e})},Ao=(e="Synced")=>{Zs({status:"synced",msg:e})},ei=e=>{Zs({status:"failed",msg:e})},ze=e=>(ei(e),a(e));import{decodeTime as tP}from"ulid";var Gf=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=K("getRepoRootDir",await Ze(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=K("getStateBranchRoot",Pe({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=K("ensureInitialCommit",await $i(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=K("bootstrapStateBranchStorage",await Hi({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=K("hasInProgressGitOperation(stateBranchRoot)",await Er(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=K("ensureStateBranchLayout",Ui(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},zf=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=K("stageStateBranchOwnEventFile",await wr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=K("hasStagedChanges(after stage)",await Pi(t));if(d(o))return a(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=K("createStateBranchSyncCommit",await Wi({repoRoot:e,stateBranchRoot:t}));return d(s)?a(s.message):(logger.debug("[sync] created sync commit",s.value),l("Committed own event file",{createdCommit:!0,commitSha:s.value}))},zr=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Ro();let n=K("ensureSyncReady",await Gf({cwd:e,ensureUpstream:!0}));if(d(n))return ze(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=K("isDetachedHead(stateBranchRoot)",await Li(o));if(d(i))return ze(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return ze("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,g=K("getStateBranch",pn(r));if(d(g))return ze(g.message);let C=g.value;logger.debug("[sync] resolved state branch",{stateBranch:C,stateBranchRoot:o});let S=K("commitOwnEventFileToStateBranch",await zf({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(S))return ze(S.message);c=S.value.createdCommit,u=S.value.commitSha;let N=K("pullBranchRebaseIfPresent",await os({cwd:o,branch:C}));if(d(N))return ze(N.message);if(m=N.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let T=K("pushStateBranch",await Wn({stateBranchRoot:o,repoRoot:r}));if(d(T)&&Mi(T.message)){let P=K("pullBranchRebaseIfPresent(retry)",await os({cwd:o,branch:C}));if(d(P))return ze(P.message);m=m||P.value,T=K("pushStateBranch(retry)",await Wn({stateBranchRoot:o,repoRoot:r}))}if(d(T))return ze(T.message);p=T.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=K("git rev-parse HEAD",await O({args:["rev-parse","HEAD"],cwd:o}));if(d(T))return ze(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Ao(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var ti=e=>{let t=Je(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},Be=async e=>{let t=ti(e);if(d(t))return t;let n=Pe({repoRoot:t.value});if(d(n))return a(n.message);let r=mn(),o=await Yt({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await O({cwd:n.value,args:["pull","--ff-only"]});d(s)&&ie.info(3,s.message);let i=xt(n.value);if(d(i))return a(i.message);let c=nn(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},Ue=()=>{let e=rr();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},Ye=()=>{let e=Ge();return d(e)?a(e.message):e},kc=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:de(t.name)})),Dc=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:de(t.name)}));var Fc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ye();if(d(n))return n;let r=Object.values(n.value.nodes).filter(A).filter(o=>e.includeClosed||o.parentNodeId!==ue).map(o=>({id:o.id,ref:Te(o.id),title:yt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===ue,readonly:!!o.readonly,tags:kc(o),assignees:Dc(o)}));return l("Listed issues",r)},Bc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=In(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=yo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=U([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},Uc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=tn(ue,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:Ce(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ue,rank:r.value}},s=U([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},Oc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Target node is not issue");if(o.parentNodeId!==ue)return a("Issue is not closed");let s=fo(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ue)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=tn(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:Ce(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=U([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},_c=async e=>{let t=ti(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Pe({repoRoot:t.value});if(d(r))return r;let o=xt(r.value);if(d(o))return o;let s=nn(o.value);if(d(s))return s;let i=tn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:Ce(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=U([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},To=async(e={})=>{Ro();let t=ti(e.repoRoot);if(d(t))return a("Sync failed");let n=Ue();if(d(n))return n;let r=await zr({cwd:t.value,ownEventFileName:en(n.value)});return d(r)?(ei(r.message),r):(Ao(),l("Synced",r.value))};var Ht=async(e={})=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ye();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(m=>Pr(m)&&!m.isDeleted),s=new Map,i=new Map;for(let m of r)if(!m.isDeleted){if(wt(m)&&m.parentNodeId){let p=s.get(m.parentNodeId)??[];p.push(m),s.set(m.parentNodeId,p)}if(A(m)&&m.parentNodeId){let p=i.get(m.parentNodeId)??[];p.push(m),i.set(m.parentNodeId,p)}}let c=rr();if(d(c))return c;let u={};for(let m of r.filter(A))m.isDeleted||(u[m.id]=I.getCommentsByIssue(m.id).map(p=>{let g=I.getContributor(p.authorId);return{id:p.id,issueId:p.issue,body:p.md,author:{id:p.authorId,name:g?.name??"Unknown",color:de(g?.name??p.authorId)},createdAt:Kf(p.id)}}));return l("Retrieved Epiq GUI state",{boards:o.sort((m,p)=>m.rank.localeCompare(p.rank)).map(m=>({id:m.id,ref:Te(m.id),title:m.title,swimlanes:(s.get(m.id)??[]).sort((p,g)=>p.rank.localeCompare(g.rank)).map(p=>({id:p.id,title:p.title,readonly:!!p.readonly,issues:(i.get(p.id)??[]).sort((g,C)=>g.rank.localeCompare(C.rank)).map(g=>({id:g.id,ref:Te(g.id),title:yt(g.title),description:g.props.description??"",readonly:!!g.readonly,tags:kc(g),assignees:Dc(g),parentNodeId:g.parentNodeId,isClosed:g.parentNodeId===ue})),parentNodeId:p.parentNodeId}))})),tags:Object.values(n.value.tags).map(m=>({...m,color:de(m.name)})),contributors:Object.values(n.value.contributors).map(m=>({...m,color:de(m.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:de(c.value.userName??"")},commentsByIssueId:u})},$c=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:Ce(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=U([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},Wc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=yt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:Ce(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=U([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},Hc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=yt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??Ce(),u=[...i?[]:[{id:Ce(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:Ce(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=U(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},jc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:Ce(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=U([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Vc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=yt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??Ce(),u=[...i?[]:[{id:Ce(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:Ce(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=U(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},Gc=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:Ce(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=U([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},wo=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=Ce(),c={id:Ce(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=U([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},Mo=async e=>{let t=await Be(e.repoRoot);if(d(t))return t;let n=Ue();if(d(n))return n;let r=Ye();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!A(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:Ce(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=U([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})};var zc=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=nr();if(d(p))return ie.error(p.message);let{autoSync:g,userName:C,preferredEditor:S}=p.value;return!!(g&&C&&S)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await To({repoRoot:e.repoRoot}),Xt({type:"state",payload:await Ht({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=nr();if(d(p))return ie.error(p.message);let{autoSyncDebounceMs:g}=p.value;i()&&(t=setTimeout(()=>{c(),m()},g??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as qf}from"ws";var Oe=(e,t)=>{e.send(JSON.stringify(t))},ar=async(e,t)=>Oe(e,{type:"state",payload:await Ht({repoRoot:t})}),ut=async(e,t,n,r,o)=>{if(Oe(e,{type:r,payload:o}),d(o))return Oe(e,{type:"failed",payload:o.message});n(),ar(e,t)},Kc=(e,t,{onStateChanged:n})=>{new qf({server:e,path:"/ws"}).on("connection",o=>{ji(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return ar(o,t);if(c==="sync"){let u=await To({repoRoot:t});return Oe(o,{type:"sync:result",payload:u}),n(),ar(o,t)}if(c==="issue:comment:add"){let u=await wo({repoRoot:t,...i.payload});return ut(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await Mo({repoRoot:t,...i.payload});return Oe(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Oe(o,{type:"failed",payload:u.message}):(n(),ar(o,t))}if(c==="issue:edit:description"){let u=await $c({repoRoot:t,...i.payload});return ut(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await Wc({repoRoot:t,...i.payload});return ut(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await Hc({repoRoot:t,...i.payload});return ut(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await jc({repoRoot:t,...i.payload});return ut(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await Vc({repoRoot:t,...i.payload});return ut(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await Gc({repoRoot:t,...i.payload});return ut(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Oe(o,{type:"issues",payload:await Fc({repoRoot:t})});if(c==="issues:create"){let u=await Bc({...i.payload,repoRoot:t});return Oe(o,{type:"issues:create:result",payload:u}),d(u)?Xt({type:"failed",payload:u.message}):(Xt({type:"issue:created",payload:u.value}),n(),ar(o,t))}if(c==="issues:move"){if(!i.payload.position)return Oe(o,{type:"error",message:"Missing move position"});let u=await _c({...i.payload,repoRoot:t});return ut(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Oe(o,{type:"error",message:"Missing issueId"});let u=await Uc({repoRoot:t,issueId:i.payload.issueId});return ut(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Oe(o,{type:"error",message:"Missing issueId"});let u=await Oc({repoRoot:t,issueId:i.payload.issueId});return ut(o,t,n,"issue:reopen:result",u)}return Oe(o,{type:"error",message:"Unknown message type"})}catch(i){return Oe(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var Qf=un.dirname(Jf(import.meta.url)),Zf=process.env.IS_LOCAL==="true"?un.resolve(process.cwd(),"dist/gui"):un.join(Qf,"gui"),mt=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},eg=async e=>new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o}),e.on("end",()=>{try{t(r?JSON.parse(r):{})}catch{n(new Error("Invalid JSON body"))}}),e.on("error",n)}),tg=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",qc=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=un.resolve(Zf),o=un.resolve(r,n),s=un.relative(r,o);if(s.startsWith("..")||un.isAbsolute(s))return mt(t,403,{isError:!0,message:"Forbidden"});try{let i=await Yf(o);return t.writeHead(200,{"content-type":tg(o)}),t.end(i)}catch{return mt(t,404,{isError:!0,message:`Not found: ${n}`})}},ng=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),Yc=async e=>{let t=Xf.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return mt(s,200,await Ht({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await eg(o);if(!c.issueId||!c.body?.trim())return mt(s,400,{isError:!0,message:"Missing issueId or body"});let u=await wo({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?mt(s,400,u):mt(s,200,await Ht({repoRoot:e.repoRoot}))}catch(c){return mt(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return mt(s,400,{isError:!0,message:"Missing comment id"});let u=await Mo({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?mt(s,400,u):mt(s,200,await Ht({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?qc("/",s):qc(i.pathname,s)});try{await ng(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=zc({repoRoot:e.repoRoot});Kc(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Xc=async e=>{let t=await Yc({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${rg.cyan(n)}`),hi(n),l("Started GUI",{url:n})};import{Box as Kt}from"ink";import re from"react";import{Box as ni,Text as dr}from"ink";import Xe,{useEffect as og,useMemo as sg}from"react";import{ulid as ig}from"ulid";var Jc=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Xe.createElement(dr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?Xe.createElement(dr,{color:n,dimColor:o},e):Xe.createElement(dr,{color:n,dimColor:o},e.slice(0,c),Xe.createElement(dr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Qc=ig(),ag=e=>`${e}`,dg=e=>{let{pendingNavTarget:t}=Ot();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(te(x.NONE,{breadCrumb:n,contextNode:r,readOnly:f().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=ro(i),u=Co.find(m=>m.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},cg=e=>Z.text({id:Qc,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),lg=(e,t,n)=>Z.text({id:ag(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),ri=[],ug=e=>{Zc();let t=I.createNode(cg(f().rootNodeId));d(t)||!Tt(t.value)||(ri=[t.value,...e.map((n,r)=>lg(n,r,Qc)).map(I.createNode).filter(oe).map(({value:n})=>n).filter(Tt)],w.navigate({contextNode:t.value,selectedIndex:0}))},Zc=()=>{let e=ri.map(t=>t.id);ri=[];for(let t of e)I.deleteNode(t)};function el({width:e,height:t}){let r=pd().value.trim().toLowerCase(),o=sg(()=>dg(r),[r]);og(()=>(ug(o),()=>{Zc()}),[o]);let s=f().selectedIndex;return Xe.createElement(ni,{flexDirection:"column",width:e,height:t-2},Xe.createElement(at,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Xe.createElement(ni,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Xe.createElement(dr,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",Xe.createElement(Jc,{text:Yi(i.command),match:r,color:m,dimColor:!i.isAvailable})),Xe.createElement(ni,{paddingLeft:2},Xe.createElement(Jc,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Tg}from"ink";import ko from"react";import lr from"chalk";import{Box as oi,Text as tl}from"ink";import cr,{useEffect as mg,useMemo as pg,useState as fg}from"react";var nl=lr.hex(y.secondary),gg=lr.inverse,vg=lr.inverse.hex(y.secondary2),yg={hint:"",hints:[],overlap:0,remainder:""},ol=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},hg=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=de(t);return{bg:r=>lr.bgHex(n).black(r),bgCursor:r=>lr.bgHex(n).inverse.black(r)}}return gs(t)},xg=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=ol({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},rl=()=>({value:Ie.value,cursorPosition:Ie.cursorPosition,commandIsPending:Ie.commandIsPending,autoCompletion:Ie.commandMeta.autoCompletion??yg,infoMessage:Ie.commandMeta.infoMessage,validationStatus:Ie.commandMeta.validity,command:Ie.commandMeta.command,inputString:Ie.commandMeta.inputString,modifier:Ie.commandMeta.modifier}),Ig=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,sl=({width:e,mode:t})=>{let[n,r]=fg(rl());mg(()=>{let N=()=>{let P=rl();r(B=>Ig(B,P)?B:P)},T=Ls(N);return N(),()=>{T()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p,validationStatus:g}=n,C=c&&g===st.Invalid,S=pg(()=>{let N=Math.max(0,Math.min(s,o.length)),T=ol({value:o,command:m}),P=xg({value:o,command:m,modifier:p}),B=m?gs(m):null,W=hg({command:m,modifier:p}),R=(le,se)=>{let Ln=T&&se>=T.start&&se<T.end,kn=P&&se>=P.start&&se<P.end;return Ln&&B?B.fg(le):kn&&W?W.bg(le):le},k=(le,se)=>{let Ln=T&&se>=T.start&&se<T.end,kn=P&&se>=P.start&&se<P.end;return Ln&&B?B.fgCursor(le):kn&&W?W.bgCursor(le):gg(le)},_=o.slice(0,N),J=o[N]??" ",Me=N<o.length?o.slice(N+1):"",qe=Array.from(_).map((le,se)=>R(le,se)).join(""),Re=k(J,N),$e=Array.from(Me).map((le,se)=>R(le,N+1+se)).join("");if(u.hint){let le=u.hint[u.overlap]??J;Re=vg(le),$e=nl(u.remainder.slice(1)+Me)}return nl(t===v.PALETTE?"?":":")+qe+Re+$e},[o,s,u,m,p]);return cr.createElement(oi,{flexDirection:"column",justifyContent:"flex-start"},cr.createElement(oi,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},cr.createElement(oi,null,cr.createElement(tl,null,S),i&&cr.createElement(tl,{wrap:"truncate",color:C?y.red:y.secondary2},` ${i} `))))};import{Box as bg,Text as Cg}from"ink";import il from"react";var Eg=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},al=({width:e,availableHints:t})=>{let n=Eg(t,e).join(" | ");return il.createElement(bg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},il.createElement(Cg,{color:y.secondary2},n.length?n:"\xA0"))};import{Box as Sg,Text as Po}from"ink";import ur,{useEffect as Ng,useRef as wn,useState as Rg}from"react";var Ag=40,Lo=.3,si="\u2500",dl=1,cl=16,ll=({width:e})=>{let{replay:t}=H(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*dl,[c,u]=Rg(0),m=wn(r);m.current=r;let p=wn(0),g=wn(0),C=wn(0),S=wn(0),N=wn(0);if(Ng(()=>{if(!n){p.current=0,C.current=0,S.current=0,N.current=0,u(0);return}p.current=m.current,g.current=Date.now(),C.current=m.current;let R=setInterval(()=>{let k=Date.now(),_=m.current;if(_!==C.current){let $e=_-C.current,le=k-g.current;if($e<0)S.current=0,N.current=0;else if($e>0&&le>0){let se=$e/le;S.current=S.current===0?se:S.current*(1-Lo)+se*Lo,N.current=N.current===0?$e:N.current*(1-Lo)+$e*Lo}p.current=_,g.current=k,C.current=_}let J=k-g.current,Me=Math.min(N.current,S.current*J),qe=Math.min(1,p.current+Me),Re=Math.round(qe*i);u($e=>$e===Re?$e:Re)},Ag);return()=>clearInterval(R)},[n,i]),!t)return null;let T=R=>{let k=s>1?R/(s-1):0,_=Math.round(k*(cl-1))/(cl-1);return kr(_)},P=Math.min(s,Math.floor(c/dl)),B=[];for(let R=0;R<P;R++){let k=T(R),_=B[B.length-1];_&&_.color===k?_.text+=si:B.push({text:si,color:k})}let W=si.repeat(Math.max(0,s-P));return ur.createElement(Sg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},ur.createElement(Po,{color:y.secondary2},"\u25B6"),ur.createElement(Po,null,B.map((R,k)=>ur.createElement(Po,{key:k,color:R.color},R.text)),ur.createElement(Po,{color:y.secondary,dimColor:!0},W)))};var mr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=H(),o=t===v.COMMAND_LINE||t===v.PALETTE;return ko.createElement(Tg,null,o?ko.createElement(sl,{width:e,mode:t}):r==="replay"?ko.createElement(ll,{width:e}):ko.createElement(al,{width:e,mode:t,availableHints:n}))};import{Box as jt,Text as Mn}from"ink";import Ne,{useEffect as wg,useMemo as Mg}from"react";import{ulid as ul}from"ulid";var Fo=ul(),Pg=()=>[...new Set([...f().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),Lg=e=>Z.text({id:Fo,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),kg=(e,t,n)=>Z.text({id:ul(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),Do=[],ml=()=>{let e=Do.filter(n=>n.id!==Fo).map(n=>n.id),t=Do.filter(n=>n.id===Fo).map(n=>n.id);Do=[];for(let n of[...e,...t])I.deleteNode(n)},Dg=e=>{ml();let t=I.createNode(Lg(f().rootNodeId));if(d(t)||!Tt(t.value))return logger.error("Could not attach help nodes");Do=[t.value,...e.map((n,r)=>kg(n,r,Fo)).map(I.createNode).filter(oe).map(({value:n})=>n).filter(Tt)],w.navigate({contextNode:t.value,selectedIndex:0})},pl=({width:e,height:t})=>{let n=Mg(()=>Pg(),[]);wg(()=>(Dg(n),()=>{ml()}),[n]);let r=f().selectedIndex;return Ne.createElement(jt,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},Ne.createElement(jt,{paddingX:1,justifyContent:"center"},Ne.createElement(Mn,{color:y.accent},"Help"),Ne.createElement(Mn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),Ne.createElement(jt,{paddingX:1,marginTop:1},Ne.createElement(jt,{width:20,justifyContent:"flex-end"},Ne.createElement(Mn,{color:y.secondary},"Key(s)")),Ne.createElement(jt,{flexGrow:1,width:40,paddingLeft:2},Ne.createElement(Mn,{color:y.secondary},"Action"))),Ne.createElement(at,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return Ne.createElement(jt,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},Ne.createElement(jt,{width:20,justifyContent:"flex-end"},Ne.createElement(Mn,{color:y.accent},o)),Ne.createElement(jt,{flexGrow:1,width:40,paddingLeft:2},Ne.createElement(Mn,{color:c?y.primary:y.secondary2},s)))})))};import Fg from"chalk";import{Box as Bo,Text as Nt}from"ink";import _e from"react";var fl=({width:e,height:t})=>_e.createElement(Bo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},_e.createElement(Nt,{color:y.accent,bold:!0},"Initialize project"),_e.createElement(Nt,null,`This folder is not an ${Fg.hex(y.accent)("epiq")} project yet.`),_e.createElement(Nt,{color:y.primary},"To start tracking issues here, we need to initialize a new",_e.createElement(Nt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),_e.createElement(Bo,{marginTop:1,flexDirection:"column"},_e.createElement(Bo,null,_e.createElement(Nt,{color:y.accent}," "),_e.createElement(Nt,{color:y.primary},"Type "),_e.createElement(Nt,{backgroundColor:y.secondary}," :init "))),_e.createElement(Bo,{marginTop:1},_e.createElement(Nt,{color:y.secondary2},"This will create, commit and push "),_e.createElement(Nt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as Uo,Text as pt}from"ink";import ye from"react";var Bg=({isDone:e,command:t,value:n})=>ye.createElement(Uo,null,ye.createElement(pt,{color:y.accent,dimColor:e},e?" \u2714 ":" "),ye.createElement(pt,{dimColor:e},"Type "),ye.createElement(pt,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&ye.createElement(ye.Fragment,null,ye.createElement(pt,{dimColor:e}," "),ye.createElement(pt,{color:y.secondary,dimColor:e},"<"+n+">"))),Ug=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function ii({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Lt(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(g=>!g.done),p=m===-1?void 0:u[m];return ye.createElement(Uo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},ye.createElement(pt,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),ye.createElement(pt,null,"Let's get you started - it's a breeze."),ye.createElement(pt,{color:y.secondary2},"Remember - you can always search available commands by typing:",ye.createElement(pt,{color:y.accent}," ? ")),p&&ye.createElement(pt,{color:y.secondary2},p.message),ye.createElement(Uo,{flexDirection:"column"},u.map((g,C)=>m===-1||C<=m?ye.createElement(Uo,{key:g.key,marginBottom:1},ye.createElement(Bg,{isDone:g.done,command:g.command,value:g.done?Ug(g.value):void 0})):null)))}import Ho from"chalk";import{Box as fr,Text as Pn}from"ink";import fe from"react";import{Box as Oo,Text as gl}from"ink";import Vt from"react";import Og from"chalk";var _g=e=>(I.getTag(e)?.name??"").length+3,$g=e=>(I.getContributor(e)?.name??"").length+3,vl=({width:e})=>{let{viewMode:t}=G(),n=H(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=ht(c?.id??o.id,"TICKET"),m=oe(u)?u.value:void 0,p=m?.props.tags??[],g=m?.props.assignees??[],C=m?.parentNodeId?!ms(o.id,m.parentNodeId)&&t==="dense":!1,S=r.map((_,J)=>{let Me=J===r.length-1,qe=z(_.id),Re=Me?qe?.[s]?.title:void 0;return`${J?" / ":""}${_.title??""}${Re?` \u25B8 ${Re}`:""}`}).join(""),N=m?I.getCommentsByIssue(m.id):[],T=N.length?String(N.length).length+11:0,P=C?p.reduce((_,J)=>_+_g(J),0)+g.reduce((_,J)=>_+$g(J),0)+T:0,B=c?.id!=null&&!(t==="wide"&&A(c)),W=Math.max(0,e-P),R=S.substring(0,W)+(B?Og.hex(y.secondary2).dim(` #${Te(c.id)}`):""),k=C?[...p.map(_=>Vt.createElement(Oo,{key:`tag-${_}`,paddingLeft:1},Vt.createElement(Nn,{id:_}))),...g.map(_=>Vt.createElement(Oo,{key:`assignee-${_}`,paddingLeft:1},Vt.createElement(Ft,{id:_}))),N.length?Vt.createElement(Oo,{key:"comments",paddingLeft:1},Vt.createElement(gl,{color:y.accent},"[",N.length," comment",N.length===1?"":"s","]")):null]:[];return Vt.createElement(Oo,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Vt.createElement(gl,{color:y.secondary2},R),k)};import{Box as Wg,Text as yl}from"ink";import _o from"react";var Hg=({filters:e})=>_o.createElement(Wg,{columnGap:1},_o.createElement(yl,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>_o.createElement(yl,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),hl=_o.memo(Hg);import{Box as jg,Text as $o}from"ink";import pr from"react";function xl(){let{eventLog:e,unappliedEvents:t}=H(),n=e.at(-1)?.id,r=Or(n??""),o=oe(r)?Ur(r.value):"INVALID DATE";return pr.createElement(jg,{paddingLeft:1},pr.createElement($o,{backgroundColor:y.accent,color:y.secondary}," Readonly "),pr.createElement($o,{color:y.accent}," "+t.length+" edits ago at "+o+"."),pr.createElement($o,{color:y.accent}," Resume with "),pr.createElement($o,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as Vg,Text as ai}from"ink";import Wo from"react";function Il(){let{replay:e}=H();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Wo.createElement(Vg,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Wo.createElement(ai,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Wo.createElement(ai,{color:y.secondary2},Ur(new Date(r))),Wo.createElement(ai,{color:y.accent},`${t}/${n} edits`))}import di from"chalk";import{Box as Gg,Text as bl}from"ink";import ci,{useEffect as zg,useState as Kg}from"react";var qg=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Yg=150,Cl=12,Xg=.36,El=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Jg=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},Qg=(e,t,n)=>{let r=El(e),o=El(t);return Jg({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Zg=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return Qg(s,i,o)};function Sl({syncStatus:e,autoSync:t}){let[n,r]=Kg(0);zg(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*Xg)+1)/2,p=Math.round(m*(Cl-1));r(g=>g===p?g:p)},Yg);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:Zg(qg,n/(Cl-1))??""}[e.status];return ci.createElement(Gg,null,ci.createElement(bl,null,di.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),ci.createElement(bl,null,di.hex(i)("\u25CF")+di.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import wl from"chalk";import{Text as Ml}from"ink";import Pl,{useEffect as rv,useState as ov}from"react";var Gt="1.2.3";import li from"chalk";var ev="https://registry.npmjs.org/epiq/latest",ui=null,Nl=0,tv=1e3*60*60*24,Rl=e=>e.replace(/^v/,""),nv=(e,t)=>{let n=Rl(e).split(".").map(Number),r=Rl(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},Al=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(ui&&Date.now()-Nl<tv)return ui;try{let t=await fetch(ev);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?nv(r,e)>0:!1};return ui=o,Nl=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Tl=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?li.hex(y.accent).dim(s):li.hex(y.secondary).dim(s)).join(li.hex(y.secondary2).dim("."))};function Ll(){let[e,t]=ov({current:Gt,latest:null,updateAvailable:!1});return rv(()=>{let n=!0;return Al(Gt).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Pl.createElement(Ml,{dimColor:!0,color:y.secondary2},Gt+" "):Pl.createElement(Ml,null,wl.hex(y.secondary2).dim(Gt),wl.hex(y.accent).dim(" \u2197 "),Tl(Gt,e.latest))}function gr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=H(),{userName:i,preferredEditor:c,autoSync:u}=G(),m=64,p=process.stdout.columns-m-8,g=t||n==="replay",C=s?Jt(s.currentLabel,Math.max(0,p)):"";return fe.createElement(fr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?fe.createElement(fr,{paddingLeft:1},fe.createElement(Pn,{color:y.secondary2},C)):g?fe.createElement(Pn,null," "):o===v.PALETTE?fe.createElement(fr,null,fe.createElement(Pn,{color:y.accent},"Command Palette"),fe.createElement(Pn,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):fe.createElement(fr,{paddingLeft:1},e.length>0?fe.createElement(hl,{filters:e}):fe.createElement(vl,{width:p})),n==="live"?fe.createElement(fr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},fe.createElement(Sl,{autoSync:!!u,syncStatus:r}),fe.createElement(Pn,null,Ho.hex(y.secondary2).dim("Mode: ")+Ho.hex(y.secondary2).dim(o.padEnd(8," "))," "),fe.createElement(kl,{icon:"@",value:i}),fe.createElement(kl,{icon:"\u276F",value:c}),fe.createElement(Ll,null)):"",n==="peek"?fe.createElement(xl,null):"",n==="replay"?fe.createElement(Il,null):"")}function kl({icon:e,value:t}){return fe.createElement(Pn,null,Ho.dim(e)+Ho.hex(y.accent)(` ${t??"-"} `))}import{Box as sv,Text as iv}from"ink";import vr from"react";import{Box as jo,Text as mi}from"ink";import zt from"react";function pi(){let e=H(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?j(t?.id):[];return zt.createElement(jo,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},zt.createElement(jo,{padding:1,paddingTop:0,paddingBottom:0},zt.createElement(mi,null,"Select a board:")),zt.createElement(jo,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,g=j(c.id).flatMap(({id:C})=>z(C)).length;return zt.createElement(jo,{key:c.id??u},zt.createElement(mi,{color:m?y.accent:y.secondary2},zt.createElement(Se,{isSelected:m})),zt.createElement(mi,{color:m?y.accent:y.secondary2},c.title," (",g," issues)",c.readonly?" \u{1F512}":""))})))}var av=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=H(),u=n.find(({context:C})=>C==="BOARD"),g=s-1-3;return vr.createElement(sv,{flexDirection:"row"},e.context==="WORKSPACE"?vr.createElement(pi,null):u?vr.createElement(mo,{height:g,width:i,swimlanes:(c[u.id]??[]).filter(C=>C!==void 0&&wt(C)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):vr.createElement(iv,null))},Dl=vr.memo(av);import{useEffect as dv}from"react";var cv=e=>{dv(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=G();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=f();u==="default"&&!c&&Kr(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Fl=({autoSync:e})=>(cv(e),null);function fi({width:e,height:t}){let n=H(),{autoSync:r,viewMode:o}=ta(),s=n.filters;if(n.mode===v.HELP)return re.createElement(Kt,{flexDirection:"column"},re.createElement(pl,{width:e,height:t}));if(n.mode===v.PALETTE)return re.createElement(Kt,{flexDirection:"column"},re.createElement(gr,{filters:s}),re.createElement(el,{width:e,height:t-2}),re.createElement(mr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Lt(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return re.createElement(Kt,{flexDirection:"column"},re.createElement(Kt,{flexDirection:"column"},re.createElement(gr,{hideBreadCrumb:!0,filters:s}),re.createElement(ii,{height:t,width:e})),re.createElement(mr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return re.createElement(Kt,{flexDirection:"column"},re.createElement(Kt,{flexDirection:"column"},re.createElement(gr,{hideBreadCrumb:!0,filters:s}),re.createElement(fl,{height:t,width:e})),re.createElement(mr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Ee(n.breadCrumb??[],"BOARD");if(oe(m)){let p=m.value.id,g=j(p).length,C=3,S=Math.floor(e/C),N=Math.floor(e/Math.max(g,1));e=Math.min(N,S)*Math.max(g,C)}return re.createElement(Kt,{flexDirection:"column"},re.createElement(Fl,{autoSync:r}),re.createElement(Kt,{flexDirection:"column"},re.createElement(gr,{filters:s}),re.createElement(Dl,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),re.createElement(mr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import lv from"readline";var Vo,Go,ft,uv=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.Yank,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),mv=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp,h.Yank]),Bl=async e=>{if(e.ctrl&&e.name==="c")return w.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=f(),s=gd(e,n);if(!s||r&&!uv.has(s)||o==="replay"&&n===v.DEFAULT&&mv.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},pv=()=>async function(t,n){n.name!=="escape"&&(ft&&(clearTimeout(ft),ft=void 0),await Bl(n))},fv=()=>async function(t){if(t.length===1&&t[0]===27){ft&&clearTimeout(ft),ft=setTimeout(()=>{Bl({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),ft=void 0},25);return}ft&&(clearTimeout(ft),ft=void 0)};function Ul(){Vo&&process.stdin.removeListener("keypress",Vo),Go&&process.stdin.removeListener("data",Go),Vo=pv(),Go=fv(),lv.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Go),process.stdin.on("keypress",Vo)}async function Ol(){try{let e=rr();oe(e)&&je(e.value);let t=Je(process.cwd()),n=[];if(oe(t)){let s=Pe({repoRoot:t.value});if(d(s))return rn(3,s.message);let i=mn(),c=await Yt({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return rn(3,c.message);let u=await O({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=xt(s.value);if(d(m))return rn(3,m.message);n=m.value}let r=nn(n);if(d(r))return rn(4,r.message);b({hasProjectDefinition:oe(t),hasInitializingEvents:!!n.length});let o=gi();return d(o)?rn(6,o.message):(Ul(),l("Booted Epiq",void 0))}catch(e){return rn(0,Vr(e))}}Vd();var hv=`${qt.bold("Epiq CLI")}
|
|
58
58
|
|
|
59
|
-
${
|
|
60
|
-
${
|
|
59
|
+
${qt.dim("Boot in directory:")}
|
|
60
|
+
${qt.cyan("$ epiq")}
|
|
61
61
|
|
|
62
|
-
${
|
|
63
|
-
${
|
|
64
|
-
`,
|
|
65
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
66
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
62
|
+
${qt.dim("Launch GUI:")}
|
|
63
|
+
${qt.cyan("$ epiq gui")}
|
|
64
|
+
`,xv=vv(hv,{importMeta:import.meta,version:Gt,flags:{init:{type:"boolean",default:!1}}}),zo=xv.input[0];zo&&zo!=="gui"&&(console.error(qt.red(`Unknown command: ${zo}`)),process.exit(1));var _l=process.stdout.columns||120,$l=process.stdout.rows||20,Ko=null,Iv=e=>{try{return Ko?(Ko.rerender(e),l("Rerendered app",void 0)):(Ko=gv(e),l("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${Vr(t)}`)}},gi=()=>Iv(yv.createElement(fi,{width:_l,height:$l}));process.stdout.on("resize",()=>{if(_l=process.stdout.columns||120,$l=process.stdout.rows||20,!Ko)return;let e=gi();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(zo==="gui"){let e=await Xc({repoRoot:process.cwd()});d(e)&&(console.error(qt.red(`Failed to start Epiq GUI:
|
|
65
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await Ol();d(e)&&(logger.info(e.message),console.error(qt.red(`Failed to boot Epiq:
|
|
66
|
+
${e.message}`)),process.exitCode=1)}export{gi as renderApp};
|