epiq 1.13.1 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Index-LDGDOFWA.js +16 -0
- package/dist/{args-Y5YFYS72.js → args-R7R2SBPG.js} +1 -1
- package/dist/chunk-3A5BVO43.js +2 -0
- package/dist/chunk-C4V7IKIG.js +110 -0
- package/dist/chunk-KQQQ5HBS.js +8 -0
- package/dist/gui/main.js +161 -147
- package/dist/index.js +1 -1
- package/dist/mcp.js +1 -1
- package/dist/server-GPNBR24F.js +31 -0
- package/dist/{virtual-nodes-COSSGT2L.js → virtual-nodes-QB7VWWF2.js} +1 -1
- package/package.json +2 -1
- package/readme.md +17 -7
- package/dist/Index-NH5R5ZCJ.js +0 -16
- package/dist/chunk-7JJFQ6UF.js +0 -8
- package/dist/chunk-HM2XGJT6.js +0 -109
- package/dist/chunk-ON2KLPMG.js +0 -2
- package/dist/server-2COW5M6S.js +0 -30
package/dist/chunk-HM2XGJT6.js
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{a as Oi,c as Hl,d as Wl,f as Gl}from"./chunk-WUCQWBQE.js";import{a as qn,b as a,c as d,d as c,e as bt}from"./chunk-5RIQL7P4.js";import{createHash as tb}from"node:crypto";var Xy=new Set(["https:","http:","ssh:","git:","file:"]),Jy=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*:[^:]+$/,Zy=/^[\x21-\x7e]+$/,Qy=2048,zl="Use https://, ssh://, git:// or user@host:path.",Vl=()=>globalThis.process?.env?.EPIQ_ALLOW_LOCAL_REPOS==="1",Or=(e,t=Vl())=>{if(e.length>Qy)return"is too long";if(!Zy.test(e))return"holds spaces or characters git would not";if(e.startsWith("-"))return"would be read as an option";if(/[\\#?]/.test(e))return"holds a character a clone URL has no use for";if(e.replace(/\[[^\]]*\]/g,"").includes("::"))return"names a remote helper";if(Jy.test(e))return null;let n;try{n=new URL(e)}catch{return"is not a remote URL"}return/%/.test(eb(e))?"percent-encodes its host":Xy.has(n.protocol)?n.password?"carries a password \u2014 use a credential helper":n.username&&n.protocol!=="ssh:"?"names a user before the host \u2014 leave it to a credential helper":n.protocol==="file:"?t?n.hostname?"names a host in a file:// URL":e.startsWith("file:///")?null:"is not a file:/// URL":"is a path on this machine, which nobody else can fetch":n.hostname?n.hostname.startsWith("-")||n.username.startsWith("-")?"would be read as an option":null:"names no host":"uses a transport epiq does not clone over"},eb=e=>{let t=e.indexOf("//");if(t===-1)return"";let n=e.slice(t+2),r=n.indexOf("/");return r===-1?n:n.slice(0,r)},Jt=(e,t=Vl())=>Or(e,t)===null;var Fi=()=>({entries:{},seq:0}),_i="default",$i="board",vn=20,nb=/^\d{4}-\d{2}-\d{2}$/,rb=/^[a-z0-9][a-z0-9._-]{0,23}$/,ql=/-[0-9a-f]{12}$/,xn=e=>e==="board"||e==="all"||ob(e),ob=e=>{if(!nb.test(e)||e<"1970-01-01")return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e},En=e=>rb.test(e)&&!ql.test(e),sb=/^([^@/]+@)([^:/]+)(:.*)$/,ib=/^([a-z][a-z0-9+.-]*:\/\/)([^/]*)(.*)$/i,ab=e=>{let t=sb.exec(e);if(t)return`${t[1]}${t[2].toLowerCase()}${t[3]}`;let n=ib.exec(e);if(!n)return e;let r=n[2],o=r.lastIndexOf("@")+1;return`${n[1].toLowerCase()}${r.slice(0,o)}${r.slice(o).toLowerCase()}${n[3]}`},Kl=e=>ab(e.trim().replace(/\/+$/,"").replace(/\.git$/i,"")),Mt=e=>(Kl(e).toLowerCase().split(/[/:]/).filter(Boolean).pop()??"").replace(/[^a-z0-9._-]/g,"-").slice(0,24).replace(/^[.-]+/,"")||"repo",Zt=e=>`${Mt(e)}-${tb("sha1").update(Kl(e)).digest("hex").slice(0,12)}`,Dr=e=>e.replace(ql,""),Yl=e=>{let t={},{branches:n,since:r,label:o}=e;return(n==="default"||n==="all")&&(t.branches=n),typeof r=="string"&&xn(r)&&(t.since=r),typeof o=="string"&&(o===""||En(o))&&(t.label=o),t},Di=(e,t)=>{let n={...e,...t.branches?{branches:t.branches}:{},...t.since?{since:t.since}:{}};return t.label===""?delete n.label:t.label&&(n.label=t.label),n},Bi=(e,t)=>{let n=t.payload&&typeof t.payload=="object"?t.payload:{},r=Yl(n);if(t.action==="connect.repo"){let l=typeof n.url=="string"?n.url.trim():"";if(l==="")return a("no URL");let u=Zt(l),p=Object.hasOwn(e.entries,u)?e.entries[u]:void 0,m=p?.live===!0?Di(p,r):Di({id:u,url:l,branches:_i,since:$i,live:!0,seq:e.seq+1},r);return p?.live||e.seq++,e.entries[u]=m,d("Connected repo",m)}let o=typeof n.repo=="string"?n.repo:"",s=Object.hasOwn(e.entries,o)?e.entries[o]:void 0;if(!s?.live)return a("no such connected repo");if(t.action==="disconnect.repo"){let l={...s,live:!1};return e.entries[o]=l,d("Disconnected repo",l)}if(Object.keys(r).length===0)return a("nothing this build reads to change");let i=Di(s,r);return e.entries[o]=i,d("Edited repo",i)},cb=e=>e==="connect.repo"||e==="edit.repo"||e==="disconnect.repo",Xl=e=>{let t=Fi();for(let n of e)cb(n.action)&&Bi(t,{action:n.action,payload:n.payload});return t},Jl=e=>{let t=Object.values(e.entries),n=t.filter(s=>s.live&&Jt(s.url)).sort((s,i)=>s.seq-i.seq),r=new Set,o=n.map(s=>{let i=[s.label,Mt(s.url)].find(l=>l!==void 0&&!r.has(l))??s.id;return r.add(i),{id:s.id,url:s.url,branches:s.branches,since:s.since,label:i}});return{live:o.slice(0,vn),overLimit:o.slice(vn),disconnected:t.filter(s=>!s.live).map(s=>s.id)}},Ui=e=>{let t=e.payload&&typeof e.payload=="object"?e.payload:{},n=typeof t.label=="string"&&t.label!==""?t.label:null;if(e.action==="connect.repo")return typeof t.url=="string"?n??Mt(t.url):"";let r=typeof t.repo=="string"?Dr(t.repo):"";if(e.action!=="edit.repo")return r;let o=Yl(t),s=[o.label!==void 0?o.label===""?"label cleared":`label ${o.label}`:null,o.branches?`${o.branches} branches`:null,o.since?`since ${o.since}`:null].filter(Boolean);return s.length>0?`${r} (${s.join(", ")})`:r};import bn from"chalk";import Hy from"string-width";import{decodeTime as Zl}from"ulid";var Yo=1440*60*1e3,ji=(e,t=Date.now())=>e>t+Yo?t:e,Rn=e=>ji(Zl(e)),Xo=e=>{let t=Date.now()+Yo,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},Ql=e=>{try{return d("Decoded date",new Date(Rn(e)))}catch(t){return a("Decoding failed + "+t.message)}},Jo=e=>{if(!e?.id)return null;try{return Zl(e.id)}catch{return null}};import Kn from"chalk";var De={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"},A={accent:De.cyan,accent2:De.magenta,primary:De.white,secondary:De.grayDark,secondary2:De.grayLight,gray:De.gray,green:De.green,yellow:De.yellow,red:De.red};var T={red:De.red,yellow:De.yellow,green:De.green,blue:De.blue,magenta:De.magenta,cyan:De.cyan},Zo={urgent:T.red,critical:T.red,important:T.red,blocker:T.red,asap:T.red,immediate:T.red,fail:T.red,failure:T.red,broken:T.red,bug:T.red,error:T.red,incident:T.red,outage:T.red,production:T.red,crash:T.red,security:T.red,warning:T.yellow,warn:T.yellow,risky:T.yellow,risk:T.yellow,attention:T.yellow,pending:T.yellow,review:T.yellow,"needs-review":T.yellow,qa:T.yellow,testing:T.yellow,test:T.yellow,validate:T.yellow,verification:T.yellow,staging:T.yellow,check:T.yellow,"follow-up":T.yellow,followup:T.yellow,waiting:T.yellow,blocked:T.yellow,hold:T.yellow,done:T.green,complete:T.green,completed:T.green,success:T.green,ok:T.green,stable:T.green,resolved:T.green,fixed:T.green,closed:T.green,merged:T.green,released:T.green,deployed:T.green,approved:T.green,verified:T.green,working:T.green,healthy:T.green,pass:T.green,passing:T.green,info:T.blue,information:T.blue,note:T.blue,docs:T.blue,documentation:T.blue,doc:T.blue,guide:T.blue,help:T.blue,explanation:T.blue,detail:T.blue,details:T.blue,context:T.blue,design:T.blue,discussion:T.blue,proposal:T.blue,idea:T.blue,feature:T.magenta,enhancement:T.magenta,improvement:T.magenta,refactor:T.magenta,refactoring:T.magenta,cleanup:T.magenta,optimize:T.magenta,optimization:T.magenta,perf:T.magenta,performance:T.magenta,upgrade:T.magenta,migration:T.magenta,modernize:T.magenta,debt:T.magenta,todo:T.cyan,next:T.cyan,planned:T.cyan,plan:T.cyan,future:T.cyan,backlog:T.cyan,investigate:T.cyan,explore:T.cyan,prototype:T.cyan};var Wi={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Gi=(e,t,n)=>Math.max(t,Math.min(n,e)),Hi=(e,t,n)=>e+(t-e)*n,td=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},lb=e=>e.toLowerCase().trim(),db=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,l=s*(1-Math.abs(i%2-1)),u=0,p=0,m=0;i>=0&&i<1?(u=s,p=l):i>=1&&i<2?(u=l,p=s):i>=2&&i<3?(p=s,m=l):i>=3&&i<4?(p=l,m=s):i>=4&&i<5?(u=l,m=s):(u=s,m=l);let f=o-s/2;return[Math.round((u+f)*255),Math.round((p+f)*255),Math.round((m+f)*255)]},zi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,ed=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},nd=(e,t,n)=>{let r=Gi(n,0,1);return[Math.round(Hi(e[0],t[0],r)),Math.round(Hi(e[1],t[1],r)),Math.round(Hi(e[2],t[2],r))]};var ub=(e,t,n)=>nd(e,t,n),Vi=e=>{let t=td(e)%360,n=db(t,Wi.stringColor.saturation,Wi.stringColor.lightness);return zi(n)},Be=(e,t=Zo)=>{let n=lb(e??"");return n&&t[n]?t[n]:Vi(n)};var rd=e=>{let t=Wi.gradient.stops,n=Gi(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 ub(t[s],t[s+1],i)},$I=(e,t)=>{if(e.length===0)return"#000000";if(e.length===1)return e[0];let n=e.length-1,r=Gi(t,0,1)*n,o=Math.min(Math.floor(r),n-1);return zi(nd(ed(e[o]),ed(e[o+1]),r-o))},od=e=>zi(rd(e)),Qo=e=>td(e.toLowerCase().trim())/4294967295,sd=e=>{let t=Qo(e);return rd(t)},mb=e=>{let[t,n,r]=sd(e);return{normal:o=>Kn.bgRgb(t,n,r).black(o),cursor:o=>Kn.bgRgb(t,n,r).white.bold(o)}},BI=e=>{let[t,n,r]=sd(e);return{fg:o=>Kn.rgb(t,n,r)(o),fgCursor:o=>Kn.rgb(t,n,r).inverse(o),bg:o=>Kn.bgRgb(t,n,r).black(o),bgCursor:o=>Kn.bgRgb(t,n,r).white.bold(o)}},es=e=>mb(e).normal(` ${e} `);var pb="Unknown",qi=(e,t)=>t?.length?t:e?.length?e:pb,Ki=(e,t)=>{let n=qi(e,t);return{id:e?.length?e:n,name:n,color:Be(n)}};var id="removed",Ze=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?d("Found node",n):a("Unable to find node in breadcrumb")},ad=["png","jpg","gif","webp"];var Qe=e=>e.trim().toLowerCase(),Yn=e=>{let t=Qe(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},Yi=(e,t)=>`${Qe(e)} ${t}`,Xi=e=>!e.tombstoned,VI=(e,t)=>{let n=Qe(t),r=new Set;for(let o of Object.values(e))Xi(o)&&o.email===n&&r.add(o.contributor);return[...r]},Xn=(e,t)=>{let n=new Set;for(let r of Object.values(e))Xi(r)&&r.contributor===t&&n.add(r.email);return[...n]},qI=e=>{let t=new Map;for(let r of Object.values(e)){if(!Xi(r))continue;let o=t.get(r.email)??new Set;o.add(r.contributor),t.set(r.email,o)}let n=new Map;for(let[r,o]of t){let[s]=[...o];o.size===1&&s&&n.set(r,s)}return n};var cd=(e,t)=>e===t.authorId||e===t.contributor;var te={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Ji(e){return e.context===te.WORKSPACE}function H(e){return e.context===te.TICKET}function ld(e){return e.context===te.TEXT}function Fe(e){return e.context===te.FIELD}function Fr(e){return e.context===te.FIELD_LIST}var ts=e=>e.context===te.SWIMLANE,dd=e=>e.context===te.BOARD,_r=e=>e.context===te.COMMENT;import{useSyncExternalStore as eI}from"react";var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"};var ud=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",md=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",pd=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",fd=(e,t)=>{if(md(e,e.sequence))return S.MoveCursorLeftOfWord;if(pd(e,e.sequence))return S.MoveCursorRightOfWord;if(ud(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.GetLastCommandFromHistory;case"down":return S.GetNextCommandFromHistory;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}},gd=(e,t)=>{if(md(e,e.sequence))return S.MoveCursorLeftOfWord;if(pd(e,e.sequence))return S.MoveCursorRightOfWord;if(ud(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.NavPreviousItem;case"down":return S.NavNextItem;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}};import hd from"string-width";function ns(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Sn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",fb=/\u001B\[[0-9;]*m/,Zi="\x1B[0m",gb=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Cn=(e,t)=>{if(t<=0)return"";if(hd(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if(fb.test(l)){o+=l,i=l!==Zi&&l!=="\x1B[m";continue}for(let u of gb(l)){let p=hd(u);if(s+p>r)return`${o}...${i?Zi:""}`;o+=u,s+=p}}return`${o}...${i?Zi:""}`},Ut=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),ew=e=>e.charAt(0).toUpperCase()+e.slice(1);var yd=e=>{let t=new Map;for(let n of e){let r=n.toLowerCase();for(let o=1;o<=n.length;o++){let s=r.slice(0,o),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},bd=(e,t)=>t?e.get(t)??[]:[];var vd=new WeakMap,hb=e=>{let t=vd.get(e);return t||(t=yd(e),vd.set(e,t)),t};var xd=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return bd(hb(e),r).filter(s=>ns(r,s.toLowerCase())>=n)};var yb={hint:"",hints:[],overlap:0,remainder:""},Rd=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[l]=s;return s.length===1&&l&&!r.trim()?Ed("",[l]):yb}let i=xd({wordList:o,inputToMatch:e,overlapThreshold:1});return Ed(t,i)},Ed=(e,t)=>{let n=t[0]??"",r=ns(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,l=!!s,m=(l&&i?o:n)+(l&&i?":":" "),f=m.slice(r);return{hint:m,hints:t,overlap:r,remainder:f}};var Jn=e=>{let t=typeof e=="number"?e:Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<3e3||t>864e5?null:t},rs=e=>e==null||!Number.isFinite(e)?1e4:Math.min(864e5,Math.max(1,e));import Yr from"node:fs";import Xr from"node:path";import{z as tr}from"zod";import Kr from"node:fs";import{ulid as Jb}from"ulid";import{z as ls}from"zod";import Gr from"node:fs";import Lt from"node:path";import Qt from"node:fs";import ze from"node:path";import bb from"node:os";import vb from"node:path";var vt=".epiq-global",We=()=>process.env.EPIQ_GLOBAL_DIR??vb.join(bb.homedir(),vt);var Qi=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let l=e(...s).then(u=>(c(u)&&n.delete(i),u));n.set(i,l)}return n.get(i)});return o.clear=()=>n.clear(),o};import xt from"fs";import oa from"path";import xb from"util";var Sd=500,sa=4*1024*1024,ea=16*1024,Eb=50,ta=0,Cd=()=>process.env.EPIQ_MCP==="true",Rb=()=>{let e=process.cwd(),t=os(e);return c(t)?Cd()?oa.join(We(),"epiq-mcp.log"):void 0:oa.join(t.value,Ue,"log","epiq.log")},Sb=(e,t)=>{let n=xt.statSync(e).size;if(n<=t)return xt.readFileSync(e,"utf8");let r=xt.openSync(e,"r");try{let o=Buffer.alloc(t);xt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
3
|
-
`);return i===-1?"":s.slice(i+1)}finally{xt.closeSync(r)}};function Cb(e){if(!xt.existsSync(e))return;let t=xt.statSync(e).size,n=Sb(e,sa).split(`
|
|
4
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=sa&&n.length<=Sd)return;let r=n.slice(-Sd).join(`
|
|
5
|
-
`)+`
|
|
6
|
-
`;xt.writeFileSync(e,r,"utf8")}var Nb=e=>{if(e.length<=ea)return e;let t=e.length-ea;return`${e.slice(0,ea)} \u2026 [${t} more chars]`};function na(e,t,n=!1){let r=Rb();if(!r)return;let o=Nb(xb.format(...t)),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
7
|
-
`;try{xt.mkdirSync(oa.dirname(r),{recursive:!0}),xt.appendFileSync(r,l,"utf8"),ta++,(ta>=Eb||xt.statSync(r).size>sa)&&(ta=0,Cb(r))}catch{}}var ra=()=>Cd()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",j={info(...e){let t=ra();(t==="info"||t==="debug")&&na("[Info]",e,!1)},debug(...e){ra()==="debug"&&na("[Debug]",e,!0)},error(...e){let t=ra();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;na("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=j;import{spawn as Ad}from"node:child_process";import Ge from"node:fs";import Re from"node:path";var ue={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>_({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>_({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>_({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>_({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>_({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push","--no-verify",...r?["-u"]:[],t,n]:["push","--no-verify"];return _({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>_({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>_({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>_({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>_({args:["worktree","prune"],cwd:e})};var Et=e=>{let t=xe(e);if(c(t))return a("Unable to resolve epiq project root");let n=je(t.value);return c(n)?a("Unable to read project.json"):d("Resolved state branch",n.value.stateBranch)},et="origin";var Td="Output past",is=e=>e.includes(Td),Md="Git command timed out",kd=e=>e.includes(Md),aa=1e4,Ib=12e4,ca=256*1024*1024,Ld=64*1024,wb=8*1024*1024,Ab=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),Tb=e=>{let t=Od(e);return t&&Ab.has(t)?Ib:aa},Mb=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(Re.delimiter))if(t)for(let n of e){let r=Re.join(t,n);try{if(!Ge.statSync(r).isFile())continue;return Ge.accessSync(r,Ge.constants.X_OK),r}catch{continue}}return"git"},Pd=Mb(),kb=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE"],Lb=e=>Object.fromEntries(Object.entries(e).filter(([t])=>!kb.includes(t))),la={...Lb(process.env),GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Pb=["-c","diff.noprefix=false","-c","diff.mnemonicPrefix=false","-c","diff.srcPrefix=a/","-c","diff.dstPrefix=b/","-c","log.showSignature=false"],Ob=new Set(["log","show","diff"]),Od=e=>e.find((t,n)=>!t.startsWith("-")&&e[n-1]!=="-c"),Db=e=>Ob.has(Od(e)??"")?Pb:[],Dd=()=>["attr.tree=refs/epiq/no-attributes",`core.hooksPath=${Re.join(We(),"repos",".no-hooks")}`,"protocol.ext.allow=never","protocol.fd.allow=never","protocol.file.allow=always","submodule.recurse=false","fetch.recurseSubmodules=false","credential.interactive=never","core.longpaths=true","gc.auto=0","maintenance.auto=false","fetch.unpackLimit=1","fetch.writeCommitGraph=false","core.logAllRefUpdates=false"].flatMap(e=>["-c",e]),Fb=/^[\w-]+[\\/][a-z0-9._-]+-[0-9a-f]{12}\.git(\.\d+(-\d+)?(\.[0-9a-f-]{36})?\.pending)?$/,Nd=e=>{try{return Ge.realpathSync(e)}catch{return Re.resolve(e)}},da=e=>{let t=Re.join(We(),"repos");return[[Re.resolve(t),Re.resolve(e)],[Nd(t),Nd(e)]].some(([n,r])=>Fb.test(Re.relative(n,r)))},_b=e=>da(e)?["--git-dir=.",...Dd()]:[],Fd={...Object.fromEntries(Object.entries(la).filter(([e])=>e!=="GIT_ALLOW_PROTOCOL")),LC_ALL:"C",LANGUAGE:"",GIT_PROTOCOL_FROM_USER:"0"},ss=new Set,Id=!1,_d=process.platform!=="win32",$d=(e,t)=>{try{if(_d&&e.pid){process.kill(-e.pid,t);return}}catch{}e.kill(t)},ia=(e="SIGTERM")=>{for(let t of ss)$d(t,e)},$b=["SIGTERM","SIGINT","SIGHUP"],Bd=!1,Ud=()=>Bd,Bb=2e3,jd=()=>{if(Id)return;Id=!0,process.once("exit",()=>ia());let e=new Map;for(let t of $b)e.set(t,()=>{Bd=!0;let n=()=>{for(let[s,i]of e)process.off(s,i);process.kill(process.pid,t)};ia();let r=Date.now()+Bb,o=()=>{if(ss.size===0)return n();if(Date.now()>=r)return ia("SIGKILL"),n();setTimeout(o,20)};o()});for(let[t,n]of e)process.once(t,n)},Hd=e=>{ss.add(e),e.once("close",()=>ss.delete(e))},Wd=({args:e,cwd:t,allowFail:n,timeoutMs:r,maxOutput:o=ca,forClone:s=!1,keepPartial:i=!1,abort:l})=>new Promise(u=>{let p=da(t),m=p||s,f=[...Db(e),...p?["--git-dir=."]:[],...m?Dd():[],...e];if(!Ge.existsSync(t)){let O=`Git cwd does not exist: ${t}`;if(n){u({stdout:"",stderr:O,exitCode:1});return}u(a(O));return}m&&jd();let g=Ad(Pd,f,{cwd:t,stdio:["ignore","pipe","pipe"],env:m?Fd:la,detached:m&&_d});m&&Hd(g);let x=O=>m?$d(g,O):g.kill(O),N=!1,E="",R="",v=O=>{N||(N=!0,clearTimeout(P),u(O))},I=r??Tb(f),k=!1,M=()=>[`git ${f.join(" ")}`,`cwd=${t}`,`${Md} after ${I}ms`].join(`
|
|
8
|
-
`),L=()=>v(n?{stdout:E,stderr:M(),exitCode:124}:a(M())),P=setTimeout(()=>{k=!0,x("SIGTERM"),setTimeout(()=>x("SIGKILL"),3e3).unref(),setTimeout(L,6e3).unref()},I),$=null,B=()=>{let O=[`git ${f.join(" ")}`,$].join(`
|
|
9
|
-
`);v(n?{stdout:E,stderr:O,exitCode:1}:a(O))},de=()=>{$=String(l?.reason??"stopped"),x("SIGTERM"),setTimeout(()=>x("SIGKILL"),3e3).unref(),setTimeout(B,6e3).unref()};l?.aborted?de():l?.addEventListener("abort",de,{once:!0}),g.stdout.setEncoding("utf8"),g.stderr.setEncoding("utf8"),g.stdout.on("data",O=>{if(E+=O,E.length>o){if(x("SIGTERM"),i&&!n){let Pe=E.slice(0,o);v(d("Git output cut",{stdout:Pe.slice(0,Pe.lastIndexOf(`
|
|
10
|
-
`)+1),stderr:R,exitCode:0,truncated:!0}));return}let q=`git ${f.join(" ")}
|
|
11
|
-
${Td} ${o} characters; stopped`;v(n?{stdout:"",stderr:q,exitCode:1}:a(q))}}),g.stderr.on("data",O=>{R.length<Ld&&(R+=O)}),g.on("error",O=>{if(n){v({stdout:E,stderr:O.message,exitCode:1});return}v(a([`git ${f.join(" ")}`,`cwd=${t}`,O.message].join(`
|
|
12
|
-
`)))}),g.on("close",O=>{if(l?.removeEventListener("abort",de),k)return L();if($!==null)return B();let q=O??1;if(n){v({stdout:E,stderr:R,exitCode:q});return}if(q!==0){v(a([`git ${f.join(" ")}`,R.trim()||E.trim()||"Git command failed"].filter(Boolean).join(`
|
|
13
|
-
`)));return}v(d("Git command succeeded",{stdout:E,stderr:R,exitCode:q}))})}),_=({args:e,cwd:t,timeoutMs:n,maxOutput:r,forClone:o,keepPartial:s,abort:i})=>Wd({args:e,cwd:t,allowFail:!1,timeoutMs:n,maxOutput:r,forClone:o,keepPartial:s,abort:i}),Se=({args:e,cwd:t})=>Wd({args:e,cwd:t,allowFail:!0}),Gd=(e,t)=>new Promise(n=>{if(e.length===0){n(d("No blobs to read",new Map));return}let r=da(t);r&&jd();let o=Ad(Pd,[..._b(t),"cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:r?Fd:la});r&&Hd(o);let s=[],i="",l=!1,u=f=>{l||(l=!0,clearTimeout(p),n(f))},p=setTimeout(()=>{o.kill("SIGTERM"),u(a(`git cat-file --batch timed out after ${aa}ms`))},aa),m=0;o.stdout.on("data",f=>{if(m+=f.length,m>ca){o.kill("SIGTERM"),u(a(`git cat-file --batch: past ${ca} bytes; stopped`));return}s.push(f)}),o.stderr.setEncoding("utf8"),o.stderr.on("data",f=>{i.length<Ld&&(i+=f)}),o.on("error",f=>u(a(f.message))),o.on("close",f=>{if(f!==0){u(a(`git cat-file --batch exited ${f}${i?`
|
|
14
|
-
${i}`:""}`));return}let g=Buffer.concat(s),x=new Map,N=0;for(let E of e){let R=g.indexOf(10,N);if(R===-1){u(a(`git cat-file --batch output ended before a header for ${E}`));return}let v=g.toString("utf8",N,R);N=R+1;let I=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(v);if(!I||!I[1]){u(a(`Unexpected git cat-file --batch header: "${v}"`));return}let k=Number(I[1]);k<=wb&&x.set(E,g.toString("utf8",N,N+k)),N+=k+1}u(d("Read blobs",x))}),o.stdin.write(e.join(`
|
|
15
|
-
`)+`
|
|
16
|
-
`),o.stdin.end()}),Qn=async({cwd:e,message:t,pathspec:n})=>{let r=await ue.commit({cwd:e,message:t,pathspec:n});if(c(r))return a(`Failed to create commit
|
|
17
|
-
${r.message}`);let o=await _({args:["rev-parse","HEAD"],cwd:e});return c(o)?a(`Commit created, but failed to read HEAD SHA
|
|
18
|
-
${o.message}`):d("Created commit and resolved SHA",o.value.stdout.trim())},$r=async e=>{let t=await _({cwd:e,args:["rev-parse","--git-dir"]});if(c(t))return a(t.message);let n=t.value.stdout.trim();return d("Resolved git dir",Re.isAbsolute(n)?n:Re.resolve(e,n))},ua=async e=>{let t=await $r(e);if(c(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Ge.existsSync(Re.join(n,s)))return d("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(Ge.existsSync(Re.join(n,s)))return d("Checked for in-progress Git operation",i);return d("Checked for in-progress Git operation",null)},zd=async e=>{let t=await ua(e);return c(t)?a(t.message):d("Checked for in-progress Git operation",t.value!==null)},jt=async({repoRoot:e})=>{let n=(await Se({args:["remote","get-url",et],cwd:e})).exitCode===0;return d(`Checked remote ${n}`,n)},Br=async({repoRoot:e,branch:t})=>{let n=await Se({args:["ls-remote","--heads",et,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${et}/${t}`):d("Checked remote branch",n.stdout.trim().length>0)},as=async({repoRoot:e,branch:t})=>{let n=await Se({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?d("Local branch exists",!0):n.exitCode===1?d("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},Zn=e=>{try{return Ge.realpathSync.native(e)}catch{return Re.resolve(e)}},Vd=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return a(n.message);let r=Zn(t),o=n.value.stdout.split(`
|
|
19
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Zn).includes(r);return d("Checked worktree registration",o)},ma=async e=>{let t=await Se({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return d("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},cs=async e=>{let t=await _({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return c(t)?a(t.message):d("Resolved current branch",t.value.stdout.trim())},qd=async e=>{let t=await _({args:["rev-parse","--short","HEAD"],cwd:e});return c(t)?a(t.message):d("Resolved short HEAD sha",t.value.stdout.trim())},Kd=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Yd=async e=>{let t=await Se({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?Ge.existsSync(Re.join(n,"rebase-merge"))||Ge.existsSync(Re.join(n,"rebase-apply")):!1},Ub=3,jb=120,Hb=e=>new Promise(t=>setTimeout(t,e)),Wb=async(e,t)=>{let n=await ue.rebaseOnto({cwd:e,ref:t});for(let r=1;r<Ub;r+=1){if(!c(n)||await Yd(e))return n;await Hb(jb),n=await ue.rebaseOnto({cwd:e,ref:t})}return n},Xd=async(e,{preserve:t=[]}={})=>{let n=await $r(e);if(c(n))return a(n.message);let r=n.value,o=[];for(let s of Ge.readdirSync(r))if(s.endsWith(".lock")&&!t.includes(s))try{Ge.rmSync(Re.join(r,s),{force:!0}),o.push(s)}catch{}return d("Cleared stale git lock files",o)},Jd=async(e,t)=>{let n=await Se({cwd:e,args:["rev-parse","--git-common-dir"]});if(n.exitCode!==0)return a(`Unable to resolve the common git directory at ${e}`);let r=Re.resolve(e,n.stdout.trim()),o=Re.join(r,"refs","heads"),s=Re.resolve(o,`${t}.lock`);if(!s.startsWith(`${o}${Re.sep}`))return a(`Refusing to clear a ref lock outside ${o}`);if(!Ge.existsSync(s))return d("No ref lock to clear",!1);try{Ge.rmSync(s,{force:!0})}catch{return d("Ref lock could not be cleared",!1)}return d("Cleared a stale ref lock",!0)},pa=async e=>{if(!await Yd(e))return d("No rebase to abort",!1);let t=await Se({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?a(`Failed to abort the rebase in progress at ${e}
|
|
20
|
-
${t.stderr.trim()}`):d("Aborted stale rebase",!0)},wd=async e=>{let t=await Se({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},Ur=e=>/could not resolve host/i.test(e)||/connection refused|connection timed out|operation timed out/i.test(e)||/network is unreachable|no route to host/i.test(e)||/failed to connect to/i.test(e),Gb=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),jr=async({cwd:e,branch:t})=>{let n=await pa(e);if(c(n))return a(n.message);let r=await wd(e),o=await ue.fetch({cwd:e,remote:et,branch:t});if(c(o))return Gb(o.message)?d("Remote branch missing, skipped pull",!1):a(`Failed to fetch ${t}
|
|
21
|
-
${o.message}`);let s=await Wb(e,`${et}/${t}`);if(c(s))return a(`Failed during rebase
|
|
22
|
-
${s.message}`);let i=await wd(e),l=r!==null&&i!==null&&r!==i;return d(l?"Pulled with rebase":"Already up to date",l)},Zd=async e=>{let t=await Se({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?d("No upstream to compare against",!1):d("Compared against upstream",Number(t.stdout.trim())>0)},Qd=async e=>{let t=await Se({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?a(t.stderr.trim()||"Unable to inspect the worktree for changes"):d("Inspected worktree for changes",t.stdout.trim().length>0)},eu=async(e,t)=>{let n=await Se({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?d("No staged changes",!1):n.exitCode===1?d("Has staged changes",!0):a(n.stderr.trim()||"Unable to inspect staged changes")};var tu=async e=>{let t=await cs(e);return c(t)?a(t.message):d("Checked detached HEAD state",t.value==="HEAD")};var ou="4b825dc642cb6eb9a060e54bf8d69288fbee4904",su=e=>ze.join(Ue,Ht,e),iu=()=>ze.join(Ue,ha),au=We,Nn=()=>ze.join(au(),"worktrees"),ye=({repoRoot:e})=>{let t=kt(e);return c(t)?a(t.message):d("Resolved state branch root",ze.join(Nn(),t.value))},zb=e=>ze.join(e,Ue),nu=e=>ze.join(zb(e),Ht);var Hr=e=>{try{return Qt.mkdirSync(e,{recursive:!0}),d("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Wr=()=>{let e=au(),t=Nn(),n=!Qt.existsSync(e)||!Qt.existsSync(t),r=Hr(e);if(c(r))return a(`Ensure epiq home failed.
|
|
23
|
-
`+r.message);let o=Hr(t);return c(o)?a(`Ensure worktrees dir failed.
|
|
24
|
-
`+o.message):d("Ensured epiq storage",n)},cu=e=>{Qt.existsSync(e)&&(j.debug("[sync] remove path",e),Qt.rmSync(e,{recursive:!0,force:!0}))};var Vb=`*.jsonl merge=union
|
|
25
|
-
`,qb=`*~pending*.jsonl
|
|
26
|
-
`,fa=()=>ze.join(Ue,Ht,".gitattributes"),ga=()=>ze.join(Ue,Ht,".gitignore"),ru=(e,t)=>{try{Qt.readFileSync(e,"utf8")!==t&&Qt.writeFileSync(e,t)}catch{Qt.writeFileSync(e,t)}},lu=(e,t)=>{for(let n of[nu(e),nu(t)]){let r=Hr(n);if(c(r))return a(r.message)}return ru(ze.join(t,fa()),Vb),ru(ze.join(t,ga()),qb),d("Ensured state branch",void 0)},du=async e=>{let t=await _({args:["ls-tree","--name-only","HEAD"],cwd:e});if(c(t))return a(`ensure state branch is storage only failed
|
|
27
|
-
`+t.message);let r=t.value.stdout.trim().split(`
|
|
28
|
-
`).filter(Boolean).filter(i=>i!==Ue);if(r.length===0)return d("State branch is storage-only",!1);let o=await _({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(c(o))return a(`Failed to clean storage branch
|
|
29
|
-
${o.message}`);let s=await Qn({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return c(s)?a(s.message):d("Cleaned storage branch",!0)},Rt=Qi(async(e=process.cwd())=>{let t=await _({args:["rev-parse","--show-toplevel"],cwd:e});return c(t)?a("Not inside a Git repository"):d("Resolved repo root",t.value.stdout.trim())},e=>ze.resolve(e)),Yw=Qi(async e=>{let t=await _({args:["rev-parse","--git-dir"],cwd:e});if(c(t))return a(t.message);let n=t.value.stdout.trim(),r=ze.isAbsolute(n)?n:ze.join(e,n);return d("Resolved git dir",r)},e=>ze.resolve(e));var nA=process.env.IS_LOCAL==="true",Ue=".epiq",Ht="events",ha="media",Kb="project.json",zr=e=>Lt.join(e,Ue),er=e=>Lt.join(zr(e),Kb),Ve=e=>Lt.join(zr(e),Ht),Vr=e=>Lt.join(zr(e),ha),uu=e=>Lt.join(e,Ue),Yb=e=>{let t=Lt.join(e,Ue);return Gr.existsSync(t)&&Gr.statSync(t).isDirectory()},qr=e=>{let t=er(e);return Gr.existsSync(t)&&Gr.statSync(t).isFile()},os=e=>{let t=Lt.resolve(e);for(;;){if(Yb(t))return d("Resolved closest .epiq root",t);let n=Lt.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Xb="No .epiq/project.json found in any parent",xe=e=>{let t=Lt.resolve(e);for(;;){if(qr(t))return d("Resolved closest epiq project root",t);let n=Lt.dirname(t);if(n===t)return a(Xb);t=n}},mu=e=>{let t=Ve(e);try{return Gr.mkdirSync(t,{recursive:!0}),d("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},le=async()=>{let e=await Rt(process.cwd());if(c(e))return e;let t=ye({repoRoot:e.value});return c(t)?t:d("Resolved persist root",t.value)};var ya="__epiq_state__",Zb=ls.object({projectId:ls.string().min(1),stateBranch:ls.string().min(1),createdAt:ls.iso.datetime()}),ds=()=>({projectId:Jb(),stateBranch:ya,createdAt:new Date().toISOString()}),je=e=>{let t=er(e);if(!Kr.existsSync(t))return a("Missing .epiq/project.json");try{let n=Kr.readFileSync(t,"utf8"),r=JSON.parse(n),o=Zb.safeParse(r);return o.success?d("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")}},kt=e=>{let t=je(e);return c(t)?a(t.message):d("Read projectId",t.value.projectId)},ba=({repoRoot:e,fileContents:t})=>{let n=zr(e),r=er(e);try{if(Kr.mkdirSync(n,{recursive:!0}),Kr.existsSync(r)){let o=je(e);return c(o)?a(o.message):d("Project already initialized",null)}return Kr.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
30
|
-
`,"utf8"),d("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var us="recent-projects.json",Qb=20,ev=tr.object({projectId:tr.string().min(1),root:tr.string().min(1),lastOpenedAt:tr.number().finite()}),tv=tr.object({projects:tr.array(ev)}),fu=()=>Xr.join(We(),us),gu=e=>Xr.basename(e)||e,pu=e=>{let t=Xr.resolve(e);try{return Yr.realpathSync(t)}catch{return t}},hu=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,yu=e=>{if(!qr(e.root))return!1;let t=kt(e.root);return!c(t)&&t.value===e.projectId},bu=()=>{let e=fu();if(!Yr.existsSync(e))return d("No recent projects recorded",[]);let t;try{t=JSON.parse(Yr.readFileSync(e,"utf8"))}catch(r){return a(`Invalid ${us}: ${r instanceof Error?r.message:String(r)}`)}let n=tv.safeParse(t);return n.success?d("Read recent projects",n.data.projects):a(`Invalid ${us} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},nv=e=>{let t=fu();try{Yr.mkdirSync(Xr.dirname(t),{recursive:!0}),Yr.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
31
|
-
`,"utf8")}catch(n){return a(`Unable to write ${us}: ${n instanceof Error?n.message:String(n)}`)}return d("Recorded recent project",e)},ms=({exclude:e}={})=>{let t=bu();if(c(t))return t;let n=e===void 0?null:pu(e);return d("Listed recent projects",t.value.filter(r=>n===null||pu(r.root)!==n).filter(yu).sort(hu))},vu=({root:e,now:t=Date.now()})=>{let n=Xr.resolve(e),r=kt(n);if(c(r))return a(r.message);let o=r.value,s=bu(),i=c(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(yu).sort(hu).slice(0,Qb);return nv(l)};import{useSyncExternalStore as rv}from"react";var Jr={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},va=new Set,ov=()=>{for(let e of va)e()},ee=()=>Jr,RA=()=>rv(e=>(va.add(e),()=>{va.delete(e)}),()=>Jr),at=e=>(Jr={...Jr,...e},ov(),Jr);var xa=null,xu=e=>{xa=e},Eu=e=>xa?xa(e):[];var Ru=[],Su=e=>{Ru=e},nr=()=>Ru;var Zr=()=>{let e=ee(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=Cu(),s=o.length>0?null:Ea(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),l=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&l,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:l,claimedEmails:o,emailSetupDeclined:i}},Ea=()=>{let e=xe(process.cwd());if(c(e))return null;let t=kt(e.value);return c(t)?null:t.value||null},Cu=()=>{let{userId:e}=ee();return e?Eu(e):[]},Nu=()=>Cu().length>0;var Ra=()=>{let e=xe(process.cwd());if(c(e))return!1;let t=je(e.value);return bt(t)},Iu=e=>e===!0?"on":e===!1?"off":null,wu=e=>e==="on"?!0:e==="off"?!1:null,Au=()=>{let e=Zr();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!Ra())return"init";if(!e.isSetEmails){let{gitEmail:t}=ee(),n=nr()[0]??t;return n&&Yn(n)?`config emails ${n}`:"config emails "}return null};var sv=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ct,ps]=sv;var iv=e=>e.props.tags??[],av=e=>e.props.assignees??[],en=e=>iv(e).map(t=>C.getTag(t)).filter(t=>!!t),tn=e=>av(e).map(t=>C.getContributor(t)).filter(t=>!!t),fs=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!H(n)?a("Invalid untag target"):d("Retrieved tags from ticket in breadcrumb",en(n))},gs=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!H(n)?a("Invalid unassign target"):d("Retrieved assignees from ticket in breadcrumb",tn(n))};var b={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",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",NONE:""};var cv=/^(\d+)(h|d|w|mo|y)$/,lv=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,dv=({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},uv=(e,t=new Date)=>{let n=e.match(cv);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}},mv=e=>{let t=e.match(lv);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),u=Number(r),p=Number(o),m=s?Number(s):0,f=i?Number(i):0;return dv({year:l,month:u,day:p,hour:m,minute:f})?new Date(l,u-1,p,m,f):null},In=e=>{let t=e.trim().toLowerCase();return uv(t)??mv(t)};var Tu=/^(\d+)(s|m)?$/,hs=e=>{let t=e.trim().toLowerCase().match(Tu);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},ys=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Tu.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Mu=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,pv=[{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}],Sa=(e=pv)=>{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 fv=["BOARD","TICKET","SWIMLANE","COMMENT"],J={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",REPO_CLONE_MAX_MB:"repoCloneMaxMb",LOG_LEVEL:"logLevel",REPO_CONNECT:"repoConnect",REPO_DISCONNECT:"repoDisconnect"},tt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Te={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},gv=[J.EDITOR,J.VIEW,J.USERNAME,J.EMAILS,J.EMAILS_UNCLAIM,J.AUTOSYNC,J.SYNC_DEBOUNCE_MS,J.ATTACHMENT_MAX_KB,J.LOG_LEVEL,J.REPO_CONNECT,J.REPO_DISCONNECT,J.REPO_CLONE_MAX_MB],hv=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":return[tt.TITLE,tt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[tt.TITLE];case"COMMENT":return[tt.COMMENT];default:return[]}},Na=[String(3e3),"5000","15000","30000","60000"],Ia=["250","500","1000"],wa=["512","2048","8192"],Pu=["10s","20s","30s","45s"],wn=[b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],bs=[b.NEW,b.EDIT,b.DELETE,b.MOVE],Ca=[b.TAG,b.UNTAG,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],ku=[b.FILTER,b.PEEK,b.REPLAY],yv={WORKSPACE:[...wn,...bs],BOARD:[...ku,...wn,...bs],SWIMLANE:[...ku,...wn,...bs],TICKET:[...wn,...bs,...Ca],FIELD:[...wn,...Ca],FIELD_LIST:[...wn,...Ca],TEXT:[...wn],COMMENT:[b.EDIT,b.DELETE,b.YANK]},bv=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Qr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&H(n)),Lu=e=>e.parentNodeId===ct,vv=({selectedNode:e,breadCrumb:t})=>{let n=hv(e?.context);return Qr({breadCrumb:t,selectedNode:e})?n.includes(tt.DESCRIPTION)?n:[...n,tt.DESCRIPTION]:n},xv=({selectedNode:e,breadCrumb:t})=>{let n=Qr({breadCrumb:t,selectedNode:e});return n?[Te.REF,Te.TITLE,...n.props?.description?.trim()?[Te.DESCRIPTION]:[],...en(n).length>0?[Te.TAGS]:[],...tn(n).length>0?[Te.ASSIGNEES]:[]]:e?[Te.REF,Te.TITLE]:[]},Aa=()=>{let e=ms({exclude:process.cwd()});return c(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},Ev=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Zr();if(!r)return[b.HELP,b.CONFIG];if(!Ra())return[b.HELP,b.INIT,b.OPEN];if(t)return[b.HELP,b.PEEK,b.REPLAY,b.EXPORT,b.CONFIG,b.YANK];let o=e?.context,s=o&&fv.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?yv[u]:[]))],l=Qr({breadCrumb:n,selectedNode:e});return i.filter(u=>u===b.MOVE?!1:u===b.YANK?!!(l??e):u===b.EDIT?s||!!l:u===b.DELETE?s:u===b.UNTAG?!!(l&&en(l).length>0):u===b.UNASSIGN?!!(l&&tn(l).length>0):u===b.RE_OPEN_ISSUE?!!(l&&Lu(l)):u===b.CLOSE_ISSUE?!!(l&&!Lu(l)):!0)},Me=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:Ev({breadCrumb:o,readOnly:r,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.OPEN]:e===b.OPEN?Aa():[],[b.HELP]:[],[b.PEEK]:[...Sa(),"now","prev","next"],[b.REPLAY]:[...Sa()],[b.EDIT]:vv({selectedNode:n,breadCrumb:o}),[b.YANK]:xv({selectedNode:n,breadCrumb:o}),[b.COMMENT]:[],[b.DELETE]:["confirm"],[b.RE_OPEN_ISSUE]:["confirm"],[b.CLOSE_ISSUE]:["confirm"],[b.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[b.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[b.TAG]:[...new Set([...Object.keys(Zo),...C.getExistingTags()])],[b.UNTAG]:[...fs()?.value?.map(({name:l})=>l)??[]],[b.UNASSIGN]:[...gs()?.value?.map(({name:l})=>l)??[]],[b.ASSIGN]:C.getExistingAssignees(),[b.NEW]:bv(s),[b.CONFIG]:[...gv]}[e]??[]};import xf from"chalk";var Ou=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import $v from"zod";import Tv from"node:path";import{z as lt}from"zod";import{accessSync as Rv,copyFileSync as Sv,existsSync as vs,mkdirSync as Du,readdirSync as Fu,readFileSync as Cv,renameSync as Nv,rmSync as Iv,statSync as _u,unlinkSync as wv,writeFileSync as Av}from"node:fs";import rr from"node:path";var Ta=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Oe={writeToFile:(e,t)=>{try{let n=rr.dirname(e);vs(n)||Du(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Av(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Cv(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Oe.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 vs(e)&&_u(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Rv(e),!0}catch{return!1}},mkDir:e=>Du(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=rr.parse(t);for(;;){let r=rr.join(t,e);try{if(vs(r)&&_u(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=rr.dirname(t)}return null},readFirstJSON(e){try{if(!Oe.dirExists(e))return null;let t=Fu(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=rr.join(e,t);return Oe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Oe.dirExists(e)?Fu(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{wv(e)}catch(t){(!Ta(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Iv(e,{recursive:!0,force:!0})}catch(t){(!Ta(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(rr.dirname(t)),!n?.overwrite&&vs(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Nv(e,t)}catch(r){if(Ta(r)&&r.code==="EXDEV"){Sv(e,t),this.rmFile(e);return}throw r}}};var Mv={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Bu=lt.object({logLevel:lt.enum(["info","error","debug"]),preferredEditor:lt.string().optional(),userName:lt.string().optional(),userId:lt.string().optional(),autoSync:lt.boolean().nullable().optional(),autoSyncDebounceMs:lt.number().optional(),attachmentMaxKb:lt.number().optional(),repoCloneMaxMb:lt.number().optional(),viewMode:lt.enum(["dense","wide"]).optional(),declinedEmailBoards:lt.array(lt.string()).optional()}).partial(),kv="config.json",Uu=We,Ma=()=>Tv.join(Uu(),kv),ka=()=>{try{return Oe.mkDir(Uu()),d(`Ensured ~/${vt} exists`,null)}catch{return a(`Unable to create ~/${vt}`)}},Lv=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${vt}/config.json JSON`)}let n=Bu.safeParse(t??{});return n.success?d("Parsed config",n.data):a(`Invalid ~/${vt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Pt=()=>{let e=ka();if(c(e))return a(e.message);let t=Ma(),n=Oe.readFile(t);return n==null||n.trim()===""?d("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Lv(n)},ju=e=>{let t=ka();if(c(t))return a(t.message);let n=Bu.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ma();try{return Oe.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
32
|
-
`),d("Config written",null)}catch{return a(`Unable to write ~/${vt}/config.json`)}},qe=e=>{let t=Pt();if(c(t))return a("Failed to read existing config");let n={...t.value,...e};return ju(n)},Hu=()=>{let e=Ma(),t=ka();if(c(t))return a(`Unable to create ~/${vt}`);if(!(Oe.readFile(e)!==null)){let E=ju(Mv);if(c(E))throw new Error(`Unable to create ~/${vt}/config.json`)}let r=Pt();if(c(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:l,autoSync:u,autoSyncDebounceMs:p,attachmentMaxKb:m,logLevel:f,viewMode:g}=r.value,x=Gl({userId:i,userName:s});if(c(x))return a(x.message);let N=x.value??{userId:i,userName:s};return!N.userName||!N.userId?a(`User name or ID not configured in ~/${vt}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,d("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:l??[],logLevel:f??"debug",preferredEditor:o??"",userName:N.userName,userId:N.userId,autoSync:u??!1,autoSyncIntervalMs:p??1e4,attachmentMaxKb:m??null,viewMode:g??"dense"}))};import Ov from"node:crypto";import eo from"node:fs";import zu from"node:path";var Wu="/media/",Gu=e=>`${Wu}${e}`,Pv=(e,t)=>`})`;var Tn=500,Dv=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,La=(e,t)=>`${e}.${t}`,Fv=e=>Dv.test(e),Vu=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?d("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?d("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?d("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?d("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${ad.join(", ")}`),qu=e=>Ov.createHash("sha256").update(e).digest("hex"),_v=(e,t=Tn)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Vu(e);return c(n)?n:d("Validated attachment data",{hash:qu(e),ext:n.value,bytes:e.length})},TT=(e,t,n=Tn)=>{let r=_v(t,n);if(c(r))return r;let o=Vr(e),s=zu.join(o,La(r.value.hash,r.value.ext));try{eo.existsSync(s)||(eo.mkdirSync(o,{recursive:!0}),eo.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return d("Wrote attachment blob",r.value)},MT=(e,t,n=Tn)=>{if(!Fv(t))return a("Invalid attachment file name");let r=zu.join(Vr(e),t);if(!eo.existsSync(r))return a("Attachment blob not found");let o;try{o=eo.readFileSync(r)}catch(u){return a(`Unable to read attachment blob: ${u instanceof Error?u.message:String(u)}`)}if(o.length>n*1024)return a(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(qu(o)!==s)return a("Attachment blob does not match its content hash");let l=Vu(o);return c(l)?l:l.value!==i?a("Attachment blob content does not match its extension"):d("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var to=50,no=5e3,Ku=()=>{let e=Y().commandMeta.inputString,t=$v.coerce.number().int().min(to).max(no).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${to}-${no} KB (default ${Tn})`);let n=qe({attachmentMaxKb:t.data});return c(n)?n:(at({attachmentMaxKb:t.data}),d(`Attachment size cap set to ${t.data} KB`,null))};import Yu from"node:fs";import Bv from"node:path";var Pa=2048,or=1,sr=1048576,Oa=e=>Number.isInteger(e)&&e>=or&&e<=sr,ir=()=>{let e=Pt(),t=c(e)?void 0:e.value.repoCloneMaxMb;return t!==void 0&&Oa(t)?t:Pa},nn=e=>{let t=0,n=r=>{let o;try{o=Yu.readdirSync(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=Bv.join(r,s.name);if(s.isDirectory()){n(i);continue}try{t+=Yu.lstatSync(i).size}catch{}}};return n(e),t},ro=e=>`Its clone would pass this machine's ${e} MB cap for a connected repo: narrow its history, or raise repoCloneMaxMb`;var St=e=>{let t=xe(e??process.cwd());return c(t)?a(t.message):d("Resolved Epiq repo root",t.value)},ar=e=>/^[0-9a-f]{7,40}$/i.test(e);import{createHash as Nx}from"node:crypto";import $m from"node:path";import Ix from"node:fs";import{ulid as wx}from"ulid";import Da from"node:fs";import Uv from"node:path";var oo=e=>e?.code==="ENOENT",Fa=3,_a=e=>Da.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),Ct=e=>{let t=Ve(e);for(let n=1;;n++){if(!Da.existsSync(t))return"none";let r=[],o=!1;for(let s of _a(t))try{let{size:i,mtimeMs:l}=Da.statSync(Uv.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!oo(i))throw i;if(n<Fa){o=!0;break}}if(!o)return r.join("|")}},Xu=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),$a=(e,t,n,r)=>{let o=Xu(t),s=Ct(e),i=Xu(s),l=u=>u===void 0?0:Number(u.slice(0,u.indexOf(":")));if(l(i.get(n))!==l(o.get(n))+r)return null;for(let[u,p]of i)if(u!==n&&o.get(u)!==p)return null;for(let u of o.keys())if(u!==n&&!i.has(u))return null;return s},Wt=null,Ju=e=>Wt&&Wt.root===e?Wt.signature:null,xs=(e,t)=>{Wt={root:e,signature:t}},Zu=(e,t,n)=>{if(!Wt||Wt.root!==e)return;let r=$a(e,Wt.signature,t,n);Wt=r===null?null:{root:e,signature:r}},Qu=()=>{Wt=null};import{z as Mn}from"zod";var em=1,tm=Mn.tuple([Mn.string().min(1),Mn.string().min(1).nullable()]),jv=Mn.looseObject({v:Mn.literal(em),id:tm}),nM=Mn.looseObject({v:Mn.number().int().positive(),id:tm}),Hv=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),Wv=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},nm=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return a("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return a("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return a("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?a("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?a("Invalid persisted event envelope: id.1"):d("Parsed persisted event envelope",Hv(e)?Wv(e):e)};var Gv=[1];var zv=new Set(Gv),Ba=e=>zv.has(e),rm=e=>{let t=jv.safeParse(e);return t.success?d("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Ua=(e,t)=>{let n={[e.action]:e.payload,v:em,id:t};return rm(n)};import ao from"node:fs";import Is from"node:path";import{decodeTime as Qv}from"ulid";import{z as Wa}from"zod";import Ce from"node:fs";import kn from"node:path";import{ulid as Vv}from"ulid";var Rs="~pending",ja=/~pending(-[0-9a-z]+)*$/i,sm=/-f(\d+)$/,im=e=>{let t=e.indexOf(".");return t===-1?`${e}${Rs}`:e.slice(0,t)+Rs+e.slice(t)},Ss=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},qv=e=>{let[t,n]=Ss(e);return ja.test(t)?t.replace(ja,"")+n:null},Ha=e=>e.replace(ja,""),Ln=e=>e.endsWith(".jsonl")&&qv(e)!==null,so=e=>Ha(Ss(e)[0]),am=e=>{let[t]=Ss(e),n=sm.exec(t);return n&&Ln(e)?Number(n[1]):null},Kv=e=>im(e).replace(Rs,`${Rs}-${Vv().toLowerCase()}`),Yv=(e,t)=>{let[n,r]=Ss(e);return`${n.replace(sm,"")}-f${t}${r}`},cm=(e,t)=>kn.join(Ve(e),im(t)),Xv=(e,t)=>Math.max(0,Ce.statSync(e).size-(am(t)??0)),lm=e=>{let t=Ve(e);try{return Ce.existsSync(t)?Ce.readdirSync(t).filter(Ln).some(n=>Xv(kn.join(t,n),n)>0):!1}catch{return!0}},Jv=3,dm=(e,t)=>{for(let n=1;;n++){let r=Ce.openSync(e,"a"),o;try{Ce.writeSync(r,t),o=Ce.fstatSync(r).ino}finally{Ce.closeSync(r)}let s;try{s=Ce.statSync(e).ino}catch{s=null}if(s===o||n>=Jv)return}},Zv=e=>{let t;try{t=Ce.openSync(e,"r")}catch{return!0}try{let{size:n}=Ce.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ce.readSync(t,r,0,1,n-1),r[0]===10}finally{Ce.closeSync(t)}},Es=10,om=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(Es)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ce.appendFileSync(e,Buffer.concat([Buffer.from(Zv(e)?"":`
|
|
33
|
-
`),o,Buffer.from(o[o.length-1]===Es?"":`
|
|
34
|
-
`)]));let s=0;for(let i of o)i===Es&&s++;return o[o.length-1]!==Es&&s++,{bytes:r,lines:s}},Cs=(e,t)=>{let n=Ve(e);if(!Ce.existsSync(n))return d("No events directory",0);try{let r=so(t),o=Ce.readdirSync(n).filter(l=>Ln(l)&&so(l)===r),s=kn.join(n,t),i=0;for(let l of o){let u=am(l);if(u!==null){let g=kn.join(n,l),x=Ce.readFileSync(g).subarray(u);i+=om(s,x,!0).lines,Ce.rmSync(g,{force:!0});continue}let p=/~pending-/i.test(l)?l:Kv(t),m=kn.join(n,p);p!==l&&Ce.renameSync(kn.join(n,l),m);let f=om(s,Ce.readFileSync(m));i+=f.lines,Ce.renameSync(m,kn.join(n,Yv(p,f.bytes)))}return d("Folded pending logs",i)}catch(r){return a(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}};var ws="unknown",ex=Wa.object({userId:Wa.string().min(1).default(ws),userName:Wa.string().min(1).default(ws)}),fm=new Set(["id","v","userId","userName"]),Ns=e=>{let t=Object.entries(e).filter(([o])=>!fm.has(o));if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},tx=/^[0-9a-hjkmnp-tv-z]{26}$/i,nx=e=>tx.test(e)?e.toUpperCase():e,gm=e=>{let t=Is.basename(e,".jsonl"),n=t.indexOf("."),r=Ha(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=ex.safeParse({userId:nx(r),userName:o});return s.success?d("Parsed event file actor",s.data):a(`Invalid event file name ${Is.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},rx=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"):d("Resolved persisted action",t[0])},ox=(e,t)=>t in e,rn=new Map,sx=3e5,ix=512,io=0,Ga=e=>e.entries.length+e.quarantined.length,ax=(e,t,n,r)=>{let o=rn.get(e);o&&(io-=Ga(o));let s={stamp:t,entries:n,quarantined:r};rn.delete(e),rn.set(e,s),io+=Ga(s);for(let[i,l]of rn){if(io<=sx&&rn.size<=ix)break;i!==e&&(rn.delete(i),io-=Ga(l))}},cx=()=>{rn.clear(),io=0},lx=2n,um=1000000n,dx=e=>{try{let{size:t,mtimeNs:n}=ao.statSync(e,{bigint:!0});return{value:`${t}:${n}`,settled:BigInt(Date.now())*um-n>lx*um}}catch{return null}},hm=(e,t)=>{let n=gm(e);if(c(n))return a(n.message);let r=dx(e),o=r?rn.get(e):void 0;if(r&&o&&o.stamp===r.value){if(t)for(let m of o.quarantined)t.push(m);return d("Parsed persisted events file",[...o.entries])}let s;try{s=ao.readFileSync(e,"utf8")}catch(m){if(oo(m))return d("Event file missing",null);throw m}let i=[],l=Is.basename(e),u=[],p=(m,f)=>{u.push({eventId:null,reason:"corrupt-line",detail:`${l}:${m} (${f})`,targetNodeId:null})};for(let[m,f]of s.split(`
|
|
35
|
-
`).entries()){let g=f.trim();if(!g)continue;let x;try{x=JSON.parse(g)}catch{p(m+1,"invalid JSON");continue}let N=nm(x);if(c(N)){p(m+1,N.message);continue}i.push({...N.value,userId:n.value.userId,userName:n.value.userName})}if(t)for(let m of u)t.push(m);return r?.settled&&ax(e,r.value,i,u),d("Parsed persisted events file",[...i])},mm=(e,t)=>e<t?-1:e>t?1:0,za=(e,t)=>{let n=mm(e.id[0],t.id[0]);return n!==0?n:mm(JSON.stringify(e),JSON.stringify(t))},pm=(e,t)=>{let n=new Map,r=new Map;for(let m of e){let f=m.id[0],g=m.id[1]??null;n.set(f,m);let x=r.get(g)??[];x.push(m),r.set(g,x)}for(let m of r.values())m.sort(za);let o=[],s=new Set,i=m=>{let f=[m];for(;f.length>0;){let g=f.pop(),x=g.id[0];if(s.has(x))continue;o.push(g),s.add(x);let N=r.get(x)??[];for(let E=N.length-1;E>=0;E--)f.push(N[E])}},l=(r.get(null)??[]).filter(m=>{let f=Object.keys(m).filter(g=>!fm.has(g));return f.length===1&&f[0]===t});for(let m of l)i(m);let u=e.filter(m=>{let f=m.id[0],g=m.id[1]??null;return s.has(f)?!1:g===null||!n.has(g)}).sort(za);for(let m of u)i(m);let p=e.filter(m=>!s.has(m.id[0])).sort(za);for(let m of p)i(m);return o},Va=e=>Xo(e.map(t=>{try{return Qv(t.id[0])}catch{return null}})),ym=(e,t)=>{let n=new Set,r=[],o=[],s=Va(e);for(let i=0;i<e.length;i++){let l=e[i],u=l.id[0],p=l.id[1],m=s[i]??null;!(m!==null&&m<t)||p&&n.has(p)?(n.add(u),o.push(l)):r.push(l)}return{appliedEvents:r,unappliedEvents:o}},bm=e=>{let t=new Set(e.actions),n=v=>t.has(v),r=v=>{let{userId:I,userName:k,...M}=v,L=rx(M);if(c(L))return a(L.message);let P=L.value,$=v.id?.[0];return $?ox(M,P)?d("Decoded persisted event",{id:$,action:P,payload:M[P],userId:I}):a(`Persisted event is missing payload for action: ${P}`):a("Persisted event is missing id")},o=(v,I)=>{let k=[],M=new Map,L=new Map;for(let P of v){if(!Ba(P.v)){L.set(P.v,(L.get(P.v)??0)+1),I?.push({eventId:P.id[0],reason:"unsupported-schema-version",detail:`v${P.v}`,targetNodeId:Ns(P)});continue}let $=r(P);if(c($)){I?.push({eventId:P.id[0],reason:"invalid-payload",detail:$.message,targetNodeId:Ns(P)});continue}let B=$.value.action;if(!n(B)){M.set(B,(M.get(B)??0)+1),I?.push({eventId:P.id[0],reason:"unknown-action",detail:B,targetNodeId:Ns(P)});continue}let de=e.readPayload(B,$.value.payload);if(c(de)){I?.push({eventId:P.id[0],reason:"invalid-payload",detail:de.message,targetNodeId:Ns(P)});continue}k.push($.value)}if(M.size>0){let P=[...M.entries()].map(([$,B])=>`${$} (x${B})`).join(", ");j.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${P}. Upgrade to apply them.`)}if(L.size>0){let P=[...L.entries()].map(([$,B])=>`v${$} (x${B})`).join(", ");j.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${P}. Upgrade to apply them.`)}return d("Decoded reconstructed events",k)},s=null;function i(v,I){let k=Ve(v),M=Ct(v);if(!ao.existsSync(k))return d("No events found",[]);let L=[],P=[];for(let B=1;;B++){L=[],P=[];let de=!1;for(let O of _a(k)){let q=hm(Is.join(k,O),P);if(c(q))return a(q.message);if(q.value===null){if(B<Fa){de=!0;break}continue}for(let Pe of q.value)L.push(Pe)}if(!de)break}if(I)for(let B of P)I.push(B);let $=pm(L,e.genesis);return s={root:v,signature:M,edge:$.at(-1)?.id?.[0]??null},d("All events loaded",$)}function l(v){let I=[],k=i(v,I);if(c(k))return a(k.message);let M=o(k.value,I);return c(M)?a(M.message):d("Loaded merged events",{events:M.value,unreadable:I})}function u(v){let I=i(v);return c(I)?a(I.message):d("Loaded event actors",I.value.map(({userId:k,userName:M})=>({userId:k,userName:M})))}function p(v){let I=new Map,k=Ve(v),M;try{if(!ao.existsSync(k))return I;M=ao.readdirSync(k)}catch{return I}let L=new Set;for(let $ of M){if(!$.endsWith(".jsonl"))continue;let B=gm($);if(c(B))continue;let{userId:de,userName:O}=B.value;if(!de||!O||O===ws)continue;let q=I.get(de);q!==void 0&&q!==O&&L.add(de),I.set(de,O)}if(L.size===0)return I;let P=u(v);if(c(P))return I;for(let{userId:$,userName:B}of P.value)L.has($)&&(!B||B===ws||I.set($,B));return I}function m(v){let I=l(v);return c(I)?a(I.message):d("Loaded merged events",I.value.events)}function f(v,I){let k=i(v);if(c(k))return a(k.message);let{appliedEvents:M,unappliedEvents:L}=ym(k.value,I),P=o(M);if(c(P))return a(P.message);let $=o(L);return c($)?a($.message):d("Loaded merged events before time",{appliedEvents:P.value,unappliedEvents:$.value})}function g(v=process.cwd()){let I=Ct(v);if(s&&s.root===v&&s.signature===I)return d("Loaded edge reference, unchanged",s.edge);let k=i(v);return c(k)?a(k.message):d("Loaded edge reference",k.value.at(-1)?.id?.[0]??null)}function x(v,I,k,M){if(!s||s.root!==v)return;let L=$a(v,s.signature,I,M);s=L===null?null:{root:v,signature:L,edge:k}}function N(){s=null,cx()}let E=v=>pm(v,e.genesis);function R(v){let I=i(v);if(c(I))return a(I.message);let k=Va(I.value);return d("Loaded effective event times",new Map(I.value.map((M,L)=>[M.id[0],k[L]??null])))}return{fromPersistedEvent:r,decodeReconstructedEvents:o,loadMergedEventsWithUnreadable:l,loadEventActors:u,loadActorNames:p,loadMergedEvents:m,loadMergedEventsBefore:f,getEdgeRef:g,advanceEdgeRef:x,clearEdgeCache:N,getSortedEvents:E,loadEffectiveEventTimes:R}};var As=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...As(e,t),convergence:!0}),cr=e=>c(e)&&e.convergence===!0,Pn=e=>{let t=e.filter(c);return{fatal:t.filter(n=>!cr(n)),skipped:t.filter(cr)}},On=e=>{e.length!==0&&j.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},ux=e=>e.userId?.length?null:As("Invalid user ID format",e),vm=e=>{let t=null;function n(o,s=!1){let i=e.apply[o.action];if(!i)return a(`Unknown event action "${o.action}", likely created by a newer epiq version. Evt id: ${o.id}`);if(!e.replay.isInitialized()&&o.action!==e.genesis)return F(`${o.action} arrived before the state was initialized`,o);if(o.action===e.genesis&&t){if(t.genesisApplied)return F("the state is already initialized",o);t.genesisApplied=!0}let l;try{l=i(o)}catch(m){return F(`threw while materializing (${m instanceof Error?m.message:String(m)})`,o)}if(c(l))return l;let u=ux(o);if(u)return u;let p=e.replay.afterApply(o,{batched:t!==null,bypassLogging:s});return p||l}return{materialize:n,materializeAll:o=>{let s=e.replay.batch(()=>{let i=t===null;i&&(t={genesisApplied:!1});let l=!1;try{let u=o.map(p=>n(p));if(i){l=!0;let p=e.replay.flush();if(p)return o.map(()=>p)}return u}finally{i&&(t=null,l||e.replay.flush())}});return c(s)?o.map(()=>a(s.message)):s.value}}};import Rm from"node:fs";import qa from"node:path";import{decodeTime as mx,monotonicFactory as px}from"ulid";var xm=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";var re=({userId:e})=>({userId:e}),Em=e=>({action:e.action,payload:e.payload});var fx=0xffffffffffff,gx=Yo,hx=e=>{let t=Date.now(),n;try{n=mx(e)}catch{return t}return n>=fx?t:n>t+gx?(j.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},lr=({userId:e})=>`${xm(e)}.jsonl`,Sm=(e,t)=>{let n;try{if(!Rm.existsSync(e))return[t];n=Rm.readdirSync(e)}catch{return[t]}let r=so(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||Ln(s)?!1:so(s)===r).sort(),t]},Cm=(e,{userId:t})=>{let n=lr({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return a(`Invalid event log file name: ${n}`);let o=qa.join(Ve(e),n);return d("Successfully resolved event log path",o)},Nm=e=>{let t=px();function n(o,s){let i;if(s&&s.current!==void 0)i=s.current;else{let u=e.getEdgeRef(o);if(c(u))return a(u.message);i=u.value}let l=i?t(hx(i)):t();return d("Minted event id",[l,i])}function r({event:o,rootDir:s,edge:i,id:l}){try{let u=mu(s);if(c(u))return u;let p=Cm(s,{userId:o.userId});if(c(p))return p;let m=cm(s,qa.basename(p.value)),f=l?d("Minted event id",l):n(s,i);if(c(f))return a(f.message);let[g,x]=f.value,N=Ua(Em(o),[g,x]);if(c(N))return a(N.message);let E=`${JSON.stringify(N.value)}
|
|
36
|
-
`;dm(m,E),i&&(i.current=g);let R=qa.basename(m);return e.advanceEdgeRef(s,R,g,Buffer.byteLength(E)),Zu(s,R,Buffer.byteLength(E)),d("Event persisted",{path:m,entry:N.value})}catch(u){let p=u instanceof Error?u.message:"Unknown persist error";return a(`Failed to persist event: ${p}`)}}return{mintEventId:n,persist:r}};var Im=(e,t,n)=>{function r(s,i,l){let u=n.mintEventId(i,l);if(c(u))return a(u.message);let p={...s,id:u.value[0]},m=t.materialize(p);if(m.status!==qn.Success)return m;let f=n.persist({event:p,rootDir:i,edge:l,id:u.value});return c(f)?(Qu(),f):m}function o(s,i){if(s.length===0||!s[0])return a("No events provided");let l=e.write.readOnlyReason();if(l)return a(l);let u=e.replay.batch(()=>{let p={},m=e.write.beforeWrite(s[0],x=>r(x,i,p));if(c(m))return a(m.message);let f=s.map(x=>r(x,i,p)),g=f.filter(c);return g.length>0?a("Materialize and persist failed: "+g.map(x=>x.message).join(", ")):d("Materialization succeeded",f.map(x=>x.value))});return c(u)?a(u.message):u.value??a("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}};var wm=e=>{let t=vm(e),n=bm(e),r=Nm(n),o=Im(e,t,r);return{...t,...n,...r,...o}};import{z as V}from"zod";var z=V.string().min(1),Nt=V.string(),on=V.string(),Ts=V.looseObject({id:z}),Ka=V.looseObject({id:z,name:Nt,parent:z,rank:on}),yx={"init.workspace":V.looseObject({id:z,name:Nt,rank:on}),"add.workspace":V.looseObject({id:z,name:Nt,rank:on}),"add.board":Ka,"add.swimlane":Ka,"add.issue":Ka,"add.field":V.looseObject({id:z,name:Nt,parent:z,rank:on}),"edit.title":V.looseObject({id:z,name:Nt}),"delete.node":Ts,"lock.node":Ts,"move.node":V.looseObject({id:z,parent:z,rank:on}),"edit.description":V.looseObject({id:z,md:V.string()}),"close.issue":V.looseObject({id:z,parent:z,rank:on}),"reopen.issue":V.looseObject({id:z,parent:z,rank:on}),"create.tag":V.looseObject({id:z,name:Nt}),"tombstone.tag":Ts,"restore.tag":V.looseObject({id:z,name:Nt}),"create.contributor":V.looseObject({id:z,name:Nt}),"rename.contributor":V.looseObject({id:z,name:Nt}),"tombstone.contributor":Ts,"restore.contributor":V.looseObject({id:z,name:Nt}),"link.contributor.user":V.looseObject({contributor:z}),"link.contributor.email":V.looseObject({contributor:z,email:z}),"unlink.contributor.email":V.looseObject({contributor:z,email:z}),"connect.repo":V.looseObject({url:V.string()}),"edit.repo":V.looseObject({repo:z}),"disconnect.repo":V.looseObject({repo:z}),"add.issue.assignee":V.looseObject({id:z,assignee:z}),"remove.issue.assignee":V.looseObject({id:z,assignee:z}),"add.issue.tag":V.looseObject({id:z,tag:z}),"remove.issue.tag":V.looseObject({id:z,tag:z}),"add.issue.comment":V.looseObject({id:z,issue:z,md:V.string()}),"edit.issue.comment":V.looseObject({id:z,issue:z,md:V.string()}),"delete.issue.comment":V.looseObject({id:z,issue:z}),"add.issue.attachment":V.looseObject({id:z,issue:z,hash:V.string().min(1),ext:V.string().min(1),name:Nt,bytes:V.number()}),"delete.issue.attachment":V.looseObject({id:z,issue:z}),"rebalance.children":V.looseObject({parent:z,ranks:V.record(V.string(),on)})},Am=(e,t)=>{let r=yx[e].safeParse(t);return r.success?d("Payload is readable",void 0):a(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};import{ulid as bx}from"ulid";var Tm=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return d("Contributor write already in flight",void 0);let{userId:n,userName:r}=ee();if(!r||n!==e.userId)return d("Not this actor own write",void 0);let o=C.getContributor(e.userId),s={id:bx(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return d("Contributor name is current",void 0);let i=t(s);return c(i)?a(i.message):d("Contributor name recorded",void 0)};var Ya=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user","link.contributor.email","unlink.contributor.email","connect.repo","edit.repo","disconnect.repo"];var Ek=new Set(Ya);var me={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var nt=e=>e.slice(-7).toUpperCase(),Xa=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?nt(e).includes(n):!0};var Ne={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:te.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:nt(e)},context:te.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:te.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:te.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:te.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:nt(e)},context:te.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:te.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:te.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var co=(e,t,n)=>C.getNode(e)?F(`a node with id ${e} already exists`,n):t===e?F("a node cannot be its own parent",n):null,Ja=e=>{let t=h().repos,n=Bi(t,e);if(c(n))return{skip:F(n.message,e)};let r=ge(o=>({...o,repos:t}));return c(r)?{skip:F("Unable to update repos",e)}:{message:n.message,entry:n.value}},Mm={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ne.workspace(t,n,r),s=lo(o);if(c(s))return As(s.message,e);let i=C.createNode(o);return c(i)?F(i.message??"Failed to initialize workspace",e):Ji(i.value)?d("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=co(t,void 0,e);if(o)return o;let s=C.createNode(Ne.workspace(t,n,r));return c(s)?F(s.message??"Failed to add workspace",e):Ji(s.value)?d("Added workspace",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=co(t,r,e);if(s)return s;let i=C.createNode(Ne.board(t,n,r,o));return c(i)?F(i.message??"Unable to create board",e):dd(i.value)?d("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=co(t,r,e);if(s)return s;let i=C.createNode(Ne.swimlane(t,n,r,o));return c(i)?F(i.message??"Unable to create swimlane",e):ts(i.value)?d("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=co(t,r,e);if(s)return s;let i=C.createNode(Ne.ticket(t,n,r,o));return c(i)?F(i.message??"Unable to create issue",e):H(i.value)?d("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=co(t,r,e);if(i)return i;let l=C.createNode(Ne.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(me.DESCRIPTION)?"vertical":"horizontal"}));return c(l)?F(l.message??`Unable to create field: ${n}`,e):Fe(l.value)?d("Added field",{action:e.action,result:l.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!C.getNode(t))return F(`Unable to locate node with id ${t}`,e);let o=C.renameNode(t,n);return c(o)?F(o.message??"Unable to edit title",e):d("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=C.tombstoneNode(t);return c(n)?F(n.message??"Unable to delete node",e):d("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=C.createTag({id:t,name:n});return c(r)?F(r.message??"Unable to create tag",e):d("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=C.tombstoneTag(t);return c(n)?F(n.message??"Unable to delete tag",e):d("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=C.restoreTag(t,n);return c(r)?F(r.message??"Unable to restore tag",e):d("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=C.createContributor({id:t,name:n});return c(r)?F(r.message??"Unable to create contributor",e):d("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=C.renameContributor(t,n);return c(r)?F(r.message??"Unable to rename contributor",e):d("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=C.tombstoneContributor(t);return c(n)?F(n.message??"Unable to remove contributor",e):d("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=C.restoreContributor(t,n);return c(r)?F(r.message??"Unable to restore contributor",e):d("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=C.tag(t,n);return c(r)?F(r.message??"Unable to tag issue",e):d("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=C.untag(t,n);return c(r)?F(r.message??"Unable to untag issue",e):d("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=C.assign(t,n);return c(r)?F(r.message??"Unable to assign issue",e):d("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=C.unassign(t,n);return c(r)?F(r.message??"Unable to unassign issue",e):d("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.moveNodeToRank({id:t,parentId:n,rank:r});return c(o)?F(o.message??"Failed to move node",e):d("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=C.editValue(t,n);return c(r)?F(r.message??"Unable to edit description",e):d("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.getNode(t);if(!o)return F("Unable to locate issue",e);if(!H(o))return F("Can only close issues",e);let s=C.getNode(ct);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let i=C.moveNodeToRank({id:t,parentId:n,rank:r});return c(i)?F(i.message??"Unable to close issue",e):d("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.getNode(t);if(!o)return F("Unable to locate issue",e);if(!H(o))return F("Can only reopen issues",e);let s=C.getNode(ct);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!C.getNode(n))return F("Reopen parent no longer exists",e);let l=C.moveNodeToRank({id:t,parentId:n,rank:r});return c(l)?F(l.message??"Unable to reopen issue",e):d("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=C.lockNode(t);return c(n)?F(n.message??"Unable to lock node",e):d("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=C.getNode(r);if(!s)return F(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return F(`Node ${r} is not child of ${t}`,e);let i=C.updateNode({...s,rank:o});if(c(i))return F(i.message??"Unable to rebalance child",e)}return d("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=C.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return c(s)?F(s.message??"Unable to add comment",e):d("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=C.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let s=C.editComment(t,r);return c(s)?F(s.message??"Unable to edit comment",e):d("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=C.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let o=C.deleteComment(t);return c(o)?F(o.message??"Unable to delete comment",e):d("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,l=C.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return c(l)?F(l.message??"Unable to add attachment",e):d("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=C.getAttachment(t);if(!r)return F("Unable to locate attachment",e);if(r.issue!==n)return F("Attachment does not belong to issue",e);let o=C.deleteAttachment(t);return c(o)?F(o.message??"Unable to delete attachment",e):d("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!Yn(n))return F(`not an email address: ${n}`,e);let r=C.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return c(r)?F(r.message??"Unable to link email",e):d("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=C.unlinkContributorEmail(n,t,e.userId);return c(r)?F(r.message??"Unable to unlink email",e):d("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=C.linkUserId({contributorId:t,userId:e.userId});return c(n)?F(n.message??"Unable to link contributor",e):d("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})},"connect.repo":e=>{let t=Ja(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})},"edit.repo":e=>{let t=Ja(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})},"disconnect.repo":e=>{let t=Ja(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})}};var km=e=>{let t=C.getNode(e);if(!t||!H(t)||t.isDeleted)return null;let n=Qa(t);return c(n)?n:null},Lm=e=>{if(!ec())return null;for(let t of e){let n=km(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=km(r);if(o)return o}return null},vx=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},xx=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},Za=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return xx(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"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":case"link.contributor.email":case"unlink.contributor.email":case"connect.repo":case"edit.repo":case"disconnect.repo":default:return[]}},Ex=e=>{ge(t=>({...t,eventLog:[...t.eventLog,e]}))},Gt=null,Rx=e=>{for(let[t,n]of e.nodeLog){let r=C.getNode(t);r&&C.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&ge(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Lm([...e.virtualNodeIds])},Pm={isInitialized:()=>dt(),batch:e=>Ms(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(Za(e))];if(t){Gt??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=Gt.nodeLog.get(o);s?s.push(e):Gt.nodeLog.set(o,[e])}if(ec()){Gt.virtualNodeIds.add(o);let s=h().nodes[o]?.parentNodeId;s&&Gt.virtualNodeIds.add(s)}}return n||Gt.appLog.push(e),null}return n||(r.forEach(o=>vx(o,e)),Ex(e)),Lm(r)},flush(){if(!Gt)return null;let e=Gt;return Gt=null,Rx(e)}};var oe=()=>{let{userName:e,userId:t}=ee();return e?t?Hl(t)?Wl(e)?d("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")};var Sx={genesis:"init.workspace",actions:Ya,readPayload:Am,apply:Mm,replay:Pm,write:{readOnlyReason:()=>{let e=h();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:Tm}},Cx=wm(Sx),{materialize:uo,materializeAll:sn,fromPersistedEvent:gL,decodeReconstructedEvents:hL,loadMergedEventsWithUnreadable:mo,loadEventActors:yL,loadActorNames:Om,loadMergedEvents:ks,loadMergedEventsBefore:Dm,getEdgeRef:bL,advanceEdgeRef:vL,clearEdgeCache:xL,getSortedEvents:EL,loadEffectiveEventTimes:Fm,mintEventId:RL,persist:_m,materializeAndPersist:SL,materializeAndPersistAll:Q}=Cx;var tc="Unchanged",Ls="Renamed ",Ax={live:[],overLimit:[],disconnected:[]},po=null,Tx=(e,t)=>{if(!dt())return null;let n=h();return n.timeMode==="live"&&n.replay===null&&Ju(e)===t?n.repos:null},rt=e=>{try{let t=ye({repoRoot:e});if(c(t))return a(t.message);let n=t.value,r=Ct(n);if(r==="none")return d("No log yet",Ax);if(po&&po.root===n&&po.signature===r)return d("Read connected repos",po.repos);let o=Tx(n,r);if(!o){let i=ks(n);if(c(i))return a(i.message);o=Xl(i.value)}let s=Jl(o);return po={root:n,signature:r,repos:s},d("Read connected repos",s)}catch(t){return a(`Could not read the connected repos: ${t instanceof Error?t.message:String(t)}`)}},Ps=e=>{let t=rt(e);return c(t)?a(t.message):d("Read other repos",t.value.live)},Bm=(e,t)=>{let n=Ps(e);return!c(n)&&n.value.some(r=>r.id===t)},nc=e=>{let t=e.url.trim(),n=Or(t);if(n)return a(`That URL ${n}. ${zl}`);if(e.since!==void 0&&!xn(e.since))return a(`"${e.since}" is not a history window: use board, all or YYYY-MM-DD.`);let r=e.label?.trim();if(r&&!En(r))return a(`"${r}" is not a label: up to 24 of a-z, 0-9, dot, dash or underscore, opening on a letter or digit.`);let o=rt(e.repoRoot);if(c(o))return a(o.message);let s=[...o.value.live,...o.value.overLimit],i=Zt(t),l=s.find(g=>g.id===i),u=r===void 0?void 0:r===Mt(l?.url??t)?"":r;if(u&&s.some(g=>g.id!==i&&g.label===u))return a(`Another repo is already called ${u}`);let p={...e.branches?{branches:e.branches}:{},...e.since?{since:e.since}:{},...u!==void 0?{label:u}:{}};if(!l){let g={id:i,url:t,branches:e.branches??_i,since:e.since??$i,label:u||Mt(t)};return d("Plan",{kind:"connect",repo:g,event:{url:t,...e.branches?{branches:e.branches}:{},...e.since?{since:e.since}:{},...u?{label:u}:{}}})}let m={...l,branches:e.branches??l.branches,since:e.since??l.since,label:u===void 0?l.label:u||Mt(l.url)};if(m.branches===l.branches&&m.since===l.since&&m.label===l.label)return d("Plan",{kind:"unchanged",repo:l});let f=m.branches===l.branches&&m.since===l.since;return d("Plan",{kind:"edit",repo:m,event:{repo:i,...p},message:`${f?Ls:"Updated "}${m.label}`})},fo=e=>{let t=ye({repoRoot:e.repoRoot});if(c(t))return a(t.message);let n=Q([{id:wx(),userId:e.actorId,...e.event}],t.value);return c(n)?a(n.message):d("Wrote repo event",null)},rc=e=>{let t=rt(e);return new Map(c(t)?[]:[...t.value.live,...t.value.overLimit].map(n=>[n.id,n.label]))},oc=e=>e.map(t=>e.filter(n=>n.label===t.label).length===1?t.label:t.id),Os=(e,t)=>{let n=t.trim(),r=e.filter(s=>s.label===n);if(r.length>1)return a(`Several repos are called ${n} \u2014 name one by its id or URL`);let o=r[0]??e.find(s=>s.id===n||Jt(n)&&s.id===Zt(n));return o?d("Found",o):a(`No repo "${n}" is connected`)},sc=(e,t)=>{let n=rt(e);return c(n)?a(n.message):Os([...n.value.live,...n.value.overLimit],t)},ic=e=>$m.join(We(),"repos",/^[\w-]+$/.test(e)?e:Nx("sha1").update(e).digest("hex")),Um=/^[a-z0-9._-]+-[0-9a-f]{12}\.git$/,Ot=(e,t)=>$m.join(ic(e),`${t}.git`),dr=e=>`${e}.json`,Ds=/^(?!-)[A-Za-z0-9._/-]{1,100}$/,jm=e=>{try{let t=JSON.parse(Ix.readFileSync(dr(e),"utf8"));return typeof t.stateBranch=="string"&&Ds.test(t.stateBranch)?t.stateBranch:null}catch{return null}},an=(e,t)=>e==="all"?null:e==="board"?t.slice(0,10):e,zt=e=>{let t=je(e);return c(t)?a(t.message):d("Read project",{projectId:t.value.projectId,createdAt:t.value.createdAt})};var Hm=(e,t)=>{let n=(e.trim().split(/\s+/)[0]??"").toUpperCase();return n&&t.has(n)?n:null};import{randomUUID as So}from"node:crypto";import D from"node:fs";import X from"node:path";import{execFileSync as Mx}from"node:child_process";import{randomUUID as zm}from"node:crypto";import Ke from"node:fs";import ho from"node:os";import Vm from"node:path";var $s="epiq-sync.lock",kx=600*1e3,qm=Date.now()-process.uptime()*1e3,Km=()=>Math.round(qm),Ym=5e3,Lx=5e3,Xm=e=>{try{if(process.platform==="linux"){let s=Ke.readFileSync(`/proc/${e}/stat`,"utf8"),i=s.slice(s.lastIndexOf(")")+2).split(" "),l=Number(i[19]),u=/^btime (\d+)$/m.exec(Ke.readFileSync("/proc/stat","utf8"))?.[1];return u&&Number.isFinite(l)?Number(u)*1e3+l*10:null}if(process.platform==="win32")return null;let t=Wm.get(e);if(t&&Date.now()-t.at<Px)return t.value;let n=Mx("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"],env:{...process.env,LC_ALL:"C"}}).trim(),r=Date.parse(n),o=Number.isNaN(r)?null:r;return Wm.set(e,{at:Date.now(),value:o}),o}catch{return null}},Jm=(e,t)=>{let n=Xm(e);return n!==null&&n>t+Ym},Px=5e3,Wm=new Map,Ox=e=>{let t=Date.now()-ho.uptime()*1e3;if(e.startedAt<t)return!1;if(Date.now()-e.startedAt<Lx||e.processStartedAt===void 0)return!0;let n=Xm(e.pid);return n===null||Math.abs(n-e.processStartedAt)<=Ym},Fs=new Map,Dx=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},Fx=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Zm=(e,t=kx,n=!1)=>e?e.hostname!==ho.hostname()?Date.now()-e.startedAt>t?"stale":null:!Fx(e.pid)||n&&!Ox(e)?"dead":Date.now()-e.startedAt>t?"stale":null:"stale",_x=e=>{let t=Vm.join(e,$s);return Ke.existsSync(t)?Zm(ur(t))===null:!1},_s=new Map,$x=e=>{let t=_s.get(e);if(t)return t;let n=$r(e).then(r=>c(r)?null:r.value,()=>null);return _s.set(e,n),n.then(r=>{r===null&&_s.get(e)===n&&_s.delete(e)}),n},oP=async e=>{let t=await $x(e);return t!==null&&_x(t)},Qm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,ur=e=>{try{return Dx(Ke.readFileSync(e,"utf8"))}catch{return null}},Bx=(e,t)=>{let n={pid:process.pid,hostname:ho.hostname(),startedAt:Date.now(),operation:t,token:zm(),processStartedAt:qm},r=`${e}.${process.pid}.pending.lock`;try{return Ke.writeFileSync(r,JSON.stringify(n)),Ke.linkSync(r,e),n}catch{return null}finally{try{Ke.rmSync(r,{force:!0})}catch{}}},Ux=async({worktreeRoot:e,operation:t})=>{let n=await $r(e);return c(n)?a(n.message):d("Tried the sync lock",yo({lockPath:Vm.join(n.value,$s),operation:t}))},yo=({lockPath:e,operation:t,staleAfterMs:n,checkProcess:r=!1})=>{let o=null,s=()=>{try{let u=ur(e);u&&Gm(u,o)&&Ke.rmSync(e)}catch{}finally{Fs.get(e)===o?.token&&Fs.delete(e)}},i=u=>(o=Bx(e,t),o?(Fs.set(e,o.token),{acquired:!0,claim:u,release:s}):null);for(let u=0;u<5;u++){let p=i("clean");if(p)return p;let m=ur(e);if(m===null&&(!Ke.existsSync(e)||(m=ur(e),m!==null)||!Ke.existsSync(e)))continue;let g=m!==null&&m.pid===process.pid&&m.hostname===ho.hostname()&&Fs.get(e)!==m.token?"dead":Zm(m,n,r);if(g===null)return{acquired:!1,heldBy:m};j.info(`Breaking an abandoned sync lock: ${m?Qm(m):"unreadable lock file"}`);let x=`${e}.${process.pid}.${zm()}.broken.lock`;try{Ke.renameSync(e,x)}catch{continue}if(!Gm(ur(x),m)){try{Ke.linkSync(x,e)}catch{}Ke.rmSync(x,{force:!0});continue}Ke.rmSync(x,{force:!0});let N=i(g);if(N)return N}return{acquired:!1,heldBy:ur(e)??{pid:-1,hostname:ho.hostname(),startedAt:Date.now(),operation:"unknown"}}},Gm=(e,t)=>e===null||t===null?e===t:e.pid===t.pid&&e.hostname===t.hostname&&e.startedAt===t.startedAt&&e.token===t.token,bo=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await Ux({worktreeRoot:e,operation:t});if(c(r))return a(r.message);if(!r.value.acquired)return j.info(`Skipping ${t}: the state worktree is held by ${Qm(r.value.heldBy)}`),d("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return d("Ran under the sync lock",await n(o))}finally{s()}};import{randomBytes as zx}from"node:crypto";import Vx from"node:fs";var jx="EPIQ_CACHE_MS",Bs=e=>{let t=process.env[jx];if(t===void 0||t.trim()==="")return e;let n=Number(t);return Number.isFinite(n)&&n>=0?n:e};import ep from"node:fs";import Hx from"node:path";var tp=new Set,ac=new Map,cc=(e,t)=>{t?ac.set(e,t):ac.delete(e)},np=e=>ac.get(e)??null,Wx=e=>{try{return new Set(ep.readFileSync(Hx.join(e,"shallow"),"utf8").split(`
|
|
37
|
-
`).map(t=>t.trim()).filter(Boolean))}catch{return tp}},mr=async e=>{let t=St(e);if(c(t))return a(t.message);let n=t.value,r=je(n);if(c(r))return a(r.message);let o={cwd:n,revisions:["--branches","--not",r.value.stateBranch],exclude:tp},s=Ps(n);if(c(s))return d("Listed sources",[o]);let i=s.value.flatMap(l=>{let u=Ot(r.value.projectId,l.id);if(!ep.existsSync(u))return[];let p=an(l.since,r.value.createdAt),m=new Set([r.value.stateBranch,ya,jm(u)].filter(f=>f!==null));return[{repo:l.id,cwd:u,revisions:[...[...m].map(f=>`--exclude=${f}`),"--branches"],exclude:Wx(u),...p?{notBefore:Date.parse(`${p}T00:00:00Z`)}:{}}]});return d("Listed sources",[o,...i])},lc=e=>t=>e.find(n=>(n.repo??"")===(t??""))?.cwd,Gx=async(e,t)=>!c(await _({cwd:e,args:["cat-file","-e",`${t}^{commit}`]})),vo=async e=>{let t=await mr(e.repoRoot);if(c(t))return a(t.message);let n=t.value;if(e.repo){let r=n.find(o=>o.repo===e.repo);return r?d("Resolved repo",r.cwd):a(`No clone of repo "${e.repo}" here yet \u2014 sync to fetch it`)}if(n.length===1)return d("Resolved repo",n[0].cwd);for(let r of n)if(await Gx(r.cwd,e.sha))return d("Resolved repo",r.cwd);return d("Resolved repo",n[0].cwd)};var qx="",Kx="",rp=5e3,Yx=12e4,Xx=32*1024*1024,Us=new Map,Jx=e=>{try{return Vx.statSync(`${e}.json`).mtimeMs}catch{return null}},Zx=e=>{let t=e.repo?zx(8).toString("hex"):"";return{field:`${qx}${t}`,record:`${Kx}${t}`}},Qx=/^[0-9a-f]{40}([0-9a-f]{24})?$/;var cn=()=>{Us.clear()},eE=(e,t,n)=>(t===void 0||e>=Math.floor(t/1e3)*1e3)&&(n===void 0||e<=n),dc=e=>Ut(e).replace(/[\u0080-\u009f\u202a-\u202e\u2066-\u2069]/g,""),tE=async(e,t)=>{let n=t.start===void 0&&t.end===void 0,r=[e.cwd,e.revisions.join(" "),e.notBefore??"",e.exclude.size].join("\0"),o=n?Us.get(r):void 0,s=e.repo?Jx(e.cwd):null;if(o&&(e.repo?o.version===s:Date.now()-o.fetchedAt<Bs(rp)))return o.result;let i=Zx(e),l=await _({cwd:e.cwd,...e.repo?{timeoutMs:Yx,maxOutput:Xx}:{},args:["log",...e.revisions,...t.start!==void 0?[`--since=@${Math.floor(t.start/1e3)}`]:[],...t.end!==void 0?[`--until=@${Math.floor(t.end/1e3)}`]:[],"--shortstat",`--format=${i.record}%H${i.field}%at${e.notBefore?`${i.field}%ct`:""}${i.field}%an${i.field}%ae${i.field}%s`]});if(c(l))return e.repo&&n&&!kd(l.message)&&Us.set(r,{fetchedAt:Date.now(),version:s,result:a(l.message)}),a(l.message);let u=l.value.stdout.split(i.record).filter(p=>p.trim().length>0).map(p=>{let[m,...f]=p.split(`
|
|
38
|
-
`),g=(m??"").split(i.field),[x,N]=g;if(e.repo&&!Qx.test(x??""))return null;let E=e.notBefore?g[2]:void 0,[R,v,...I]=g.slice(e.notBefore?3:2);if(!x||!N||e.exclude.has(x)||e.notBefore&&Number(E)*1e3<e.notBefore)return null;let k=f.join(" "),M=Number(/(\d+) insertion/.exec(k)?.[1]??0),L=Number(/(\d+) deletion/.exec(k)?.[1]??0);return{sha:x,...e.repo?{repo:e.repo}:{},time:Number(N)*1e3,author:dc(R)||"unknown",authorEmail:dc(v),subject:dc(I.join(i.field)),linesChanged:M+L,insertions:M,deletions:L}}).filter(p=>p!==null).filter(p=>eE(p.time,t.start,t.end));return n&&Us.set(r,{fetchedAt:Date.now(),version:s,result:d("Computed commit timeline",u)}),d("Computed commit timeline",u)},op=async(e,t)=>{let n=await mr(e);if(c(n))return a(n.message);let r=n.value,o=[];for(let i of r)o.push(await tE(i,t));let s=[];for(let[i,l]of o.entries()){let u=r[i].repo;if(c(l)){if(!u)return a(l.message);j.info(`[repos] could not read a clone: ${l.message}`),cc(u,is(l.message)?"its history is too long to read; narrow its window":"its history could not be read");continue}u&&cc(u,null),s.push(l.value)}return d("Read every source",s)},js=e=>{if(e.length<=1)return e;let t=new Set;return e.map(n=>{let r=n.filter(o=>!t.has(o.sha));for(let o of r)t.add(o.sha);return r})},sp=e=>{let t=e.filter(n=>n.length>0);return t.length<=1?t[0]??[]:t.flat().sort((n,r)=>r.time-n.time)},nE=async(e={})=>{let t=await op(e.repoRoot,{start:e.start,end:e.end});return c(t)?a(t.message):d("Computed commit timeline",sp(js(t.value)))},uc=async e=>{let t=e.ref.trim();if(!t)return a("ref must not be empty");if(t.length!==7)return a(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await op(e.repoRoot,{});if(c(n))return a(n.message);let r=`${t.toUpperCase()} `,o=s=>s.subject.toUpperCase().startsWith(r);return d("Matched commits by ref",n.value.map(s=>{let i=[];for(let[l,u]of s.entries()){if(!o(u))continue;let p=s[l+1];i.push({...u,precedingSha:p&&o(p)?p.sha:null})}return i}))},mc=async e=>{let t=await uc(e);return c(t)?a(t.message):d("Matched commits by ref",sp(js(t.value)))};var Hs=1800*1e3,Ft=e=>`${e}.removed`,ip=e=>{try{D.writeFileSync(Ft(e),"",{flag:"wx"})}catch(t){if(t.code!=="EEXIST")throw t;if(Ws(Ft(e)))throw new Error("The removal mark is a link, which epiq will not use")}},hc=()=>`${process.pid}-${Km()}`,gc=e=>{try{let t=JSON.parse(D.readFileSync(dr(e),"utf8"));return{fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:null,attemptedAt:typeof t.attemptedAt=="number"?t.attemptedAt:null,error:typeof t.error=="string"?t.error:null,branches:t.branches==="all"||t.branches==="default"?t.branches:null,since:typeof t.since=="string"?t.since:null,restartedAt:typeof t.restartedAt=="number"?t.restartedAt:null,restartTriedAt:typeof t.restartTriedAt=="number"?t.restartTriedAt:null,restarts:typeof t.restarts=="number"&&t.restarts>=0?t.restarts:0,bytes:typeof t.bytes=="number"&&t.bytes>=0?t.bytes:null,stateBranch:typeof t.stateBranch=="string"&&Ds.test(t.stateBranch)?t.stateBranch:null}}catch{return null}},pp=(e,t)=>{try{let n=`${dr(e)}.${hc()}.${So()}.tmp`;D.writeFileSync(n,JSON.stringify(t)+`
|
|
39
|
-
`,{flag:"wx"}),D.renameSync(n,dr(e))}catch(n){j.info(`[repos] could not record fetch status: ${String(n)}`)}},yc=e=>{let t=zt(e);if(c(t))return a(t.message);let n=rt(e);if(c(n))return a(n.message);let r=(o,s)=>{let i=Ot(t.value.projectId,o.id),l=gc(i),u=D.existsSync(i);return{...o,cloned:u,overLimit:s,bytes:u?l?.bytes??null:null,fetchedAt:l?.fetchedAt??null,error:l?.error??np(o.id)}};return d("Listed repos",[...n.value.live.map(o=>r(o,!1)),...n.value.overLimit.map(o=>r(o,!0))])},Ie=e=>_({...e,forClone:!0}),rE=(e,t)=>Ie({cwd:e,args:t,timeoutMs:Hs}),oE=1e3,Ro=async(e,t,n,{undo:r}={})=>{let o=ir(),s=o*1024*1024,i=new AbortController,l=setInterval(()=>{nn(n)>s&&i.abort(ro(o))},oE),u;try{u=await Ie({cwd:e,args:t,timeoutMs:Hs,abort:i.signal})}finally{clearInterval(l)}return i.signal.aborted||!c(u)&&nn(n)>s?(gp(n),r&&(aE(n,r),Cp(n)),a(ro(o))):u},xo=e=>{try{return D.readFileSync(e)}catch{return null}},bc=e=>{try{return D.readdirSync(e)}catch{return[]}},sE=e=>{let t=new Map,n=r=>{let o=X.join(e,r);for(let s of D.readdirSync(o,{withFileTypes:!0})){let i=X.join(r,s.name);s.isDirectory()?n(i):t.set(i,D.readFileSync(X.join(e,i)))}};return D.existsSync(X.join(e,"refs"))&&n("refs"),{refs:t,packedRefs:xo(X.join(e,"packed-refs")),head:xo(X.join(e,"HEAD")),config:xo(X.join(e,"config")),shallow:xo(X.join(e,"shallow")),packs:new Set(bc(X.join(e,"objects","pack")))}},fp="epiq-restore-",ap=(e,t,n)=>{let r=X.join(e,`${fp}${So()}.tmp`);D.writeFileSync(r,n,{flag:"wx"}),D.mkdirSync(X.dirname(X.join(e,t)),{recursive:!0}),D.renameSync(r,X.join(e,t))},iE=e=>{let t=[],n=r=>{for(let o of D.readdirSync(X.join(e,r),{withFileTypes:!0})){let s=X.join(r,o.name);o.isDirectory()?n(s):t.push(s)}};return D.existsSync(X.join(e,"refs"))&&n("refs"),t},aE=(e,t)=>{for(let[r,o]of t.refs)ap(e,r,o);for(let r of iE(e))t.refs.has(r)||D.rmSync(X.join(e,r),{force:!0});for(let[r,o]of[["packed-refs",t.packedRefs],["HEAD",t.head],["config",t.config],["shallow",t.shallow]])o?ap(e,r,o):D.rmSync(X.join(e,r),{force:!0});let n=X.join(e,"objects","pack");for(let r of bc(n))t.packs.has(r)||D.rmSync(X.join(n,r));Dn.delete(e)},gp=e=>{let t=X.join(e,"objects");for(let[n,r]of[[X.join(t,"pack"),"tmp_"],[X.join(t,"pack"),".tmp-"],[t,"incoming-"],[e,fp]])try{for(let o of D.readdirSync(n))o.startsWith(r)&&D.rmSync(X.join(n,o),{recursive:!0,force:!0})}catch{}},cE=/could not read from remote repository|the remote end hung up unexpectedly|early EOF|fetch-pack: invalid index-pack output/i,hp=e=>{let t=e.split(`
|
|
40
|
-
`).map(s=>s.replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g,"").trim()).filter(s=>s&&!s.startsWith("git ")),n=t.filter(s=>/^(fatal|error):/i.test(s));return(n.filter(s=>!cE.test(s))[0]??n[n.length-1]??t[t.length-1]??e).replace(/^(fatal|error):\s*/i,"").slice(0,300)},lE=64*1024,yp=async e=>{let t="HEAD:.epiq/project.json",n=await Ie({cwd:e,args:["cat-file","-s",t]});if(c(n)||!(Number(n.value.stdout.trim())<=lE))return null;let r=await Ie({cwd:e,args:["cat-file","blob",t]});if(c(r))return null;try{let{stateBranch:o}=JSON.parse(r.value.stdout);return typeof o=="string"&&Ds.test(o)?o:null}catch{return null}},vc=async e=>{let t=await Ie({cwd:e,args:["symbolic-ref","--short","HEAD"]});return c(t)?null:t.value.stdout.trim()||null},dE=async(e,t)=>{if(t==="all")return d("All branches","+refs/heads/*:refs/heads/*");let n=await vc(e);return n?d("Default branch",`+refs/heads/${n}:refs/heads/${n}`):a("Could not tell which branch is the default")},uE=async e=>{let t=await vc(e);if(!t)return;let n=await Ie({cwd:e,args:["for-each-ref","--format=%(refname)","refs/heads/"]});if(!c(n))for(let r of n.value.stdout.split(`
|
|
41
|
-
`).filter(Boolean))r!==`refs/heads/${t}`&&await Ie({cwd:e,args:["update-ref","-d",r]})},bp=async e=>{let t=await Ie({cwd:e,args:["for-each-ref","--count=1","--format=x","refs/heads/"]});return!c(t)&&t.value.stdout.trim()!==""},vp=e=>`--shallow-since=@${Math.floor(Date.parse(`${e}T00:00:00Z`)/1e3)}`,xp=async(e,t)=>{if(!await bp(e))return d("Empty",null);let n=await Ro(e,["fetch","--no-tags","--deepen=1","origin"],e,{undo:t});return c(n)?a(n.message):d("Deepened",null)},mE=/no commits selected for shallow requests|error processing shallow info/i,Ep=async(e,t,n)=>{let r=X.dirname(e);D.mkdirSync(r,{recursive:!0}),D.rmSync(e,{recursive:!0,force:!0});let o=u=>["clone","--bare","--no-tags",t.branches==="default"?"--single-branch":"--no-single-branch",...u,"--",t.url,e],s=await Ro(r,o(n?[vp(n)]:[]),e),i=n!==null;if(c(s)&&n&&mE.test(s.message)&&(D.rmSync(e,{recursive:!0,force:!0}),s=await Ro(r,o(["--depth=1"]),e),i=!1),c(s))return D.rmSync(e,{recursive:!0,force:!0}),a(s.message);let l=await dE(e,t.branches);if(c(l))return D.rmSync(e,{recursive:!0,force:!0}),a(l.message);if(await Ie({cwd:e,args:["config","remote.origin.fetch",l.value]}),i){let u=await xp(e);if(c(u))return D.rmSync(e,{recursive:!0,force:!0}),a(u.message)}return d("Built clone",null)},cp=async(e,t,n,{replace:r=!1}={})=>{let o=`${e}.${hc()}.pending`,s=await Ep(o,t,n);if(c(s))return s;if(r&&D.existsSync(e)){let i=`${e}.${So()}.deleting`;D.renameSync(e,i),D.renameSync(o,e);try{D.rmSync(i,{recursive:!0,force:!0})}catch(l){j.info(`[repos] could not clear an old clone: ${ot(l)}`)}return d("Cloned anew",null)}return D.existsSync(e)?(D.rmSync(o,{recursive:!0,force:!0}),d("Cloned elsewhere",null)):Ws(e)?(D.rmSync(o,{recursive:!0,force:!0}),a("The clone path is a link, which epiq will not use")):(D.renameSync(o,e),d("Cloned",null))},pE=async(e,t)=>!/[*:]/.test(t)&&!c(await Ie({cwd:e,args:["check-ref-format",`refs/heads/${t}`]})),Rp=async e=>{let t=await rE(e,["ls-remote","--symref","origin","HEAD"]);if(c(t))return null;let n=/^ref: refs\/heads\/(\S+)\tHEAD$/m.exec(t.value.stdout)?.[1],r=/^[0-9a-f]{40,64}\tHEAD$/m.test(t.value.stdout);return n&&r&&await pE(e,n)?n:null},Sp=async(e,t)=>{let n=t??await Rp(e);if(!n)return a("Could not tell which branch the remote now defaults to");let r=await Ie({cwd:e,args:["symbolic-ref","HEAD",`refs/heads/${n}`]});if(c(r))return a(r.message);let o=await Ie({cwd:e,args:["config","remote.origin.fetch",`+refs/heads/${n}:refs/heads/${n}`]});return c(o)?a(o.message):d("Followed",null)},Cp=e=>{let t=(n,r)=>{for(let o of D.readdirSync(n,{withFileTypes:!0})){let s=X.join(n,o.name);o.isFile()&&o.name.endsWith(".lock")?D.rmSync(s,{force:!0}):o.isDirectory()&&r>0&&t(s,r-1)}};try{for(let r of D.readdirSync(e))r.endsWith(".lock")&&D.rmSync(X.join(e,r),{force:!0});let n=X.join(e,"refs");D.existsSync(n)&&t(n,16)}catch(n){j.info(`[repos] could not clear stale locks: ${String(n)}`)}},Np=e=>D.existsSync(X.join(e,"shallow")),fE=20,gE=async e=>{if(bc(X.join(e,"objects","pack")).filter(r=>r.endsWith(".pack")).length<=fE)return;let n=await Ie({cwd:e,args:["repack","--geometric=2","-d","-q"],timeoutMs:Hs});c(n)&&j.info(`[repos] repack: ${n.message}`)},hE=async e=>{let t=await Ie({cwd:e,args:["config","--get","remote.origin.fetch"]});return c(t)?null:t.value.stdout.trim()||null},yE=e=>`+refs/heads/${e}:refs/heads/${e}`,bE=async(e,t)=>{let n=await hE(e);if(t==="all"){let s="+refs/heads/*:refs/heads/*";if(n===s)return d("Tracking",null);let i=await Ie({cwd:e,args:["config","remote.origin.fetch",s]});return c(i)?a(i.message):d("Tracking",null)}let r=await vc(e),o=await Rp(e)??r;return o?r===o&&n===yE(o)?d("Tracking",null):Sp(e,o):a("Could not tell which branch is the default")},lp=async(e,t,n,r)=>{let o=ir();if(nn(e)>o*1024*1024)return a(ro(o));let s=sE(e),i=await bE(e,t.branches);if(c(i))return a(i.message);let l=n===null?Np(e)?["--unshallow"]:[]:r?.since&&n<r.since?[vp(n)]:[],u=["fetch","--prune","--no-tags",...l,"origin"],p=await Ro(e,u,e,{undo:s});if(c(p)&&t.branches==="default"&&/couldn't find remote ref/i.test(p.message)){let m=await Sp(e);if(c(m))return a(m.message);p=await Ro(e,u,e,{undo:s})}if(c(p))return a(p.message);if(l[0]?.startsWith("--shallow-since")){let m=await xp(e,s);if(c(m))return a(m.message)}return t.branches==="default"&&await uE(e),await gE(e),d("Fetched",null)},pc=async e=>{if(!D.existsSync(e))return"";let t=await Ie({cwd:e,args:["for-each-ref","--format=%(objectname) %(refname)"]}),n=Np(e)?D.readFileSync(X.join(e,"shallow"),"utf8"):"";return`${c(t)?"":t.value.stdout}
|
|
42
|
-
${n}`},Dn=new Map,dp=(e,t)=>{let n=Dn.get(e);return Dn.set(e,t),n!==void 0&&n!==t},vE=async(e,t)=>{let n=await Ie({cwd:e,args:["config","--get","remote.origin.url"]});return c(n)?"unknown":Zt(n.value.stdout.trim())===t.id?"this":"other"},Ip=e=>{let t=X.join(e,".gitignore");try{if(D.lstatSync(t,{throwIfNoEntry:!1}))return;D.writeFileSync(t,`*
|
|
43
|
-
`,{flag:"wx"})}catch(n){j.info(`[repos] could not write ${t}: ${ot(n)}`)}},Ws=e=>{try{return D.lstatSync(e).isSymbolicLink()}catch{return!1}},ot=e=>e instanceof Error?e.message:String(e),xc=".lock",Ec=Hs*4,wp=async(e,t,n)=>{let r=Date.now()+n;for(;;){let o=yo({lockPath:`${e}${xc}`,operation:t,staleAfterMs:Ec,checkProcess:!0});if(o.acquired||Date.now()>=r)return o;await new Promise(s=>setTimeout(s,250))}},Eo=e=>{let t=`${e}.${So()}.deleting`;try{D.renameSync(e,t)}catch(n){if(n.code!=="ENOENT")throw n}D.rmSync(t,{recursive:!0,force:!0}),D.rmSync(dr(e),{force:!0}),D.rmSync(Ft(e),{force:!0}),Dn.delete(e)},Ap=5e3,xE=async e=>{let t=await Ie({cwd:e,args:["config","--get","remote.origin.url"]});if(c(t)||!t.value.stdout.trim())return!1;let n=xo(X.join(e,"shallow"));return n&&!/^(?:[0-9a-f]{40}(?:[0-9a-f]{24})?\n)*$/.test(n.toString("utf8"))?!1:await bp(e)?!c(await Ie({cwd:e,args:["rev-list","--max-count=1","--branches"]})):!0},up=[0,6e4,10*6e4,60*6e4],Tp=e=>{if(!e?.restartTriedAt||Date.now()<e.restartTriedAt)return!0;let t=up[Math.min(e.restarts,up.length-1)];return Date.now()-e.restartTriedAt>=t},EE=360*60*1e3,RE=e=>{let t=e?.restartTriedAt??e?.restartedAt;return Tp(e)&&(!t||Date.now()<t||Date.now()-t>=EE)},SE=6e4,CE=async(e,t,n)=>{let r=ir();return nn(e)>r*1024*1024?"past the cap":n.endsWith(ro(r))?null:await Mp(e,t)?"remote answers":null},Mp=async(e,t)=>!c(await Ie({cwd:X.dirname(e),args:["ls-remote","--",t.url,"HEAD"],timeoutMs:SE})),NE=async(e,t,n,r,o)=>{let s=(m,f,g=!1)=>({id:r.id,label:r.label,ok:m,changed:g,message:f}),i=Ot(t,r.id),l=an(r.since,n);try{D.mkdirSync(X.dirname(i),{recursive:!0}),Ip(X.dirname(i))}catch(m){return s(!1,ot(m))}let u=gc(i);if(u?.attemptedAt&&(u.error!==null||u.branches===r.branches&&u.since===l)&&Date.now()>=u.attemptedAt&&Date.now()-u.attemptedAt<o&&!D.existsSync(Ft(i))){let m=D.existsSync(i)&&dp(i,await pc(i));return u.error?s(!1,u.error,m):s(!0,"Fetched recently",m)}if(Ws(i))return s(!1,"The clone path is a link, which epiq will not use");let p=await wp(i,`fetch ${r.label}`,o===0?Ap:0);if(!p.acquired)return{...s(!0,"Being fetched by another process"),skipped:!0};try{let m=D.existsSync(Ft(i));m&&Eo(i);let f=D.existsSync(i);f&&await vE(i,r)==="other"&&(Eo(i),f=!1);let g=f?gc(i):null;if(f&&!Dn.has(i)&&Dn.set(i,await pc(i)),f&&(Cp(i),gp(i)),!f&&m&&!Bm(e,r.id))return s(!0,"Removed before it was cloned");let N=f&&!await xE(i)&&Tp(g),E=N&&await Mp(i,r),R=f?N?a(E?"Its clone will not open":"Its clone will not open, and its remote does not answer"):await lp(i,r,l,g):await cp(i,r,l);if(f&&!E&&c(R)&&RE(g)){let M=await CE(i,r,R.message);M==="remote answers"&&(R=await lp(i,r,l,g)),E=M!==null&&c(R)}E&&(j.info(`[repos] ${r.label}: starting its clone over`),R=await cp(i,r,l,{replace:!0}),Dn.delete(i));let v=E&&!(c(R)&&Ud()),I=c(R)?hp(R.message):"Fetched",k=c(R)?g?.stateBranch??null:await yp(i);return pp(i,{fetchedAt:c(R)?g?.fetchedAt??null:Date.now(),attemptedAt:Date.now(),error:c(R)?I:null,branches:c(R)?g?.branches??r.branches:r.branches,since:c(R)?g?.since??l:l,stateBranch:k,restartedAt:E&&!c(R)?Date.now():g?.restartedAt??null,restartTriedAt:v?Date.now():g?.restartTriedAt??null,restarts:v?(g?.restarts??0)+1:c(R)?g?.restarts??0:0,bytes:c(R)?g?.bytes??null:nn(i)}),c(R)?(j.info(`[repos] ${r.label}: ${R.message}`),s(!1,I)):s(!0,I,dp(i,await pc(i))||!f||E)}catch(m){return j.info(`[repos] ${r.label}: ${ot(m)}`),s(!1,ot(m))}finally{try{D.existsSync(Ft(i))&&Eo(i)}catch(m){j.info(`[repos] ${r.label}: could not delete the clone: ${ot(m)}`)}p.release(),kp(i)}},kp=e=>{if(!D.existsSync(Ft(e)))return;let t=yo({lockPath:`${e}${xc}`,operation:"remove",staleAfterMs:Ec,checkProcess:!0});if(t.acquired)try{D.existsSync(Ft(e))&&Eo(e)}catch(n){j.info(`[repos] could not delete a clone: ${ot(n)}`)}finally{t.release()}},IE=e=>{let t=ic(e);if(D.existsSync(t))for(let n of D.readdirSync(t)){let r=/^.+\.git(?:\.json)?\.(\d+)(?:-(\d+))?(?:\.[0-9a-f-]{36})?\.(?:pending|tmp)$/.exec(n);if(r&&!AE(Number(r[1]),r[2]===void 0?null:Number(r[2]))||/\.git\.[0-9a-f-]{36}\.deleting$/.test(n))try{D.rmSync(X.join(t,n),{recursive:!0,force:!0})}catch(o){j.info(`[repos] could not sweep ${n}: ${ot(o)}`)}}},Lp=async(e,t)=>{let n=zt(e);if(c(n))return a(n.message);let r=Ot(n.value.projectId,t.id),o=`${r}.${hc()}.${So()}.pending`;try{D.mkdirSync(X.dirname(r),{recursive:!0}),Ip(X.dirname(r));let s=await Ep(o,t,an(t.since,n.value.createdAt));return c(s)?a(hp(s.message)):d("Staged",{stagePath:o,bytes:nn(o)})}catch(s){return Dt(o),a(ot(s))}},Dt=e=>{try{D.rmSync(e,{recursive:!0,force:!0})}catch(t){j.info(`[repos] could not clear a stage: ${ot(t)}`)}},Pp=async(e,t,n)=>{let r=zt(e);if(c(r))return Dt(n);let{projectId:o,createdAt:s}=r.value,i=Ot(o,t.id),l=await wp(i,`connect ${t.label}`,Ap);if(!l.acquired)return Dt(n);try{if(D.rmSync(Ft(i),{force:!0}),D.existsSync(i)||Ws(i))return Dt(n);D.renameSync(n,i),pp(i,{fetchedAt:Date.now(),attemptedAt:Date.now(),error:null,branches:t.branches,since:an(t.since,s),stateBranch:await yp(i),restartedAt:null,restartTriedAt:null,restarts:0,bytes:nn(i)}),cn()}catch(u){j.info(`[repos] could not place ${t.label}: ${ot(u)}`),Dt(n)}finally{l.release()}},Rc=e=>{let t=sc(e.repoRoot,e.repo);if(c(t))return t;let n=fo({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"disconnect.repo",payload:{repo:t.value.id}}});if(c(n))return a(n.message);let r=Sc({repoRoot:e.repoRoot,repoId:t.value.id});cn();let o=zt(e.repoRoot);!c(r)&&!c(o)&&Op(o.value.projectId,t.value.id);let s=`Disconnected ${t.value.label}`;return c(r)?d(`${s}, but its clone stays: ${r.message}`,t.value):d(s,t.value)},Sc=e=>{let t=zt(e.repoRoot);if(c(t))return a(t.message);if(!Um.test(`${e.repoId}.git`))return a("Not a clone epiq made");let n=Ot(t.value.projectId,e.repoId);try{D.mkdirSync(X.dirname(n),{recursive:!0})}catch(o){return a(`Could not remove the clone: ${ot(o)}`)}let r=yo({lockPath:`${n}${xc}`,operation:"remove",staleAfterMs:Ec,checkProcess:!0});try{return r.acquired?(Eo(n),ip(n),d("Removed clone",null)):(ip(n),kp(n),d("Removed once its fetch ends",null))}catch(o){return a(`Could not remove the clone: ${String(o)}`)}finally{r.acquired&&r.release()}},Op=(e,t)=>{let n=Ot(e,t);D.existsSync(n)||D.rmSync(Ft(n),{force:!0})},wE=(e,t,n)=>{for(let r of n){if(!D.existsSync(Ot(t,r)))continue;let o=Sc({repoRoot:e,repoId:r});if(c(o)){j.info(`[repos] could not clear ${r}: ${o.message}`);continue}cn(),Op(t,r)}},AE=(e,t)=>TE(e)&&(t===null||!Jm(e,t)),TE=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},mp=4,Gs=e=>{let t=e.minIntervalMs??0,n=fc.get(e.repoRoot);if(n)return n.minIntervalMs<=t?n.result:n.result.then(()=>Gs(e));let r=ME(e.repoRoot,t).catch(o=>a(ot(o))).finally(()=>{fc.delete(e.repoRoot)});return fc.set(e.repoRoot,{result:r,minIntervalMs:t}),r},fc=new Map,ME=async(e,t)=>{let n=zt(e);if(c(n))return a(n.message);let r=rt(e);if(c(r))return a(r.message);let{projectId:o,createdAt:s}=n.value,i=r.value.live;try{IE(o)}catch(u){j.info(`[repos] sweep failed: ${String(u)}`)}if(wE(e,o,r.value.disconnected),i.length===0)return d("No other repos",[]);let l=[];for(let u=0;u<i.length;u+=mp)l.push(...await Promise.all(i.slice(u,u+mp).map(p=>NE(e,o,s,p,t))));return l.some(u=>u.changed)&&cn(),d("Fetched other repos",l)},Cc=e=>{let t=e.filter(o=>!o.ok),n=e.filter(o=>o.skipped),r=[t.length>0&&`could not fetch ${t.map(o=>`${o.label} (${o.message.slice(0,80)})`).join(", ")}`,n.length>0&&`another process is fetching ${n.map(o=>o.label).join(", ")}`].filter(Boolean);return r.length>0?r.join("; "):null};var Ic=900*1e3,pr=new Map,Dp=0,wc=new Map,Fp=e=>{let t=(wc.get(e)??0)+1;return wc.set(e,t),t},kE=(e,t)=>JSON.stringify([e,t.id,t.branches,t.since]),Ac=e=>{let t=pr.get(e);t&&(clearTimeout(t.timer),pr.delete(e),Dt(t.stagePath))},LE=e=>{Fp(e),Ac(e)},_p=e=>{if(e.startsWith("file:"))return"this machine";let t=/^[^@/]+@([^:/]+):/.exec(e);if(t?.[1])return t[1];try{return new URL(e).host||e}catch{return e}},Nc=async(e,t)=>{let n=await _({cwd:e,args:t,forClone:!0,keepPartial:!0});return c(n)?null:n.value.stdout},PE=async(e,t,n)=>{let r=(await Nc(e,["symbolic-ref","--short","HEAD"]))?.trim().replace(/^refs\/heads\//,""),o=await Nc(e,["log","-1","--format=%s%x00%an%x00%cI","HEAD"]),[s,i,l]=(o??"").trim().split("\0"),p=(await Nc(e,["log","--branches","--max-count=100000",...t?[`--since=@${Math.floor(Date.parse(`${t}T00:00:00Z`)/1e3)}`]:[],"--format=%s"])??"").split(`
|
|
44
|
-
`).filter(Boolean);return{defaultBranch:r||null,latest:s!==void 0&&s!==""&&i&&l?{subject:s,author:i,date:l}:null,commits:p.length,ticketCommits:p.filter(m=>Hm(m,n)).length}},OE=()=>{if(!dt())return{knownRefs:new Set,contributors:0};let e=h();return{knownRefs:new Set(Object.values(e.nodes).filter(t=>H(t)).map(t=>nt(t.id))),contributors:Object.values(e.contributors).filter(t=>!t.tombstoned).length}},$p=e=>{let t=yc(e);return c(t)?0:t.value.reduce((n,r)=>n+(r.bytes??0),0)},Tc=async e=>{let t=nc(e);if(c(t))return a(t.message);let n=t.value;if(n.kind!=="connect"&&e.mode==="preview")return a(`${n.repo.label} is already connected`);if(n.kind==="unchanged")return d(tc,{kind:"unchanged",repo:n.repo});if(n.kind==="edit"){let E=fo({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"edit.repo",payload:n.event}});return c(E)?a(E.message):(n.message.startsWith(Ls)||cn(),d(n.message,{kind:"updated",repo:n.repo}))}let r=kE(e.repoRoot,n.repo),o=pr.get(n.repo.id);if(e.mode==="confirm"&&o?.key!==r)return a("Nothing is staged for this connect here, or it was staged with other options: preview it again");if(e.mode==="confirm"&&o){clearTimeout(o.timer),pr.delete(n.repo.id);let E=fo({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"connect.repo",payload:n.event}});if(c(E))return Dt(o.stagePath),a(E.message);await Pp(e.repoRoot,n.repo,o.stagePath);let R=rt(e.repoRoot),v=!c(R)&&R.value.overLimit.some(I=>I.id===n.repo.id);return d(v?`Connected ${n.repo.label}, but the board already reads ${vn} repos: it is not fetched until one ahead of it is disconnected`:`Connected ${n.repo.label}`,{kind:"connected",repo:n.repo})}for(let E of[...pr.keys()])Ac(E);let s=Fp(n.repo.id),i=++Dp,l=()=>wc.get(n.repo.id)!==s||Dp!==i,u=zt(e.repoRoot);if(c(u))return a(u.message);let p=await Lp(e.repoRoot,n.repo);if(c(p))return a(`Could not clone it: ${p.message}`);if(l())return Dt(p.value.stagePath),a("Cancelled");let m=OE(),f=await PE(p.value.stagePath,an(n.repo.since,u.value.createdAt),m.knownRefs),g=rt(e.repoRoot),x={repo:n.repo,host:_p(n.repo.url),...f,bytes:p.value.bytes,contributors:m.contributors,claimedBytes:$p(e.repoRoot),overLimit:!c(g)&&g.value.live.length>=vn,expiresAt:Date.now()+Ic};if(l())return Dt(p.value.stagePath),a("Cancelled");let N=setTimeout(()=>Ac(n.repo.id),Ic);return N.unref(),pr.set(n.repo.id,{stagePath:p.value.stagePath,key:r,preview:x,timer:N}),d("Preview: nothing is connected until you confirm",{kind:"preview",preview:x})};import DE from"node:path";var FE=async e=>{let t=await Se({cwd:e,args:["config","--get","remote.origin.url"]}),n=t.exitCode===0&&t.stdout.trim()||null;return{label:n?Mt(n):DE.basename(e),url:n,path:e}};import _E from"node:fs";import $E from"node:path";var BE=8*1024*1024,Lc=async e=>{if(!ar(e.sha))return a("Invalid commit sha");let t=await vo(e);if(c(t))return a(t.message);let n=await _({cwd:t.value,maxOutput:BE,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return c(n)?a(is(n.message)?"This commit is too large to show here; open it in your editor":n.message):d("Read commit patch",n.value.stdout)},UE=200,Bp=e=>/^0+$/.test(e),zs=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,Up=/^(\d+|-)\t(\d+|-)\t(.+)$/,Mc=async(e,t,n,r)=>{let o=await _({cwd:e,args:["diff","--raw","--numstat","--no-renames","--abbrev=40",t,n,...r&&r.length>0?["--",...r]:[]]});if(c(o))return j.info(`[commits] diff ${t} ${n}: ${o.message}`),a(Wp);let s=o.value.stdout.split(`
|
|
45
|
-
`).filter(p=>p!==""),i=s.filter(p=>!zs.test(p)&&!Up.test(p));if(i.length>0)return a(`Could not parse ${i.length} line(s) of "git diff --raw --numstat" output, e.g. "${i[0]}"`);let l=new Map;for(let p of s){let m=Up.exec(p);m&&l.set(m[3]??"",{insertions:m[1]==="-"?0:Number(m[1]),deletions:m[2]==="-"?0:Number(m[2]),isBinary:m[1]==="-"&&m[2]==="-"})}let u=s.filter(p=>zs.test(p)).map(p=>{let m=zs.exec(p),f=m?.[1]??"",g=m?.[2]??"",x=m?.[3]??"";return{path:x,beforeBlob:Bp(f)?null:f,afterBlob:Bp(g)?null:g,...l.get(x)??{insertions:0,deletions:0,isBinary:!1}}});return d("Listed changed files with blob hashes",u)},Hp=async(e,t)=>{if(t.length>UE)return a(`${t.length} files changed \u2014 too many to show as a diff`);let n=t.flatMap(i=>i.isBinary?[]:[i.beforeBlob,i.afterBlob].filter(l=>l!==null)),r=await Gd(n,e);if(c(r))return a(r.message);let o=r.value,s=i=>i!==null&&!o.has(i);return d("Read changed file contents",t.map(i=>{let l=i.isBinary||s(i.beforeBlob)||s(i.afterBlob);return{path:i.path,before:l||!i.beforeBlob?"":o.get(i.beforeBlob)??"",after:l||!i.afterBlob?"":o.get(i.afterBlob)??"",insertions:i.insertions,deletions:i.deletions,isBinary:l}}))},jE=async e=>{if(!ar(e.sha))return a("Invalid commit sha");let t=await vo(e);if(c(t))return a(t.message);let n=t.value,r=await Mc(n,`${e.sha}~1`,e.sha);if(c(r)&&r.message===Wp){let i=await Gp(n,e.sha);if(c(i))return a(i.message);i.value===kc&&(r=await Mc(n,kc,e.sha))}if(c(r))return a(r.message);if(r.value.length===0)return a("No changed files found for this commit");let o=await Hp(n,r.value);if(c(o))return a(o.message);let s=o.value;return d("Loaded commit diff",{sha:e.sha,...e.repo?{repo:e.repo}:{},files:s})},HE=/^[0-9a-f]{40}$/,WE=async(e,t,n)=>{let r=await _({cwd:e,args:["log","--raw","--no-renames","--abbrev=40","--format=%H",`${t}..${n}`]});if(c(r))return a(r.message);let o=new Map,s=null;for(let i of r.value.stdout.split(`
|
|
46
|
-
`)){if(HE.test(i)){s=new Set,o.set(i,s);continue}let l=zs.exec(i);l&&s&&s.add(l[3]??"")}return d("Listed changed paths per commit",o)},jp=e=>{let t=new Set;for(let n of e)for(let r of n)t.add(r);return t},GE=async(e,t,n)=>{if(t===n)return!0;let r=await _({cwd:e,args:["merge-base","--is-ancestor",t,n]});return!c(r)},kc="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Wp="Could not read this commit's diff",zE="Its parent is outside the fetched history. Widen since to see this diff.",VE=async(e,t)=>{let n=await _({cwd:e,args:["rev-parse","--git-path","shallow"]});if(c(n))return!1;try{return _E.readFileSync($E.resolve(e,n.value.stdout.trim()),"utf8").split(`
|
|
47
|
-
`).some(r=>r!==""&&r.startsWith(t))}catch{return!1}},Gp=async(e,t)=>{let n=await _({cwd:e,args:["rev-parse","--verify","--quiet",`${t}^1`]});return c(n)?await VE(e,t)?a(zE):d("A root commit",kc):d("Parent",`${t}~1`)},qE=async e=>{let t=St(e.repoRoot);if(c(t))return a(t.message);let n=t.value,r=await uc({repoRoot:n,ref:e.ref});if(c(r))return a(r.message);let o=new Set(r.value.flat().map(g=>g.sha)),s=await mr(n);if(c(s))return a(s.message);let i=lc(s.value),l=new Map;for(let g of js(r.value))g.length>0&&l.set(g[0].repo??"",g);let u=[],p=0;for(let[g,x]of l){let N=i(g);if(!N){p+=1;continue}let E=await KE(N,e.ref,x,o);if(c(E)){if(!g)return a(E.message);j.info(`[repos] could not squash ${g}: ${E.message}`),p+=1;continue}let R=g||void 0;u.push({repo:R,diff:{...E.value,files:E.value.files.map(v=>R?{...v,repo:R}:v),overlappingPaths:E.value.overlappingPaths.map(v=>R?`${R}:${v}`:v)}})}let[m,...f]=u;return m?f.length===0?d("Loaded squashed diff",m.diff):d("Loaded squashed diff",{...m.diff,commits:u.reduce((g,x)=>g+x.diff.commits,0),files:u.flatMap(g=>g.diff.files),contiguous:u.every(g=>g.diff.contiguous),overlappingPaths:u.flatMap(g=>g.diff.overlappingPaths),parts:u.map(({repo:g,diff:x})=>({...g?{repo:g}:{},from:x.from,to:x.to,commits:x.commits,contiguous:x.contiguous}))}):a(p>0?"The clone holding this ticket\u2019s commits could not be read":"No commits reference this ticket")},KE=async(e,t,n,r=new Set)=>{let o=n[0].sha,s=o;for(let P=n.length-1;P>0;P--){let $=n[P].sha;if(await GE(e,$,o)){s=$;break}}let i=await Gp(e,s);if(c(i))return a(i.message);let l=i.value,u=await WE(e,l,o);if(c(u))return a(u.message);let p=u.value,m=new Set(n.map(P=>P.sha)),f=new Set([...m,...r]),g=[...p.keys()].filter(P=>m.has(P)),x=[...p.keys()].filter(P=>f.has(P)),N=x.length===p.size,E=x.length>g.length,R=new Map;for(let P of g)for(let $ of p.get(P)??[])R.has($)||R.set($,P);let v=(P,$)=>d("Loaded squashed diff",{ref:t.trim().toUpperCase(),from:l,to:o,commits:g.length,files:P.map(B=>({...B,sha:R.get(B.path)??o})),contiguous:N,overlappingPaths:$}),I,k=[];if(!N||E){let P=jp(g.map(B=>p.get(B)??new Set)),$=jp([...p.entries()].filter(([B])=>!f.has(B)).map(([,B])=>B));if(P.size===0)return v([],[]);I=[...P],k=[...P].filter(B=>$.has(B)).sort()}let M=await Mc(e,l,o,I);if(c(M))return a(M.message);let L=await Hp(e,M.value);return c(L)?a(L.message):v(L.value,k)};var Vp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Pc=e=>e.replace(Vp,""),YE=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,zp=e=>e==="additions"||e==="deletions",Co=e=>{let t=Vp.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!zp(r.side)||!zp(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var qp=/```\n([\s\S]*?)\n?```\s*$/,Kp=e=>qp.exec(e)?.[1]??null,XE=/`[^`\n]+`[^\n]*\n?$/,Yp=e=>Pc(e).replace(qp,"").replace(XE,"").trim(),Xp=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},Oc=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Xp(e)}`;var JE=e=>{let t=e.split(`
|
|
48
|
-
`),n=t.filter(r=>r.trim()!=="").reduce((r,o)=>{let s=/^[ \t]*/.exec(o)?.[0].length??0;return r===null?s:Math.min(r,s)},null);return n?t.map(r=>r.slice(n)).join(`
|
|
49
|
-
`):e},Jp=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],YE({...t,note:n}),`\`${t.filePath}\` ${Xp(t)}`,"```",JE(e),"```"].join(`
|
|
50
|
-
`)};var ZE=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,Vs=e=>{if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),n="";for(let r=0;r<t.length;r++){if(t[r]!=="\\"){n+=t[r];continue}let o=t[++r];if(o==="n")n+=`
|
|
51
|
-
`;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},Zp=e=>{let t=Vs(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},Fc=e=>{let t=[],n=null,r=0,o=0,s=()=>{let i={path:"",oldPath:null,binary:!1,added:0,removed:0,lines:[]};return t.push(i),i};for(let i of e.split(`
|
|
52
|
-
`)){if(i.startsWith("diff --git ")){n=s();let m=i.slice(11),f=m.lastIndexOf(" b/");f!==-1&&(n.path=Vs(m.slice(f+1)).replace(/^b\//,""));continue}if(!n){if(!i.trim())continue;n=s()}let l=n,u=l.lines.length===0;if(u&&i.startsWith("--- ")){let m=Zp(i.slice(4));m&&(l.oldPath=m);continue}if(u&&i.startsWith("+++ ")){let m=Zp(i.slice(4));m&&(l.path=m);continue}if(u&&i.startsWith("rename from ")){l.oldPath=Vs(i.slice(12));continue}if(u&&i.startsWith("rename to ")){l.path=Vs(i.slice(10));continue}if(u&&(i.startsWith("Binary files ")||i.startsWith("GIT binary patch"))){l.binary=!0,l.lines.push({kind:"note",text:"Binary file"});continue}let p=ZE.exec(i);if(p){r=Number(p[1]),o=Number(p[3]),l.lines.push({kind:"hunk",text:i});continue}if(!u){if(i.startsWith("\\")){l.lines.push({kind:"note",text:i.slice(1).trim()});continue}if(i.startsWith("+")){l.added++,l.lines.push({kind:"added",text:i.slice(1),newLine:o++});continue}if(i.startsWith("-")){l.removed++,l.lines.push({kind:"removed",text:i.slice(1),oldLine:r++});continue}if(i.startsWith(" ")){l.lines.push({kind:"context",text:i.slice(1),oldLine:r++,newLine:o++});continue}i===""&&l.lines.push({kind:"context",text:"",oldLine:r++,newLine:o++})}}for(let i of t)!i.path&&i.oldPath&&(i.path=i.oldPath);return t.filter(i=>i.path!=="")},Dc=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null;var _c=e=>e.flatMap(t=>[{kind:"file",text:`${Dc(t)?`${Dc(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),qs=e=>{let t="",n=-1;return e.map(r=>(r.kind==="file"&&(t=r.file.path),r.kind==="hunk"&&n++,{file:t,hunk:n}))},$c=(e,t,n)=>{let r=t.map(i=>Co(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(r.length===0)return new Set;let o=qs(e),s=new Set;return e.forEach((i,l)=>{let u=i.newLine;if(u===void 0)return;let p=o[l]?.file;r.some(m=>m.filePath===p&&m.start<=u&&u<=m.end)&&s.add(l)}),s},Qp=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,QE=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,ef=e=>{let t=QE.exec(e);if(!t)return null;let n=Number(t[1]),r=t[2]===void 0?n:Number(t[2]);return{start:Math.min(n,r),end:Math.max(n,r),note:e.slice(t[0].length)}},tf=(e,t)=>qs(e)[t]?.file??null,nf=(e,t,n,r)=>{let o=qs(e),s=u=>e.findIndex((p,m)=>o[m]?.file===t&&(p.kind==="added"||p.kind==="context")&&p.newLine===u),i=s(n),l=s(r);return i===-1||l===-1?{ok:!1,reason:`${t} has no line ${i===-1?n:r} on the new side`}:Bc(e,i,l)},Bc=(e,t,n)=>{let[r,o]=t<=n?[t,n]:[n,t],s=e[r],i=e[o];if(!s||!i)return{ok:!1,reason:"That line is not in the diff"};let l=g=>(g.kind==="added"||g.kind==="context")&&g.newLine!==void 0;if(!l(s)||!l(i))return{ok:!1,reason:"Comments anchor to the new side: pick an added or unchanged line"};let u=qs(e),p=u[r],m=u[o];if(p.file!==m.file)return{ok:!1,reason:"A comment covers one file at a time"};if(p.hunk!==m.hunk)return{ok:!1,reason:"A comment covers one hunk at a time"};let f=e.slice(r,o+1).filter(l);return{ok:!0,value:{filePath:p.file,start:f[0].newLine,end:f[f.length-1].newLine,snippet:f.map(g=>g.text).join(`
|
|
53
|
-
`)}}};import{existsSync as Wc}from"node:fs";import{chmod as Gc}from"node:fs/promises";import Ys from"node:path";import{spawn as eR,spawnSync as tR}from"node:child_process";import nR from"node:os";import rf from"node:path";import{ulid as rR}from"ulid";function Uc(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function oR(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Ks(){let{preferredEditor:e}=ee(),t=[e?oR(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function jc(e){let[t=""]=Uc(e);return/(^|\/)code(-insiders)?$/.test(t)}function of(e,t){let[n="",...r]=Uc(e);return{command:n,args:[...r,...t]}}function sf(e,t){return of(e,jc(e)?["--wait",t]:[t])}function sR(e,t,n,r="new"){return of(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function af(e){let t=rf.join(nR.tmpdir(),"epiq");Oe.mkDir(t);let n=rf.join(t,rR());Oe.writeToFile(n,e??"");let r=Ks();for(let o of r){let{command:s,args:i}=sf(o,n);if(!s)continue;let l=tR(s,i,{stdio:"inherit"});if(!l.error&&l.status===0){let u=Oe.readFile(n);if(u==null)return a("Unable to read edited file");let p=u.replace(/\r?\n$/,"");return d("Successfully edited",p)}}return a("Unable to open editor")}var iR=new Set(["vim","vi","nvim","nano","pico","ed"]);function aR(e){let[t=""]=Uc(e),n=t.split("/").pop()??t;return iR.has(n)}var cR=600;function cf({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=eR(e,t,{stdio:"ignore",detached:!0}),s=!1,i=u=>{s||(s=!0,clearTimeout(l),r(u))};o.on("error",u=>i(a(u.message))),o.on("exit",u=>{i(u===0?d("Opened editor",!0):a(`"${n}" exited with code ${u}`))});let l=setTimeout(()=>{o.unref(),i(d("Opened editor",!0))},cR)})}function lR(e,t){return aR(e)?Promise.resolve(a(`"${e}" is a terminal editor and can't open from the GUI (no terminal attached). Set preferredEditor to a GUI editor (e.g. "code"), or open the file yourself: ${t}`)):cf(sf(e,t),e)}function Hc(e,t,n,r="new"){return cf(sR(e,t,n,r),e)}async function lf(e){let t=Ks();if(t.length===0)return a("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=a("Unable to open editor");for(let r of t){let o=await lR(r,e);if(!c(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}import{chmodSync as dR,existsSync as uR,lstatSync as mR,mkdirSync as pR}from"node:fs";import fR from"node:os";import gR from"node:path";var No=(...e)=>{let t=gR.join(fR.tmpdir(),"epiq",...e);try{return uR(t)&&mR(t).isSymbolicLink()?a(`Refusing to write through a symlink at ${t}`):(pR(t,{recursive:!0,mode:448}),dR(t,448),d("Prepared private temp dir",t))}catch(n){return a(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var hR=async(e,t)=>{let n=await _({cwd:e,args:["show","--no-ext-diff",t]});if(c(n))return a(n.message);let r=No("commit-diffs");if(c(r))return a(r.message);let o=Ys.join(r.value,`${t}.diff`);return Wc(o)||(Oe.writeToFile(o,n.value.stdout),await Gc(o,292)),lf(o)},yR=12,bR=800,df=async(e,t,n)=>{let r=await _({cwd:e,args:["show",`${t}:${n}`]});return c(r)?"":r.value.stdout},vR=async(e,t)=>{let n=await _({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(c(n))return a(n.message);let r=n.value.stdout.split(`
|
|
54
|
-
`).map(o=>o.trim()).filter(Boolean);return r.length===0?a("No changed files found for this commit"):d("Listed changed files",r)},xR=async(e,t,n)=>{let r=await vR(e,t);if(c(r))return a(r.message);let o=r.value;if(o.length>yR)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=No("commit-diffs",t);if(c(s))return a(s.message);let i=s.value,l=await Promise.all(o.map(async(g,x)=>{let[N,E]=await Promise.all([df(e,`${t}~1`,g),df(e,t,g)]),R=Ys.basename(g),v=Ys.join(i,String(x),"before",R),I=Ys.join(i,String(x),"after",R);return Wc(v)||(Oe.writeToFile(v,N),await Gc(v,292)),Wc(I)||(Oe.writeToFile(I,E),await Gc(I,292)),{beforePath:v,afterPath:I}})),[u,...p]=l;if(!u)return a("No changed files found for this commit");let m=await Hc(n,u.beforePath,u.afterPath,"new");if(c(m)||p.length===0)return m;await new Promise(g=>setTimeout(g,bR));let f=await Promise.all(p.map(({beforePath:g,afterPath:x})=>Hc(n,g,x,"reuse")));for(let g of f)c(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return m},zc=async e=>{if(!ar(e.sha))return a("Invalid commit sha");let t=await vo(e);if(c(t))return a(t.message);let n=t.value,r=Ks()[0];if(r&&jc(r)){let o=await xR(n,e.sha,r);if(!c(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return hR(n,e.sha)};var uf=e=>{if(e<1024)return`${e} B`;let t=["KB","MB","GB","TB"],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=10?Math.round(n):n.toFixed(1)} ${t[r]}`};var Vc=["branches=default","branches=all","since=board","since=all","since=YYYY-MM-DD","label=<name>","confirm"],qc=e=>{let[t="",...n]=e.trim().split(/\s+/).filter(Boolean);if(!t)return a("a remote URL to read commits from");if(!Jt(t))return a("https://, ssh://, git://, file:/// or user@host:path");let r={url:t},o=new Set;for(let s of n){let i=s.indexOf("="),l=i===-1?s:s.slice(0,i),u=i===-1?"":s.slice(i+1);if(o.has(l))return a(`one ${l}=, not two`);if(o.add(l),s==="confirm")r.confirm=!0;else if(l==="branches"&&(u==="default"||u==="all"))r.branches=u;else if(l==="since"&&xn(u))r.since=u;else if(l==="label"&&(u===""||En(u)))r.label=u;else return a(`${Vc.join(", ")}; not "${s}"`)}return d("Parsed",r)},mf=()=>{let e=St();if(c(e))return[];let t=rt(e.value);return c(t)?[]:[...t.value.live,...t.value.overLimit]},ER=e=>{let t=e.latest?`latest "${Ut(e.latest.subject).slice(0,60)}" by ${Ut(e.latest.author).slice(0,40)}`:"no commits",n=e.ticketCommits===0?"none linked, wrong repo?":`${e.ticketCommits} linked`;return[`${e.repo.label} from ${e.host}`,e.defaultBranch?Ut(e.defaultBranch).slice(0,60):"no default branch",t,`${e.commits} commits, ${n}`,uf(e.bytes),e.overLimit?"over the limit: not downloaded until another repo is disconnected":e.contributors>1?`all ${e.contributors} contributors download it on next sync`:"everyone downloads it on next sync"].join(" \xB7 ")},fr=null,RR=e=>`${e.trim()} confirm`,pf=e=>fr&&fr.line===e.trim()?fr.summary:null,ff=async()=>{let e=Y().commandMeta.inputString,t=qc(e);if(c(t))return a(`Expected ${t.message}`);let{userId:n}=ee();if(!n)return a("Set a username first with :config username");let r=St();if(c(r))return r;let o=await Tc({repoRoot:r.value,actorId:n,url:t.value.url,branches:t.value.branches,since:t.value.since,label:t.value.label,mode:t.value.confirm?"confirm":"auto"});if(c(o))return a(o.message);if(o.value.kind==="preview"){let s=RR(e);return fr={line:s,summary:ER(o.value.preview)},d(fr.summary,{followUp:`config repoConnect ${s}`})}return t.value.confirm&&(fr=null),d(o.value.kind==="connected"?`${o.message} \u2014 it syncs with the board; :sync fetches it`:o.message,null)},gf=()=>{let{userId:e}=ee();if(!e)return a("Set a username first with :config username");let t=St();if(c(t))return t;let n=Rc({repoRoot:t.value,actorId:e,repo:Y().commandMeta.inputString});return c(n)?a(n.message):d(`${n.message} \u2014 it syncs with the board`,null)};var vO=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as SR}from"node:crypto";var CR="0123456789ABCDEFGHJKMNPQRSTVWXYZ",NR=e=>{let t=SR("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+=CR[Number(n>>s&31n)]}return r},hf=new Map,pe=(e,t)=>{let n=`${e}:virtual:${t}`,r=hf.get(n);if(r!==void 0)return r;let o=NR(n);return hf.set(n,o),o};import yf from"chalk";var ce=e=>yf.dim(e),fe=e=>yf.hex(A.primary)(e),be=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let m=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,g)=>Qo(f)-Qo(g)).slice(0,r).map(f=>es(f)).join(" ");return m?`${ce(e)}${m}${ce(n)}`:""};var ln={None:"none",Invalid:"invalid",Valid:"valid"};var IR=["BOARD","TICKET","SWIMLANE"],bf=()=>{let e=h().selectedNode;if(!e?.context)return W({message:ce("Missing target context")});if(IR.includes(e.context))return Z();if(e.parentNodeId){let t=h().nodes[e.parentNodeId];if(t?.id===pe(t?.parentNodeId??"","comments"))return Z()}return W({message:ce("Command not available in this context")})},se="<ENTER> to confirm",wR=()=>{let{userId:e}=ee(),t=ve();return!e||c(t)?[]:Xn(t.value.emailLinks,e)},Z=(e="",t=[],n=!0)=>({message:n?ce(e):e,validity:ln.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:ln.Invalid,message:e,completionWordList:t}),hr=e=>e.length===0,vf=(e,t)=>{let n=Ze(h().breadCrumb,"BOARD");if(c(n))return W({message:fe("Command is not applicable in this context")});let r=Ql(n.value.id);return c(r)?W({message:fe(`Unable to ${t}: board id is not a valid ULID`)}):Mu({date:e,horizonDate:r.value})?null:W({message:fe(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Xs=e=>` ${xf.hex("#000").bgHex(Be(e))(` ${e} `)} `,Kc=({modifier:e})=>{let t="confirm";return e===t?Z(se):W({message:hr(e)?ce("if you are certain, enter ")+es(t):"",completionWordList:[t]})},AR=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?W({message:ce(n)}):Z():W({message:hr(r)?t:"",completionWordList:[...e]}),gr=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>hr(n)&&hr(r)?W({message:e,completionWordList:[]}):Z(t??se),TR=({modifier:e,inputString:t})=>{let n=Aa();return!hr(e)||!hr(t)?Z(se):W({message:n.length?ce("number from the list, or a path"):ce("path to an epiq project"),completionWordList:n})},MR=({modifier:e,inputString:t})=>{let n=Me(b.CONFIG);if(!n.includes(e))return W({message:be({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case J.EDITOR:{let r=[...Ou];return t.trim()?r.includes(t.trim())?Z(se):W({message:be({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):W({message:be({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case J.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?Z(se):W({message:be({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case J.USERNAME:{let r=ee().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(p=>p.startsWith(s)),u=i.length===1&&i[0]===s?"":be({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?u?Z(`${u} ${ce(se)}`,o,!1):Z(se,o):W({message:u||fe("Enter a user name. Saved in ")+xf.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case J.EMAILS:{let r=ee().gitEmail,o=nr(),s=o.length>0||!r?o:[r],i=[...s,"none"],l=t.trim(),u=(N,E)=>W({message:be({prefix:N,wordList:i,noOfHints:3,inputString:E,minLengthForHints:0}),completionWordList:i});if(!l)return Z(`${se} to see your addresses, or name one`,i);let p=l.split(/[,\s]+/).filter(Boolean),m=p[p.length-1]??"",f=N=>N==="none"||s.includes(N.toLowerCase()),g=N=>i.some(E=>E.startsWith(N.toLowerCase())),x=p.filter(N=>!f(N)&&!g(N));return x.length>0?W({message:fe(`no address here matches ${x.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(m)?Z(se):u("",m)}case J.EMAILS_UNCLAIM:{let r=wR(),o=t.trim();return r.length===0?W({message:fe("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?Z(se):W({message:be({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case J.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?Z(se):W({message:be({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case J.AUTOSYNC:{let r=["on","off"],o=ee().autoSync;if(!r.includes(t.trim())){let s=Iu(o);return W({message:be({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return Z(se)}case J.ATTACHMENT_MAX_KB:{let r=ee().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<to||o>no){let s=be({prefix:" examples: ",wordList:Ia,minLengthForHints:0,inputString:t});return W({message:fe(`provide a size cap in KB (${to}-${no}). current: ${r??Tn} KB.`)+s,completionWordList:Ia})}return Z(se)}case J.REPO_CLONE_MAX_MB:{let r=t.trim();if(!/^\d+$/.test(r)||!Oa(Number(r))){let o=be({prefix:" examples: ",wordList:wa,minLengthForHints:0,inputString:t});return W({message:fe(`provide a connected repo's clone cap in MB (${or}-${sr}). current: ${ir()} MB.`)+o,completionWordList:wa})}return Z(se)}case J.REPO_CONNECT:{let r=qc(t);if(c(r))return W({message:fe(r.message),completionWordList:[]});let o=r.value.confirm?pf(t):null;return r.value.confirm&&!o?W({message:fe("preview it first: run the line without confirm"),completionWordList:[]}):Z(`${o??ce(Vc.join(" "))} ${se}`,[],!1)}case J.REPO_DISCONNECT:{let r=mf(),o=oc(r),s=t.trim();return o.length===0?W({message:fe("no other repos are connected"),completionWordList:[]}):s&&!c(Os(r,s))?Z(se):W({message:be({prefix:"stop reading ",wordList:o,noOfHints:3,inputString:s,minLengthForHints:0}),completionWordList:o})}case J.SYNC_DEBOUNCE_MS:{let r=ee().autoSyncIntervalMs,o=Jn(t);if(!t.trim()||o===null){let s=be({prefix:" examples: ",wordList:Na,minLengthForHints:0,inputString:t});return W({message:fe(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:Na})}return Z(se)}default:return W({message:fe("Unknown config option"),completionWordList:n})}},kR=({modifier:e,inputString:t})=>{let n=Me(b.EDIT);if(!n.length)return W({message:fe("Command not available in this context")});if(!n.includes(e)){let r=be({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:r||fe("Unknown edit option"),completionWordList:n})}switch(e){case tt.COMMENT:return t.trim()?Z(se):W({message:ce("write a comment...")});case tt.TITLE:return Z(se);case tt.DESCRIPTION:{let{preferredEditor:r}=ee();return r?Z(ce("<ENTER> to edit in ")+r):W({message:"No editor selected"})}default:return W({message:fe("Unknown edit option"),completionWordList:n})}},LR=({modifier:e})=>{let t=Me(b.YANK);return t.length?t.includes(e)?Z(se+ce(" and copy to clipboard")):W({message:be({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:fe("Nothing selected to copy from")})},PR={[b.EXPORT]:()=>Z(se+ce(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return Z(se);let n={message:ce("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=In(r);if(!r||!o)return W(n);let s=vf(o,"peek");return s||Z(se)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=ys(e.modifier,e.inputString),r={message:ce("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=In(t);if(!t||!o)return W(r);let s=vf(o,"replay");return s||(n&&hs(n)===null?W({message:fe("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):Z("<ENTER> to replay board history",n?Pu:[]))},[b.EXIT]:()=>Z(se+ce(" and exit the application")),[b.INIT]:()=>Z(se),[b.OPEN]:TR,[b.PALETTE]:()=>Z(se),[b.FILTER]:e=>{if(e.modifier==="clear")return Z(se);let t=s=>Me(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:be({wordList:Me(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Me(b.FILTER)});let n=Object.values(h().tags).map(s=>s.name),r=Object.values(h().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?W({message:be({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):Z():W({message:be({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[b.NONE]:e=>{let t=Me(b.NONE);return W({message:be({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>AR({list:Me(b.NEW),hint:be({wordList:Me(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>Z(se),[b.EDIT]:kR,[b.COMMENT]:e=>{let t=gr({hint:ce(`write a comment (max ${4e3} char)...`),onOk:ce(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===ln.Invalid?t:e.inputString.length>4e3?Z(fe("max input exceeded")):t},[b.CONFIG]:MR,[b.YANK]:LR,[b.DELETE]:e=>{let t=bf();return t.validity==="invalid"?t:Kc(e)},[b.CLOSE_ISSUE]:e=>Kc(e),[b.RE_OPEN_ISSUE]:e=>Kc(e),[b.MOVE]:e=>{let t=bf();return t.validity==="invalid"?t:gr({hint:be({prefix:"hey hacker! These commands are blocked for you... ",wordList:Me(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=C.getExistingTags().slice(0,10).map(Xs).join("");return gr({hint:n.length?ce("create tag or reuse:")+n+ce(""):ce("create tag ...")})(e)},[b.UNTAG]:e=>{let t=fs();if(c(t))return W({message:fe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Xs).slice(0,10);return n.length?gr({hint:ce(" ... ")+n.join("")})(e):W({message:fe("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=C.getExistingAssignees().map(Xs).slice(0,10);return gr({hint:ce("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=gs();if(c(t))return W({message:fe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Xs).slice(0,10);return n.length?gr({hint:ce("remove assignee... ")+n.join("")})(e):W({message:fe("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>Z(se)},Ef=Object.fromEntries(Object.entries(PR).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Js=["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 OR=3,DR=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"]),FR=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},_R=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=OR&&!DR.has(t)&&!/^\d+$/.test(t)),$R=e=>{let t=new Map;for(let s of FR(e))for(let i of _R(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=Js.filter(s=>!r.has(s));return[...n,...o]},Rf=Js,Sf=-1,Cf=()=>{let e=ve();if(c(e))return Js;let t=e.value,n=t.eventLog.length;return n!==Sf&&(Rf=$R(t),Sf=n),Rf};var Nf=e=>Object.values(b).includes(e),If=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:u}=Ef[n].validate(n,r,s),p=n!==b.PEEK&&n!==b.REPLAY,m=o==="command"||o==="modifier"?Me(n):p?Cf():[],{mode:f}=h(),g=f===y.COMMAND_LINE?i??"":"",x=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Rd(e,x,u):{hint:"",hints:[],remainder:"",overlap:0}}};var wf=e=>{let t=e.trimStart(),n=UR(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=jR(e),l=Nf(r)?r:null,u=l!==null,p=r!=="",m=l?Me(l)??[]:[],f=l&&m.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let x=s?"":i,N=BR(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:p,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:x,inputString:N}},BR=(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},UR=e=>e.trim()?e.trim().split(/\s+/):[],jR=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as HR}from"react";var yr=e=>e===Yc||e===":",Yc=" ",wo=40,br={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:ln.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Xc=new Set,Af=()=>{for(let e of Xc)e()},WR=e=>(Xc.add(e),()=>Xc.delete(e)),ut=e=>{let n=e(br),r=wf(n.value),o=n.cursorPosition===n.value.length;br={...n,commandMeta:If(r,o)},Af()},Ao=({message:e,status:t})=>{let n=structuredClone(br);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,br=n,Af(),d(e,null)},Jc=e=>{ut(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Zc=e=>{ut(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&yr(n[o-1]);)o--;for(;o>0&&!yr(n[o-1]);)o--}else{for(;o<n.length&&!yr(n[o]);)o++;for(;o<n.length&&yr(n[o]);)o++}return{...t,cursorPosition:o}})},Tf=()=>{ut(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}})},Mf=()=>{ut(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&yr(t[r-1]);)r--;for(;r>0&&!yr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Zs=e=>{ut(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,l=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:l,commandIsPending:!1}})},kf=()=>{ut(e=>({...e,commandIsPending:!0}))},K=e=>{ut(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Lf=({addToHistory:e=!0,line:t})=>{ut(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,wo):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},Pf=e=>{ut(t=>({...t,commandHistory:e.slice(0,wo),commandHistoryIndex:-1}))},Of=()=>{ut(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},Df=()=>{ut(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}})},Ff=()=>{ut(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Y=()=>br,TD=()=>HR(WR,Y,Y),Qs=()=>{let[e,...t]=br.value.split(Yc);return t.join(Yc).trim()};var S={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",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",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},GR=e=>e.shift===!0,zR={[S.NavPreviousItem]:S.NavPreviousItemJump,[S.NavNextItem]:S.NavNextItemJump,[S.MovePreviousItem]:S.MovePreviousItemJump,[S.MoveNextItem]:S.MoveNextItemJump};function VR(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function qR(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function KR(e,t,n){let r=h().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 _D(e,t){let n=Y();if(e.sequence==="?"&&t!==y.PALETTE)return S.InitCommandPalette;if(e.sequence===":"&&t!==y.COMMAND_LINE)return S.InitCommandLine;if(t===y.MOVE)switch(e.name){case"m":case"return":return S.ConfirmMove}if(t===y.COMMAND_LINE)return fd(e,n.value);if(t===y.PALETTE)return gd(e,n.value);let r=VR(e)||qR(e);if(r)return YR(r,t,GR(e));if(e.ctrl&&e.name==="c")return S.Exit;switch(e.name){case"r":return S.EditTitle;case"e":return S.EditDescription;case"n":return S.AddItem;case"m":return S.InitMove;case"d":return S.Delete;case"y":return S.Yank;case"o":return S.OpenInEditor;case"s":return S.MarkDiffLine;case"c":return S.CommentOnDiffLine;case"return":return S.Confirm;case"space":return S.Confirm;case"v":return ee().viewMode==="wide"?S.SetViewDense:S.SetViewWide;case"q":case"escape":return S.Exit;default:return null}}function YR(e,t,n=!1){let r=t===y.MOVE?{prevItem:S.MovePreviousItem,nextItem:S.MoveNextItem,prevContainer:S.MoveToPreviousContainer,nextContainer:S.MoveToNextContainer}:{prevItem:S.NavPreviousItem,nextItem:S.NavNextItem,prevContainer:S.NavToPreviousContainer,nextContainer:S.NavToNextContainer},o=KR(h().contextNode.childRenderAxis,e,r);return!o||!n?o:zR[o]??o}import{ulid as ZR}from"ulid";var To=24n,XR=To*4n,It=(1n<<XR)-1n,JR=/^[0-9a-f]+$/;function _f(e){return!e||!JR.test(e)?a(`Invalid hex rank: ${e}`):d("Converted rank to bigint",BigInt("0x"+e))}function st(e,t=To){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return d("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function He(e,t){if(!e&&!t)return st(It/2n,To);let n=e?_f(e):d("Resolved lower bound",0n);if(c(n))return n;let r=t?_f(t):d("Resolved upper bound",It);if(c(r))return r;let o=n.value,s=r.value;if(s<=o)return a("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):st(i,To)}function $f(e){if(e<=0)return d("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=It*BigInt(r+1)/(t+1n),s=st(o,To);if(c(s))return s;n.push(s.value)}return d("Resolved evenly spaced ranks",n)}var Qc=(e,t)=>{let n=he(e),r=$f(n.length);if(c(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],l=r.value[s];if(!i||!l)return a("Unable to assign rebalance rank");o[i.id]=l}return d("Created rebalance event",{id:ZR(),action:"rebalance.children",payload:{parent:e,ranks:o},...re(t)})};var _n=e=>e.trim().toLocaleLowerCase(),el=(e,t)=>_n(e).includes(_n(t));var QR=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},eS=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Bf=null,Uf=new Map,tS=()=>{let e=h().eventLog??[];if(e===Bf)return Uf;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return Bf=e,Uf=t,t},nS=e=>{let{contributors:t}=h(),n=tS().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},jf=(e,t)=>{let n=_n(t.value);if(!n)return!0;switch(t.target){case"title":return el(e.title??"",n);case"description":return el(e.props.description??"",n);case"tag":return QR(e).map(_n).some(o=>o.includes(n));case"assignee":return eS(e).map(_n).some(o=>o.includes(n));case"actor":return nS(e).map(_n).some(o=>o.includes(n));case"ref":return Xa(e.id,t.value);default:return!0}};var tl=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,rS=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Hf=(e,t)=>Object.values(e).filter(n=>rS(n,t)).sort(tl),Wf=(e,t)=>{let n={};for(let r of Object.values(e)){if(H(r)&&t.length>0&&!t.every(s=>jf(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(tl);return n},Gf=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(tl);return n};var zf=e=>ei(he(e),{at:"end"}),ei=(e,t={at:"end"})=>{let n=o=>c(o)?d("Rank space exhausted",{rank:"",needsRebalance:!0}):d("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(He(void 0,void 0));let r=()=>n(He(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(He(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(He(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=Vf(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(He(i?.rank,s.rank))}case"after":{let o=Vf(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(He(s.rank,i?.rank))}}},he=e=>{let t=h();if(!Kf()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Hf(t.nodes,e)},Vf=(e,t)=>e.findIndex(n=>n.id===t),qf=(e,t,n={at:"end"})=>ei(he(t).filter(r=>r.id!==e),n),ti=(e,t,n,r,o)=>{let s=qf(t,e,n);if(c(s))return s;if(!s.value.needsRebalance)return d("Resolved rank",s.value.rank);let i=Qc(e,r);if(c(i))return i;let l=Q([i.value],o);if(c(l))return l;let u=qf(t,e,n);return c(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):d("Resolved rank after rebalance",u.value.rank)},ni=(e,t,n)=>{let r=zf(e);if(c(r))return r;if(!r.value.needsRebalance)return d("Resolved rank",r.value.rank);let o=Qc(e,t);if(c(o))return o;let s=Q([o.value],n);if(c(s))return s;let i=zf(e);return c(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):d("Resolved rank after rebalance",i.value.rank)};var Mo=5,U={exit(){process.exit(0)},enterChildNode(){let e=h(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=ae(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||U.navigate({contextNode:o,selectedIndex:ae(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=h();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=ae(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Yf(1),navigateToPreviousItem:()=>Yf(-1),jumpToNextItem:()=>Xf(Mo),jumpToPreviousItem:()=>Xf(-Mo),navigateToNextContainer:()=>Jf(1),navigateToPreviousContainer:()=>Jf(-1),navigate:({contextNode:e,selectedIndex:t})=>{w({contextNodeId:e.id,selectedIndex:t})}},Yf=e=>{let{selectedIndex:t,contextNode:n}=h(),r=ae(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;U.navigate({selectedIndex:s,contextNode:n})},Xf=e=>{let{selectedIndex:t,contextNode:n}=h(),r=ae(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);U.navigate({selectedIndex:s,contextNode:n})},Jf=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=h();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=ae(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let l=s.at(i+e)??s.at(0);if(!l)return;let u=ae(l.id),p=Math.max(0,u.length-1),m=Math.min(Math.max(0,r),p),f=u.length?m:-1;U.navigate({contextNode:l,selectedIndex:f})};var Qf=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),eg=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},oS=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&&Fe(t)&&t.childRenderAxis==="vertical"},ri=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=he(r.id);return U.navigate({contextNode:r,selectedIndex:Qf(t,o.length)}),!0},tg=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return ri(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=he(o.id).findIndex(l=>l.id===n.id);return i>=0?(U.navigate({contextNode:o,selectedIndex:i}),!0):tg(o.id)},Zf=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),tg(n))return!0;n=t[n]?.parentNodeId}return!1},sS=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},ng=e=>{let{nodes:t,rootNodeId:n}=h();if(oS(e.contextNodeId)&&ri(e.contextNodeId,e.selectedIndex))return d("Restored navigation inside text container",null);if(sS(e.selectedNodeId)&&e.selectedNodeId&&Zf(e.selectedNodeId))return d("Restored navigation to selected node or ancestor",null);if(ri(e.contextNodeId,e.selectedIndex))return d("Restored navigation to previous container",null);if(e.parentNodeId&&ri(e.parentNodeId,e.selectedIndex))return d("Restored navigation to previous parent",null);if(Zf(e.contextNodeId))return d("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=he(r.id);return U.navigate({contextNode:r,selectedIndex:Qf(e.selectedIndex,o.length)}),d("Restored navigation to root",null)};import{monotonicFactory as iS,ulid as _t}from"ulid";var ko=iS();function aS(){let e=ve();if(c(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)return a("No workspace found in event log");let[r]=ae(n.id),[o]=r?ae(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return d("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?d("Resolved boot nav target",{contextNode:r,selectedIndex:0}):d("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function cS(){let e=aS();return c(e)?e:U.navigate(e.value)}function rg({userId:e,userName:t}){let n=ko(),r=ko(),o=ko(),s=ko(),i=ko(),l=He(void 0,void 0);if(c(l))return l;let u=He(void 0,void 0);if(c(u))return u;let p=He(u.value,void 0);if(c(p))return p;let m=He(void 0,void 0);if(c(m))return m;let f=He(m.value,void 0);if(c(f))return f;let g=He(f.value,void 0);if(c(g))return g;let x=He(void 0,void 0);return c(x)?x:d("Created default events",[{id:_t(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:_t(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:_t(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:_t(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:m.value}},{id:_t(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:_t(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:_t(),userId:e,action:"add.board",payload:{id:ps,name:"Closed",parent:n,rank:p.value}},{id:_t(),userId:e,action:"add.swimlane",payload:{id:ct,name:"Closed",parent:ps,rank:x.value}},{id:_t(),userId:e,action:"lock.node",payload:{id:ps}},{id:_t(),userId:e,action:"lock.node",payload:{id:ct}}])}var lS=()=>{let e=ve();if(c(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},dS=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");j.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");j.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function Lo(e,t=[]){if(lS())return d("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ne.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=lo(s);return c(i)?i:(w({hasProjectDefinition:!1,mode:y.DEFAULT}),d("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=sn(e),{fatal:r,skipped:o}=Pn(n);return r.length>0?a(`Materializing failed:
|
|
55
|
-
${r.map(s=>s.message).join(`
|
|
56
|
-
`)}`):(On(o),cS(),w({hasProjectDefinition:!0}),dS(t),d("State booted successfully",null))}import{WebSocket as uS}from"ws";var oi=new Set,FF=e=>{oi.add(e),e.on("close",()=>{oi.delete(e)}),e.on("error",()=>{oi.delete(e)})},og=e=>{let t=JSON.stringify(e);for(let n of oi)n.readyState===uS.OPEN&&n.send(t)};var si=e=>{dt()&&(w({syncStatus:e}),og({type:"sync-status",payload:e}))},ii=(e="Syncing...")=>{si({status:"syncing",msg:e})},Po=(e="Synced")=>{si({status:"synced",msg:e})},mS=e=>{si({status:"failed",msg:e})},ai=e=>{si({status:"offline",msg:e})},we=e=>(mS(e),a(e));var $n=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),sg=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)}},ie=(e,t)=>(c(t)&&logger.info(`[${e}]:failed`,t.message),t);import Eg from"node:fs";import Vt from"node:fs";import qt from"node:path";import ci from"node:fs";import ig from"node:path";var _e=".epiq/project.json",ag=e=>ig.join(e,_e),pS=e=>{if(!ci.existsSync(ag(e)))return d("State branch carries no identity yet",null);let t=je(e);return c(t)?a(`On the state branch: ${t.message}`):d("Read the state branch identity",t.value)},nl=(e,t)=>{try{let n=ag(e);return ci.mkdirSync(ig.dirname(n),{recursive:!0}),ci.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
57
|
-
`,"utf8"),d("Wrote the state branch identity",void 0)}catch(n){return a(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},fS=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${_e} names project ${e.projectId}`,`(created ${e.createdAt}), but the state branch ${n}`,`belongs to project ${t.projectId} (created ${t.createdAt}).`,"","The branch holds the board, so its id is the one that counts. Point the","checkout at it and commit the change:","",` git show ${n}:${_e} > ${_e}`,"","A second id is minted when init runs in a checkout that has no","project file while the state branch already exists; nothing on the","board is lost by it, but every checkout has to agree on one."].join(`
|
|
58
|
-
`);var cg=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!ci.existsSync(er(e)))return d("No project file to compare","no-checkout-file");let r=je(e);if(c(r))return a(r.message);let o=pS(t);if(c(o))return a(o.message);if(o.value===null){let s=nl(t,r.value);return c(s)?a(s.message):d("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?a(fS({checkout:r.value,branch:o.value,stateBranch:n})):d("The checkout and the state branch agree","matched")};import $t from"node:fs";import Oo from"node:path";var vr=e=>e.split(`
|
|
59
|
-
`).filter(t=>t.trim().length>0),lg=e=>{let t=Oo.join(e,Ue,Ht);try{if(!$t.existsSync(t))return d("No events directory",[]);let n=$t.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>vr($t.readFileSync(Oo.join(t,r),"utf8")).length>0);return d("Looked for stranded event logs",n)}catch(n){return a(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},dg=e=>Oo.join(e,Ue,Ht),ug=e=>{let t=dg(e),n=new Map;try{if(!$t.existsSync(t))return n;for(let r of $t.readdirSync(t))if(r.endsWith(".jsonl")&&!Ln(r))try{n.set(r,vr($t.readFileSync(Oo.join(t,r),"utf8")))}catch(o){if(!oo(o))throw o}}catch{return n}return n},gS=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},mg=(e,t)=>{if(t.size===0)return[];let n=dg(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Oo.join(n,o);try{let l=$t.existsSync(i)?$t.readFileSync(i,"utf8"):null,u=new Set(l===null?[]:vr(l)),p=s.filter(f=>!u.has(f)).filter(gS);if(p.length===0)continue;$t.mkdirSync(n,{recursive:!0});let m=l!==null&&l.length>0&&!l.endsWith(`
|
|
60
|
-
`);$t.appendFileSync(i,`${m?`
|
|
61
|
-
`:""}${p.join(`
|
|
62
|
-
`)}
|
|
63
|
-
`,"utf8"),r.push(`${o} (${p.length})`)}catch{continue}}return r},hS=(e,t)=>{let n=new Set(vr(t));return vr(e).filter(r=>!n.has(r))},yS=(e,t,n)=>[`Refusing to commit ${e}: it is missing ${t.length} of the ${n} event(s) already committed.`,"","The event log is append-only, so a line can never legitimately go","missing. The working copy on disk is damaged; committing it would","publish that damage to everyone who pulls, and the log carries no way","to undo it.","","Nothing has been committed. The committed history is intact \u2014 recover","the file from it before syncing again:",` git show HEAD:${e}`,"","First dropped event:",` ${t[0]?.slice(0,200)??"<none>"}`].join(`
|
|
64
|
-
`),pg=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Se({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return d("No committed log to compare against",void 0);let o=hS(r.stdout,n);return o.length>0?a(yS(t,o,vr(r.stdout).length)):d("Event log only grew",void 0)};var bS="[epiq:init-repo]",gg=async e=>{let t=await Se({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return d("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return a(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
|
|
65
|
-
`));j.info("Creating initial commit");let r=await _({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(c(r))return a(r.message);let o=await _({args:["commit-tree",r.value.stdout.trim(),"-m",bS],cwd:e});if(c(o))return a(o.message);let s=await _({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return c(s)?a(s.message):d("Created initial commit",!0)},fg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",vS=async e=>{let t=await cs(e);if(c(t))return a(t.message);let n=await qd(e);return c(n)?a(n.message):d("Built sync commit message",`[sync|branch:${fg(t.value)}:sha:${fg(n.value)}]`)},rl=async({repoRoot:e,stateBranchName:t})=>{j.info(`Creating ${t}`);let n=await _({args:["commit-tree",ou,"-m","[epiq:init-state-branch]"],cwd:e});if(c(n))return a(`Failed to create state branch commit
|
|
66
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await _({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return c(o)?a(`Failed to create ${t}
|
|
67
|
-
${o.message}`):d("Created state branch",!0)},ol=async({repoRoot:e,stateBranchName:t})=>{let n=await as({repoRoot:e,branch:t});if(c(n))return a(`Ensure local state branch failed
|
|
68
|
-
`+n.message);if(n.value)return d("Local state branch already exists",!1);let r=await jt({repoRoot:e});if(c(r))return a(`Ensure local state branch failed
|
|
69
|
-
`+r.message);let o=r.value,s=o?await Br({repoRoot:e,branch:t}):d("No remote, no remote state branch",!1);if(c(s))return a(`Ensure local state branch failed
|
|
70
|
-
`+s.message);let i=s.value;if(o&&i){let l=await ue.fetch({cwd:e,remote:et,branch:t});if(c(l))return a(`Failed to fetch ${t} from remote
|
|
71
|
-
${l.message}`)}if(i){let l=await _({args:["branch","--track",t,`${et}/${t}`],cwd:e});return c(l)?a(`Failed to create local ${t} from remote
|
|
72
|
-
${l.message}`):d("Created local state branch from remote",!0)}return rl({repoRoot:e,stateBranchName:t})},xS=async({repoRoot:e,branch:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return a(n.message);let r=n.value.stdout.split(`
|
|
73
|
-
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return d("Found worktree for branch",o)}return d("No worktree found for branch",null)},ES=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Hr(qt.dirname(t));if(c(r))return a(`Failed to create state branch worktree
|
|
74
|
-
`+r.message);if(Vt.existsSync(t)&&!Vt.existsSync(qt.join(t,".git"))){let s=lg(t);if(c(s))return a(s.message);if(s.value.length>0)return a([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(i=>` ${i}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
|
|
75
|
-
`));j.info("Removing broken state branch worktree path"),cu(t)}j.info("Creating state branch worktree");let o=await ue.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return c(o)?a(`Failed to create state branch worktree
|
|
76
|
-
${o.message}`):d("Created state branch worktree",!0)},xr=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await SS({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(c(r))return r;let o=cg({repoRoot:e,stateBranchRoot:t,stateBranch:n});return c(o)?a(o.message):(o.value==="stamped"&&j.info("Stamped the state branch with this project\u2019s identity"),r)},RS=(e,t)=>{let n=Zn(Nn());return qt.dirname(e)===n&&qt.dirname(t)===n},SS=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await xS({repoRoot:e,branch:n});if(c(r))return a(r.message);let o=Zn(t),s=r.value?Zn(r.value):null;if(s&&s===o&&Vt.existsSync(s))return d("State branch already checked out in expected worktree",!1);if(s&&s!==o&&RS(s,o))return a([`The state branch ${n} is checked out under project ${qt.basename(s)}, but this checkout names project ${qt.basename(o)}.`,"","Two ids for one branch means a checkout minted a second identity for","a board that already existed. Nothing on the board is lost by it, but",`every checkout has to agree on one: compare ${_e} here`,`with \`git show ${n}:${_e}\`, and keep the branch's.`].join(`
|
|
77
|
-
`));if(s&&s!==o){let u=await Qd(s);if(c(u))return a(u.message);if(u.value||lm(s))return a([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${o}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
78
|
-
`));j.info("Moving state branch worktree to expected location");let p=await ue.worktreeRemove({cwd:e,worktreeRoot:s});if(c(p))return a(`Failed to remove existing state branch worktree
|
|
79
|
-
${p.message}`)}if(s&&!Vt.existsSync(s)){j.info("Pruning stale state branch worktree");let u=await ue.worktreePrune({cwd:e});if(c(u))return a(`Failed to prune stale worktrees
|
|
80
|
-
${u.message}`)}let i=await Vd({repoRoot:e,worktreeRoot:t});if(c(i))return a(i.message);let l=Vt.existsSync(t);if(i.value&&l)return d("State branch worktree already exists",!1);if(i.value&&!l){j.info("Pruning missing registered state branch worktree");let u=await ue.worktreePrune({cwd:e});if(c(u))return a(`Failed to prune stale worktrees
|
|
81
|
-
${u.message}`)}return ES({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},CS=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await cs(e);if(c(n))return a(n.message);if(n.value===t)return d("State branch already checked out",!1);(await Se({cwd:e,args:["rebase","--abort"]})).exitCode===0&&j.info("Aborted stale state branch rebase");let o=await ue.checkout({cwd:e,branch:t});return c(o)?a(`Failed to checkout ${t}
|
|
82
|
-
${o.message}`):d("Checked out state branch",!0)},NS=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ma(t);if(c(n))return a(n.message);if(n.value)return d("State branch upstream already configured",!1);let r=await jt({repoRoot:t});if(c(r))return a(r.message);if(!r.value)return d("No remote available for state branch upstream",!1);let o=Et(e);if(c(o))return o;let s=o.value,i=await Br({repoRoot:t,branch:s});if(c(i))return a(i.message);if(!i.value)return d("Remote state branch missing; upstream will be configured on first push",!1);j.info(`Configuring ${s} upstream`);let l=await ue.fetch({cwd:t,remote:et,branch:s});if(c(l))return a(`Failed to fetch ${s}
|
|
83
|
-
${l.message}`);let u=await ue.setUpstream({cwd:t,branch:s,upstream:`${et}/${s}`});return c(u)?a(`Failed to set state branch upstream
|
|
84
|
-
${u.message}`):d("Configured state branch upstream",!0)},li=async({stateBranchRoot:e,eventFileName:t})=>{let n=su(t),r=qt.join(e,n);if(!Vt.existsSync(r))return d("No event file to stage",null);let o=await pg({stateBranchRoot:e,relativePath:n,workingContent:Vt.readFileSync(r,"utf8")});if(c(o))return a(o.message);let s=await ue.stage({cwd:e,pathspec:[n]});return c(s)?a(`Failed to stage state branch event file
|
|
85
|
-
${s.message}`):d("Staged state branch event file",n)},hg=async({stateBranchRoot:e})=>{let t=iu(),n=qt.join(e,t);if(!Vt.existsSync(n))return d("No media directory to stage",null);let r=await ue.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return c(r)?a(`Failed to stage state branch media files
|
|
86
|
-
${r.message}`):d("Staged state branch media files",t)},yg=async({stateBranchRoot:e})=>{let t=[fa(),ga(),_e].filter(r=>Vt.existsSync(qt.join(e,r)));if(t.length===0)return d("No event log config to stage",[]);let n=await ue.stage({cwd:e,pathspec:t});return c(n)?a(`Failed to stage event log config
|
|
87
|
-
${n.message}`):d("Staged event log config",t)},bg=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await vS(e);return c(r)?a(`Create state branch sync commit failed
|
|
88
|
-
`+r.message):Qn({cwd:t,message:r.value,pathspec:n})},Do=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ma(t);if(c(n))return a(n.message);let r=Et(e);if(c(r))return r;let o=r.value,s=n.value?await ue.push({cwd:t}):await ue.push({cwd:t,remote:et,branch:o,setUpstream:!0});if(c(s))return a(`Failed during state branch push
|
|
89
|
-
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return d(i?"Pushed state branch":"Remote already up to date",i)},vg=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Et(e);if(c(o))return o;let s=o.value,i=[Wr(),await ol({repoRoot:e,stateBranchName:s}),await xr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await CS({stateBranchRoot:t,stateBranchName:s}),await du(t),n?await NS({stateBranchRoot:t,repoRoot:e}):d("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(c(l))return a(l.message);r=r||!!l.value}return d(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};var IS=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ie("getRepoRootDir",await Rt(t));if(c(r))return a(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ie("getStateBranchRoot",ye({repoRoot:o}));if(c(s))return a(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&Eg.existsSync(i)){let m=await Xd(i,{preserve:[$s]});if(c(m))return a(m.message);m.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:m.value,stateBranchRoot:i});let f=Et(o);if(c(f))return a(f.message);let g=await Jd(i,f.value);if(c(g))return a(g.message);g.value&&logger.info("[sync] cleared a ref lock left by a dead process",{branch:f.value,stateBranchRoot:i});let x=ie("abortRebaseIfPresent(stateBranchRoot)",await pa(i));if(c(x))return a(x.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let l=ie("bootstrapStateBranchStorage",await vg({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(c(l))return a(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=ie("getInProgressGitOperation(stateBranchRoot)",await ua(i));if(c(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),a(`Cannot sync while there is a ${u.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let p=ie("ensureStateBranchLayout",lu(o,i));return c(p)?a(p.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}),d("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}))},wS=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=[];for(let p of Sm(Ve(t),n)){let m=ie("stageStateBranchOwnEventFile",await li({stateBranchRoot:t,eventFileName:p}));if(c(m))return a(m.message);r.push(m.value)}let o=ie("stageStateBranchMediaFiles",await hg({stateBranchRoot:t}));if(c(o))return a(o.message);let s=ie("stageStateBranchEventConfig",await yg({stateBranchRoot:t}));if(c(s))return a(s.message);let i=[...r,o.value,...s.value].filter(p=>p!==null);if(i.length===0)return d("Nothing to stage",{createdCommit:!1});let l=ie("hasStagedChanges(after stage)",await eu(t,i));if(c(l))return a(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.value)return logger.info("[sync] no own event file changes to commit"),d("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=ie("createStateBranchSyncCommit",await bg({repoRoot:e,stateBranchRoot:t,pathspec:i}));return c(u)?a(u.message):(logger.debug("[sync] created sync commit",u.value),d("Committed own event file",{createdCommit:!0,commitSha:u.value}))},sl=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return ai(n),d(n,{...e,pulled:!1,pushed:!1,offline:!0})},xg=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{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");ii();let r=ie("ensureSyncReady",await IS({claim:n,cwd:e,ensureUpstream:!0}));if(c(r))return we(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,l=ie("isDetachedHead(stateBranchRoot)",await tu(s));if(c(l))return we(l.message);if(logger.debug("[sync] detached state branch check result",{detached:l.value}),l.value)return we("Cannot run :sync while the state branch is in detached HEAD state");let u=!1,p,m=!1,f=!1,g=ie("getStateBranch",Et(o));if(c(g))return we(g.message);let x=g.value;logger.debug("[sync] resolved state branch",{stateBranch:x,stateBranchRoot:s});let N=ie("flushPendingLogs",Cs(s,t));c(N)&&logger.error(`[sync] ${N.message}`);let E=ie("commitOwnEventFileToStateBranch",await wS({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(c(E))return we(E.message);u=E.value.createdCommit,p=E.value.commitSha;let R=ie("hasRemote",await jt({repoRoot:s}));if(c(R))return we(R.message);if(!R.value)return sl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i},"no remote");let v=ie("pullBranchRebaseIfPresent",await jr({cwd:s,branch:x}));if(c(v))return Ur(v.message)?sl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):we(v.message);m=v.value;let I=ie("isAheadOfUpstream",await Zd(s));if(c(I))return we(I.message);if(u||i||I.value){logger.info("[sync] pushing state branch",{createdCommit:u,bootstrapped:i,stateBranchRoot:s});let k=ie("pushStateBranch",await Do({stateBranchRoot:s,repoRoot:o}));if(c(k)&&Kd(k.message)){let M=ie("pullBranchRebaseIfPresent(retry)",await jr({cwd:s,branch:x}));if(c(M))return we(M.message);m=m||M.value,k=ie("pushStateBranch(retry)",await Do({stateBranchRoot:s,repoRoot:o}))}if(c(k))return Ur(k.message)?sl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):we(k.message);f=k.value}if(u){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let k=ie("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:s}));if(c(k))return we(k.message);p=k.value.stdout.trim(),logger.debug("[sync] final sync commit sha",p)}return Po(f?"Synced and pushed":m||u?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),d("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,pulled:m,pushed:f,bootstrapped:i,offline:!1})},di=async(e,t)=>{let n=ug(e);try{return await t()}finally{let r=mg(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},Rg=async e=>{let t=e.cwd??process.cwd(),n=await Rt(t);if(c(n))return we(n.message);let r=ye({repoRoot:n.value});if(c(r))return we(r.message);let o=r.value;if(!Eg.existsSync(o))return xg(e,"clean");let s=await bo({worktreeRoot:o,operation:"sync",fn:i=>di(o,()=>xg(e,i))});return c(s)?we(s.message):s.value===null?d("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var Er=null,ui=async({reposMinIntervalMs:e=0}={})=>(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Er,currentStatus:h().syncStatus?.status,currentMessage:h().syncStatus?.msg}),Er?(logger.debug("[sync] syncAndReloadState joining existing promise"),Er):(logger.debug("[sync] syncAndReloadState creating promise"),Er=AS(e).finally(()=>{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:h().syncStatus?.status,statusMessageBeforeClear:h().syncStatus?.msg}),Er=null}),Er)),AS=async e=>{let t;try{t=await TS(e),logger.debug("[sync] syncAndReloadState promise resolved",{success:!c(t),message:t.message,statusAfterResolve:h().syncStatus?.status,statusMessageAfterResolve:h().syncStatus?.msg})}catch(r){let o=r instanceof Error?r.message:String(r);logger.error("[sync] syncAndReloadState promise threw",{message:o,error:r}),t=a(o)}let n=ve();return c(t)&&!c(n)&&n.value.syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),w({syncStatus:{msg:t.message,status:"failed"}})),t},TS=async e=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let t=Sg();if(t)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:h().mode,message:t.message,syncStatus:h().syncStatus}),t;logger.debug("[sync] syncAndReloadState:start");let n=ie("resolveActorId",oe());if(c(n)||!n.value)return logger.info("[sync] unable to resolve actor id",{message:c(n)?n.message:"Missing actor id"}),a("Unable to resolve event log path");w({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:h().syncStatus});let r=lr(n.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:r}),logger.debug("[sync] syncEpiqWithRemote:start");let o=ie("syncEpiqWithRemote",await Rg({ownEventFileName:r}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!c(o),message:(c(o),o.message)}),c(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),w({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:h().syncStatus}),we(`Unable to sync state. ${o.message}`);let{stateBranchRoot:s,offline:i,repoRoot:l}=o.value,u=il(s);return c(u)?u:(w({hasProjectDefinition:!0,syncStatus:i?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:h().syncStatus}),MS(l,e),d("Synced",!0))},MS=async(e,t)=>{let n=await Gs({repoRoot:e,minIntervalMs:t}),r=c(n)?null:Cc(n.value),o=h().syncStatus;r&&o?.status==="synced"&&w({syncStatus:{msg:`Synced \xB7 ${r}`,status:"synced"}})},il=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=Ct(e),n=ie("loadMergedEvents",mo(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!c(n),message:(c(n),n.message),count:c(n)?void 0:n.value.events.length}),c(n))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:h().syncStatus}),a(`Unable to load events. ${n.message}`);logger.debug("[sync] loaded merged events after sync",{count:n.value.events.length});let r=Sg();if(r)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:r.message,syncStatus:h().syncStatus}),r;let o=eg(),s=h().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id,selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual}),!h().selectedNode?.isVirtual&&!h().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:n.value.events.length});let l=ve(),u=!c(l)&&l.value.timeMode==="live",p=ie("bootStateFromEventLog",Lo(n.value.events,n.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!c(p),message:(c(p),p.message)}),c(p))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:h().syncStatus}),a(`Unable to boot synced state. ${p.message}`);u&&xs(e,t)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),w({filters:s}),logger.debug("[sync] restoreNavigationAnchor:start");let i=ie("restoreNavigationAnchor",ng(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!c(i),message:c(i)?i.message:"Navigation restored",selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id}),c(i)?(w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:h().syncStatus}),i):d("Reloaded state from event log",null)},Sg=()=>h().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:h().mode,syncStatus:h().syncStatus}),w({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Cg=0,al,cl=!1,Fo=!1,ll=()=>{if(cl)return!0;let e=ve();return c(e)?!1:e.value.syncStatus.status==="syncing"},kS=()=>{let e=rs(ee().autoSyncIntervalMs),t=Date.now()-Cg;return Math.max(0,e-t)},Ng=()=>{al||(al=setTimeout(async()=>{if(al=void 0,!!dt()){if(ll()){Fo=!0;return}Fo=!1,await LS()}},kS()))},LS=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!dt())return a("Cannot auto-sync before state is initialized");if(ll())return Fo=!0,a("Sync already in progress");cl=!0,Cg=Date.now(),w({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ui({reposMinIntervalMs:6e4})}finally{cl=!1,Fo&&Ng()}},Ig=()=>{dt()&&(Fo=!0,!ll()&&Ng())};var wg=e=>{let{context:t}=h().contextNode;if(!t)return G.None;switch(e){case b.EXIT:return G.Exit;case b.EXPORT:return G.Export;case b.INIT:return G.Init;case b.OPEN:return G.OpenProject;case b.DELETE:return G.Delete;case b.EDIT:return G.Edit;case b.COMMENT:return G.Comment;case b.HELP:return G.ViewHelp;case b.RE_OPEN_ISSUE:return G.ReopenIssue;case b.CLOSE_ISSUE:return G.CloseIssue;case b.TAG:return G.TagTicket;case b.UNTAG:return G.UntagTicket;case b.ASSIGN:return G.AssignUserToTicket;case b.UNASSIGN:return G.UnassignUserFromTicket;case b.NEW:return G.NewItem;case b.FILTER:return G.Filter;case b.MOVE:return G.Move;case b.PEEK:return G.Peek;case b.REPLAY:return G.Replay;case b.CONFIG:return G.Config;case b.YANK:return G.Yank;case b.SYNC:return G.Sync;default:return G.None}},G={Exit:"exit",Init:"init",OpenProject:"open-project",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"};import hh from"node:fs";import WC from"node:path";import GC from"react";import{Box as jC}from"ink";import Si from"react";import XS from"chalk";import{Box as ml,Text as JS}from"ink";import Bt from"react";import{Text as Ag}from"ink";import Tg,{useEffect as Mg,useState as PS}from"react";var kg={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},mt=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Le(),r=kg[n]??kg.default,[o,s]=PS(0);if(Mg(()=>{s(0)},[r]),Mg(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Tg.createElement(Ag,null,t);let i=r[o]??r[0]??t;return Tg.createElement(Ag,{color:A.accent,dimColor:o===1},i)};import{Box as dl,Text as OS}from"ink";import mi from"react";var DS=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,i=n+1,l=o(n);for(;i<t&&l+o(i)<=r;)l+=o(i),i++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:i}},pt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),p=Math.max(1,Math.floor(i/l)),m=Math.max(0,e.length-p),{start:f,end:g}=o?DS(o,e.length,u,i):s?{start:Math.min(m,Math.max(0,u-p+1)),end:Math.min(m,Math.max(0,u-p+1))+p}:{start:Math.min(m,Math.floor(u/p)*p),end:Math.min(m,Math.floor(u/p)*p)+p},x=Math.max(1,g-f),N=e.slice(f,g),E=e.length>x,R=i,v=E?Math.max(1,Math.floor(x/e.length*R)):R,I=Math.max(0,R-v),k=Math.max(1,e.length-x),M=E?Math.floor(f/k*I):0;return mi.createElement(dl,{flexDirection:"row",height:i,width:"100%"},mi.createElement(dl,{flexDirection:"column",flexGrow:1,height:i},N),mi.createElement(dl,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((L,P)=>mi.createElement(OS,{key:P,color:E&&P>=M&&P<M+v?A.accent:A.secondary},E?"\u2502":" "))))};import{Box as Cr,Text as Nr}from"ink";import Ye from"react";var Lg,ul,FS=()=>{let{eventLog:e=[]}=h();if(ul&&Lg===e)return ul;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Lg=e,ul=t,t},pi=e=>FS().has(e);import{Text as _S}from"ink";import $S from"react";var Rr=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Sn(o,n);return $S.createElement(_S,{underline:t,color:Be(o)},"@"+s,pi(e)?"":"\u2197")};import{Text as BS}from"ink";import US from"react";var fi=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getTag(e);if(!r)return;let o=n===void 0?r.name:Sn(r.name,n);return US.createElement(BS,{underline:t,backgroundColor:Be(r.name),color:A.secondary}," "+o+" ")};import{useEffect as jS,useState as HS}from"react";var WS=80,Pg=1400,gi=new Set,_o=null,GS=e=>(gi.add(e),_o||(_o=setInterval(()=>{for(let t of gi)t()},WS)),()=>{gi.delete(e),gi.size===0&&_o&&(clearInterval(_o),_o=null)}),zS=()=>{let e=Date.now()%Pg/Pg;return e<.5?e*2:(1-e)*2},Sr=e=>{let[,t]=HS(0);return jS(()=>{if(e)return GS(()=>t(n=>n+1))},[e]),od(zS())};var VS=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),Sn(e.slice(o).trim(),n)]},Og=3,qS=2,KS=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,l=i>0?String(i).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Dg=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Sr(r),s=e-4,i=s-7-1,[l,u]=VS(Ut(t.title),i,s),p=u?null:Sn(Ut(t.props.description),s)||null,m=en(t),f=tn(t).map(v=>({...v,name:v.name})),g=Math.max(1,s-Og),x=C.getCommentsByIssue(t.id),N=x.length?String(x.length).length+2+1:0,{shown:E,hidden:R}=KS([...m.map(v=>({id:v.id,isTag:!0,width:Math.min(v.name.length,g)+Og})),...f.map(v=>({id:v.id,isTag:!1,width:Math.min(v.name.length,g)+qS+(pi(v.id)?0:1)}))],s-N);return Ye.createElement(Cr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?A.accent:A.secondary,justifyContent:"space-between"},Ye.createElement(Cr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Ye.createElement(Cr,{justifyContent:"space-between"},Ye.createElement(Nr,{color:A.primary},l),Ye.createElement(Nr,{color:A.secondary2,dimColor:!0},nt(t.id))),u&&Ye.createElement(Nr,{color:A.primary},u),p&&Ye.createElement(Nr,{color:A.secondary2,dimColor:!0},p)),Ye.createElement(Cr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Ye.createElement(Cr,{flexDirection:"row"},E.map(v=>Ye.createElement(Cr,{paddingRight:1,key:v.id},v.isTag?Ye.createElement(fi,{id:v.id,maxWidth:g}):Ye.createElement(Rr,{id:v.id,maxWidth:g}))),R>0&&Ye.createElement(Nr,{color:A.secondary2,dimColor:!0},"+",R)),x.length>0&&Ye.createElement(Nr,{color:A.accent},"[",x.length,"]")))};import{Box as Bn,Text as $o}from"ink";import it from"react";var YS=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Fg=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=Sr(s),u=(r.props.tags??[]).map(L=>C.getTag(L)).filter(L=>!!L),p=(r.props.assignees??[]).map(L=>C.getContributor(L)).map(L=>L&&{...L,name:L.name}).filter(L=>!!L),m=1,f=u.length*(1+m),g=p.length*(2+m),x=u.map(L=>it.createElement(Bn,{key:L.id,paddingRight:m},it.createElement($o,{color:Be(L.name)},"\u25A0"))),N=p.map(L=>it.createElement(Bn,{key:L.id,paddingRight:m},it.createElement($o,{color:Vi(L.name)},"@"+L.name.at(0)))),E=s?l:o?A.accent:i===y.MOVE?A.secondary:A.primary,R=C.getCommentsByIssue(r.id),v=R.length?String(R.length).length+2+m:0,I=R.length?it.createElement(Bn,{paddingRight:m},it.createElement($o,{color:A.accent},"[",R.length,"]")):null,k=f+g+v,M=Math.max(1,n-t-k-(k>0?1:0));return it.createElement(Bn,{justifyContent:"space-between"},it.createElement(Bn,null,it.createElement(Bn,{width:t},o?it.createElement(mt,{isSelected:!0}):it.createElement($o,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),it.createElement($o,{wrap:"truncate",color:E},YS(r.title,M))),it.createElement(Bn,null,x,N,I))};var ZS=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:u,replay:p}=Le(),m=u[e.id]??[],f=p?new Set(p.flashNodeIds):null,g=f?.has(e.id)??!1,x=Sr(g),N=`${e.title} ${XS.hex(A.secondary2).dim("("+m.length+")")}`,E=3,R=o?1:5,v=s&&i===-1,I=n-3-(o?1:0)-(v?2:0),k=Math.max(2,String(m.length).length+1),M=r-E-1,L=Bt.createElement(ml,{borderStyle:"round",borderColor:A.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Bt.createElement(mt,{isSelected:t}),Bt.createElement(JS,{bold:!0,color:g?x:t?A.accent:A.primary},N," ",e.readonly?"\u{1F512}":"")),P=($,B)=>{let de=s&&i===B;if(!H($))return null;let O=f?.has($.id)??!1;return o?Bt.createElement(Fg,{key:$.id,index:B,labelWidth:k,width:I,ticket:$,isSelected:de,isFlashing:O,mode:l}):Bt.createElement(Dg,{key:$.id,width:I,ticket:$,isSelected:de,isFlashing:O})};return Bt.createElement(ml,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?A.accent:A.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},L,Bt.createElement(ml,null,m.length>0&&Bt.createElement(pt,{selectedIndex:i,height:M,itemHeight:R},m.map(P)),v&&Bt.createElement(mt,{isSelected:!0})))},_g=Bt.memo(ZS);import{Box as Tr,Text as DC}from"ink";import Xe,{useMemo as Mr}from"react";var $g=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},Bg=(e,t,n)=>Ne.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var Ug=e=>e.action==="add.issue.comment";import{Box as Ir,Text as Kt}from"ink";import $e,{useEffect as QS,useMemo as eC,useRef as tC}from"react";import{decodeTime as jg}from"ulid";var dn=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"},hi=e=>String(e).padStart(2,"0"),EB=e=>`${e.getFullYear()}-${hi(e.getMonth()+1)}-${hi(e.getDate())} ${hi(e.getHours())}:${hi(e.getMinutes())}`;var nC=e=>pe(e,"attachments"),rC=e=>C.getAttachmentsByIssue(e.id).sort((t,n)=>jg(t.id)-jg(n.id)),Hg=e=>{for(let t of e)C.deleteNode(t.id)},oC=(e,t,n)=>Ne.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),sC=(e,t)=>{let n=C.getNode(nC(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>oC(o,s,n.id)).map(o=>C.createNode(o)).filter(bt).map(({value:o})=>o).filter(Fe);return t.length>0&&h().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},iC=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Wg({ticket:e,width:t,height:n}){let r=eC(()=>rC(e),[e]),o=tC([]);QS(()=>(Hg(o.current),o.current=sC(e,r),()=>{Hg(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Le(),l=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?$e.createElement(Ir,{flexDirection:"column",width:t,height:n,padding:1},$e.createElement(Kt,{color:A.primary},"No attachments yet."),$e.createElement(Ir,{paddingTop:1},$e.createElement(Kt,{color:A.primary},"Attach images from the browser GUI"),$e.createElement(Kt,{color:A.accent}," epiq gui "),$e.createElement(Kt,{color:A.primary},"by dropping or pasting them."))):$e.createElement(Ir,{flexDirection:"column",width:t,height:n},$e.createElement(Ir,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},$e.createElement(Kt,{color:A.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),$e.createElement(pt,{height:l,itemHeight:2,selectedIndex:s},r.map((p,m)=>{let f=m===s,g=p.name.length>u?p.name.slice(0,u-1)+"\u2026":p.name;return $e.createElement(Ir,{key:p.id,flexDirection:"row",paddingX:1,paddingBottom:1},$e.createElement(Kt,{color:A.accent},f?"\u276F ":" "),$e.createElement(Ir,{paddingLeft:1},$e.createElement(Kt,{color:A.secondary2},`#${m+1} `),$e.createElement(Kt,{color:f?A.accent:A.primary},g),$e.createElement(Kt,{color:A.secondary2}," "+iC(p.bytes)+" "+dn(Rn(p.id)))))})))}import{Box as un,Text as mn}from"ink";import ke,{useEffect as mC,useMemo as Xg,useRef as pC}from"react";import{decodeTime as Jg}from"ulid";var aC=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let l=i;for(;l.length>n;)s&&(o.push(s),s=""),o.push(l.slice(0,n)),l=l.slice(n);s?s.length+1+l.length<=n?s=`${s} ${l}`:(o.push(s),s=l):s=l}return s&&o.push(s),o},Bo=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},cC=/!\[([^\]]*)\]\([^)]*\)/g,lC=e=>e.replace(cC,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),dC=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),uC=4,yi=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(uC)),pl=e=>{let t=!1;return e.map(yi).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Co(n);if(r)return{kind:"caption",text:Oc(r)};let o=lC(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:Bo(s[1]??"")}:{kind:"text",spans:Bo(o)}})},zg=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Gg=(e,t)=>{let n=[];for(let r of pl(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of zg(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of aC(dC(r.spans),t))n.push({kind:r.kind,spans:Bo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Vg=(e,t)=>{let n=Co(e),r=n?Kp(e):null;if(!n||r===null)return Gg(Pc(e).split(`
|
|
90
|
-
`),t);let o=Yp(e),s=r.split(`
|
|
91
|
-
`).map(yi),i=n.side===n.endSide?n.start:void 0,l=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...Gg(o.split(`
|
|
92
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:Oc(n)},...s.flatMap((u,p)=>zg(u,Math.max(1,t-l)).map((m,f)=>({kind:"code",text:m,number:i===void 0||f>0?void 0:i+p})))]};import{Box as qg,Text as Un}from"ink";import ft from"react";var Kg=({spans:e,bold:t,wrap:n})=>ft.createElement(Un,{color:A.primary,bold:t,wrap:n},e.map((r,o)=>r.code?ft.createElement(Un,{key:o,color:A.yellow},r.text):ft.createElement(Un,{key:o},r.text))),fl=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return ft.createElement(Un,null," ");case"fence":return ft.createElement(Un,{color:A.secondary2},"```");case"caption":return ft.createElement(Un,{color:A.accent,wrap:r},e.text);case"heading":return ft.createElement(Kg,{spans:e.spans,bold:!0,wrap:r});case"text":return ft.createElement(Kg,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return ft.createElement(Un,{backgroundColor:A.secondary,color:A.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},Yg=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return ft.createElement(qg,{flexDirection:"column"},e.map((o,s)=>ft.createElement(qg,{key:s},ft.createElement(fl,{line:o,width:t,gutter:r}))))};var fC=4,gC=e=>pe(e,"comments"),hC=e=>C.getCommentsByIssue(e.id).sort((t,n)=>Jg(t.id)-Jg(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),Zg=e=>{for(let t of e)C.deleteNode(t.id)},yC=(e,t)=>{let n=C.getNode(gC(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>Bg(o,s,n.id)).map(C.createNode).filter(bt).map(({value:o})=>o).filter(_r);return t.length>0&&h().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r};function Qg({ticket:e,width:t,height:n}){let r=Xg(()=>hC(e),[e]),o=pC([]);mC(()=>(Zg(o.current),o.current=yC(e,r),()=>{Zg(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Le(),l=Math.max(1,n-4),u=Math.max(20,t-8),p=Xg(()=>r.map(f=>{let g=Vg(f.md,u);return g.length>0?g:[{kind:"blank"}]}),[r,u]),m=p.map(f=>f.length+fC);return r.length===0?ke.createElement(un,{flexDirection:"column",width:t,height:n,padding:1},ke.createElement(mn,{color:A.primary},"No comments yet."),ke.createElement(un,{paddingTop:1},ke.createElement(mn,{color:A.primary},"Use"),ke.createElement(mn,{color:A.accent}," :comment "),ke.createElement(mn,{color:A.primary},"to add the first one."))):ke.createElement(un,{flexDirection:"column",width:t,height:n},ke.createElement(un,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},ke.createElement(mn,{color:A.secondary2},"Comments (",r.length,") ")),ke.createElement(pt,{height:l,itemHeights:m,selectedIndex:s},r.map((f,g)=>{let x=g===s;return ke.createElement(un,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:A.secondary,borderStyle:"single"},ke.createElement(un,{flexDirection:"row",paddingBottom:1},ke.createElement(mn,{color:A.accent},x?"\u276F ":" "),ke.createElement(un,{paddingLeft:1},ke.createElement(mn,{color:A.secondary2},`#${g+1} `),ke.createElement(Rr,{id:f.authorId}),ke.createElement(mn,{color:A.secondary2}," "+dn(Rn(f.id))))),ke.createElement(un,{paddingLeft:3,paddingBottom:1},ke.createElement(Yg,{lines:p[g]??[],width:u})))})))}import{Box as Hn,Text as At}from"ink";import Ae,{useEffect as ch,useRef as NC,useState as IC}from"react";import{Box as wt,Text as Yt}from"ink";import Ee,{useEffect as bl,useMemo as rh,useRef as xC,useState as EC}from"react";var bi=(e,t,n)=>{let r=[],o=Ms(()=>{for(let s=0;s<t;s++){let i=st(BigInt(s+1));if(!bt(i))continue;let l=C.createNode(Ne.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));bt(l)&&r.push(l.value)}});return c(o)&&logger.error(`Line nodes: ${o.message}`),r},wr=e=>{C.deleteNodes(e.map(t=>t.id))};import{useSyncExternalStore as bC}from"react";var xi=null,vi=null,gl=new Set,eh=()=>{for(let e of gl)e()},hl=e=>{xi=e,eh()},Ei=()=>xi,th={mark:null},jn=e=>{vi=e,th={mark:e},eh()};var yl=e=>vi&&vi.sha===e?vi.row:null,nh=()=>bC(e=>(gl.add(e),()=>{gl.delete(e)}),()=>th),pn=()=>{let{contextNode:e}=h();return xi&&xi.sha===e.id?e.id:null};import RC from"string-width";var vl=(e,t)=>`${e}::patch::${t}`,oh=e=>yi(e).replace(/[\x00-\x1f\x7f-\x9f]/g,"\uFFFD"),SC=e=>{switch(e){case"added":return A.green;case"removed":return A.red;case"hunk":return A.accent;case"file":return A.primary;default:return A.secondary2}},sh=(e,t)=>{let n=RC(e);return n>=t?e:e+"\xA0".repeat(t-n)},CC=e=>e==="added"?"+":e==="removed"?"-":" ",ih=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine);function ah({ticket:e,sha:t,repo:n,subject:r,width:o,height:s}){let[i,l]=EC({state:"loading"});bl(()=>{let M=!0;return l({state:"loading"}),Lc({sha:t,repo:n}).then(L=>{M&&l(c(L)?{state:"failed",message:L.message}:{state:"loaded",rows:_c(Fc(L.value))})}),()=>{M=!1}},[t,n]);let u=i.state==="loaded"?i.rows:null,p=u!==null&&u.length>4e3,m=xC([]);bl(()=>(wr(m.current),m.current=u&&!p?bi(t,u.length,M=>vl(t,M)):[],()=>{wr(m.current),m.current=[]}),[t,u,p]),bl(()=>(hl(u?{sha:t,rows:u}:null),jn(null),()=>{hl(null),jn(null)}),[t,u]);let{selectedIndex:f}=Le(),{mark:g}=nh(),x=rh(()=>u?$c(u,C.getCommentsByIssue(e.id),t):new Set,[u,t,e]),N=g&&g.sha===t?g.row:null,E=M=>N!==null&&M>=Math.min(N,f)&&M<=Math.max(N,f),R=rh(()=>u?Math.max(5,u.reduce((M,L)=>Math.max(M,ih(L).length),0)+2):5,[u]),v=Math.max(1,s-4),I=Math.max(8,o-R-6);if(i.state!=="loaded")return Ee.createElement(wt,{flexDirection:"column",width:o,height:s,padding:1},Ee.createElement(Yt,{color:A.primary},i.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${i.message}`));let k=M=>Ee.createElement(wt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},Ee.createElement(Yt,{color:A.secondary2,wrap:"truncate-end"},Cn(`${t.slice(0,7)} ${r} \u2014 ${M}`,Math.max(8,o-6))));return i.rows.length===0?Ee.createElement(wt,{flexDirection:"column",width:o,height:s},k("no changes"),Ee.createElement(wt,{paddingX:1},Ee.createElement(Yt,{color:A.primary},"This commit changed no files."))):p?Ee.createElement(wt,{flexDirection:"column",width:o,height:s},k("too large to draw here"),Ee.createElement(wt,{paddingX:1,flexDirection:"column"},Ee.createElement(Yt,{color:A.primary},`${i.rows.length.toLocaleString()} lines of diff.`),Ee.createElement(Yt,{color:A.secondary2},"Press o to open it in your editor."))):Ee.createElement(wt,{flexDirection:"column",width:o,height:s},k(N===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),Ee.createElement(pt,{scrollByOne:!0,height:v,selectedIndex:f,itemHeight:1},i.rows.map((M,L)=>{let P=L===f,$=SC(M.kind);if(M.kind==="file")return Ee.createElement(wt,{key:vl(t,L),paddingX:1},Ee.createElement(Yt,{backgroundColor:A.secondary,color:P?A.accent:$,bold:!0,wrap:"truncate-end"},sh(` ${Cn(oh(M.text),I)}`,I+R+1)));let B=E(L),de=`${CC(M.kind)}${Cn(oh(M.text),I)}`;return Ee.createElement(wt,{key:vl(t,L),paddingX:1},Ee.createElement(wt,{flexShrink:0},Ee.createElement(Yt,{color:P||B?A.accent:A.secondary2,dimColor:!P&&!B,wrap:"truncate-end"},`${P?"\u276F":"\xA0"}${B?"\u258C":"\xA0"}${ih(M).padStart(R-2,"\xA0")}`)),Ee.createElement(wt,{flexShrink:0},Ee.createElement(Yt,{color:A.yellow,wrap:"truncate-end"},x.has(L)?"\u2502":"\xA0")),Ee.createElement(Yt,{color:P?A.accent:$,backgroundColor:P||B?A.secondary:void 0,wrap:"truncate-end"},P||B?sh(de,I+1):de))})))}var wC=e=>pe(e,"diff"),lh=e=>{for(let t of e)C.deleteNode(t.id)},AC=(e,t,n)=>Ne.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),TC=(e,t)=>{let n=C.getNode(wC(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>AC(o,s,n.id)).map(o=>C.createNode(o)).filter(bt).map(({value:o})=>o).filter(Fe);return t.length>0&&h().selectedIndex<0&&h().contextNode.id===n.id&&U.navigate({contextNode:n,selectedIndex:0}),r},MC=e=>`+${e.insertions} -${e.deletions}`;function dh({ticket:e,width:t,height:n}){let[r,o]=IC({state:"loading"}),s=nt(e.id);ch(()=>{let E=!0;return o({state:"loading"}),mc({ref:s}).then(R=>{if(!E)return;let v=St();o(c(R)?{state:"failed",message:R.message}:{state:"loaded",commits:R.value,labels:c(v)?new Map:rc(v.value)})}),()=>{E=!1}},[s]);let i=NC([]),l=r.state==="loaded"?r.commits:null,u=r.state==="loaded"?r.labels:null;ch(()=>(lh(i.current),i.current=l?TC(e,l):[],()=>{lh(i.current),i.current=[]}),[e,l]);let{selectedIndex:p,contextNode:m}=Le(),f=l?.find(E=>E.sha===m.id)??null,x=Math.max(1,n-4),N=Math.max(12,t-34);return r.state!=="loaded"?Ae.createElement(Hn,{flexDirection:"column",width:t,height:n,padding:1},Ae.createElement(At,{color:A.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):f?Ae.createElement(ah,{ticket:e,sha:f.sha,repo:f.repo,subject:f.subject,width:t,height:n}):r.commits.length===0?Ae.createElement(Hn,{flexDirection:"column",width:t,height:n,padding:1},Ae.createElement(At,{color:A.primary},"No commits reference this ticket."),Ae.createElement(Hn,{paddingTop:1},Ae.createElement(At,{color:A.primary},"Commits are matched by the"),Ae.createElement(At,{color:A.accent},` ${s} `),Ae.createElement(At,{color:A.primary},"prefix on their subject line."))):Ae.createElement(Hn,{flexDirection:"column",width:t,height:n},Ae.createElement(Hn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},Ae.createElement(At,{color:A.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),Ae.createElement(pt,{height:x,itemHeight:2,selectedIndex:p},r.commits.map((E,R)=>{let v=R===p,I=E.subject.length>N?E.subject.slice(0,N-1)+"\u2026":E.subject;return Ae.createElement(Hn,{key:E.sha,flexDirection:"row",paddingX:1,paddingBottom:1},Ae.createElement(At,{color:A.accent},v?"\u276F ":" "),Ae.createElement(Hn,{paddingLeft:1},Ae.createElement(At,{color:A.secondary2},`${E.sha.slice(0,7)} `),E.repo&&Ae.createElement(At,{color:A.secondary2},`[${u?.get(E.repo)??Dr(E.repo)}] `),Ae.createElement(At,{color:v?A.accent:A.primary},I),Ae.createElement(At,{color:A.secondary2},` ${MC(E)} ${dn(E.time)}`)))})))}import{Box as Ri,Text as kC}from"ink";import Xt from"react";var uh=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Le(),{title:o}=t,s=t.parentNodeId?C.getNode(t.parentNodeId):void 0,i=s&&H(s)?o===me.ASSIGNEES?s.props.assignees??[]:o===me.TAGS?(s.props.tags??[]).filter(l=>C.getTag(l)):[]:[];return Xt.createElement(Ri,{alignItems:"center",paddingTop:1},Xt.createElement(Ri,{minWidth:12},Xt.createElement(mt,{isSelected:n}),Xt.createElement(kC,{color:n?A.accent:A.secondary2},o,":")),Xt.createElement(Ri,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,u)=>{let p=r.id===t.id&&u===e;return Xt.createElement(Ri,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Xt.createElement(mt,{isSelected:p}),o===me.ASSIGNEES?Xt.createElement(Rr,{isSelected:p,id:l}):o===me.TAGS?Xt.createElement(fi,{isSelected:p,id:l}):null)})))};import{Box as Ar,Text as Rl}from"ink";import gt,{useEffect as LC,useMemo as Sl,useRef as PC}from"react";var xl=e=>Math.max(5,String(Math.max(e,1)).length+3),mh=(e,t)=>Math.max(0,e-6-xl(t));var El=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0));var OC="\u2029",ph=(e,t)=>`${e}::inline-line::${t}`,Cl=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=Le(),u=Sl(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),p=Sl(()=>u.join("\0"),[u]),m=PC([]);LC(()=>(wr(m.current),m.current=bi(e,u.length,E=>ph(e,E)),()=>{wr(m.current),m.current=[]}),[e,p]);let f=xl(u.length),g=mh(s,u.length),N=Sl(()=>pl(u).map(E=>{if(E.kind==="code"||E.kind==="caption")return{...E,text:Cn(E.text,g)};if(E.kind==="text"||E.kind==="heading"){let R=E.spans.map(v=>v.code?`\`${v.text}\``:v.text).join("");return{...E,spans:Bo(Cn(R,g))}}return E}),[u,g]).map((E,R)=>{let v=l.id===e&&i===R;return gt.createElement(Ar,{key:ph(e,R)},gt.createElement(Ar,{flexShrink:0},gt.createElement(Rl,{color:v?A.primary:A.secondary2,dimColor:!v},`${R+1} `.padStart(f,"\xA0"))),E.kind==="blank"?gt.createElement(Rl,{backgroundColor:v?"gray":void 0},OC):gt.createElement(Ar,null,gt.createElement(fl,{line:E,width:E.kind==="code"?g:0,wrap:"truncate-end"})))});return gt.createElement(Ar,{flexDirection:"column",paddingTop:1},gt.createElement(Ar,null,gt.createElement(mt,{isSelected:o}),gt.createElement(Rl,{color:o?A.accent:A.secondary2},t)),gt.createElement(Ar,{flexDirection:"row",borderStyle:"round",borderColor:A.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},gt.createElement(pt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},N)))};var FC=e=>pe(e,"description"),_C=e=>pe(e,"comments"),$C=e=>pe(e,"history"),BC=e=>pe(e,"diff"),UC=e=>pe(e,"attachments"),fh=({ticket:e,height:t})=>{let n=Mr(()=>$g(e),[e]),{selectedIndex:r,contextNode:o}=Le(),s=process.stdout.columns||120,i=Mr(()=>FC(e.id),[e.id]),l=Mr(()=>_C(e.id),[e.id]),u=Mr(()=>$C(e.id),[e.id]),p=Mr(()=>BC(e.id),[e.id]),m=Mr(()=>UC(e.id),[e.id]),f=C.getAttachmentsByIssue(e.id).length,g=o.id===e.id,x=o.id===l||o.parentNodeId===l,N=o.id===u||o.parentNodeId===u,E=o.id===m||o.parentNodeId===m,R=o.id===p||o.parentNodeId===p,v=ae(e.id);if(x){let q=t-3;return Xe.createElement(Tr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Xe.createElement(Qg,{ticket:e,width:s,height:q}))}if(E){let q=t-3;return Xe.createElement(Tr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Xe.createElement(Wg,{ticket:e,width:s,height:q}))}if(R){let q=t-3;return Xe.createElement(Tr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Xe.createElement(dh,{ticket:e,width:s,height:q}))}if(N){let O=C.getNode(u),q=O&&Fe(O)?O.props.value??"":"",Pe=El(t);return Xe.createElement(Tr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},O?Xe.createElement(Cl,{id:O.id,label:"Event log",text:q,selected:!1,maxWidth:s,rows:Pe}):null)}let I=[u,p,l,m],k=O=>I.includes(O),M=v.reduce((O,q)=>Fr(q)?O+1:O,0),L=v.reduce((O,q)=>k(q.id)?O+1:O,0),P=v.findIndex(O=>k(O.id)),$=El(t,M,L),B=(O,q,Pe,Pr)=>Xe.createElement(Tr,{key:O.id,paddingTop:q===P?1:0},Xe.createElement(mt,{isSelected:Pe}),Xe.createElement(DC,{backgroundColor:A.secondary,color:Pe?A.accent:A.primary},Pr)),de=(O,q,Pe)=>O.id===i?Xe.createElement(Cl,{key:O.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:q,maxWidth:s,rows:$}):Fr(O)?Xe.createElement(uh,{key:O.id,parent:O,selected:q,selectedIndex:r}):O.id===l?B(O,Pe,q,` Comments (${n}) \u203A\u203A `):O.id===m?B(O,Pe,q,` Attachments (${f}) \u203A\u203A `):O.id===u?B(O,Pe,q," History \u203A\u203A "):O.id===p?B(O,Pe,q," Diff \u203A\u203A "):null;return Xe.createElement(Tr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},v.map((O,q)=>de(O,g&&r===q,q)))};var HC=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let u=t.context,p=u===te.TICKET||u===te.FIELD_LIST||u===te.FIELD,m=u===te.BOARD||u===te.SWIMLANE,f=u===te.TICKET?t:r.find(R=>R.context===te.TICKET),g=Math.floor(l/3),x=Math.floor(l/Math.max(e.length,1)),N=Math.min(x,g),E=s==="dense";return Si.createElement(jC,{flexDirection:"row",height:i},m&&e.map((R,v)=>{let I=t.id===R.id,k=I?n:-1,M=t.context===te.BOARD&&n===v;return Si.createElement(_g,{key:R.id,height:i,width:N,swimlane:R,isSelected:M,isDense:E,isFocused:I,listSelectedIndex:k,mode:o})}),p&&f&&Si.createElement(fh,{height:i,ticket:f}))},gh=Si.memo(HC);import{render as zC}from"ink";import{Writable as VC}from"node:stream";var Uo=e=>String(e).padStart(2,"0"),qC=e=>{let t=e.getUTCFullYear(),n=Uo(e.getUTCMonth()+1),r=Uo(e.getUTCDate()),o=Uo(e.getUTCHours()),s=Uo(e.getUTCMinutes()),i=Uo(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},KC=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",YC=async(e,{width:t,height:n})=>{let r="",o=new VC({write(i,l,u){let p=XC(i.toString()).trimEnd();p.trim().length>0&&p.includes("\u256D")&&(r=p),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=zC(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},XC=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),yh=async()=>{let{viewMode:e}=ee(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=h(),i=r.find(v=>v.context==="BOARD");if(!i)return a("No board found to export");let l=120,u=40,p=await YC(GC.createElement(gh,{height:u,width:l,swimlanes:(s[i.id]??[]).filter(v=>v!==void 0&&ts(v)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!p)return a("Failed to render board export");let m=os(process.cwd());if(c(m))return a("Unable to export, epiq root not found");let f=new Date,g=qC(f),x=`board_${KC(i.title)}_${g}.md`,N=uu(m.value);hh.mkdirSync(N,{recursive:!0});let E=WC.join(N,x),R=`# Board - ${i.title}
|
|
93
|
-
Date: ${f.toISOString()}
|
|
94
|
-
|
|
95
|
-
\`\`\`text
|
|
96
|
-
${p}
|
|
97
|
-
\`\`\`
|
|
98
|
-
`;return hh.writeFileSync(E,R,"utf8"),d("Exported board layout",E)};import{useSyncExternalStore as f1}from"react";var Ci,JC=new Set,bh=()=>{for(let e of JC)e()};var kr=()=>{if(!Ci)throw new Error("Ui state not initialized. Call initUiState() first.");return Ci};var y1=(e={})=>(Ci=e,bh(),d("UX state initialized",null)),ZC=e=>{let t=kr();return Ci=e(t),bh(),d("UX state updated",null)},fn=e=>ZC(t=>({...t,...e}));import{ulid as Nl}from"ulid";var vh=async e=>{let{contextNode:t,selectedIndex:n}=h(),r=ae(t.id)[n];if(e.modifier===tt.DESCRIPTION)return eN();if(r&&_r(r))return QC(e);if(e.modifier===tt.TITLE){let o=oe();if(c(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 l=await le();return c(l)?l:Q([{id:Nl(),action:"edit.title",payload:{id:s.id,name:i},...re(o.value)}],l.value)}return a("Unknown edit command")},QC=async e=>{let t=oe();if(c(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=h(),o=ae(n.id)[r];if(!o||!_r(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=h().nodes[s];if(!i||!H(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",u=C.getComment(l);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 p=e.inputString.trim();if(!p)return a("Provide a comment");let m=await le();if(c(m))return m;let f=m.value;return Q([{id:Nl(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:p},...re(t.value)}],f)},eN=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let t=await le();if(c(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=h(),s=Ze([...r,o],"TICKET");if(c(s))return a("Edit target must be an issue");let i=s.value;if(!H(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let l=ae(i.id).find(f=>f.title===me.DESCRIPTION);if(!l)return a("No target found");if(l.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 p=af(u);if(c(p))return a("Failed to edit field");let m=p.value;return m===u?d("No changes made",null):Q([{id:Nl(),action:"edit.description",payload:{id:i.id,md:m},...re(e.value)}],n)};import nN from"node:fs";import wl from"node:path";import Il from"node:fs";import tN from"node:path";var xh=async e=>{let t=tN.join(e,".gitignore"),n=Il.existsSync(t)?Il.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
99
|
-
`).map(u=>u.trim()),s=r.filter(u=>!o.some(p=>p===u||p===u.replace(/\/$/,"")||p==="/"+u||p==="/"+u.replace(/\/$/,"")));if(s.length===0)return d("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
100
|
-
`);return n=n.trimEnd()+`
|
|
101
|
-
|
|
102
|
-
${l}
|
|
103
|
-
`,Il.writeFileSync(t,n,"utf8"),j.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),d("Local epiq paths ignored",!0)};var rN=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return c(t)?t:d("Checked git diff",t.value.stdout.split(`
|
|
104
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},ne=(e,t)=>a(`[${e}] ${t}`),Eh=async({cwd:e,user:t})=>{let n=ds(),r=await Rt(e);if(c(r))return ne(1,r.message);let o=r.value,s=await zd(o);if(c(s))return ne(2,s.message);if(s.value)return ne(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await rN(o);if(c(i))return ne(2.5,i.message);if(i.value.length>0)return ne(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(qr(o))return ne(4,"Epiq project already initialized");let{userId:l,userName:u}=t;if(!l||!u)return ne(5,"Missing Epiq user id");let p=await gg(o);if(c(p))return ne(6,p.message);let m=n.stateBranch,f=await as({repoRoot:o,branch:m});if(c(f))return ne(6,f.message);if(f.value)return ne(6,`State branch already exists: ${m}`);let g=await oN({repoRoot:o,stateBranch:m});if(c(g))return ne(6,g.message);if(g.value)return sN({repoRoot:o,stateBranch:m});let x=await rl({repoRoot:o,stateBranchName:m});if(c(x))return ne(6,x.message);let N=Wr();if(c(N))return ne(7,N.message);let E=wl.join(Nn(),n.projectId),R=await xr({repoRoot:o,stateBranchRoot:E,stateBranchName:m});if(c(R))return ne(8,R.message);let v=wl.join(E,".epiq");nN.mkdirSync(v,{recursive:!0});let I=rg({userId:l,userName:u});if(c(I))return ne(9,I.message);for(let Yy of I.value){let jl=_m({event:Yy,rootDir:E});if(c(jl))return ne(9,jl.message)}let k=lr({userId:l}),M=Cs(E,k);if(c(M))return ne(9,M.message);let L=nl(E,n);if(c(L))return ne(9,L.message);let P=await li({stateBranchRoot:E,eventFileName:k});if(c(P))return ne(10,P.message);let $=await ue.stage({cwd:E,pathspec:[_e]});if(c($))return ne(10,$.message);let B=await Qn({cwd:E,message:"[epiq:init]"});if(c(B))return ne(10,B.message);let de=await xh(o);if(c(de))return ne(11,de.message);let O=ba({repoRoot:o,fileContents:n});if(c(O))return ne(12,O.message);let q=await ue.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(c(q))return ne(13,q.message);let Pe=await ue.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(c(Pe))return ne(13,Pe.message);let Pr=[],Bl=await _({cwd:o,args:["push","-u","origin","HEAD"]});c(Bl)&&Pr.push(`[init:14] ${Bl.message}`);let Ul=await Do({repoRoot:o,stateBranchRoot:E});return c(Ul)&&Pr.push(`[init:15] ${Ul.message}`),d("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:m,stateBranchRoot:E,defaultEvents:I.value,warnings:Pr})},oN=async({repoRoot:e,stateBranch:t})=>{let n=await jt({repoRoot:e});if(c(n))return a(n.message);if(!n.value)return d("No remote",!1);let r=await Br({repoRoot:e,branch:t});return c(r)?a(`Could not ask origin whether ${t} exists: ${r.message}`):r},sN=async({repoRoot:e,stateBranch:t})=>{let n=await _({cwd:e,args:["fetch","origin",t]});if(c(n))return ne(6,n.message);let r=await _({cwd:e,args:["show",`origin/${t}:${_e}`]});if(c(r))return ne(6,[`This repository is already an epiq project: origin has the state branch ${t}.`,"Initialising again would mint a second id for the same board.","","The branch was written before branches carried their identity, so restore",`${_e} from a checkout that has it, for example:`,"",` git show origin/main:${_e} > ${_e}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
|
|
105
|
-
`));let o;try{o=JSON.parse(r.value.stdout)}catch(N){return ne(6,`The identity on origin/${t} is not readable: ${N instanceof Error?N.message:String(N)}`)}let s=ba({repoRoot:e,fileContents:o});if(c(s))return ne(12,s.message);let i=await ue.stage({cwd:e,pathspec:[_e]});if(c(i))return ne(13,i.message);let l=await ue.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[_e]});if(c(l))return ne(13,l.message);let u=Wr();if(c(u))return ne(7,u.message);let p=wl.join(Nn(),o.projectId),m=await ol({repoRoot:e,stateBranchName:t});if(c(m))return ne(8,m.message);let f=await xr({repoRoot:e,stateBranchRoot:p,stateBranchName:t});if(c(f))return ne(8,f.message);let g=[],x=await _({cwd:e,args:["push","-u","origin","HEAD"]});return c(x)&&g.push(`[init:14] ${x.message}`),d("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:p,defaultEvents:[],warnings:g})};var jo=(e,t)=>a(`[${e}] ${t}`),Rh=async()=>{K("");let e=Zr();if(!e.isSetupDone||!e.userName)return jo(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=ee(),n=t.userName,r=t.userId;if(!r||!n)return jo(5,"Missing Epiq user id");let o=await Eh({cwd:process.cwd(),user:{userId:r,userName:n}});if(c(o))return o;let s="Project initialized!";for(let g of o.value.warnings)s+=` Warn: ${g}`;let l=sn(o.value.defaultEvents).filter(c);if(l.length>0)return jo(16,l.map(g=>g.message).join(`
|
|
106
|
-
`));let u=ve();if(c(u))return jo(16,u.message);let{rootNodeId:p,nodes:m}=u.value,f=m[p];return f?(U.navigate({contextNode:f,selectedIndex:0}),w({hasProjectDefinition:!0}),d(s,null)):jo(16,"Unable to resolve initialized root node")};import{ulid as aN}from"ulid";import{ulid as iN}from"ulid";var Sh=null,Tt=()=>structuredClone(Sh),Ho=e=>{Sh=e},Ch=()=>{let{contextNode:e,selectedIndex:t}=h(),r=he(e.id)[t];return r?d("Resolved selected child",r):a("Target node not found")},Al=({id:e,parentId:t,position:n={at:"end"}})=>{let r=he(t).filter(o=>o.id!==e);return ei(r,n)},Nh=({id:e,parentId:t,position:n={at:"end"}})=>{let r=oe();if(c(r))return a("Unable to resolve user ID");let o=Al({parentId:t,id:e,position:n});return c(o)?o:d("Created pending move state",{id:iN(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Ih=e=>{Ho(e);let t=uo(e,!0);return c(t)?t:d("Node moved successfully",t.value)};function Tl(e){let t=Ch();if(c(t))return t;let{contextNode:n,nodes:r}=h();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=he(o.id),i=s.findIndex(({id:p})=>p===n.id);if(i<0)return a("Current node not found among siblings");let l=s[i+e];if(!l)return a("Missing sibling node");let u=Nh({id:t.value.id,parentId:l.id,position:{at:"end"}});return c(u)?u:Ih(u.value)}function Wo(e,t=1){let n=Ch();if(c(n))return n;let{contextNode:r,selectedIndex:o}=h(),s=he(r.id),i=Math.min(Math.max(o+e*t,0),s.length-1),l=i===o?void 0:s[i];if(!l)return a("Missing sibling node");let u=Nh({id:n.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:l.id}});return c(u)?u:Ih(u.value)}var wh=()=>{let e=Tt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=h().nodes[n];if(!r)return a("Move parent not found");let o=he(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(U.navigate({contextNode:r,selectedIndex:o}),d("Synchronized navigation to moved node",null))},Lr=(e,t="Moved preview")=>{if(c(e))return Tt()&&w({mode:y.MOVE}),e;let n=wh();return c(n)?n:(w({mode:y.MOVE}),d(t,null))},Ah=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{modifier:t}=Y().commandMeta,{contextNode:n,selectedIndex:r}=h(),o=he(n.id)[r];if(!o)return w({mode:y.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=he(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let l=s[i-1],u=s[i+1],p=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},m=Al({parentId:o.parentNodeId,id:o.id,position:p});return c(m)?m:(Ho({id:aN(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:m.value.rank},...re(e.value)}),w({mode:y.MOVE}),d("Move initialized",null))}if(t==="next")return Lr(Wo(1));if(t==="previous")return Lr(Wo(-1));if(t==="jump-next")return Lr(Wo(1,Mo));if(t==="jump-previous")return Lr(Wo(-1,Mo));if(t==="to-next")return Lr(Tl(1));if(t==="to-previous")return Lr(Tl(-1));if(t==="confirm"){let s=Tt();if(!s)return a("No pending move to confirm");let i=await le();if(c(i))return i;let l=Q([s],i.value);if(c(l))return l;let u=wh();return c(u)?u:(Ho(null),w({mode:y.DEFAULT}),d("Moved item",null))}return t==="cancel"?(Ho(null),w({mode:y.DEFAULT}),d("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Ni}from"ulid";import{monotonicFactory as cN,ulid as lN}from"ulid";var dN=cN(),Th=({name:e,parent:t,rank:n,user:{userId:r}})=>{let o=dN();return d("Created issue events",[{id:lN(),userId:r,action:"add.issue",payload:{id:o,parent:t,name:e,rank:n}}])};var Mh=async(e,t)=>{let n=oe();if(c(n))return a("Unable to resolve user ID");let r=await le();if(c(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:l}=h(),u=p=>{let m=Q([p],o);if(c(m))return m;let f=C.getNode(m.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return m;let g=C.getNode(f.parentNodeId);return g?(U.navigate({contextNode:g,selectedIndex:C.getSiblings(f.parentNodeId).findIndex(({id:x})=>x===f.id)}),m):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:p}=h(),m=C.getNode(p);if(!m)return a("Workspace not found");let f=ni(m.id,n.value,o);return c(f)?f:u({id:Ni(),action:"add.board",payload:{id:Ni(),name:t.inputString,parent:m.id,rank:f.value},...re(n.value)})}if(t.modifier==="swimlane"){let p=Ze(s,"BOARD");if(c(p))return a("Unable to add swimlane in this context");let m=ni(p.value.id,n.value,o);return c(m)?m:u({id:Ni(),action:"add.swimlane",payload:{id:Ni(),name:t.inputString,parent:p.value.id,rank:m.value},...re(n.value)})}if(t.modifier==="issue"){let p=ae(i.id)[l],m=i.context==="SWIMLANE"?i:i.context==="BOARD"&&p?.context==="SWIMLANE"?p:(()=>{let I=Ze(s,"SWIMLANE");return c(I)?null:I.value})();if(!m)return a("Unable to add issue in this context");let f=ni(m.id,n.value,o);if(c(f))return f;let g=Th({name:t.inputString,parent:m.id,rank:f.value,user:n.value});if(c(g))return g;let x=g.value,N=Q([...x],o);if(c(N))return N;if(!N.value[0])return a("Issue creation failed");let v=x.find(I=>I.action==="add.issue")?.payload.id;return v?(U.navigate({contextNode:m,selectedIndex:C.getSiblings(m.id).findIndex(({id:I})=>I===v)}),d("Issue created",null)):a("Unable to determine ticket id")}return d("Success",null)};import xN from"node:os";import $h from"node:path";import Go from"node:fs";import uN from"node:path";import{z as Wn}from"zod";var zo="command-history.json",mN=20,pN=Wn.object({projectId:Wn.string().min(1),commands:Wn.array(Wn.string()),lastUsedAt:Wn.number().finite()}),fN=Wn.object({projects:Wn.array(pN)}),kh=()=>{let e=No();return c(e)?e:d("Resolved command history path",uN.join(e.value,zo))},gN=()=>{try{let e=xe(process.cwd());return c(e)?null:e.value}catch{return null}},Lh=e=>{if(!Go.existsSync(e))return d("No command history recorded",{state:"read",projects:[]});let t;try{t=Go.readFileSync(e,"utf8")}catch(o){return a(`Unable to read ${zo}: ${o instanceof Error?o.message:String(o)}`)}let n;try{n=JSON.parse(t)}catch(o){return d("Unparsable command history",{state:"corrupt",reason:`Invalid ${zo}: ${o instanceof Error?o.message:String(o)}`})}let r=fN.safeParse(n);return r.success?d("Read command history",{state:"read",projects:r.data.projects}):d("Command history in an unknown shape",{state:"corrupt",reason:`Invalid ${zo} shape: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`})},Ph=({root:e})=>{let t=kt(e);if(c(t))return a(t.message);let n=kh();if(c(n))return n;let r=Lh(n.value);if(c(r))return r;let o=r.value;if(o.state==="corrupt")return a(o.reason);let s=o.projects.find(i=>i.projectId===t.value);return d("Read command history",s?.commands.slice(0,wo)??[])},Oh=({commands:e,root:t=gN(),now:n=Date.now()})=>{if(t===null)return d("No project; command history not stored",null);let r=kt(t);if(c(r))return a(r.message);let o=kh();if(c(o))return o;let s=o.value,i=Lh(s);if(c(i))return i;let l=i.value,u=l.state==="read"?l.projects:[],p=[{projectId:r.value,commands:e.slice(0,wo),lastUsedAt:n},...u.filter(f=>f.projectId!==r.value)].sort((f,g)=>g.lastUsedAt-f.lastUsedAt).slice(0,mN),m=`${s}.${process.pid}.tmp`;try{Go.writeFileSync(m,JSON.stringify({projects:p},null,2)+`
|
|
107
|
-
`,"utf8"),Go.renameSync(m,s)}catch(f){try{Go.rmSync(m,{force:!0})}catch{}return a(`Unable to write ${zo}: ${f instanceof Error?f.message:String(f)}`)}return d("Stored command history",null)};var hN=e=>e.some(t=>t.action==="init.workspace"),Dh=async(e,t)=>{let n=Et(e);return c(n)?a(n.message):jr({cwd:t,branch:n.value})},yN=e=>{let t=xe(process.cwd());if(c(t))return!1;let n=ye({repoRoot:t.value});return!c(n)&&n.value===e},Ml=!1,kW=()=>Ml,Fh=async e=>{Ml=!0;try{return await bN(e)}finally{Ml=!1}},bN=async e=>{let t=ye({repoRoot:e});if(c(t))return $n(3,t.message);let n=t.value,r=await xr({repoRoot:e,stateBranchRoot:n,stateBranchName:ds().stateBranch});if(c(r))return $n(3,r.message);let o=Ct(n),s=mo(n);if(c(s))return $n(3,s.message);if(!hN(s.value.events)){let f=await bo({worktreeRoot:n,operation:"boot pull",fn:()=>di(n,()=>Dh(e,n))});if(c(f)?logger.info(3,f.message):f.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):c(f.value)&&logger.info(3,f.value.message),o=Ct(n),s=mo(n),c(s))return $n(3,s.message)}let{events:i,unreadable:l}=s.value,u=Lo(i,l);if(c(u))return $n(4,u.message);xs(n,o),w({hasProjectDefinition:!0,hasInitializingEvents:!!i.length});let p=vu({root:e});c(p)&&logger.info(p.message);let m=Ph({root:e});return c(m)&&logger.info(m.message),Pf(c(m)?[]:m.value),d("Loaded project",void 0)},vN=async e=>{let t=ye({repoRoot:e});if(c(t))return a(t.message);let n=t.value,r=await jt({repoRoot:n});if(c(r))return a(r.message);if(!r.value)return d("No remote to pull",void 0);let o=await bo({worktreeRoot:n,operation:"boot pull",fn:()=>di(n,()=>(ii("Pulling"),Dh(e,n)))});if(c(o))return we(o.message);if(o.value===null)return d("Another process holds the state worktree",void 0);let s=o.value;if(c(s))return Ur(s.message)?(ai("Offline"),d("Offline",void 0)):we(s.message);if(!s.value)return Po("Already synced"),d("Already synced",void 0);if(!yN(n))return d("Project changed during the pull",void 0);let i=il(n);return c(i)?i:(Po("Pulled"),d("Pulled and reloaded",void 0))},_h=e=>{vN(e).then(t=>{c(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${sg(t)}`)})},LW=()=>{let e=Lo([]);return c(e)?$n(4,e.message):(w({hasProjectDefinition:!1,hasInitializingEvents:!1}),d("Booted without a project",void 0))};var EN=e=>e==="~"||e.startsWith("~/")?$h.join(xN.homedir(),e.slice(1)):e,RN=(e,t)=>{let n=e.trim();if(!n)return a("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?d("Resolved recent project",o.root):a(`No recent project #${n}`)}let r=xe($h.resolve(EN(n)));return c(r)?a(`No epiq project at ${n}`):d("Resolved project path",r.value)},Bh=async()=>{let e=Qs();if(K(""),h().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=ms({exclude:process.cwd()}),n=c(t)?[]:t.value,r=RN(e,n);if(c(r))return a(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return a(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await Fh(o);return c(i)?(process.chdir(s),a(i.message)):(_h(o),d(`Opened ${gu(o)}`,null))};var Ii=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=Dm(n,t);if(c(s))return a(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,u=gn();if(c(u))return u;let p=sn(i),{fatal:m,skipped:f}=Pn(p);if(m.length>0)return gn(),w(o),a(m.map(x=>x.message).join(", "));On(f);let g=h().nodes[e];return g?(U.navigate({contextNode:g,selectedIndex:r}),d("",{unappliedEvents:l})):(gn(),w(o),a("Board did not exist at that date"))};var Uh=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)};var SN=20,CN=16,NN=150,wi=null,Ai=null;var Gn=()=>{wi!==null&&(clearInterval(wi),wi=null),Ai!==null&&(clearTimeout(Ai),Ai=null)},jh=()=>{Gn(),w({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Hh=({events:e,startTime:t,durationMs:n})=>{Gn();let r=e.length,o=Xo(e.map(f=>Jo(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=Uh(o),l=Math.max(1,Math.round(n*SN/1e3)),u=Math.max(Math.round(n/l),CN),p=0,m=0;w({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),wi=setInterval(()=>{p++;let f=p/l,g=[],x,N;for(;m<r&&i[m]<=f;){let R=e[m],v=uo(R);if(c(v)){if(cr(v)){m++;continue}jh();return}g.push(...Za(R)),x=R,N=o[m],m++}if(m>=r||p>=l){for(;m<r;m++){let v=uo(e[m]);if(c(v)&&!cr(v))break}let R=h().replay;w({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),Gn(),Ai=setTimeout(jh,NN);return}let E=h().replay;w({unappliedEvents:e.slice(m),replay:{progress:Math.min(1,f),appliedCount:m,totalCount:r,startTime:t,endTime:s,currentTime:x?N??E?.currentTime??t:E?.currentTime??t,currentLabel:x?Wh(x):E?.currentLabel??"",flashNodeIds:x?[...new Set(g)]:E?.flashNodeIds??[]}})},u)};var Gh=async()=>{let e=Ze(h().breadCrumb,"BOARD");if(c(e))return e;let t=await Rt(process.cwd());if(c(t))return a("Unable to locate repo root");let n=ye({repoRoot:t.value});if(c(n))return n;let{modifier:r,inputString:o}=Y().commandMeta;if(Gn(),r==="now"){let l=ks(n.value);if(c(l))return a(l.message);let u=gn();if(c(u))return u;let p=sn(l.value),{fatal:m,skipped:f}=Pn(p);return m.length>0?a(m.map(g=>g.message).join(", ")):(On(f),w({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),d("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=Fm(n.value);if(c(l))return l;let u=r==="prev"?h().eventLog.at(-1):h().unappliedEvents.at(0),p=u===void 0?null:Jo(u),m=(u===void 0?null:l.value.get(u.id)??null)??(p===null?null:ji(p));if(m===null)return a(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?m:m+1}else{let l=In(r||o.trim());if(!l)return a("Invalid peek date");s=l.getTime()}let i=Ii({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return c(i)?i:(w({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),d("Peeking",!0))};var zh=async()=>{let e=Ze(h().breadCrumb,"BOARD");if(c(e))return e;let t=await Rt(process.cwd());if(c(t))return a("Unable to locate repo root");let n=ye({repoRoot:t.value});if(c(n))return n;let{modifier:r,inputString:o}=Y().commandMeta,{dateInput:s,durationInput:i}=ys(r,o);if(Gn(),h().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let l=In(s);if(!l)return a("Invalid replay date");let u=i?hs(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let p=l.getTime(),m=h(),f=Ii({boardId:e.value.id,targetTime:p,stateBranchRoot:n.value,selectedIndex:-1});if(c(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(gn(),w(m),d("Nothing to replay from that point",!0)):(Hh({events:g,startTime:p,durationMs:u}),d("Replaying board history",!0))};import{spawn as wN}from"node:child_process";var AN=()=>{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"]}}},Vh=async e=>new Promise(t=>{let{command:n,args:r}=AN();try{let o=wN(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?d("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 Vo=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await Vh(e);return c(n)?n:d(`Copied ${t} to clipboard`,null)},qh=async e=>{let{breadCrumb:t,selectedNode:n}=h(),r=Qr({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case Te.REF:return Vo(nt(o.id),"ref");case Te.TITLE:return Vo(o.title,"title");case Te.DESCRIPTION:return r?Vo(r.props?.description??"","description"):a("No issue in scope");case Te.TAGS:{if(!r)return a("No issue in scope");let s=en(r).map(({name:i})=>i);return Vo(s.join(", "),"tags")}case Te.ASSIGNEES:{if(!r)return a("No issue in scope");let s=tn(r).map(({name:i})=>i);return Vo(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var Kh=async()=>{K(""),w({mode:y.DEFAULT});let e=ve();if(c(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");w({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await ui();return c(t)?(w({syncStatus:{msg:t.message,status:"failed"}}),t):(w({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as Yh}from"ulid";var Xh=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=ae(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await le();if(c(o))return o;if(r.context==="COMMENT"){let s=r.id,i=H(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let l=h().nodes[i];if(!l||!H(l))return a("Unable to resolve comment issue");let u=l.log?.filter(Ug).find(p=>p.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):Q([{id:Yh(),action:"delete.issue.comment",payload:{id:s,issue:i},...re(e.value)}],o.value):a("Unable to resolve comment")}return Q([{id:Yh(),action:"delete.node",payload:{id:r.id},...re(e.value)}],o.value)};import{ulid as TN}from"ulid";var Jh=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=ae(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!H(r))return a("Cannot close in this context");let o=h().nodes[ct];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await le();if(c(s))return s;let i=s.value,l=ti(o.id,r.id,{at:"end"},e.value,i);if(c(l))return l;let u=Q([{id:TN(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...re(e.value)}],i);return c(u)?u:d("Issue closed",null)};import{ulid as MN}from"ulid";var Zh=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};var Qh=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=ae(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?d("Resolved ticket",r):ht(r.id,"TICKET");if(c(o))return a("Cannot reopen in this context");let s=o.value,i=h().nodes[ct];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!H(s))return a("Target node is not issue");let l=Zh(s);if(!l)return a("Unable to resolve previous parent from issue history");if(l===i.id)return a("Previous parent resolves to closed swimlane");let u=h().nodes[l];if(!u)return a("Previous parent no longer exists");let p=await le();if(c(p))return p;let m=p.value,f=ti(u.id,s.id,{at:"end"},e.value,m);if(c(f))return f;let g=Q([{id:MN(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...re(e.value)}],m);return c(g)?g:d("Issue reopened",null)};import{ulid as kN}from"ulid";var ey=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=ae(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=Qs();if(!o)return a("Provide a title");let s=await le();return c(s)?s:Q([{id:kN(),action:"edit.title",payload:{id:r.id,name:o},...re(e.value)}],s.value)};import{ulid as LN}from"ulid";var ty=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=C.findTagByName(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=h();if(!s)return a("Invalid untag target");let i=ht(s.id,"TICKET");if(c(i))return a("Unable to untag issue in this context");let l=i.value;if(!H(l))return a("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let p=await le();return c(p)?p:Q([{id:LN(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...re(e.value)}],p.value)};import{ulid as kl}from"ulid";var ny=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=h();if(!o)return a("Invalid tag target");let s=ht(o.id,"TICKET");if(c(s))return a("Unable to tag issue in this context");let i=s.value;if(!H(i))return a("Target node is not issue");let l=await le();if(c(l))return l;let u=C.findTagByName(r),p=u?.id??kl();return(i.props.tags??[]).includes(p)?a("Already tagged with that tag"):Q([...u?[]:[{id:kl(),action:"create.tag",payload:{id:p,name:r},...re(e.value)}],{id:kl(),action:"add.issue.tag",payload:{id:i.id,tag:p},...re(e.value)}],l.value)};import{ulid as Ll}from"ulid";var ry=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},lV=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=Qe(t),s=n.get(o),i=s?r[s]:void 0;return s?{...Ki(s,i?.name),resolved:!0}:{...Ki(o||e,e),resolved:!1}};var Ti=e=>{let{eventLog:t=[],contributors:n}=h();return ry({events:t,registry:n,logFileNames:Om(e)})};var oy=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:l}=h(),u=ae(l.id)[i];if(!u)return a("Invalid assign target");let p=ht(u.id,"TICKET");if(c(p))return a("Unable to assign issue in this context");let m=p.value;if(!H(m))return a("Target node is not issue");let f=await le();if(c(f))return f;let g=Ti(f.value),x=!o&&s.toLowerCase()==="me",N,E;if(x)N=e.value.userId,E=g.find(I=>I.id===N)?.name??e.value.userName;else{let I=g.filter(M=>M.name===s);if(I.length>1)return a(`"${s}" matches ${I.length} contributors (${I.map(M=>M.id).join(", ")}). Assign from the GUI to choose by id.`);let k=I[0];if(!k&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);N=k?.id??Ll(),E=k?.name??s}if((m.props.assignees??[]).includes(N))return a("Assignee already assigned");let v=!!h().contributors[N];return Q([...v?[]:[{id:Ll(),action:"create.contributor",payload:{id:N,name:E},...re(e.value)}],{id:Ll(),action:"add.issue.assignee",payload:{id:m.id,assignee:N},...re(e.value)}],f.value)};import{ulid as PN}from"ulid";var sy=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=h();if(!o)return a("Invalid unassign target");let s=ht(o.id,"TICKET");if(c(s))return a("Unable to unassign in this context");let i=s.value;if(!H(i))return a("Target node is not issue");let l=i.props.assignees??[],u=r.toLowerCase()==="me",p=await le();if(c(p))return p;let m=u?l.filter(g=>g===e.value.userId):Ti(p.value).filter(g=>g.name===r&&l.includes(g.id)).map(g=>g.id);if(m.length>1)return a(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let f=m[0];return f?Q([{id:PN(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...re(e.value)}],p.value):a(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)};import{ulid as iy}from"ulid";var ON=e=>{let t=e.trim(),n=pn(),r=n?ef(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=Ei();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=tf(o.rows,Math.max(0,h().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=nf(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:Jp({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},ay=async e=>{let t=ON(e.inputString);if(!t.ok)return a(t.reason);let{md:n,anchored:r}=t;if(!n)return a("Provide a comment");if(n.length>4e3)return a(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=oe();if(c(o))return a("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=h(),l=Ze([...s,i],"TICKET");if(c(l))return a("Edit target must be an issue");let u=l.value;if(!u)return a("Invalid comment target");let p=u.context==="TICKET"?d("Resolved ticket",u):ht(u.id,"TICKET");if(c(p))return a("Unable to comment on issue in this context");let m=p.value;if(!H(m))return a("Target node is not issue");let f=await le();if(c(f))return f;let g=await Q([{id:iy(),action:"add.issue.comment",payload:{id:iy(),issue:m.id,author:o.value.userId,md:n},...re(o.value)}],f.value);return r&&!c(g)&&jn(null),g};import{ulid as jN}from"ulid";var cy=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",DN=e=>{let t=Hu();return c(t)?cy({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:cy(t.value)},ly=()=>{let e=Pt();return c(e)?a(e.message):d("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:rs(e.value.autoSyncDebounceMs),blockedReason:DN(e.value)})},Mi=e=>{let t=e.intervalMs===void 0?void 0:Jn(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return a(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=ly();if(c(n))return n;let r=qe({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(c(r))return a(r.message);at({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=ly();return c(o)?d("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o};var dy=()=>{let e=Y().commandMeta.inputString,t=Jn(e);if(t===null)return a(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=Mi({intervalMs:t});return c(n)?n:d(`Auto sync interval set to ${t}ms`,null)};import FN from"zod";var uy=()=>{let e=FN.coerce.number().int().min(or).max(sr).safeParse(Y().commandMeta.inputString);if(!e.success)return a(`A connected repo's clone cap must be ${or}-${sr} MB (default ${Pa})`);let t=qe({repoCloneMaxMb:e.data});return c(t)?t:d(`Connected repo clone cap set to ${e.data} MB`,null)};var my=()=>{let e=Y().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=wu(e),n=Mi({enabled:t===!0});return c(n)?n:d(`Auto sync set to "${e}"`,null)};import{ulid as BN}from"ulid";var Pl=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),py="",fy=new Map,_N=15e3;var $N=async(e,t)=>{let n=`${e} ${t??""}`,r=fy.get(n);if(r&&Date.now()-r.at<Bs(_N))return d("Cached author scan",r.authors);let o=await Se({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${py}%ae`]});if(o.exitCode!==0)return a(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
|
|
108
|
-
`)){let l=i.lastIndexOf(py);if(l===-1)continue;let u=i.slice(0,l),p=Qe(i.slice(l+1));if(!Yn(p))continue;let m=s.get(p)??{names:new Set,commits:0};u&&m.names.add(u),m.commits+=1,s.set(p,m)}return fy.set(n,{at:Date.now(),authors:s}),d("Scanned repository authors",s)},gy=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await $N(e,t);if(c(o))return a(o.message);let s=o.value,i=new Map;for(let u of Object.values(r)){if(u.tombstoned)continue;let p=i.get(u.email)??new Set;p.add(u.contributor),i.set(u.email,p)}let l=new Set(n.flatMap(u=>Pl(u??"")));return d("Found candidates",[...s.entries()].map(([u,p])=>({email:u,names:[...p.names],commits:p.commits,looksLikeYours:[...p.names].some(m=>Pl(m).some(f=>l.has(f)))||Pl(u.split("@")[0]??"").some(m=>l.has(m)),claimedBy:[...i.get(u)??[]]})).sort((u,p)=>u.looksLikeYours===p.looksLikeYours?p.commits-u.commits:Number(p.looksLikeYours)-Number(u.looksLikeYours)))},hy=e=>e.filter(t=>t.claimedBy.length===0);var yy=()=>{let e=Ea();if(!e)return d("Nothing here to decline",null);let t=Pt(),n=c(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=qe({declinedEmailBoards:r});return c(o)?a(o.message):(at({declinedEmailBoards:[...new Set([...ee().declinedEmailBoards??[],e])]}),d("Declined",null))},by=async()=>{let e=Y().commandMeta.inputString.trim();if(e==="none"){let R=yy();return c(R)?R:d("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=ee();if(!t)return a("Set a username first with :config username");let o=ve();if(c(o))return a("Board is not loaded");let s=xe(process.cwd());if(c(s))return a(s.message);let i=Et(s.value),l=await gy({repoRoot:s.value,stateBranch:c(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(c(l))return l;let p=hy(l.value);if(Su(p.map(R=>R.email)),p.length===0){if(!Nu()){let R=yy();if(c(R))return R}return d("No unclaimed addresses in this history.",null)}if(!e)return w({mode:y.IDENTITY}),d("Opened identity",null);let m=e.split(/[,\s]+/).filter(Boolean),f=[],g=[];for(let R of m){let v=p.find(I=>I.email===Qe(R));if(!v){g.push(R);continue}f.includes(v)||f.push(v)}if(g.length>0)return a(`Not on the list: ${g.join(", ")}. Pick one of ${p.map(R=>R.email).join(", ")}.`);let x=ye({repoRoot:s.value});if(c(x))return x;let N=f.map(R=>({id:BN(),action:"link.contributor.email",payload:{contributor:t,email:R.email},userId:t})),E=Q(N,x.value);return c(E)?a(E.message):d(`Claimed ${f.map(R=>R.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)};import{ulid as UN}from"ulid";var vy=()=>{let e=Y().commandMeta.inputString.trim(),{userId:t}=ee();if(!t)return a("Set a username first with :config username");let n=ve();if(c(n))return a("Board is not loaded");let r=Xn(n.value.emailLinks,t);if(r.length===0)return a("You have not claimed any addresses.");if(!e)return a(`Which one? ${r.join(", ")}.`);let o=r.find(u=>u===Qe(e));if(!o)return a(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=xe(process.cwd());if(c(s))return s;let i=ye({repoRoot:s.value});if(c(i))return i;let l=Q([{id:UN(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return c(l)?a(l.message):d(`Unclaimed ${o}`,null)};var xy=()=>{let e=Y().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=qe({logLevel:e});return c(n)?n:(at({logLevel:e}),d(`Auto sync set to "${e}"`,null))};var Ey=e=>{let t=e.inputString.trim();switch(e.modifier){case J.USERNAME:{if(process.env[Oi])return a(`Cannot change the configured user while ${Oi} names this process`);let n=Pt();if(c(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||jN();if(!i||!l)return a("Unable to resolve user name or id");let u=qe({userName:i,userId:l,preferredEditor:o??""});return c(u)?u:(at({userName:i,userId:l}),d(`Username set to "${i}"`,null))}case J.EDITOR:{if(!t)return a("No editor provided");let n=qe({preferredEditor:t});return c(n)?n:(at({preferredEditor:t}),d(`Editor configuration set to "${t}"`,null))}case J.VIEW:{if(t!=="wide"&&t!=="dense")return a("Invalid view mode");let n=qe({viewMode:t});return c(n)?n:(at({viewMode:t}),d(`View set to "${t}"`,null))}case J.EMAILS:return by();case J.EMAILS_UNCLAIM:return vy();case J.AUTOSYNC:return my();case J.LOG_LEVEL:return xy();case J.SYNC_DEBOUNCE_MS:return dy();case J.ATTACHMENT_MAX_KB:return Ku();case J.REPO_CLONE_MAX_MB:return uy();case J.REPO_CONNECT:return ff();case J.REPO_DISCONNECT:return gf();default:return a("Unknown config command")}};var Ol=()=>{let e=Au(),t=h().mode;if(!(t!==y.COMMAND_LINE&&t!==y.DEFAULT)){if(!e){w({mode:y.DEFAULT});return}w({mode:y.COMMAND_LINE}),K(e)}};var Ry=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:Ah},{intent:G.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:Xh,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Y().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Me(b.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return ge(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:y.DEFAULT})),d("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return fn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),w({mode:y.HELP}),d("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:Jh,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:Qh,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:Rh,onSuccess:Ol},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:y.COMMAND_LINE,action:Bh,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:Mh,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:ey,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:ty,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:ny,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:oy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:sy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>ay(t),onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:Kh},{intent:G.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:Gh},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:zh},{intent:G.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await yh();return c(e)?e:(w({mode:y.DEFAULT}),d("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(U.exit(),d("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>vh(t),onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>qh(t),onSuccess:()=>w({mode:y.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>Ey(t),onSuccess:Ol}];var HN=e=>{let t=e.value;return t&&typeof t=="object"&&typeof t.followUp=="string"?t.followUp:null},WN=new Set(["peek","replay","filter","view-help","yank"]),yt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=Y();if(!n)return a("No command to confirm");if(!e&&r===ln.Invalid)return a("Invalid command");let i=wg(n);kf();let{readOnly:l}=h();if(l&&!WN.has(i))return Ao({status:qn.Fail,message:"Command not available in readonly state",value:null});let u=Ry.filter(g=>e||g.systemOnly!==!0).find(g=>g.intent===i);if(!u)return Ao({status:qn.Fail,message:"Command not found",value:null});let p;try{p=await u.action(u,{command:n,inputString:s,modifier:o})}catch(g){return Ao({status:qn.Fail,message:g instanceof Error?g.message:"Command failed",value:null})}if(c(p))return Ao(p);let m=!e;if(Lf({addToHistory:m,line:t}),m){let g=Oh({commands:Y().commandHistory});c(g)&&logger.info(g.message)}let f=HN(p);return f!==null?(K(f),p):(u.onSuccess?.(),ee().autoSync&&Ig(),p)};var ki=[{intent:S.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:y.COMMAND_LINE}),K("move cancel"),yt({isForceExecutedBySystem:!0}))},{intent:S.InitMove,mode:y.DEFAULT,description:"[m] move",action:()=>(w({mode:y.COMMAND_LINE}),K("move start"),yt({isForceExecutedBySystem:!0}))},{intent:S.ConfirmMove,mode:y.MOVE,description:"[m] confirm move",action:()=>(w({mode:y.COMMAND_LINE}),K("move confirm"),yt({isForceExecutedBySystem:!0}))}],Li=[{intent:S.MovePreviousItem,mode:y.MOVE,action:()=>Tt()?(w({mode:y.COMMAND_LINE}),K("move previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveNextItem,mode:y.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>Tt()?(w({mode:y.COMMAND_LINE}),K("move next"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MovePreviousItemJump,mode:y.MOVE,action:()=>Tt()?(w({mode:y.COMMAND_LINE}),K("move jump-previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveNextItemJump,mode:y.MOVE,action:()=>Tt()?(w({mode:y.COMMAND_LINE}),K("move jump-next"),yt({isForceExecutedBySystem:!0})):a("No pending move")}],Sy=[{intent:S.MoveToNextContainer,mode:y.MOVE,action:()=>Tt()?(w({mode:y.COMMAND_LINE}),K("move to-next"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveToPreviousContainer,mode:y.MOVE,action:()=>Tt()?(w({mode:y.COMMAND_LINE}),K("move to-previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")}];var Cy={[te.WORKSPACE]:[...ki,...Li],[te.BOARD]:[...ki,...Li],[te.SWIMLANE]:[...ki,...Li,...Sy],[te.TICKET]:[],[te.FIELD]:[],[te.FIELD_LIST]:[],[te.TEXT]:[],[te.COMMENT]:[]};import zN from"node:fs";import VN from"node:path";import{spawn as GN}from"node:child_process";function Ny(e){let t=process.platform,o=GN(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}var Iy=e=>{let t=xe(process.cwd());if(c(t))return a("Unable to resolve project root");let n=ye({repoRoot:t.value});if(c(n))return a(n.message);let r=La(e.hash,e.ext),o=VN.join(Vr(n.value),r);return zN.existsSync(o)?(Ny(o),d(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var wy=()=>{K("");let{pendingNavTarget:e}=kr();w({mode:y.DEFAULT}),e&&U.navigate(e),fn({pendingNavTarget:void 0})},Ay=[{intent:S.ExitCommandLine,mode:y.HELP,action:()=>(wy(),d("Exiting help",null))},{intent:S.Exit,mode:y.HELP,action:()=>(wy(),d("Closed help",null))},{intent:S.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),d("Navigating to previous help item",null))},{intent:S.NavNextItem,mode:y.HELP,action:()=>(U.navigateToNextItem(),d("Navigating to next help item",null))},{intent:S.NavPreviousItemJump,mode:y.HELP,action:()=>(U.jumpToPreviousItem(),d("Jumping to previous help item",null))},{intent:S.NavNextItemJump,mode:y.HELP,action:()=>(U.jumpToNextItem(),d("Jumping to next help item",null))},{intent:S.NavToPreviousContainer,mode:y.HELP,action:()=>(U.navigateToPreviousContainer(),d("Navigating to previous help container",null))},{intent:S.NavToNextContainer,mode:y.HELP,action:()=>(U.navigateToNextContainer(),d("Navigating to next help container",null))}];var Ty=()=>{K(""),w({mode:y.DEFAULT})},My=[{intent:S.Confirm,mode:y.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=nr();return e?(w({mode:y.COMMAND_LINE}),K(`config emails ${e}`),d("Proposed claim",null)):d("Nothing left to claim",null)}},{intent:S.ExitCommandLine,mode:y.IDENTITY,action:()=>(Ty(),d("Closed identity",null))},{intent:S.Exit,mode:y.IDENTITY,description:"[esc] close",action:()=>(Ty(),d("Closed identity",null))}];var qN=e=>{w({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=kr();t&&U.navigate(t),fn({pendingNavTarget:void 0}),K(`${e} `)},ky=()=>{K("");let{pendingNavTarget:e}=kr();e&&U.navigate(e),fn({pendingNavTarget:void 0}),w({mode:y.DEFAULT})},Ly=[{intent:S.InitCommandPalette,mode:y.DEFAULT,description:"[?] command palette",action:()=>{K("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return fn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),w({mode:y.PALETTE}),d("Opening command palette",null)}},{intent:S.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=h();if(!e||!ld(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?(qN(t),d("Selected command",t)):d("No command selected",null)}},{intent:S.ExitCommandLine,mode:y.PALETTE,action:()=>(ky(),d("Exiting palette",null))},{intent:S.Exit,mode:y.PALETTE,action:()=>(ky(),d("Closed command palette",null))},{intent:S.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:S.NavNextItem,mode:y.PALETTE,action:()=>(U.navigateToNextItem(),d("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:y.PALETTE,action:()=>(U.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:y.PALETTE,action:()=>(U.navigateToNextContainer(),d("Navigating to next container",null))}];var Py=()=>{let e=pn();if(!e)return d("Nothing to comment on here",null);let t=Ei();if(!t||t.sha!==e)return a("The diff is still loading");let{selectedIndex:n}=h(),r=Math.max(0,n),o=Bc(t.rows,yl(e)??r,r);return o.ok?(w({mode:y.COMMAND_LINE}),K(`${b.COMMENT} ${Qp(o.value.start,o.value.end)} `),d("Commenting on a diff line",null)):a(o.reason)},Oy=[{intent:S.InitCommandLine,mode:y.DEFAULT,description:"[:] write command",action:()=>(w({mode:y.COMMAND_LINE}),K(""),d("Entering command line mode",null))},...Ay,...My,...Ly,{intent:S.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(w({mode:y.COMMAND_LINE}),K(`${b.NEW} `),d("Adding new item",null))},{intent:S.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(w({mode:y.COMMAND_LINE}),K(`${b.DELETE} `),d("Deleting item",null))},{intent:S.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=h();if(!he(e?.id??"")?.length){let r=e?C.getAttachment(e.id):void 0;if(r)return Iy(r);if(pn())return Py();if(e?.title===me.DESCRIPTION)return w({mode:y.COMMAND_LINE}),K(`${b.EDIT} description `),d("Propose command",!0);if(e?.title===me.ASSIGNEES)return w({mode:y.COMMAND_LINE}),K(`${b.ASSIGN} `),d("Propose command",!0);if(e?.title===me.TAGS)return w({mode:y.COMMAND_LINE}),K(`${b.TAG} `),d("Propose command",!0);if(t.title===me.DESCRIPTION&&e?.context==="TEXT")return w({mode:y.COMMAND_LINE}),K(`${b.EDIT} description `),d("Propose command",!0)}return U.enterChildNode(),d("Entering context",null)}},{intent:S.OpenInEditor,mode:y.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=h(),n=t.parentNodeId,o=!!n&&t.id===pe(n,"diff")?e?.id:pn()??void 0;return o?zc({sha:o}):d("Nothing here opens in an editor",null)}},{intent:S.MarkDiffLine,mode:y.DEFAULT,action:()=>{let e=pn();if(!e)return d("Nothing to mark here",null);let{selectedIndex:t}=h(),n=yl(e);return jn(n===t?null:{sha:e,row:Math.max(0,t)}),d("Marked diff line",null)}},{intent:S.CommentOnDiffLine,mode:y.DEFAULT,action:()=>pn()?Py():d("Nothing to comment on here",null)},{intent:S.Yank,mode:y.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=h(),t=e?.title===me.DESCRIPTION?Te.DESCRIPTION:e?.title===me.TAGS?Te.TAGS:e?.title===me.ASSIGNEES?Te.ASSIGNEES:Te.REF,r=Me(b.YANK).includes(t)?t:Te.REF;return w({mode:y.COMMAND_LINE}),K(`${b.YANK} ${r}`),d("Propose command",!0)}},{intent:S.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(w({mode:y.COMMAND_LINE}),K(`${b.EDIT} title ${h().selectedNode?.title}`),d("Exiting context",null))},{intent:S.EditDescription,mode:y.DEFAULT,description:"[e] edit desc",action:()=>(w({mode:y.COMMAND_LINE}),K(`${b.EDIT} description `),d("Exiting context",null))},{intent:S.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),d("Exiting context",null))},{intent:S.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:S.NavNextItem,mode:y.DEFAULT,action:()=>(U.navigateToNextItem(),d("Navigating to next item",null))},{intent:S.NavPreviousItemJump,mode:y.DEFAULT,action:()=>(U.jumpToPreviousItem(),d("Jumping to previous item",null))},{intent:S.NavNextItemJump,mode:y.DEFAULT,action:()=>(U.jumpToNextItem(),d("Jumping to next item",null))},{intent:S.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(U.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:y.DEFAULT,action:()=>(U.navigateToNextContainer(),d("Navigating to next container",null))}];var KN=500,YN=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Dy=e=>{let t=YN(e);t&&Zs(n=>(n+t).slice(0,KN))};var XN=[y.COMMAND_LINE,y.PALETTE],JN=e=>e==="edit title "?h().selectedNode?.title??"":"",ZN=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>(Jc(-1),d("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>(Jc(1),d("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(Zc("left"),d("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(Zc("right"),d("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(Zs((t,{remainder:n})=>{let r=n?t+n:t;return r+JN(r)}),d("Auto-completing command",null))},{intent:S.CaptureInput,mode:e,action:(t,{sequence:n})=>(Dy(n??""),d("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(Tf(),d("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(Mf(),d("Erasing input word",null))}],Fy=[{intent:S.Confirm,mode:y.COMMAND_LINE,action:()=>(yt(),d("Executing command",null))},{intent:S.ViewHelp,mode:y.DEFAULT,action:()=>(w({mode:y.HELP}),d("Viewing help",null))},...XN.flatMap(ZN),{intent:S.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(Of(),w({mode:y.DEFAULT}),d("Exiting command line",null))},{intent:S.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Df(),d("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Ff(),d("Getting next command from history",null))}];var QN=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},_y=({keys:e})=>e.length===1?0:1,$y=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(QN).filter(r=>r!==null).sort((r,o)=>_y(r)-_y(o))};function By(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),d("Breadcrumb built",o))}var Uy=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 Je,Dl,Fl=new Set,_l=()=>{for(let e of Fl)e()},tI=e=>(Fl.add(e),()=>Fl.delete(e));function $l(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 l=o[t];if(!l)return a("Unable to derive state, contextNode not found");let u=By(t,o,r);if(c(u))return logger.error(u.message),u;let p=u.value,{context:m}=l,f=[...Oy,...Cy[m]??[],...Fy],g=$y(f,n),x=Uy(f),N=nI(o,s),E=N[t]?.[e.selectedIndex]??null;return d("Derived successfully",{...e,contextNode:l,breadCrumb:p,availableHints:g,availableActions:f,actionIndex:x,selectedNode:E,renderedChildrenIndex:N})}var h=()=>{if(!Je)throw new Error("State not initialized. Call initWorkspaceState() first.");return Je},ve=()=>Je?d("Retrieved state",Je):a("State not initialized. Call initWorkspaceState() first.");xu(e=>Je?Xn(Je.emailLinks,e):[]);function lo(e){Dl=e;let t=xe(process.cwd()),n=!1;if(!c(t)){let s=je(t.value);if(c(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},repos:Fi(),mode:y.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:{},attachments:{}},o=$l(r);return c(o)?o:(Je=o.value,_l(),d("State initialized",null))}var zn=!1,qo=null;function ge(e){let t=h(),n=e(t);if(zn)return n.nodes!==t.nodes&&(hn=null),qo=n,Je={...t,...n},d("State updated",null);let r=$l(n);return c(r)?a(r.message??"Unable to update state"):(Je=r.value,_l(),d("State updated",null))}function Ms(e){if(zn)return d("Joined batch",e());zn=!0,qo=null,hn=new Set;let t=()=>{let n=qo;if(zn=!1,qo=null,n===null)return null;let r=$l(n);return c(r)?a(r.message??"Unable to update state"):(Je=r.value,_l(),d("State updated",null))};try{let n=e(),r=t();return r&&c(r)?a(r.message):d("State updated",n)}finally{zn&&t()}}var Kf=()=>zn,w=e=>ge(t=>({...t,...e}));function Vn(e,t,n){if(!zn)return ge(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=h(),o=r[e]??{};if(e==="nodes"){let i=o[t],l=n;i?.parentNodeId&&hn?.add(i.parentNodeId),l.parentNodeId&&hn?.add(l.parentNodeId)}o[t]=n;let s={...r,[e]:o};return qo=s,Je={...r,...s},d("State updated",null)}var Le=()=>eI(tI,h,h),hn=null,jy=null,nI=(e,t)=>{let n=Je?.renderedChildrenIndex,r=n!==void 0&&hn!==null&&e===jy&&t.length===0&&Je?.filters.length===0,o;if(r){o={...n};let s=Gf(e,hn);for(let i of hn){let l=s[i];l?o[i]=l:delete o[i]}}else o=Wf(e,t);return jy=e,hn=new Set,o},ae=e=>h()?.renderedChildrenIndex[e]??[],gn=()=>Dl?lo(Dl):a("Cannot reset state: no initial workspace found"),dt=()=>Je!==void 0;var ht=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return d("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return d("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},rI=(e,t)=>{let{nodes:n}=h(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},yn=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),C={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=ge(s=>({...s,contributors:{...s.contributors,[e]:r}}));return c(o)?a("Unable to link contributor to user"):d("Linked contributor to user",r)},deleteNode(e){C.deleteNodes([e])},deleteNodes(e){e.length!==0&&ge(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!H(t))return a("Can only comment on issues");let n=Vn("comments",e.id,{...e,deleted:!1});return c(n)?a("Unable to create comment"):d("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(!H(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Vn("comments",e,o);return c(s)?a("Unable to edit comment"):d("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=Vn("comments",e,n);return c(r)?a("Unable to delete comment"):d("Deleted comment",n)},getComment(e){return h().comments?.[e]},getCommentsByIssue(e){return Object.values(h().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!H(t))return a("Can only attach to issues");let n=ge(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return c(n)?a("Unable to create attachment"):d("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=ge(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return c(r)?a("Unable to delete attachment"):d("Deleted attachment",n)},getAttachment(e){return h().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(h().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=h(),r=n[e];if(!r)return a("Edit target node not found");let o=yn(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),d("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=yn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),d("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return he(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=h(),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=yn(o,"move");if(i)return i;if(rI(t,e))return a("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),d("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=yn(o,"delete");if(s)return s;let i=new Set,l=p=>{let m=t[p];if(!(!m||i.has(p))){i.add(p);for(let f of he(m.id))l(f.id)}};l(e);let u={...structuredClone(t)};for(let p of i){if(!u[p])return a("Unable to locate node to delete");u[p]={...u[p],isDeleted:!0}}return n?(w({nodes:u}),d("Successfully tomb stoned",o)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:id,tombstoned:!0},r=ge(o=>({...o,contributors:{...o.contributors,[e]:n}}));return c(r)?a("Unable to remove contributor"):d("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.tombstoned)return a("Cannot rename a removed contributor");let r={...n,name:t},o=ge(s=>({...s,contributors:{...s.contributors,[e]:r}}));return c(o)?a("Unable to rename contributor"):d("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=ge(s=>({...s,contributors:{...s.contributors,[e]:r}}));return c(o)?a("Unable to restore contributor"):d("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return a("Unable to link email, missing contributor");let r={email:Qe(e),contributor:t,authorId:n},o=Yi(r.email,t),s=h().emailLinks[o];if(s&&!s.tombstoned)return d("Email already linked",s);let i=ge(l=>({...l,emailLinks:{...l.emailLinks,[o]:r}}));return c(i)?a("Unable to link email"):d("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=Yi(e,t),o=h().emailLinks[r];if(!o)return a("Unable to unlink, no such link");if(o.tombstoned)return d("Email already unlinked",o);if(!cd(n,o))return a("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=ge(l=>({...l,emailLinks:{...l.emailLinks,[r]:s}}));return c(i)?a("Unable to unlink email"):d("Unlinked email from contributor",s)},getEmailLinks(){return h().emailLinks},createContributor(e){let t=ge(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return c(t)?a("Unable to create contributor"):d("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=yn(r,"edit");if(o)return o;if(!H(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),d("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=yn(r,"edit");if(o)return o;if(!H(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return d("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(i),d("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=yn(r,"edit");if(o)return o;if(!H(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),d("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(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=yn(r,"edit");if(o)return o;if(!H(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return d("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(i),d("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return a("Tag not found");let n={...t,tombstoned:!0},r=ge(o=>({...o,tags:{...o.tags,[e]:n}}));return c(r)?a("Unable to delete tag"):d("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return a("Tag not found");let r={...n,name:t,tombstoned:!1},o=ge(s=>({...s,tags:{...s.tags,[e]:r}}));return c(o)?a("Unable to restore tag"):d("Restored tag",r)},createTag(e){let t=ge(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?a("Could not create tag"):d("Tag created",e)},createNode(e){let t=Vn("nodes",e.id,e);return c(t)?a("Unable to create node"):d("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=Vn("nodes",e,n);return c(r)?a(r.message):d("Locked node",n)},updateNode(e){let t=Vn("nodes",e.id,e);return c(t)?t:d("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){let t=h().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return h().tags[e]},getTags(){return Object.values(h().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return h().nodes[e]},getSiblings(e){return he(e)}};var oI=(e,t)=>e+" ".repeat(Math.max(0,t-Hy(e))),sI=(e,t)=>" ".repeat(Math.max(0,t-Hy(e)))+e,Wy=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","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","connect.repo":"Connected repo","edit.repo":"Edited repo","disconnect.repo":"Disconnected repo","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),iI=(e,t)=>t?e<t?"up":e>t?"down":null:null,aI=(e,t)=>{let n=C.getNode(e.payload.parent),r=n?bn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=iI(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Gy=e=>`${Math.max(1,Math.round(e/1024))} KB`,zy=e=>C.getAttachment(e)?.name??"",cI=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?bn.bgHex(Be(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?bn.bgHex(Be(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?bn.hex(Be(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?bn.hex(Be(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"connect.repo":case"edit.repo":case"disconnect.repo":return Ui(e);case"add.issue.attachment":return`"${e.payload.name}" ${bn.dim(`(${Gy(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=zy(e.payload.id);return t?`"${t}"`:""}default:return""}},lI=e=>{let t=dn(Rn(e));return bn.gray(sI(t,8))},dI=12,uI=e=>oI(`${e}`,dI),mI=e=>{let t=ve();return c(t)?e:qi(e,t.value.contributors[e]?.name)},pI=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"connect.repo":case"edit.repo":case"disconnect.repo":return Ui(e);case"move.node":{let t=C.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Gy(e.payload.bytes)})`;case"delete.issue.attachment":{let t=zy(e.payload.id);return t?`"${t}"`:""}default:return""}},Wh=e=>[Wy(e.action),pI(e)].filter(Boolean).join(" "),Vy=(e,t)=>{let n=lI(e.id),r=uI(mI(e.userId)),o=bn.dim("\u203A"),s=e.action==="move.node"?aI(e,t):[Wy(e.action),cI(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var fI=e=>pe(e,"comments"),gI=e=>pe(e,"description"),hI=e=>pe(e,"assignees"),yI=e=>pe(e,"tags"),bI=e=>pe(e,"history"),vI=e=>pe(e,"diff"),xI=e=>pe(e,"attachments"),Ko=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=C.getNode(e);if(!l){let m=C.createNode({...Ne.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return c(m)?m:d("Virtual field created",void 0)}if(!Fe(l))return a(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==i))return d("Virtual field unchanged",void 0);let p=C.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return c(p)?p:d("Virtual field updated",void 0)},qy=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=C.getNode(e);if(!i){let p=C.createNode({...Ne.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return c(p)?p:d("Virtual field list created",void 0)}if(!Fr(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 d("Virtual field list unchanged",void 0);let u=C.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return c(u)?u:d("Virtual field list updated",void 0)},Pi=null,EI=()=>{if(Pi)return d("Virtual field ranks",Pi);let e=st(It/4n),t=st(It/2n),n=st(It*3n/4n),r=st(It*7n/8n),o=st(It*15n/16n),s=st(It*13n/16n),i=st(It*27n/32n);return c(e)?e:c(t)?t:c(n)?n:c(r)?r:c(o)?o:c(s)?s:c(i)?i:(Pi={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},d("Virtual field ranks",Pi))},Qa=e=>{let t=EI();if(c(t))return t;let n=t.value,r=Ko({id:gI(e.id),name:me.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(c(r))return r;let o=qy({id:hI(e.id),name:me.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(c(o))return o;let s=qy({id:yI(e.id),name:me.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(c(s))return s;let i=Ko({id:fI(e.id),name:me.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(c(i))return i;let l=Ko({id:xI(e.id),name:me.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(c(l))return l;let u=Ko({id:bI(e.id),name:me.HISTORY,parentNodeId:e.id,rank:n.log,value:RI(e),readonly:!0,childRenderAxis:"vertical"});if(c(u))return u;let p=Ko({id:vI(e.id),name:me.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return c(p)?p:d("Ticket virtual nodes materialized",void 0)},RI=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=>Vy(r,n.get(r.action)??[])).join(`
|
|
109
|
-
`)},Ky=!0,n4=e=>{Ky=e},ec=()=>Ky,r4=()=>{let{nodes:e}=h();for(let t of Object.values(e)){if(!H(t))continue;let n=Qa(t);if(c(n))return n}return d("Virtual nodes materialized",void 0)};export{rs as a,j as b,Et as c,_ as d,Se as e,Gd as f,ye as g,Rt as h,zr as i,Xb as j,xe as k,Pt as l,qe as m,Hu as n,ee as o,RA as p,at as q,A as r,Be as s,rd as t,$I as u,od as v,BI as w,Qy as x,Vl as y,vn as z,Zt as A,cb as B,Ui as C,ji as D,Rn as E,Xo as F,Ql as G,Jo as H,qi as I,Ki as J,id as K,Ze as L,Qe as M,Yn as N,Yi as O,VI as P,Xn as Q,qI as R,cd as S,H as T,ld as U,ts as V,dd as W,y as X,Sn as Y,Cn as Z,Ut as _,ew as $,gu as aa,ms as ba,vu as ca,Su as da,Zr as ea,ct as fa,en as ga,tn as ha,b as ia,Me as ja,Pv as ka,Tn as la,La as ma,TT as na,MT as oa,St as pa,Ct as qa,Ju as ra,xs as sa,Pn as ta,On as ua,re as va,lr as wa,nt as xa,Xa as ya,Ne as za,sn as Aa,mo as Ba,yL as Ca,Om as Da,ks as Ea,Dm as Fa,Fm as Ga,Q as Ha,tc as Ia,Ls as Ja,rt as Ka,oP as La,mr as Ma,lc as Na,nE as Oa,mc as Pa,yc as Qa,Rc as Ra,Gs as Sa,Cc as Ta,LE as Ua,$p as Va,Tc as Wa,FE as Xa,jE as Ya,qE as Za,zc as _a,vO as $a,ln as ab,se as bb,br as cb,WR as db,TD as eb,S as fb,_D as gb,he as hb,ti as ib,ni as jb,U as kb,Lo as lb,FF as mb,og as nb,ii as ob,Po as pb,mS as qb,$n as rb,sg as sb,ol as tb,xr as ub,Rg as vb,il as wb,Ig as xb,wg as yb,mt as zb,pt as Ab,Rr as Bb,fi as Cb,EB as Db,gh as Eb,kr as Fb,y1 as Gb,Eh as Hb,Th as Ib,kW as Jb,Fh as Kb,_h as Lb,LW as Mb,Zh as Nb,ry as Ob,lV as Pb,cy as Qb,ly as Rb,Mi as Sb,gy as Tb,hy as Ub,Ry as Vb,QN as Wb,h as Xb,ve as Yb,w as Zb,Le as _b,ae as $b,gn as ac,dt as bc,ht as cc,rI as dc,C as ec,Wy as fc,Wh as gc,Ko as hc,qy as ic,Qa as jc,n4 as kc,ec as lc,r4 as mc};
|