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
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as Fi,c as Vl,d as ql,f as Kl}from"./chunk-WUCQWBQE.js";import{a as Yn,b as a,c as d,d as c,e as vt}from"./chunk-5RIQL7P4.js";import{createHash as cb}from"node:crypto";var rb=new Set(["https:","http:","ssh:","git:","file:"]),ob=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*:[^:]+$/,sb=/^[\x21-\x7e]+$/,ib=2048,Yl="Use https://, ssh://, git:// or user@host:path.",Xl=()=>globalThis.process?.env?.EPIQ_ALLOW_LOCAL_REPOS==="1",Fr=(e,t=Xl())=>{if(e.length>ib)return"is too long";if(!sb.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(ob.test(e))return null;let n;try{n=new URL(e)}catch{return"is not a remote URL"}return/%/.test(ab(e))?"percent-encodes its host":rb.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"},ab=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=Xl())=>Fr(e,t)===null;var $i=()=>({entries:{},seq:0}),Bi="default",Ui="board",xn=20,lb=/^\d{4}-\d{2}-\d{2}$/,db=/^[a-z0-9][a-z0-9._-]{0,23}$/,Jl=/-[0-9a-f]{12}$/,En=e=>e==="board"||e==="all"||ub(e),ub=e=>{if(!lb.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},Rn=e=>db.test(e)&&!Jl.test(e),mb=/^([^@/]+@)([^:/]+)(:.*)$/,pb=/^([a-z][a-z0-9+.-]*:\/\/)([^/]*)(.*)$/i,fb=e=>{let t=mb.exec(e);if(t)return`${t[1]}${t[2].toLowerCase()}${t[3]}`;let n=pb.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]}`},Zl=e=>fb(e.trim().replace(/\/+$/,"").replace(/\.git$/i,"")),Mt=e=>(Zl(e).toLowerCase().split(/[/:]/).filter(Boolean).pop()??"").replace(/[^a-z0-9._-]/g,"-").slice(0,24).replace(/^[.-]+/,"")||"repo",Zt=e=>`${Mt(e)}-${cb("sha1").update(Zl(e)).digest("hex").slice(0,12)}`,_r=e=>e.replace(Jl,""),Ql=e=>{let t={},{branches:n,since:r,label:o}=e;return(n==="default"||n==="all")&&(t.branches=n),typeof r=="string"&&En(r)&&(t.since=r),typeof o=="string"&&(o===""||Rn(o))&&(t.label=o),t},_i=(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},ji=(e,t)=>{let n=t.payload&&typeof t.payload=="object"?t.payload:{},r=Ql(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?_i(p,r):_i({id:u,url:l,branches:Bi,since:Ui,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=_i(s,r);return e.entries[o]=i,d("Edited repo",i)},gb=e=>e==="connect.repo"||e==="edit.repo"||e==="disconnect.repo",ed=e=>{let t=$i();for(let n of e)gb(n.action)&&ji(t,{action:n.action,payload:n.payload});return t},td=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,xn),overLimit:o.slice(xn),disconnected:t.filter(s=>!s.live).map(s=>s.id)}},Hi=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"?_r(t.repo):"";if(e.action!=="edit.repo")return r;let o=Ql(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 vn from"chalk";import Yy from"string-width";import{decodeTime as nd}from"ulid";var Jo=1440*60*1e3,Wi=(e,t=Date.now())=>e>t+Jo?t:e,Sn=e=>Wi(nd(e)),Zo=e=>{let t=Date.now()+Jo,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})},rd=e=>{try{return d("Decoded date",new Date(Sn(e)))}catch(t){return a("Decoding failed + "+t.message)}},Qo=e=>{if(!e?.id)return null;try{return nd(e.id)}catch{return null}};import Xn 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"},w={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},es={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 zi={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Vi=(e,t,n)=>Math.max(t,Math.min(n,e)),Gi=(e,t,n)=>e+(t-e)*n,sd=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},hb=e=>e.toLowerCase().trim(),yb=(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)]},qi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,od=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},id=(e,t,n)=>{let r=Vi(n,0,1);return[Math.round(Gi(e[0],t[0],r)),Math.round(Gi(e[1],t[1],r)),Math.round(Gi(e[2],t[2],r))]};var bb=(e,t,n)=>id(e,t,n),Ki=e=>{let t=sd(e)%360,n=yb(t,zi.stringColor.saturation,zi.stringColor.lightness);return qi(n)},Be=(e,t=es)=>{let n=hb(e??"");return n&&t[n]?t[n]:Ki(n)};var ad=e=>{let t=zi.gradient.stops,n=Vi(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 bb(t[s],t[s+1],i)},JI=(e,t)=>{if(e.length===0)return"#000000";if(e.length===1)return e[0];let n=e.length-1,r=Vi(t,0,1)*n,o=Math.min(Math.floor(r),n-1);return qi(id(od(e[o]),od(e[o+1]),r-o))},cd=e=>qi(ad(e)),ts=e=>sd(e.toLowerCase().trim())/4294967295,ld=e=>{let t=ts(e);return ad(t)},vb=e=>{let[t,n,r]=ld(e);return{normal:o=>Xn.bgRgb(t,n,r).black(o),cursor:o=>Xn.bgRgb(t,n,r).white.bold(o)}},ZI=e=>{let[t,n,r]=ld(e);return{fg:o=>Xn.rgb(t,n,r)(o),fgCursor:o=>Xn.rgb(t,n,r).inverse(o),bg:o=>Xn.bgRgb(t,n,r).black(o),bgCursor:o=>Xn.bgRgb(t,n,r).white.bold(o)}},ns=e=>vb(e).normal(` ${e} `);var xb="Unknown",Yi=(e,t)=>t?.length?t:e?.length?e:xb,Xi=(e,t)=>{let n=Yi(e,t);return{id:e?.length?e:n,name:n,color:Be(n)}};var dd="removed",Qe=(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")},ud=["png","jpg","gif","webp"];var et=e=>e.trim().toLowerCase(),Jn=e=>{let t=et(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},Ji=(e,t)=>`${et(e)} ${t}`,Zi=e=>!e.tombstoned,sw=(e,t)=>{let n=et(t),r=new Set;for(let o of Object.values(e))Zi(o)&&o.email===n&&r.add(o.contributor);return[...r]},Zn=(e,t)=>{let n=new Set;for(let r of Object.values(e))Zi(r)&&r.contributor===t&&n.add(r.email);return[...n]},iw=e=>{let t=new Map;for(let r of Object.values(e)){if(!Zi(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 md=(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 Qi(e){return e.context===te.WORKSPACE}function j(e){return e.context===te.TICKET}function pd(e){return e.context===te.TEXT}function Fe(e){return e.context===te.FIELD}function $r(e){return e.context===te.FIELD_LIST}var Qn=e=>e.context===te.SWIMLANE,Br=e=>e.context===te.BOARD,Ur=e=>e.context===te.COMMENT;import{useSyncExternalStore as pI}from"react";var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"};var fd=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",gd=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",hd=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",yd=(e,t)=>{if(gd(e,e.sequence))return S.MoveCursorLeftOfWord;if(hd(e,e.sequence))return S.MoveCursorRightOfWord;if(fd(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}},bd=(e,t)=>{if(gd(e,e.sequence))return S.MoveCursorLeftOfWord;if(hd(e,e.sequence))return S.MoveCursorRightOfWord;if(fd(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 vd from"string-width";function rs(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Cn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Eb=/\u001B\[[0-9;]*m/,ea="\x1B[0m",Rb=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Nn=(e,t)=>{if(t<=0)return"";if(vd(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(Eb.test(l)){o+=l,i=l!==ea&&l!=="\x1B[m";continue}for(let u of Rb(l)){let p=vd(u);if(s+p>r)return`${o}...${i?ea:""}`;o+=u,s+=p}}return`${o}...${i?ea:""}`},Ut=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),pw=e=>e.charAt(0).toUpperCase()+e.slice(1);var xd=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},Ed=(e,t)=>t?e.get(t)??[]:[];var Rd=new WeakMap,Sb=e=>{let t=Rd.get(e);return t||(t=xd(e),Rd.set(e,t)),t};var Sd=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ed(Sb(e),r).filter(s=>rs(r,s.toLowerCase())>=n)};var Cb={hint:"",hints:[],overlap:0,remainder:""},Nd=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[l]=s;return s.length===1&&l&&!r.trim()?Cd("",[l]):Cb}let i=Sd({wordList:o,inputToMatch:e,overlapThreshold:1});return Cd(t,i)},Cd=(e,t)=>{let n=t[0]??"",r=rs(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 er=e=>{let t=typeof e=="number"?e:Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<3e3||t>864e5?null:t},os=e=>e==null||!Number.isFinite(e)?1e4:Math.min(864e5,Math.max(1,e));import Zr from"node:fs";import Qr from"node:path";import{z as or}from"zod";import Jr from"node:fs";import{ulid as ov}from"ulid";import{z as ds}from"zod";import qr from"node:fs";import Lt from"node:path";import Qt from"node:fs";import ze from"node:path";import Nb from"node:os";import Ib from"node:path";var xt=".epiq-global",We=()=>process.env.EPIQ_GLOBAL_DIR??Ib.join(Nb.homedir(),xt);var ta=(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 Et from"fs";import ia from"path";import wb from"util";var Id=500,aa=4*1024*1024,na=16*1024,Ab=50,ra=0,wd=()=>process.env.EPIQ_MCP==="true",Tb=()=>{let e=process.cwd(),t=ss(e);return c(t)?wd()?ia.join(We(),"epiq-mcp.log"):void 0:ia.join(t.value,Ue,"log","epiq.log")},Mb=(e,t)=>{let n=Et.statSync(e).size;if(n<=t)return Et.readFileSync(e,"utf8");let r=Et.openSync(e,"r");try{let o=Buffer.alloc(t);Et.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
3
|
+
`);return i===-1?"":s.slice(i+1)}finally{Et.closeSync(r)}};function kb(e){if(!Et.existsSync(e))return;let t=Et.statSync(e).size,n=Mb(e,aa).split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=aa&&n.length<=Id)return;let r=n.slice(-Id).join(`
|
|
5
|
+
`)+`
|
|
6
|
+
`;Et.writeFileSync(e,r,"utf8")}var Lb=e=>{if(e.length<=na)return e;let t=e.length-na;return`${e.slice(0,na)} \u2026 [${t} more chars]`};function oa(e,t,n=!1){let r=Tb();if(!r)return;let o=Lb(wb.format(...t)),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
7
|
+
`;try{Et.mkdirSync(ia.dirname(r),{recursive:!0}),Et.appendFileSync(r,l,"utf8"),ra++,(ra>=Ab||Et.statSync(r).size>aa)&&(ra=0,kb(r))}catch{}}var sa=()=>wd()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",H={info(...e){let t=sa();(t==="info"||t==="debug")&&oa("[Info]",e,!1)},debug(...e){sa()==="debug"&&oa("[Debug]",e,!0)},error(...e){let t=sa();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;oa("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=H;import{spawn as kd}from"node:child_process";import Ge from"node:fs";import Se 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 Rt=e=>{let t=Ee(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)},tt="origin";var Ld="Output past",as=e=>e.includes(Ld),Pd="Git command timed out",Od=e=>e.includes(Pd),la=1e4,Pb=12e4,da=256*1024*1024,Dd=64*1024,Ob=8*1024*1024,Db=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),Fb=e=>{let t=_d(e);return t&&Db.has(t)?Pb:la},_b=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(Se.delimiter))if(t)for(let n of e){let r=Se.join(t,n);try{if(!Ge.statSync(r).isFile())continue;return Ge.accessSync(r,Ge.constants.X_OK),r}catch{continue}}return"git"},Fd=_b(),$b=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE"],Bb=e=>Object.fromEntries(Object.entries(e).filter(([t])=>!$b.includes(t))),ua={...Bb(process.env),GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Ub=["-c","diff.noprefix=false","-c","diff.mnemonicPrefix=false","-c","diff.srcPrefix=a/","-c","diff.dstPrefix=b/","-c","log.showSignature=false"],jb=new Set(["log","show","diff"]),_d=e=>e.find((t,n)=>!t.startsWith("-")&&e[n-1]!=="-c"),Hb=e=>jb.has(_d(e)??"")?Ub:[],$d=()=>["attr.tree=refs/epiq/no-attributes",`core.hooksPath=${Se.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]),Wb=/^[\w-]+[\\/][a-z0-9._-]+-[0-9a-f]{12}\.git(\.\d+(-\d+)?(\.[0-9a-f-]{36})?\.pending)?$/,Ad=e=>{try{return Ge.realpathSync(e)}catch{return Se.resolve(e)}},ma=e=>{let t=Se.join(We(),"repos");return[[Se.resolve(t),Se.resolve(e)],[Ad(t),Ad(e)]].some(([n,r])=>Wb.test(Se.relative(n,r)))},Gb=e=>ma(e)?["--git-dir=.",...$d()]:[],Bd={...Object.fromEntries(Object.entries(ua).filter(([e])=>e!=="GIT_ALLOW_PROTOCOL")),LC_ALL:"C",LANGUAGE:"",GIT_PROTOCOL_FROM_USER:"0"},is=new Set,Td=!1,Ud=process.platform!=="win32",jd=(e,t)=>{try{if(Ud&&e.pid){process.kill(-e.pid,t);return}}catch{}e.kill(t)},ca=(e="SIGTERM")=>{for(let t of is)jd(t,e)},zb=["SIGTERM","SIGINT","SIGHUP"],Hd=!1,Wd=()=>Hd,Vb=2e3,Gd=()=>{if(Td)return;Td=!0,process.once("exit",()=>ca());let e=new Map;for(let t of zb)e.set(t,()=>{Hd=!0;let n=()=>{for(let[s,i]of e)process.off(s,i);process.kill(process.pid,t)};ca();let r=Date.now()+Vb,o=()=>{if(is.size===0)return n();if(Date.now()>=r)return ca("SIGKILL"),n();setTimeout(o,20)};o()});for(let[t,n]of e)process.once(t,n)},zd=e=>{is.add(e),e.once("close",()=>is.delete(e))},Vd=({args:e,cwd:t,allowFail:n,timeoutMs:r,maxOutput:o=da,forClone:s=!1,keepPartial:i=!1,abort:l})=>new Promise(u=>{let p=ma(t),m=p||s,f=[...Hb(e),...p?["--git-dir=."]:[],...m?$d():[],...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&&Gd();let g=kd(Fd,f,{cwd:t,stdio:["ignore","pipe","pipe"],env:m?Bd:ua,detached:m&&Ud});m&&zd(g);let b=O=>m?jd(g,O):g.kill(O),N=!1,E="",R="",v=O=>{N||(N=!0,clearTimeout(L),u(O))},I=r??Fb(f),M=!1,k=()=>[`git ${f.join(" ")}`,`cwd=${t}`,`${Pd} after ${I}ms`].join(`
|
|
8
|
+
`),P=()=>v(n?{stdout:E,stderr:k(),exitCode:124}:a(k())),L=setTimeout(()=>{M=!0,b("SIGTERM"),setTimeout(()=>b("SIGKILL"),3e3).unref(),setTimeout(P,6e3).unref()},I),$=null,B=()=>{let O=[`git ${f.join(" ")}`,$].join(`
|
|
9
|
+
`);v(n?{stdout:E,stderr:O,exitCode:1}:a(O))},ce=()=>{$=String(l?.reason??"stopped"),b("SIGTERM"),setTimeout(()=>b("SIGKILL"),3e3).unref(),setTimeout(B,6e3).unref()};l?.aborted?ce():l?.addEventListener("abort",ce,{once:!0}),g.stdout.setEncoding("utf8"),g.stderr.setEncoding("utf8"),g.stdout.on("data",O=>{if(E+=O,E.length>o){if(b("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 V=`git ${f.join(" ")}
|
|
11
|
+
${Ld} ${o} characters; stopped`;v(n?{stdout:"",stderr:V,exitCode:1}:a(V))}}),g.stderr.on("data",O=>{R.length<Dd&&(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",ce),M)return P();if($!==null)return B();let V=O??1;if(n){v({stdout:E,stderr:R,exitCode:V});return}if(V!==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:V}))})}),_=({args:e,cwd:t,timeoutMs:n,maxOutput:r,forClone:o,keepPartial:s,abort:i})=>Vd({args:e,cwd:t,allowFail:!1,timeoutMs:n,maxOutput:r,forClone:o,keepPartial:s,abort:i}),Ce=({args:e,cwd:t})=>Vd({args:e,cwd:t,allowFail:!0}),qd=(e,t)=>new Promise(n=>{if(e.length===0){n(d("No blobs to read",new Map));return}let r=ma(t);r&&Gd();let o=kd(Fd,[...Gb(t),"cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:r?Bd:ua});r&&zd(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 ${la}ms`))},la),m=0;o.stdout.on("data",f=>{if(m+=f.length,m>da){o.kill("SIGTERM"),u(a(`git cat-file --batch: past ${da} bytes; stopped`));return}s.push(f)}),o.stderr.setEncoding("utf8"),o.stderr.on("data",f=>{i.length<Dd&&(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),b=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 M=Number(I[1]);M<=Ob&&b.set(E,g.toString("utf8",N,N+M)),N+=M+1}u(d("Read blobs",b))}),o.stdin.write(e.join(`
|
|
15
|
+
`)+`
|
|
16
|
+
`),o.stdin.end()}),nr=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())},jr=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",Se.isAbsolute(n)?n:Se.resolve(e,n))},pa=async e=>{let t=await jr(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(Se.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(Se.join(n,s)))return d("Checked for in-progress Git operation",i);return d("Checked for in-progress Git operation",null)},Kd=async e=>{let t=await pa(e);return c(t)?a(t.message):d("Checked for in-progress Git operation",t.value!==null)},jt=async({repoRoot:e})=>{let n=(await Ce({args:["remote","get-url",tt],cwd:e})).exitCode===0;return d(`Checked remote ${n}`,n)},Hr=async({repoRoot:e,branch:t})=>{let n=await Ce({args:["ls-remote","--heads",tt,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${tt}/${t}`):d("Checked remote branch",n.stdout.trim().length>0)},cs=async({repoRoot:e,branch:t})=>{let n=await Ce({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}`)},tr=e=>{try{return Ge.realpathSync.native(e)}catch{return Se.resolve(e)}},Yd=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return a(n.message);let r=tr(t),o=n.value.stdout.split(`
|
|
19
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(tr).includes(r);return d("Checked worktree registration",o)},fa=async e=>{let t=await Ce({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return d("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},ls=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())},Xd=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())},Jd=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Zd=async e=>{let t=await Ce({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?Ge.existsSync(Se.join(n,"rebase-merge"))||Ge.existsSync(Se.join(n,"rebase-apply")):!1},qb=3,Kb=120,Yb=e=>new Promise(t=>setTimeout(t,e)),Xb=async(e,t)=>{let n=await ue.rebaseOnto({cwd:e,ref:t});for(let r=1;r<qb;r+=1){if(!c(n)||await Zd(e))return n;await Yb(Kb),n=await ue.rebaseOnto({cwd:e,ref:t})}return n},Qd=async(e,{preserve:t=[]}={})=>{let n=await jr(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(Se.join(r,s),{force:!0}),o.push(s)}catch{}return d("Cleared stale git lock files",o)},eu=async(e,t)=>{let n=await Ce({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=Se.resolve(e,n.stdout.trim()),o=Se.join(r,"refs","heads"),s=Se.resolve(o,`${t}.lock`);if(!s.startsWith(`${o}${Se.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)},ga=async e=>{if(!await Zd(e))return d("No rebase to abort",!1);let t=await Ce({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)},Md=async e=>{let t=await Ce({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},Wr=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),Jb=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),Gr=async({cwd:e,branch:t})=>{let n=await ga(e);if(c(n))return a(n.message);let r=await Md(e),o=await ue.fetch({cwd:e,remote:tt,branch:t});if(c(o))return Jb(o.message)?d("Remote branch missing, skipped pull",!1):a(`Failed to fetch ${t}
|
|
21
|
+
${o.message}`);let s=await Xb(e,`${tt}/${t}`);if(c(s))return a(`Failed during rebase
|
|
22
|
+
${s.message}`);let i=await Md(e),l=r!==null&&i!==null&&r!==i;return d(l?"Pulled with rebase":"Already up to date",l)},tu=async e=>{let t=await Ce({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)},nu=async e=>{let t=await Ce({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)},ru=async(e,t)=>{let n=await Ce({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 ou=async e=>{let t=await ls(e);return c(t)?a(t.message):d("Checked detached HEAD state",t.value==="HEAD")};var au="4b825dc642cb6eb9a060e54bf8d69288fbee4904",cu=e=>ze.join(Ue,Ht,e),lu=()=>ze.join(Ue,ba),du=We,In=()=>ze.join(du(),"worktrees"),be=({repoRoot:e})=>{let t=kt(e);return c(t)?a(t.message):d("Resolved state branch root",ze.join(In(),t.value))},Zb=e=>ze.join(e,Ue),su=e=>ze.join(Zb(e),Ht);var zr=e=>{try{return Qt.mkdirSync(e,{recursive:!0}),d("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Vr=()=>{let e=du(),t=In(),n=!Qt.existsSync(e)||!Qt.existsSync(t),r=zr(e);if(c(r))return a(`Ensure epiq home failed.
|
|
23
|
+
`+r.message);let o=zr(t);return c(o)?a(`Ensure worktrees dir failed.
|
|
24
|
+
`+o.message):d("Ensured epiq storage",n)},uu=e=>{Qt.existsSync(e)&&(H.debug("[sync] remove path",e),Qt.rmSync(e,{recursive:!0,force:!0}))};var Qb=`*.jsonl merge=union
|
|
25
|
+
`,ev=`*~pending*.jsonl
|
|
26
|
+
`,ha=()=>ze.join(Ue,Ht,".gitattributes"),ya=()=>ze.join(Ue,Ht,".gitignore"),iu=(e,t)=>{try{Qt.readFileSync(e,"utf8")!==t&&Qt.writeFileSync(e,t)}catch{Qt.writeFileSync(e,t)}},mu=(e,t)=>{for(let n of[su(e),su(t)]){let r=zr(n);if(c(r))return a(r.message)}return iu(ze.join(t,ha()),Qb),iu(ze.join(t,ya()),ev),d("Ensured state branch",void 0)},pu=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 nr({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return c(s)?a(s.message):d("Cleaned storage branch",!0)},St=ta(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)),cA=ta(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 gA=process.env.IS_LOCAL==="true",Ue=".epiq",Ht="events",ba="media",tv="project.json",Kr=e=>Lt.join(e,Ue),rr=e=>Lt.join(Kr(e),tv),Ve=e=>Lt.join(Kr(e),Ht),Yr=e=>Lt.join(Kr(e),ba),fu=e=>Lt.join(e,Ue),nv=e=>{let t=Lt.join(e,Ue);return qr.existsSync(t)&&qr.statSync(t).isDirectory()},Xr=e=>{let t=rr(e);return qr.existsSync(t)&&qr.statSync(t).isFile()},ss=e=>{let t=Lt.resolve(e);for(;;){if(nv(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}},rv="No .epiq/project.json found in any parent",Ee=e=>{let t=Lt.resolve(e);for(;;){if(Xr(t))return d("Resolved closest epiq project root",t);let n=Lt.dirname(t);if(n===t)return a(rv);t=n}},gu=e=>{let t=Ve(e);try{return qr.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 St(process.cwd());if(c(e))return e;let t=be({repoRoot:e.value});return c(t)?t:d("Resolved persist root",t.value)};var va="__epiq_state__",sv=ds.object({projectId:ds.string().min(1),stateBranch:ds.string().min(1),createdAt:ds.iso.datetime()}),us=()=>({projectId:ov(),stateBranch:va,createdAt:new Date().toISOString()}),je=e=>{let t=rr(e);if(!Jr.existsSync(t))return a("Missing .epiq/project.json");try{let n=Jr.readFileSync(t,"utf8"),r=JSON.parse(n),o=sv.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)},xa=({repoRoot:e,fileContents:t})=>{let n=Kr(e),r=rr(e);try{if(Jr.mkdirSync(n,{recursive:!0}),Jr.existsSync(r)){let o=je(e);return c(o)?a(o.message):d("Project already initialized",null)}return Jr.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 ms="recent-projects.json",iv=20,av=or.object({projectId:or.string().min(1),root:or.string().min(1),lastOpenedAt:or.number().finite()}),cv=or.object({projects:or.array(av)}),yu=()=>Qr.join(We(),ms),bu=e=>Qr.basename(e)||e,hu=e=>{let t=Qr.resolve(e);try{return Zr.realpathSync(t)}catch{return t}},vu=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,xu=e=>{if(!Xr(e.root))return!1;let t=kt(e.root);return!c(t)&&t.value===e.projectId},Eu=()=>{let e=yu();if(!Zr.existsSync(e))return d("No recent projects recorded",[]);let t;try{t=JSON.parse(Zr.readFileSync(e,"utf8"))}catch(r){return a(`Invalid ${ms}: ${r instanceof Error?r.message:String(r)}`)}let n=cv.safeParse(t);return n.success?d("Read recent projects",n.data.projects):a(`Invalid ${ms} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},lv=e=>{let t=yu();try{Zr.mkdirSync(Qr.dirname(t),{recursive:!0}),Zr.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
31
|
+
`,"utf8")}catch(n){return a(`Unable to write ${ms}: ${n instanceof Error?n.message:String(n)}`)}return d("Recorded recent project",e)},ps=({exclude:e}={})=>{let t=Eu();if(c(t))return t;let n=e===void 0?null:hu(e);return d("Listed recent projects",t.value.filter(r=>n===null||hu(r.root)!==n).filter(xu).sort(vu))},Ru=({root:e,now:t=Date.now()})=>{let n=Qr.resolve(e),r=kt(n);if(c(r))return a(r.message);let o=r.value,s=Eu(),i=c(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(xu).sort(vu).slice(0,iv);return lv(l)};import{useSyncExternalStore as dv}from"react";var eo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},Ea=new Set,uv=()=>{for(let e of Ea)e()},ee=()=>eo,DA=()=>dv(e=>(Ea.add(e),()=>{Ea.delete(e)}),()=>eo),at=e=>(eo={...eo,...e},uv(),eo);var Ra=null,Su=e=>{Ra=e},Cu=e=>Ra?Ra(e):[];var Nu=[],Iu=e=>{Nu=e},sr=()=>Nu;var to=()=>{let e=ee(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=wu(),s=o.length>0?null:Sa(),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}},Sa=()=>{let e=Ee(process.cwd());if(c(e))return null;let t=kt(e.value);return c(t)?null:t.value||null},wu=()=>{let{userId:e}=ee();return e?Cu(e):[]},Au=()=>wu().length>0;var Ca=()=>{let e=Ee(process.cwd());if(c(e))return!1;let t=je(e.value);return vt(t)},Tu=e=>e===!0?"on":e===!1?"off":null,Mu=e=>e==="on"?!0:e==="off"?!1:null,ku=()=>{let e=to();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!Ca())return"init";if(!e.isSetEmails){let{gitEmail:t}=ee(),n=sr()[0]??t;return n&&Jn(n)?`config emails ${n}`:"config emails "}return null};var mv=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ct,fs]=mv;var pv=e=>e.props.tags??[],fv=e=>e.props.assignees??[],en=e=>pv(e).map(t=>C.getTag(t)).filter(t=>!!t),tn=e=>fv(e).map(t=>C.getContributor(t)).filter(t=>!!t),gs=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!j(n)?a("Invalid untag target"):d("Retrieved tags from ticket in breadcrumb",en(n))},hs=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!j(n)?a("Invalid unassign target"):d("Retrieved assignees from ticket in breadcrumb",tn(n))};var x={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 gv=/^(\d+)(h|d|w|mo|y)$/,hv=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,yv=({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},bv=(e,t=new Date)=>{let n=e.match(gv);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}},vv=e=>{let t=e.match(hv);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 yv({year:l,month:u,day:p,hour:m,minute:f})?new Date(l,u-1,p,m,f):null},wn=e=>{let t=e.trim().toLowerCase();return bv(t)??vv(t)};var Lu=/^(\d+)(s|m)?$/,ys=e=>{let t=e.trim().toLowerCase().match(Lu);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},bs=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Lu.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Pu=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,xv=[{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}],Na=(e=xv)=>{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 Ev=["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"},lt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Te={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Rv=[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],Sv=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":case"BOARD":case"SWIMLANE":return[lt.TITLE,lt.DESCRIPTION];case"COMMENT":return[lt.COMMENT];default:return[]}},wa=[String(3e3),"5000","15000","30000","60000"],Aa=["250","500","1000"],Ta=["512","2048","8192"],Fu=["10s","20s","30s","45s"],An=[x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG,x.YANK],vs=[x.NEW,x.EDIT,x.DELETE,x.MOVE],Ia=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],Ou=[x.FILTER,x.PEEK,x.REPLAY],Cv={WORKSPACE:[...An,...vs],BOARD:[...Ou,...An,...vs],SWIMLANE:[...Ou,...An,...vs],TICKET:[...An,...vs,...Ia],FIELD:[...An,...Ia],FIELD_LIST:[...An,...Ia],TEXT:[...An],COMMENT:[x.EDIT,x.DELETE,x.YANK]},Nv=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],no=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&j(n)),Du=e=>e.parentNodeId===ct,Iv=({selectedNode:e,breadCrumb:t})=>{let n=Sv(e?.context);return no({breadCrumb:t,selectedNode:e})?n.includes(lt.DESCRIPTION)?n:[...n,lt.DESCRIPTION]:n},wv=({selectedNode:e,breadCrumb:t})=>{let n=no({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]:[]},Ma=()=>{let e=ps({exclude:process.cwd()});return c(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},Av=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=to();if(!r)return[x.HELP,x.CONFIG];if(!Ca())return[x.HELP,x.INIT,x.OPEN];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG,x.YANK];let o=e?.context,s=o&&Ev.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Cv[u]:[]))],l=no({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.YANK?!!(l??e):u===x.EDIT?s||!!l:u===x.DELETE?s:u===x.UNTAG?!!(l&&en(l).length>0):u===x.UNASSIGN?!!(l&&tn(l).length>0):u===x.RE_OPEN_ISSUE?!!(l&&Du(l)):u===x.CLOSE_ISSUE?!!(l&&!Du(l)):!0)},Me=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:Av({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.OPEN]:e===x.OPEN?Ma():[],[x.HELP]:[],[x.PEEK]:[...Na(),"now","prev","next"],[x.REPLAY]:[...Na()],[x.EDIT]:Iv({selectedNode:n,breadCrumb:o}),[x.YANK]:wv({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(es),...C.getExistingTags()])],[x.UNTAG]:[...gs()?.value?.map(({name:l})=>l)??[]],[x.UNASSIGN]:[...hs()?.value?.map(({name:l})=>l)??[]],[x.ASSIGN]:C.getExistingAssignees(),[x.NEW]:Nv(s),[x.CONFIG]:[...Rv]}[e]??[]};import wf from"chalk";var _u=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import zv from"zod";import Fv from"node:path";import{z as dt}from"zod";import{accessSync as Tv,copyFileSync as Mv,existsSync as xs,mkdirSync as $u,readdirSync as Bu,readFileSync as kv,renameSync as Lv,rmSync as Pv,statSync as Uu,unlinkSync as Ov,writeFileSync as Dv}from"node:fs";import ir from"node:path";var ka=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Oe={writeToFile:(e,t)=>{try{let n=ir.dirname(e);xs(n)||$u(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Dv(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return kv(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 xs(e)&&Uu(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Tv(e),!0}catch{return!1}},mkDir:e=>$u(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ir.parse(t);for(;;){let r=ir.join(t,e);try{if(xs(r)&&Uu(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ir.dirname(t)}return null},readFirstJSON(e){try{if(!Oe.dirExists(e))return null;let t=Bu(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=ir.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)?Bu(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Ov(e)}catch(t){(!ka(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Pv(e,{recursive:!0,force:!0})}catch(t){(!ka(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ir.dirname(t)),!n?.overwrite&&xs(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Lv(e,t)}catch(r){if(ka(r)&&r.code==="EXDEV"){Mv(e,t),this.rmFile(e);return}throw r}}};var _v={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Hu=dt.object({logLevel:dt.enum(["info","error","debug"]),preferredEditor:dt.string().optional(),userName:dt.string().optional(),userId:dt.string().optional(),autoSync:dt.boolean().nullable().optional(),autoSyncDebounceMs:dt.number().optional(),attachmentMaxKb:dt.number().optional(),repoCloneMaxMb:dt.number().optional(),viewMode:dt.enum(["dense","wide"]).optional(),declinedEmailBoards:dt.array(dt.string()).optional()}).partial(),$v="config.json",Wu=We,La=()=>Fv.join(Wu(),$v),Pa=()=>{try{return Oe.mkDir(Wu()),d(`Ensured ~/${xt} exists`,null)}catch{return a(`Unable to create ~/${xt}`)}},Bv=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${xt}/config.json JSON`)}let n=Hu.safeParse(t??{});return n.success?d("Parsed config",n.data):a(`Invalid ~/${xt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Pt=()=>{let e=Pa();if(c(e))return a(e.message);let t=La(),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}):Bv(n)},Gu=e=>{let t=Pa();if(c(t))return a(t.message);let n=Hu.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=La();try{return Oe.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
32
|
+
`),d("Config written",null)}catch{return a(`Unable to write ~/${xt}/config.json`)}},qe=e=>{let t=Pt();if(c(t))return a("Failed to read existing config");let n={...t.value,...e};return Gu(n)},zu=()=>{let e=La(),t=Pa();if(c(t))return a(`Unable to create ~/${xt}`);if(!(Oe.readFile(e)!==null)){let E=Gu(_v);if(c(E))throw new Error(`Unable to create ~/${xt}/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,b=Kl({userId:i,userName:s});if(c(b))return a(b.message);let N=b.value??{userId:i,userName:s};return!N.userName||!N.userId?a(`User name or ID not configured in ~/${xt}/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 jv from"node:crypto";import ro from"node:fs";import Ku from"node:path";var Vu="/media/",qu=e=>`${Vu}${e}`,Uv=(e,t)=>`})`;var Mn=500,Hv=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Oa=(e,t)=>`${e}.${t}`,Wv=e=>Hv.test(e),Yu=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: ${ud.join(", ")}`),Xu=e=>jv.createHash("sha256").update(e).digest("hex"),Gv=(e,t=Mn)=>{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=Yu(e);return c(n)?n:d("Validated attachment data",{hash:Xu(e),ext:n.value,bytes:e.length})},HT=(e,t,n=Mn)=>{let r=Gv(t,n);if(c(r))return r;let o=Yr(e),s=Ku.join(o,Oa(r.value.hash,r.value.ext));try{ro.existsSync(s)||(ro.mkdirSync(o,{recursive:!0}),ro.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)},WT=(e,t,n=Mn)=>{if(!Wv(t))return a("Invalid attachment file name");let r=Ku.join(Yr(e),t);if(!ro.existsSync(r))return a("Attachment blob not found");let o;try{o=ro.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(Xu(o)!==s)return a("Attachment blob does not match its content hash");let l=Yu(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 oo=50,so=5e3,Ju=()=>{let e=Y().commandMeta.inputString,t=zv.coerce.number().int().min(oo).max(so).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${oo}-${so} KB (default ${Mn})`);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 Zu from"node:fs";import Vv from"node:path";var Da=2048,ar=1,cr=1048576,Fa=e=>Number.isInteger(e)&&e>=ar&&e<=cr,lr=()=>{let e=Pt(),t=c(e)?void 0:e.value.repoCloneMaxMb;return t!==void 0&&Fa(t)?t:Da},nn=e=>{let t=0,n=r=>{let o;try{o=Zu.readdirSync(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=Vv.join(r,s.name);if(s.isDirectory()){n(i);continue}try{t+=Zu.lstatSync(i).size}catch{}}};return n(e),t},io=e=>`Its clone would pass this machine's ${e} MB cap for a connected repo: narrow its history, or raise repoCloneMaxMb`;var Ct=e=>{let t=Ee(e??process.cwd());return c(t)?a(t.message):d("Resolved Epiq repo root",t.value)},kn=e=>/^[0-9a-f]{7,40}$/i.test(e);import{createHash as Lx}from"node:crypto";import jm from"node:path";import Px from"node:fs";import{ulid as Ox}from"ulid";import _a from"node:fs";import qv from"node:path";var ao=e=>e?.code==="ENOENT",$a=3,Ba=e=>_a.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),Nt=e=>{let t=Ve(e);for(let n=1;;n++){if(!_a.existsSync(t))return"none";let r=[],o=!1;for(let s of Ba(t))try{let{size:i,mtimeMs:l}=_a.statSync(qv.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!ao(i))throw i;if(n<$a){o=!0;break}}if(!o)return r.join("|")}},Qu=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Ua=(e,t,n,r)=>{let o=Qu(t),s=Nt(e),i=Qu(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,em=e=>Wt&&Wt.root===e?Wt.signature:null,Es=(e,t)=>{Wt={root:e,signature:t}},tm=(e,t,n)=>{if(!Wt||Wt.root!==e)return;let r=Ua(e,Wt.signature,t,n);Wt=r===null?null:{root:e,signature:r}},nm=()=>{Wt=null};import{z as Ln}from"zod";var rm=1,om=Ln.tuple([Ln.string().min(1),Ln.string().min(1).nullable()]),Kv=Ln.looseObject({v:Ln.literal(rm),id:om}),gM=Ln.looseObject({v:Ln.number().int().positive(),id:om}),Yv=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),Xv=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},sm=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",Yv(e)?Xv(e):e)};var Jv=[1];var Zv=new Set(Jv),ja=e=>Zv.has(e),im=e=>{let t=Kv.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(", ")}`)},Ha=(e,t)=>{let n={[e.action]:e.payload,v:rm,id:t};return im(n)};import uo from"node:fs";import ws from"node:path";import{decodeTime as ix}from"ulid";import{z as za}from"zod";import Ne from"node:fs";import Pn from"node:path";import{ulid as Qv}from"ulid";var Ss="~pending",Wa=/~pending(-[0-9a-z]+)*$/i,cm=/-f(\d+)$/,lm=e=>{let t=e.indexOf(".");return t===-1?`${e}${Ss}`:e.slice(0,t)+Ss+e.slice(t)},Cs=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},ex=e=>{let[t,n]=Cs(e);return Wa.test(t)?t.replace(Wa,"")+n:null},Ga=e=>e.replace(Wa,""),On=e=>e.endsWith(".jsonl")&&ex(e)!==null,co=e=>Ga(Cs(e)[0]),dm=e=>{let[t]=Cs(e),n=cm.exec(t);return n&&On(e)?Number(n[1]):null},tx=e=>lm(e).replace(Ss,`${Ss}-${Qv().toLowerCase()}`),nx=(e,t)=>{let[n,r]=Cs(e);return`${n.replace(cm,"")}-f${t}${r}`},um=(e,t)=>Pn.join(Ve(e),lm(t)),rx=(e,t)=>Math.max(0,Ne.statSync(e).size-(dm(t)??0)),mm=e=>{let t=Ve(e);try{return Ne.existsSync(t)?Ne.readdirSync(t).filter(On).some(n=>rx(Pn.join(t,n),n)>0):!1}catch{return!0}},ox=3,pm=(e,t)=>{for(let n=1;;n++){let r=Ne.openSync(e,"a"),o;try{Ne.writeSync(r,t),o=Ne.fstatSync(r).ino}finally{Ne.closeSync(r)}let s;try{s=Ne.statSync(e).ino}catch{s=null}if(s===o||n>=ox)return}},sx=e=>{let t;try{t=Ne.openSync(e,"r")}catch{return!0}try{let{size:n}=Ne.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ne.readSync(t,r,0,1,n-1),r[0]===10}finally{Ne.closeSync(t)}},Rs=10,am=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(Rs)+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};Ne.appendFileSync(e,Buffer.concat([Buffer.from(sx(e)?"":`
|
|
33
|
+
`),o,Buffer.from(o[o.length-1]===Rs?"":`
|
|
34
|
+
`)]));let s=0;for(let i of o)i===Rs&&s++;return o[o.length-1]!==Rs&&s++,{bytes:r,lines:s}},Ns=(e,t)=>{let n=Ve(e);if(!Ne.existsSync(n))return d("No events directory",0);try{let r=co(t),o=Ne.readdirSync(n).filter(l=>On(l)&&co(l)===r),s=Pn.join(n,t),i=0;for(let l of o){let u=dm(l);if(u!==null){let g=Pn.join(n,l),b=Ne.readFileSync(g).subarray(u);i+=am(s,b,!0).lines,Ne.rmSync(g,{force:!0});continue}let p=/~pending-/i.test(l)?l:tx(t),m=Pn.join(n,p);p!==l&&Ne.renameSync(Pn.join(n,l),m);let f=am(s,Ne.readFileSync(m));i+=f.lines,Ne.renameSync(m,Pn.join(n,nx(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 As="unknown",ax=za.object({userId:za.string().min(1).default(As),userName:za.string().min(1).default(As)}),ym=new Set(["id","v","userId","userName"]),Is=e=>{let t=Object.entries(e).filter(([o])=>!ym.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},cx=/^[0-9a-hjkmnp-tv-z]{26}$/i,lx=e=>cx.test(e)?e.toUpperCase():e,bm=e=>{let t=ws.basename(e,".jsonl"),n=t.indexOf("."),r=Ga(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=ax.safeParse({userId:lx(r),userName:o});return s.success?d("Parsed event file actor",s.data):a(`Invalid event file name ${ws.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},dx=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])},ux=(e,t)=>t in e,rn=new Map,mx=3e5,px=512,lo=0,Va=e=>e.entries.length+e.quarantined.length,fx=(e,t,n,r)=>{let o=rn.get(e);o&&(lo-=Va(o));let s={stamp:t,entries:n,quarantined:r};rn.delete(e),rn.set(e,s),lo+=Va(s);for(let[i,l]of rn){if(lo<=mx&&rn.size<=px)break;i!==e&&(rn.delete(i),lo-=Va(l))}},gx=()=>{rn.clear(),lo=0},hx=2n,fm=1000000n,yx=e=>{try{let{size:t,mtimeNs:n}=uo.statSync(e,{bigint:!0});return{value:`${t}:${n}`,settled:BigInt(Date.now())*fm-n>hx*fm}}catch{return null}},vm=(e,t)=>{let n=bm(e);if(c(n))return a(n.message);let r=yx(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=uo.readFileSync(e,"utf8")}catch(m){if(ao(m))return d("Event file missing",null);throw m}let i=[],l=ws.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 b;try{b=JSON.parse(g)}catch{p(m+1,"invalid JSON");continue}let N=sm(b);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&&fx(e,r.value,i,u),d("Parsed persisted events file",[...i])},gm=(e,t)=>e<t?-1:e>t?1:0,qa=(e,t)=>{let n=gm(e.id[0],t.id[0]);return n!==0?n:gm(JSON.stringify(e),JSON.stringify(t))},hm=(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 b=r.get(g)??[];b.push(m),r.set(g,b)}for(let m of r.values())m.sort(qa);let o=[],s=new Set,i=m=>{let f=[m];for(;f.length>0;){let g=f.pop(),b=g.id[0];if(s.has(b))continue;o.push(g),s.add(b);let N=r.get(b)??[];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=>!ym.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(qa);for(let m of u)i(m);let p=e.filter(m=>!s.has(m.id[0])).sort(qa);for(let m of p)i(m);return o},Ka=e=>Zo(e.map(t=>{try{return ix(t.id[0])}catch{return null}})),xm=(e,t)=>{let n=new Set,r=[],o=[],s=Ka(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}},Em=e=>{let t=new Set(e.actions),n=v=>t.has(v),r=v=>{let{userId:I,userName:M,...k}=v,P=dx(k);if(c(P))return a(P.message);let L=P.value,$=v.id?.[0];return $?ux(k,L)?d("Decoded persisted event",{id:$,action:L,payload:k[L],userId:I}):a(`Persisted event is missing payload for action: ${L}`):a("Persisted event is missing id")},o=(v,I)=>{let M=[],k=new Map,P=new Map;for(let L of v){if(!ja(L.v)){P.set(L.v,(P.get(L.v)??0)+1),I?.push({eventId:L.id[0],reason:"unsupported-schema-version",detail:`v${L.v}`,targetNodeId:Is(L)});continue}let $=r(L);if(c($)){I?.push({eventId:L.id[0],reason:"invalid-payload",detail:$.message,targetNodeId:Is(L)});continue}let B=$.value.action;if(!n(B)){k.set(B,(k.get(B)??0)+1),I?.push({eventId:L.id[0],reason:"unknown-action",detail:B,targetNodeId:Is(L)});continue}let ce=e.readPayload(B,$.value.payload);if(c(ce)){I?.push({eventId:L.id[0],reason:"invalid-payload",detail:ce.message,targetNodeId:Is(L)});continue}M.push($.value)}if(k.size>0){let L=[...k.entries()].map(([$,B])=>`${$} (x${B})`).join(", ");H.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${L}. Upgrade to apply them.`)}if(P.size>0){let L=[...P.entries()].map(([$,B])=>`v${$} (x${B})`).join(", ");H.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${L}. Upgrade to apply them.`)}return d("Decoded reconstructed events",M)},s=null;function i(v,I){let M=Ve(v),k=Nt(v);if(!uo.existsSync(M))return d("No events found",[]);let P=[],L=[];for(let B=1;;B++){P=[],L=[];let ce=!1;for(let O of Ba(M)){let V=vm(ws.join(M,O),L);if(c(V))return a(V.message);if(V.value===null){if(B<$a){ce=!0;break}continue}for(let Pe of V.value)P.push(Pe)}if(!ce)break}if(I)for(let B of L)I.push(B);let $=hm(P,e.genesis);return s={root:v,signature:k,edge:$.at(-1)?.id?.[0]??null},d("All events loaded",$)}function l(v){let I=[],M=i(v,I);if(c(M))return a(M.message);let k=o(M.value,I);return c(k)?a(k.message):d("Loaded merged events",{events:k.value,unreadable:I})}function u(v){let I=i(v);return c(I)?a(I.message):d("Loaded event actors",I.value.map(({userId:M,userName:k})=>({userId:M,userName:k})))}function p(v){let I=new Map,M=Ve(v),k;try{if(!uo.existsSync(M))return I;k=uo.readdirSync(M)}catch{return I}let P=new Set;for(let $ of k){if(!$.endsWith(".jsonl"))continue;let B=bm($);if(c(B))continue;let{userId:ce,userName:O}=B.value;if(!ce||!O||O===As)continue;let V=I.get(ce);V!==void 0&&V!==O&&P.add(ce),I.set(ce,O)}if(P.size===0)return I;let L=u(v);if(c(L))return I;for(let{userId:$,userName:B}of L.value)P.has($)&&(!B||B===As||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 M=i(v);if(c(M))return a(M.message);let{appliedEvents:k,unappliedEvents:P}=xm(M.value,I),L=o(k);if(c(L))return a(L.message);let $=o(P);return c($)?a($.message):d("Loaded merged events before time",{appliedEvents:L.value,unappliedEvents:$.value})}function g(v=process.cwd()){let I=Nt(v);if(s&&s.root===v&&s.signature===I)return d("Loaded edge reference, unchanged",s.edge);let M=i(v);return c(M)?a(M.message):d("Loaded edge reference",M.value.at(-1)?.id?.[0]??null)}function b(v,I,M,k){if(!s||s.root!==v)return;let P=Ua(v,s.signature,I,k);s=P===null?null:{root:v,signature:P,edge:M}}function N(){s=null,gx()}let E=v=>hm(v,e.genesis);function R(v){let I=i(v);if(c(I))return a(I.message);let M=Ka(I.value);return d("Loaded effective event times",new Map(I.value.map((k,P)=>[k.id[0],M[P]??null])))}return{fromPersistedEvent:r,decodeReconstructedEvents:o,loadMergedEventsWithUnreadable:l,loadEventActors:u,loadActorNames:p,loadMergedEvents:m,loadMergedEventsBefore:f,getEdgeRef:g,advanceEdgeRef:b,clearEdgeCache:N,getSortedEvents:E,loadEffectiveEventTimes:R}};var Ts=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...Ts(e,t),convergence:!0}),dr=e=>c(e)&&e.convergence===!0,Dn=e=>{let t=e.filter(c);return{fatal:t.filter(n=>!dr(n)),skipped:t.filter(dr)}},Fn=e=>{e.length!==0&&H.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},bx=e=>e.userId?.length?null:Ts("Invalid user ID format",e),Rm=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=bx(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 Nm from"node:fs";import Ya from"node:path";import{decodeTime as vx,monotonicFactory as xx}from"ulid";var Sm=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";var ne=({userId:e})=>({userId:e}),Cm=e=>({action:e.action,payload:e.payload});var Ex=0xffffffffffff,Rx=Jo,Sx=e=>{let t=Date.now(),n;try{n=vx(e)}catch{return t}return n>=Ex?t:n>t+Rx?(H.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)},ur=({userId:e})=>`${Sm(e)}.jsonl`,Im=(e,t)=>{let n;try{if(!Nm.existsSync(e))return[t];n=Nm.readdirSync(e)}catch{return[t]}let r=co(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||On(s)?!1:co(s)===r).sort(),t]},wm=(e,{userId:t})=>{let n=ur({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return a(`Invalid event log file name: ${n}`);let o=Ya.join(Ve(e),n);return d("Successfully resolved event log path",o)},Am=e=>{let t=xx();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(Sx(i)):t();return d("Minted event id",[l,i])}function r({event:o,rootDir:s,edge:i,id:l}){try{let u=gu(s);if(c(u))return u;let p=wm(s,{userId:o.userId});if(c(p))return p;let m=um(s,Ya.basename(p.value)),f=l?d("Minted event id",l):n(s,i);if(c(f))return a(f.message);let[g,b]=f.value,N=Ha(Cm(o),[g,b]);if(c(N))return a(N.message);let E=`${JSON.stringify(N.value)}
|
|
36
|
+
`;pm(m,E),i&&(i.current=g);let R=Ya.basename(m);return e.advanceEdgeRef(s,R,g,Buffer.byteLength(E)),tm(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 Tm=(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!==Yn.Success)return m;let f=n.persist({event:p,rootDir:i,edge:l,id:u.value});return c(f)?(nm(),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],b=>r(b,i,p));if(c(m))return a(m.message);let f=s.map(b=>r(b,i,p)),g=f.filter(c);return g.length>0?a("Materialize and persist failed: "+g.map(b=>b.message).join(", ")):d("Materialization succeeded",f.map(b=>b.value))});return c(u)?a(u.message):u.value??a("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}};var Mm=e=>{let t=Rm(e),n=Em(e),r=Am(n),o=Tm(e,t,r);return{...t,...n,...r,...o}};import{z as q}from"zod";var z=q.string().min(1),It=q.string(),on=q.string(),Ms=q.looseObject({id:z}),Xa=q.looseObject({id:z,name:It,parent:z,rank:on}),Cx={"init.workspace":q.looseObject({id:z,name:It,rank:on}),"add.workspace":q.looseObject({id:z,name:It,rank:on}),"add.board":Xa,"add.swimlane":Xa,"add.issue":Xa,"add.field":q.looseObject({id:z,name:It,parent:z,rank:on}),"edit.title":q.looseObject({id:z,name:It}),"delete.node":Ms,"lock.node":Ms,"move.node":q.looseObject({id:z,parent:z,rank:on}),"edit.description":q.looseObject({id:z,md:q.string()}),"close.issue":q.looseObject({id:z,parent:z,rank:on}),"reopen.issue":q.looseObject({id:z,parent:z,rank:on}),"create.tag":q.looseObject({id:z,name:It}),"tombstone.tag":Ms,"restore.tag":q.looseObject({id:z,name:It}),"create.contributor":q.looseObject({id:z,name:It}),"rename.contributor":q.looseObject({id:z,name:It}),"tombstone.contributor":Ms,"restore.contributor":q.looseObject({id:z,name:It}),"link.contributor.user":q.looseObject({contributor:z}),"link.contributor.email":q.looseObject({contributor:z,email:z}),"unlink.contributor.email":q.looseObject({contributor:z,email:z}),"connect.repo":q.looseObject({url:q.string()}),"edit.repo":q.looseObject({repo:z}),"disconnect.repo":q.looseObject({repo:z}),"add.issue.assignee":q.looseObject({id:z,assignee:z}),"remove.issue.assignee":q.looseObject({id:z,assignee:z}),"add.issue.tag":q.looseObject({id:z,tag:z}),"remove.issue.tag":q.looseObject({id:z,tag:z}),"add.issue.comment":q.looseObject({id:z,issue:z,md:q.string()}),"edit.issue.comment":q.looseObject({id:z,issue:z,md:q.string()}),"delete.issue.comment":q.looseObject({id:z,issue:z}),"add.issue.attachment":q.looseObject({id:z,issue:z,hash:q.string().min(1),ext:q.string().min(1),name:It,bytes:q.number()}),"delete.issue.attachment":q.looseObject({id:z,issue:z}),"rebalance.children":q.looseObject({parent:z,ranks:q.record(q.string(),on)})},km=(e,t)=>{let r=Cx[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 Nx}from"ulid";var Lm=(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:Nx(),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 Ja=["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 Ok=new Set(Ja);var me={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var nt=e=>e.slice(-7).toUpperCase(),Za=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?nt(e).includes(n):!0};var Ie={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 mo=(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,Qa=e=>{let t=h().repos,n=ji(t,e);if(c(n))return{skip:F(n.message,e)};let r=he(o=>({...o,repos:t}));return c(r)?{skip:F("Unable to update repos",e)}:{message:n.message,entry:n.value}},Pm={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ie.workspace(t,n,r),s=po(o);if(c(s))return Ts(s.message,e);let i=C.createNode(o);return c(i)?F(i.message??"Failed to initialize workspace",e):Qi(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=mo(t,void 0,e);if(o)return o;let s=C.createNode(Ie.workspace(t,n,r));return c(s)?F(s.message??"Failed to add workspace",e):Qi(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=mo(t,r,e);if(s)return s;let i=C.createNode(Ie.board(t,n,r,o));return c(i)?F(i.message??"Unable to create board",e):Br(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=mo(t,r,e);if(s)return s;let i=C.createNode(Ie.swimlane(t,n,r,o));return c(i)?F(i.message??"Unable to create swimlane",e):Qn(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=mo(t,r,e);if(s)return s;let i=C.createNode(Ie.ticket(t,n,r,o));return c(i)?F(i.message??"Unable to create issue",e):j(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=mo(t,r,e);if(i)return i;let l=C.createNode(Ie.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(!j(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(!j(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(!Jn(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=Qa(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})},"edit.repo":e=>{let t=Qa(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})},"disconnect.repo":e=>{let t=Qa(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})}};var Om=e=>{let t=C.getNode(e);if(!t||!j(t)||t.isDeleted)return null;let n=tc(t);return c(n)?n:null},Dm=e=>{if(!nc())return null;for(let t of e){let n=Om(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=Om(r);if(o)return o}return null},Ix=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},wx=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},ec=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 wx(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[]}},Ax=e=>{he(t=>({...t,eventLog:[...t.eventLog,e]}))},Gt=null,Tx=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&&he(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Dm([...e.virtualNodeIds])},Fm={isInitialized:()=>ut(),batch:e=>ks(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(ec(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(nc()){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=>Ix(o,e)),Ax(e)),Dm(r)},flush(){if(!Gt)return null;let e=Gt;return Gt=null,Tx(e)}};var oe=()=>{let{userName:e,userId:t}=ee();return e?t?Vl(t)?ql(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 Mx={genesis:"init.workspace",actions:Ja,readPayload:km,apply:Pm,replay:Fm,write:{readOnlyReason:()=>{let e=h();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:Lm}},kx=Mm(Mx),{materialize:fo,materializeAll:sn,fromPersistedEvent:AL,decodeReconstructedEvents:TL,loadMergedEventsWithUnreadable:go,loadEventActors:ML,loadActorNames:_m,loadMergedEvents:Ls,loadMergedEventsBefore:$m,getEdgeRef:kL,advanceEdgeRef:LL,clearEdgeCache:PL,getSortedEvents:OL,loadEffectiveEventTimes:Bm,mintEventId:DL,persist:Um,materializeAndPersist:FL,materializeAndPersistAll:Z}=kx;var rc="Unchanged",Ps="Renamed ",Dx={live:[],overLimit:[],disconnected:[]},ho=null,Fx=(e,t)=>{if(!ut())return null;let n=h();return n.timeMode==="live"&&n.replay===null&&em(e)===t?n.repos:null},rt=e=>{try{let t=be({repoRoot:e});if(c(t))return a(t.message);let n=t.value,r=Nt(n);if(r==="none")return d("No log yet",Dx);if(ho&&ho.root===n&&ho.signature===r)return d("Read connected repos",ho.repos);let o=Fx(n,r);if(!o){let i=Ls(n);if(c(i))return a(i.message);o=ed(i.value)}let s=td(o);return ho={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)}`)}},Os=e=>{let t=rt(e);return c(t)?a(t.message):d("Read other repos",t.value.live)},Hm=(e,t)=>{let n=Os(e);return!c(n)&&n.value.some(r=>r.id===t)},oc=e=>{let t=e.url.trim(),n=Fr(t);if(n)return a(`That URL ${n}. ${Yl}`);if(e.since!==void 0&&!En(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&&!Rn(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??Bi,since:e.since??Ui,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?Ps:"Updated "}${m.label}`})},yo=e=>{let t=be({repoRoot:e.repoRoot});if(c(t))return a(t.message);let n=Z([{id:Ox(),userId:e.actorId,...e.event}],t.value);return c(n)?a(n.message):d("Wrote repo event",null)},sc=e=>{let t=rt(e);return new Map(c(t)?[]:[...t.value.live,...t.value.overLimit].map(n=>[n.id,n.label]))},ic=e=>e.map(t=>e.filter(n=>n.label===t.label).length===1?t.label:t.id),Ds=(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`)},ac=(e,t)=>{let n=rt(e);return c(n)?a(n.message):Ds([...n.value.live,...n.value.overLimit],t)},cc=e=>jm.join(We(),"repos",/^[\w-]+$/.test(e)?e:Lx("sha1").update(e).digest("hex")),Wm=/^[a-z0-9._-]+-[0-9a-f]{12}\.git$/,Ot=(e,t)=>jm.join(cc(e),`${t}.git`),mr=e=>`${e}.json`,Fs=/^(?!-)[A-Za-z0-9._/-]{1,100}$/,Gm=e=>{try{let t=JSON.parse(Px.readFileSync(mr(e),"utf8"));return typeof t.stateBranch=="string"&&Fs.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 _x=(e,t)=>{let n=(e.trim().split(/\s+/)[0]??"").toUpperCase();return n&&t.has(n)?n:null},zm=(e,t)=>{let n=_x(e.subject,t),r=(e.refs??[]).map(o=>o.toUpperCase());return[...new Set([...n?[n]:[],...r])].filter(o=>t.has(o))};import{randomUUID as No}from"node:crypto";import D from"node:fs";import X from"node:path";import{execFileSync as $x}from"node:child_process";import{randomUUID as Km}from"node:crypto";import Ke from"node:fs";import bo from"node:os";import Ym from"node:path";var Bs="epiq-sync.lock",Bx=600*1e3,Xm=Date.now()-process.uptime()*1e3,Jm=()=>Math.round(Xm),Zm=5e3,Ux=5e3,Qm=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=Vm.get(e);if(t&&Date.now()-t.at<jx)return t.value;let n=$x("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 Vm.set(e,{at:Date.now(),value:o}),o}catch{return null}},ep=(e,t)=>{let n=Qm(e);return n!==null&&n>t+Zm},jx=5e3,Vm=new Map,Hx=e=>{let t=Date.now()-bo.uptime()*1e3;if(e.startedAt<t)return!1;if(Date.now()-e.startedAt<Ux||e.processStartedAt===void 0)return!0;let n=Qm(e.pid);return n===null||Math.abs(n-e.processStartedAt)<=Zm},_s=new Map,Wx=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}},Gx=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},tp=(e,t=Bx,n=!1)=>e?e.hostname!==bo.hostname()?Date.now()-e.startedAt>t?"stale":null:!Gx(e.pid)||n&&!Hx(e)?"dead":Date.now()-e.startedAt>t?"stale":null:"stale",zx=e=>{let t=Ym.join(e,Bs);return Ke.existsSync(t)?tp(fr(t))===null:!1},$s=new Map,Vx=e=>{let t=$s.get(e);if(t)return t;let n=jr(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},yP=async e=>{let t=await Vx(e);return t!==null&&zx(t)},np=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,fr=e=>{try{return Wx(Ke.readFileSync(e,"utf8"))}catch{return null}},qx=(e,t)=>{let n={pid:process.pid,hostname:bo.hostname(),startedAt:Date.now(),operation:t,token:Km(),processStartedAt:Xm},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{}}},Kx=async({worktreeRoot:e,operation:t})=>{let n=await jr(e);return c(n)?a(n.message):d("Tried the sync lock",vo({lockPath:Ym.join(n.value,Bs),operation:t}))},vo=({lockPath:e,operation:t,staleAfterMs:n,checkProcess:r=!1})=>{let o=null,s=()=>{try{let u=fr(e);u&&qm(u,o)&&Ke.rmSync(e)}catch{}finally{_s.get(e)===o?.token&&_s.delete(e)}},i=u=>(o=qx(e,t),o?(_s.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=fr(e);if(m===null&&(!Ke.existsSync(e)||(m=fr(e),m!==null)||!Ke.existsSync(e)))continue;let g=m!==null&&m.pid===process.pid&&m.hostname===bo.hostname()&&_s.get(e)!==m.token?"dead":tp(m,n,r);if(g===null)return{acquired:!1,heldBy:m};H.info(`Breaking an abandoned sync lock: ${m?np(m):"unreadable lock file"}`);let b=`${e}.${process.pid}.${Km()}.broken.lock`;try{Ke.renameSync(e,b)}catch{continue}if(!qm(fr(b),m)){try{Ke.linkSync(b,e)}catch{}Ke.rmSync(b,{force:!0});continue}Ke.rmSync(b,{force:!0});let N=i(g);if(N)return N}return{acquired:!1,heldBy:fr(e)??{pid:-1,hostname:bo.hostname(),startedAt:Date.now(),operation:"unknown"}}},qm=(e,t)=>e===null||t===null?e===t:e.pid===t.pid&&e.hostname===t.hostname&&e.startedAt===t.startedAt&&e.token===t.token,xo=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await Kx({worktreeRoot:e,operation:t});if(c(r))return a(r.message);if(!r.value.acquired)return H.info(`Skipping ${t}: the state worktree is held by ${np(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 Qx}from"node:crypto";import eE from"node:fs";var Yx="EPIQ_CACHE_MS",Us=e=>{let t=process.env[Yx];if(t===void 0||t.trim()==="")return e;let n=Number(t);return Number.isFinite(n)&&n>=0?n:e};import rp from"node:fs";import Xx from"node:path";var op=new Set,lc=new Map,dc=(e,t)=>{t?lc.set(e,t):lc.delete(e)},sp=e=>lc.get(e)??null,Jx=e=>{try{return new Set(rp.readFileSync(Xx.join(e,"shallow"),"utf8").split(`
|
|
37
|
+
`).map(t=>t.trim()).filter(Boolean))}catch{return op}},_n=async e=>{let t=Ct(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:op},s=Os(n);if(c(s))return d("Listed sources",[o]);let i=s.value.flatMap(l=>{let u=Ot(r.value.projectId,l.id);if(!rp.existsSync(u))return[];let p=an(l.since,r.value.createdAt),m=new Set([r.value.stateBranch,va,Gm(u)].filter(f=>f!==null));return[{repo:l.id,cwd:u,revisions:[...[...m].map(f=>`--exclude=${f}`),"--branches"],exclude:Jx(u),...p?{notBefore:Date.parse(`${p}T00:00:00Z`)}:{}}]});return d("Listed sources",[o,...i])},uc=e=>t=>e.find(n=>(n.repo??"")===(t??""))?.cwd,Zx=async(e,t)=>!c(await _({cwd:e,args:["cat-file","-e",`${t}^{commit}`]})),Eo=async e=>{let t=await _n(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 Zx(r.cwd,e.sha))return d("Resolved repo",r.cwd);return d("Resolved repo",n[0].cwd)};var mc="",tE="",ip=5e3,nE=12e4,rE=32*1024*1024,js=new Map,oE=e=>{try{return eE.statSync(`${e}.json`).mtimeMs}catch{return null}},sE=()=>{let e=Qx(8).toString("hex");return{field:`${mc}${e}`,record:`${tE}${e}`,body:`${mc}B${e}`,end:`${mc}E${e}`}},iE=/^[ \t]*Epiq-Ref:[ \t]*(.*)$/gim,aE=new RegExp(`^[0-9A-HJKMNP-TV-Z]{${7}}$`,"i"),fc=e=>[...new Set([...e.matchAll(iE)].flatMap(t=>t[1].split(/[\s,]+/)).filter(t=>aE.test(t)).map(t=>t.toUpperCase()))],cE=/^[0-9a-f]{40}([0-9a-f]{24})?$/;var cn=()=>{js.clear()},lE=(e,t,n)=>(t===void 0||e>=Math.floor(t/1e3)*1e3)&&(n===void 0||e<=n),pc=e=>Ut(e).replace(/[\u0080-\u009f\u202a-\u202e\u2066-\u2069]/g,""),dE=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?js.get(r):void 0,s=e.repo?oE(e.cwd):null;if(o&&(e.repo?o.version===s:Date.now()-o.fetchedAt<Us(ip)))return o.result;let i=sE(),l=await _({cwd:e.cwd,...e.repo?{timeoutMs:nE,maxOutput:rE}:{},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${i.body}%b${i.end}`]});if(c(l))return e.repo&&n&&!Od(l.message)&&js.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=p.indexOf(i.end),[f="",...g]=p.split(`
|
|
38
|
+
`),b=m===-1?f:p.slice(0,m),N=m===-1?g:p.slice(m+i.end.length).split(`
|
|
39
|
+
`),E=b.indexOf(i.body),R=E===-1?b:b.slice(0,E),v=E===-1?[]:fc(b.slice(E+i.body.length)),I=R.split(i.field),[M,k]=I;if(e.repo&&!cE.test(M??""))return null;let P=e.notBefore?I[2]:void 0,[L,$,...B]=I.slice(e.notBefore?3:2);if(!M||!k||e.exclude.has(M)||e.notBefore&&Number(P)*1e3<e.notBefore)return null;let ce=N.join(" "),O=Number(/(\d+) insertion/.exec(ce)?.[1]??0),V=Number(/(\d+) deletion/.exec(ce)?.[1]??0);return{sha:M,...e.repo?{repo:e.repo}:{},time:Number(k)*1e3,author:pc(L)||"unknown",authorEmail:pc($),subject:pc(B.join(i.field)),...v.length>0?{refs:v}:{},linesChanged:O+V,insertions:O,deletions:V}}).filter(p=>p!==null).filter(p=>lE(p.time,t.start,t.end));return n&&js.set(r,{fetchedAt:Date.now(),version:s,result:d("Computed commit timeline",u)}),d("Computed commit timeline",u)},ap=async(e,t)=>{let n=await _n(e);if(c(n))return a(n.message);let r=n.value,o=[];for(let i of r)o.push(await dE(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);H.info(`[repos] could not read a clone: ${l.message}`),dc(u,as(l.message)?"its history is too long to read; narrow its window":"its history could not be read");continue}u&&dc(u,null),s.push(l.value)}return d("Read every source",s)},Hs=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})},cp=e=>{let t=e.filter(n=>n.length>0);return t.length<=1?t[0]??[]:t.flat().sort((n,r)=>r.time-n.time)},uE=async(e={})=>{let t=await ap(e.repoRoot,{start:e.start,end:e.end});return c(t)?a(t.message):d("Computed commit timeline",cp(Hs(t.value)))},gc=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 ap(e.repoRoot,{});if(c(n))return a(n.message);let r=`${t.toUpperCase()} `,o=s=>s.subject.toUpperCase().startsWith(r)||s.refs?.includes(t.toUpperCase())===!0;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}))},hc=async e=>{let t=await gc(e);return c(t)?a(t.message):d("Matched commits by ref",cp(Hs(t.value)))};var Ws=1800*1e3,Ft=e=>`${e}.removed`,lp=e=>{try{D.writeFileSync(Ft(e),"",{flag:"wx"})}catch(t){if(t.code!=="EEXIST")throw t;if(Gs(Ft(e)))throw new Error("The removal mark is a link, which epiq will not use")}},xc=()=>`${process.pid}-${Jm()}`,vc=e=>{try{let t=JSON.parse(D.readFileSync(mr(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"&&Fs.test(t.stateBranch)?t.stateBranch:null}}catch{return null}},hp=(e,t)=>{try{let n=`${mr(e)}.${xc()}.${No()}.tmp`;D.writeFileSync(n,JSON.stringify(t)+`
|
|
40
|
+
`,{flag:"wx"}),D.renameSync(n,mr(e))}catch(n){H.info(`[repos] could not record fetch status: ${String(n)}`)}},Ec=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=vc(i),u=D.existsSync(i);return{...o,cloned:u,overLimit:s,bytes:u?l?.bytes??null:null,fetchedAt:l?.fetchedAt??null,error:l?.error??sp(o.id)}};return d("Listed repos",[...n.value.live.map(o=>r(o,!1)),...n.value.overLimit.map(o=>r(o,!0))])},we=e=>_({...e,forClone:!0}),mE=(e,t)=>we({cwd:e,args:t,timeoutMs:Ws}),pE=1e3,Co=async(e,t,n,{undo:r}={})=>{let o=lr(),s=o*1024*1024,i=new AbortController,l=setInterval(()=>{nn(n)>s&&i.abort(io(o))},pE),u;try{u=await we({cwd:e,args:t,timeoutMs:Ws,abort:i.signal})}finally{clearInterval(l)}return i.signal.aborted||!c(u)&&nn(n)>s?(bp(n),r&&(hE(n,r),wp(n)),a(io(o))):u},Ro=e=>{try{return D.readFileSync(e)}catch{return null}},Rc=e=>{try{return D.readdirSync(e)}catch{return[]}},fE=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:Ro(X.join(e,"packed-refs")),head:Ro(X.join(e,"HEAD")),config:Ro(X.join(e,"config")),shallow:Ro(X.join(e,"shallow")),packs:new Set(Rc(X.join(e,"objects","pack")))}},yp="epiq-restore-",dp=(e,t,n)=>{let r=X.join(e,`${yp}${No()}.tmp`);D.writeFileSync(r,n,{flag:"wx"}),D.mkdirSync(X.dirname(X.join(e,t)),{recursive:!0}),D.renameSync(r,X.join(e,t))},gE=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},hE=(e,t)=>{for(let[r,o]of t.refs)dp(e,r,o);for(let r of gE(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?dp(e,r,o):D.rmSync(X.join(e,r),{force:!0});let n=X.join(e,"objects","pack");for(let r of Rc(n))t.packs.has(r)||D.rmSync(X.join(n,r));$n.delete(e)},bp=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,yp]])try{for(let o of D.readdirSync(n))o.startsWith(r)&&D.rmSync(X.join(n,o),{recursive:!0,force:!0})}catch{}},yE=/could not read from remote repository|the remote end hung up unexpectedly|early EOF|fetch-pack: invalid index-pack output/i,vp=e=>{let t=e.split(`
|
|
41
|
+
`).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=>!yE.test(s))[0]??n[n.length-1]??t[t.length-1]??e).replace(/^(fatal|error):\s*/i,"").slice(0,300)},bE=64*1024,xp=async e=>{let t="HEAD:.epiq/project.json",n=await we({cwd:e,args:["cat-file","-s",t]});if(c(n)||!(Number(n.value.stdout.trim())<=bE))return null;let r=await we({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"&&Fs.test(o)?o:null}catch{return null}},Sc=async e=>{let t=await we({cwd:e,args:["symbolic-ref","--short","HEAD"]});return c(t)?null:t.value.stdout.trim()||null},vE=async(e,t)=>{if(t==="all")return d("All branches","+refs/heads/*:refs/heads/*");let n=await Sc(e);return n?d("Default branch",`+refs/heads/${n}:refs/heads/${n}`):a("Could not tell which branch is the default")},xE=async e=>{let t=await Sc(e);if(!t)return;let n=await we({cwd:e,args:["for-each-ref","--format=%(refname)","refs/heads/"]});if(!c(n))for(let r of n.value.stdout.split(`
|
|
42
|
+
`).filter(Boolean))r!==`refs/heads/${t}`&&await we({cwd:e,args:["update-ref","-d",r]})},Ep=async e=>{let t=await we({cwd:e,args:["for-each-ref","--count=1","--format=x","refs/heads/"]});return!c(t)&&t.value.stdout.trim()!==""},Rp=e=>`--shallow-since=@${Math.floor(Date.parse(`${e}T00:00:00Z`)/1e3)}`,Sp=async(e,t)=>{if(!await Ep(e))return d("Empty",null);let n=await Co(e,["fetch","--no-tags","--deepen=1","origin"],e,{undo:t});return c(n)?a(n.message):d("Deepened",null)},EE=/no commits selected for shallow requests|error processing shallow info/i,Cp=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 Co(r,o(n?[Rp(n)]:[]),e),i=n!==null;if(c(s)&&n&&EE.test(s.message)&&(D.rmSync(e,{recursive:!0,force:!0}),s=await Co(r,o(["--depth=1"]),e),i=!1),c(s))return D.rmSync(e,{recursive:!0,force:!0}),a(s.message);let l=await vE(e,t.branches);if(c(l))return D.rmSync(e,{recursive:!0,force:!0}),a(l.message);if(await we({cwd:e,args:["config","remote.origin.fetch",l.value]}),i){let u=await Sp(e);if(c(u))return D.rmSync(e,{recursive:!0,force:!0}),a(u.message)}return d("Built clone",null)},up=async(e,t,n,{replace:r=!1}={})=>{let o=`${e}.${xc()}.pending`,s=await Cp(o,t,n);if(c(s))return s;if(r&&D.existsSync(e)){let i=`${e}.${No()}.deleting`;D.renameSync(e,i),D.renameSync(o,e);try{D.rmSync(i,{recursive:!0,force:!0})}catch(l){H.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)):Gs(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))},RE=async(e,t)=>!/[*:]/.test(t)&&!c(await we({cwd:e,args:["check-ref-format",`refs/heads/${t}`]})),Np=async e=>{let t=await mE(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 RE(e,n)?n:null},Ip=async(e,t)=>{let n=t??await Np(e);if(!n)return a("Could not tell which branch the remote now defaults to");let r=await we({cwd:e,args:["symbolic-ref","HEAD",`refs/heads/${n}`]});if(c(r))return a(r.message);let o=await we({cwd:e,args:["config","remote.origin.fetch",`+refs/heads/${n}:refs/heads/${n}`]});return c(o)?a(o.message):d("Followed",null)},wp=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){H.info(`[repos] could not clear stale locks: ${String(n)}`)}},Ap=e=>D.existsSync(X.join(e,"shallow")),SE=20,CE=async e=>{if(Rc(X.join(e,"objects","pack")).filter(r=>r.endsWith(".pack")).length<=SE)return;let n=await we({cwd:e,args:["repack","--geometric=2","-d","-q"],timeoutMs:Ws});c(n)&&H.info(`[repos] repack: ${n.message}`)},NE=async e=>{let t=await we({cwd:e,args:["config","--get","remote.origin.fetch"]});return c(t)?null:t.value.stdout.trim()||null},IE=e=>`+refs/heads/${e}:refs/heads/${e}`,wE=async(e,t)=>{let n=await NE(e);if(t==="all"){let s="+refs/heads/*:refs/heads/*";if(n===s)return d("Tracking",null);let i=await we({cwd:e,args:["config","remote.origin.fetch",s]});return c(i)?a(i.message):d("Tracking",null)}let r=await Sc(e),o=await Np(e)??r;return o?r===o&&n===IE(o)?d("Tracking",null):Ip(e,o):a("Could not tell which branch is the default")},mp=async(e,t,n,r)=>{let o=lr();if(nn(e)>o*1024*1024)return a(io(o));let s=fE(e),i=await wE(e,t.branches);if(c(i))return a(i.message);let l=n===null?Ap(e)?["--unshallow"]:[]:r?.since&&n<r.since?[Rp(n)]:[],u=["fetch","--prune","--no-tags",...l,"origin"],p=await Co(e,u,e,{undo:s});if(c(p)&&t.branches==="default"&&/couldn't find remote ref/i.test(p.message)){let m=await Ip(e);if(c(m))return a(m.message);p=await Co(e,u,e,{undo:s})}if(c(p))return a(p.message);if(l[0]?.startsWith("--shallow-since")){let m=await Sp(e,s);if(c(m))return a(m.message)}return t.branches==="default"&&await xE(e),await CE(e),d("Fetched",null)},yc=async e=>{if(!D.existsSync(e))return"";let t=await we({cwd:e,args:["for-each-ref","--format=%(objectname) %(refname)"]}),n=Ap(e)?D.readFileSync(X.join(e,"shallow"),"utf8"):"";return`${c(t)?"":t.value.stdout}
|
|
43
|
+
${n}`},$n=new Map,pp=(e,t)=>{let n=$n.get(e);return $n.set(e,t),n!==void 0&&n!==t},AE=async(e,t)=>{let n=await we({cwd:e,args:["config","--get","remote.origin.url"]});return c(n)?"unknown":Zt(n.value.stdout.trim())===t.id?"this":"other"},Tp=e=>{let t=X.join(e,".gitignore");try{if(D.lstatSync(t,{throwIfNoEntry:!1}))return;D.writeFileSync(t,`*
|
|
44
|
+
`,{flag:"wx"})}catch(n){H.info(`[repos] could not write ${t}: ${ot(n)}`)}},Gs=e=>{try{return D.lstatSync(e).isSymbolicLink()}catch{return!1}},ot=e=>e instanceof Error?e.message:String(e),Cc=".lock",Nc=Ws*4,Mp=async(e,t,n)=>{let r=Date.now()+n;for(;;){let o=vo({lockPath:`${e}${Cc}`,operation:t,staleAfterMs:Nc,checkProcess:!0});if(o.acquired||Date.now()>=r)return o;await new Promise(s=>setTimeout(s,250))}},So=e=>{let t=`${e}.${No()}.deleting`;try{D.renameSync(e,t)}catch(n){if(n.code!=="ENOENT")throw n}D.rmSync(t,{recursive:!0,force:!0}),D.rmSync(mr(e),{force:!0}),D.rmSync(Ft(e),{force:!0}),$n.delete(e)},kp=5e3,TE=async e=>{let t=await we({cwd:e,args:["config","--get","remote.origin.url"]});if(c(t)||!t.value.stdout.trim())return!1;let n=Ro(X.join(e,"shallow"));return n&&!/^(?:[0-9a-f]{40}(?:[0-9a-f]{24})?\n)*$/.test(n.toString("utf8"))?!1:await Ep(e)?!c(await we({cwd:e,args:["rev-list","--max-count=1","--branches"]})):!0},fp=[0,6e4,10*6e4,60*6e4],Lp=e=>{if(!e?.restartTriedAt||Date.now()<e.restartTriedAt)return!0;let t=fp[Math.min(e.restarts,fp.length-1)];return Date.now()-e.restartTriedAt>=t},ME=360*60*1e3,kE=e=>{let t=e?.restartTriedAt??e?.restartedAt;return Lp(e)&&(!t||Date.now()<t||Date.now()-t>=ME)},LE=6e4,PE=async(e,t,n)=>{let r=lr();return nn(e)>r*1024*1024?"past the cap":n.endsWith(io(r))?null:await Pp(e,t)?"remote answers":null},Pp=async(e,t)=>!c(await we({cwd:X.dirname(e),args:["ls-remote","--",t.url,"HEAD"],timeoutMs:LE})),OE=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}),Tp(X.dirname(i))}catch(m){return s(!1,ot(m))}let u=vc(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)&&pp(i,await yc(i));return u.error?s(!1,u.error,m):s(!0,"Fetched recently",m)}if(Gs(i))return s(!1,"The clone path is a link, which epiq will not use");let p=await Mp(i,`fetch ${r.label}`,o===0?kp:0);if(!p.acquired)return{...s(!0,"Being fetched by another process"),skipped:!0};try{let m=D.existsSync(Ft(i));m&&So(i);let f=D.existsSync(i);f&&await AE(i,r)==="other"&&(So(i),f=!1);let g=f?vc(i):null;if(f&&!$n.has(i)&&$n.set(i,await yc(i)),f&&(wp(i),bp(i)),!f&&m&&!Hm(e,r.id))return s(!0,"Removed before it was cloned");let N=f&&!await TE(i)&&Lp(g),E=N&&await Pp(i,r),R=f?N?a(E?"Its clone will not open":"Its clone will not open, and its remote does not answer"):await mp(i,r,l,g):await up(i,r,l);if(f&&!E&&c(R)&&kE(g)){let k=await PE(i,r,R.message);k==="remote answers"&&(R=await mp(i,r,l,g)),E=k!==null&&c(R)}E&&(H.info(`[repos] ${r.label}: starting its clone over`),R=await up(i,r,l,{replace:!0}),$n.delete(i));let v=E&&!(c(R)&&Wd()),I=c(R)?vp(R.message):"Fetched",M=c(R)?g?.stateBranch??null:await xp(i);return hp(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:M,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)?(H.info(`[repos] ${r.label}: ${R.message}`),s(!1,I)):s(!0,I,pp(i,await yc(i))||!f||E)}catch(m){return H.info(`[repos] ${r.label}: ${ot(m)}`),s(!1,ot(m))}finally{try{D.existsSync(Ft(i))&&So(i)}catch(m){H.info(`[repos] ${r.label}: could not delete the clone: ${ot(m)}`)}p.release(),Op(i)}},Op=e=>{if(!D.existsSync(Ft(e)))return;let t=vo({lockPath:`${e}${Cc}`,operation:"remove",staleAfterMs:Nc,checkProcess:!0});if(t.acquired)try{D.existsSync(Ft(e))&&So(e)}catch(n){H.info(`[repos] could not delete a clone: ${ot(n)}`)}finally{t.release()}},DE=e=>{let t=cc(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&&!_E(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){H.info(`[repos] could not sweep ${n}: ${ot(o)}`)}}},Dp=async(e,t)=>{let n=zt(e);if(c(n))return a(n.message);let r=Ot(n.value.projectId,t.id),o=`${r}.${xc()}.${No()}.pending`;try{D.mkdirSync(X.dirname(r),{recursive:!0}),Tp(X.dirname(r));let s=await Cp(o,t,an(t.since,n.value.createdAt));return c(s)?a(vp(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){H.info(`[repos] could not clear a stage: ${ot(t)}`)}},Fp=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 Mp(i,`connect ${t.label}`,kp);if(!l.acquired)return Dt(n);try{if(D.rmSync(Ft(i),{force:!0}),D.existsSync(i)||Gs(i))return Dt(n);D.renameSync(n,i),hp(i,{fetchedAt:Date.now(),attemptedAt:Date.now(),error:null,branches:t.branches,since:an(t.since,s),stateBranch:await xp(i),restartedAt:null,restartTriedAt:null,restarts:0,bytes:nn(i)}),cn()}catch(u){H.info(`[repos] could not place ${t.label}: ${ot(u)}`),Dt(n)}finally{l.release()}},Ic=e=>{let t=ac(e.repoRoot,e.repo);if(c(t))return t;let n=yo({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"disconnect.repo",payload:{repo:t.value.id}}});if(c(n))return a(n.message);let r=wc({repoRoot:e.repoRoot,repoId:t.value.id});cn();let o=zt(e.repoRoot);!c(r)&&!c(o)&&_p(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)},wc=e=>{let t=zt(e.repoRoot);if(c(t))return a(t.message);if(!Wm.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=vo({lockPath:`${n}${Cc}`,operation:"remove",staleAfterMs:Nc,checkProcess:!0});try{return r.acquired?(So(n),lp(n),d("Removed clone",null)):(lp(n),Op(n),d("Removed once its fetch ends",null))}catch(o){return a(`Could not remove the clone: ${String(o)}`)}finally{r.acquired&&r.release()}},_p=(e,t)=>{let n=Ot(e,t);D.existsSync(n)||D.rmSync(Ft(n),{force:!0})},FE=(e,t,n)=>{for(let r of n){if(!D.existsSync(Ot(t,r)))continue;let o=wc({repoRoot:e,repoId:r});if(c(o)){H.info(`[repos] could not clear ${r}: ${o.message}`);continue}cn(),_p(t,r)}},_E=(e,t)=>$E(e)&&(t===null||!ep(e,t)),$E=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},gp=4,zs=e=>{let t=e.minIntervalMs??0,n=bc.get(e.repoRoot);if(n)return n.minIntervalMs<=t?n.result:n.result.then(()=>zs(e));let r=BE(e.repoRoot,t).catch(o=>a(ot(o))).finally(()=>{bc.delete(e.repoRoot)});return bc.set(e.repoRoot,{result:r,minIntervalMs:t}),r},bc=new Map,BE=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{DE(o)}catch(u){H.info(`[repos] sweep failed: ${String(u)}`)}if(FE(e,o,r.value.disconnected),i.length===0)return d("No other repos",[]);let l=[];for(let u=0;u<i.length;u+=gp)l.push(...await Promise.all(i.slice(u,u+gp).map(p=>OE(e,o,s,p,t))));return l.some(u=>u.changed)&&cn(),d("Fetched other repos",l)},Ac=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 Mc=900*1e3,gr=new Map,$p=0,kc=new Map,Bp=e=>{let t=(kc.get(e)??0)+1;return kc.set(e,t),t},UE=(e,t)=>JSON.stringify([e,t.id,t.branches,t.since]),Lc=e=>{let t=gr.get(e);t&&(clearTimeout(t.timer),gr.delete(e),Dt(t.stagePath))},jE=e=>{Bp(e),Lc(e)},Up=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}},Tc=async(e,t)=>{let n=await _({cwd:e,args:t,forClone:!0,keepPartial:!0});return c(n)?null:n.value.stdout},HE=async(e,t,n)=>{let r=(await Tc(e,["symbolic-ref","--short","HEAD"]))?.trim().replace(/^refs\/heads\//,""),o=await Tc(e,["log","-1","--format=%s%x00%an%x00%cI","HEAD"]),[s,i,l]=(o??"").trim().split("\0"),p=(await Tc(e,["log","--branches","--max-count=100000",...t?[`--since=@${Math.floor(Date.parse(`${t}T00:00:00Z`)/1e3)}`]:[],"--format=%x1e%s%x1f%b"])??"").split("").filter(Boolean).map(m=>{let[f="",g=""]=m.split("");return{subject:f.trim(),refs:fc(g)}});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=>zm(m,n).length>0).length}},WE=()=>{if(!ut())return{knownRefs:new Set,contributors:0};let e=h();return{knownRefs:new Set(Object.values(e.nodes).filter(t=>j(t)).map(t=>nt(t.id))),contributors:Object.values(e.contributors).filter(t=>!t.tombstoned).length}},jp=e=>{let t=Ec(e);return c(t)?0:t.value.reduce((n,r)=>n+(r.bytes??0),0)},Pc=async e=>{let t=oc(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(rc,{kind:"unchanged",repo:n.repo});if(n.kind==="edit"){let E=yo({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"edit.repo",payload:n.event}});return c(E)?a(E.message):(n.message.startsWith(Ps)||cn(),d(n.message,{kind:"updated",repo:n.repo}))}let r=UE(e.repoRoot,n.repo),o=gr.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),gr.delete(n.repo.id);let E=yo({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"connect.repo",payload:n.event}});if(c(E))return Dt(o.stagePath),a(E.message);await Fp(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 ${xn} 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[...gr.keys()])Lc(E);let s=Bp(n.repo.id),i=++$p,l=()=>kc.get(n.repo.id)!==s||$p!==i,u=zt(e.repoRoot);if(c(u))return a(u.message);let p=await Dp(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=WE(),f=await HE(p.value.stagePath,an(n.repo.since,u.value.createdAt),m.knownRefs),g=rt(e.repoRoot),b={repo:n.repo,host:Up(n.repo.url),...f,bytes:p.value.bytes,contributors:m.contributors,claimedBytes:jp(e.repoRoot),overLimit:!c(g)&&g.value.live.length>=xn,expiresAt:Date.now()+Mc};if(l())return Dt(p.value.stagePath),a("Cancelled");let N=setTimeout(()=>Lc(n.repo.id),Mc);return N.unref(),gr.set(n.repo.id,{stagePath:p.value.stagePath,key:r,preview:b,timer:N}),d("Preview: nothing is connected until you confirm",{kind:"preview",preview:b})};import GE from"node:path";var zE=async e=>{let t=await Ce({cwd:e,args:["config","--get","remote.origin.url"]}),n=t.exitCode===0&&t.stdout.trim()||null;return{label:n?Mt(n):GE.basename(e),url:n,path:e}};import{randomBytes as VE}from"node:crypto";import qE from"node:fs";import KE from"node:path";var Vp=e=>e.replace(/\r\n?/g,`
|
|
45
|
+
`).replace(/[\x00-\x08\x0B-\x1F\x7F\u0080-\u009f\u202a-\u202e\u2066-\u2069]/g,"").trim(),Hp=200,YE=async(e,t)=>{let n=await _({cwd:e,args:["log","-1","--no-show-signature","--format=%b",t,"--"]});return c(n)?"":Vp(n.value.stdout)},XE=async(e,t)=>{if(c(t)||t.value.length===0)return t;let n=await _n(e);if(c(n))return t;let r=VE(8).toString("hex"),o=`${r}`,s=`${r}`,i=new Map,l=async(u,p)=>{let m=await _({cwd:u,args:["log","--no-walk=unsorted","--no-show-signature",`--format=${o}%H${s}%b`,...p,"--"]});if(!c(m))for(let f of m.value.stdout.split(o)){let g=f.indexOf(s);if(g===-1)continue;let b=Vp(f.slice(g+s.length));b&&i.set(f.slice(0,g).trim(),b)}};for(let u of n.value){let p=t.value.filter(m=>m.repo===u.repo).map(m=>m.sha).filter(kn);for(let m=0;m<p.length;m+=Hp)await l(u.cwd,p.slice(m,m+Hp))}return d(t.message,t.value.map(u=>{let p=i.get(u.sha);return p?{...u,body:p}:u}))},JE=8*1024*1024,Fc=async e=>{if(!kn(e.sha))return a("Invalid commit sha");let t=await Eo(e);if(c(t))return a(t.message);let n=await _({cwd:t.value,maxOutput:JE,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return c(n)?a(as(n.message)?"This commit is too large to show here; open it in your editor":n.message):d("Read commit patch",n.value.stdout)},ZE=200,Wp=e=>/^0+$/.test(e),Vs=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,Gp=/^(\d+|-)\t(\d+|-)\t(.+)$/,Oc=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 H.info(`[commits] diff ${t} ${n}: ${o.message}`),a(Kp);let s=o.value.stdout.split(`
|
|
46
|
+
`).filter(p=>p!==""),i=s.filter(p=>!Vs.test(p)&&!Gp.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=Gp.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=>Vs.test(p)).map(p=>{let m=Vs.exec(p),f=m?.[1]??"",g=m?.[2]??"",b=m?.[3]??"";return{path:b,beforeBlob:Wp(f)?null:f,afterBlob:Wp(g)?null:g,...l.get(b)??{insertions:0,deletions:0,isBinary:!1}}});return d("Listed changed files with blob hashes",u)},qp=async(e,t)=>{if(t.length>ZE)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 qd(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}}))},QE=async e=>{if(!kn(e.sha))return a("Invalid commit sha");let t=await Eo(e);if(c(t))return a(t.message);let n=t.value,r=YE(n,e.sha),o=await Oc(n,`${e.sha}~1`,e.sha);if(c(o)&&o.message===Kp){let u=await Yp(n,e.sha);if(c(u))return a(u.message);u.value===Dc&&(o=await Oc(n,Dc,e.sha))}if(c(o))return a(o.message);if(o.value.length===0)return a("No changed files found for this commit");let s=await qp(n,o.value);if(c(s))return a(s.message);let i=s.value,l=await r;return d("Loaded commit diff",{sha:e.sha,...e.repo?{repo:e.repo}:{},files:i,...l?{body:l}:{}})},eR=/^[0-9a-f]{40}$/,tR=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(`
|
|
47
|
+
`)){if(eR.test(i)){s=new Set,o.set(i,s);continue}let l=Vs.exec(i);l&&s&&s.add(l[3]??"")}return d("Listed changed paths per commit",o)},zp=e=>{let t=new Set;for(let n of e)for(let r of n)t.add(r);return t},nR=async(e,t,n)=>{if(t===n)return!0;let r=await _({cwd:e,args:["merge-base","--is-ancestor",t,n]});return!c(r)},Dc="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Kp="Could not read this commit's diff",rR="Its parent is outside the fetched history. Widen since to see this diff.",oR=async(e,t)=>{let n=await _({cwd:e,args:["rev-parse","--git-path","shallow"]});if(c(n))return!1;try{return qE.readFileSync(KE.resolve(e,n.value.stdout.trim()),"utf8").split(`
|
|
48
|
+
`).some(r=>r!==""&&r.startsWith(t))}catch{return!1}},Yp=async(e,t)=>{let n=await _({cwd:e,args:["rev-parse","--verify","--quiet",`${t}^1`]});return c(n)?await oR(e,t)?a(rR):d("A root commit",Dc):d("Parent",`${t}~1`)},sR=async e=>{let t=Ct(e.repoRoot);if(c(t))return a(t.message);let n=t.value,r=await gc({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 _n(n);if(c(s))return a(s.message);let i=uc(s.value),l=new Map;for(let g of Hs(r.value))g.length>0&&l.set(g[0].repo??"",g);let u=[],p=0;for(let[g,b]of l){let N=i(g);if(!N){p+=1;continue}let E=await iR(N,e.ref,b,o);if(c(E)){if(!g)return a(E.message);H.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,b)=>g+b.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:b})=>({...g?{repo:g}:{},from:b.from,to:b.to,commits:b.commits,contiguous:b.contiguous}))}):a(p>0?"The clone holding this ticket\u2019s commits could not be read":"No commits reference this ticket")},iR=async(e,t,n,r=new Set)=>{let o=n[0].sha,s=o;for(let L=n.length-1;L>0;L--){let $=n[L].sha;if(await nR(e,$,o)){s=$;break}}let i=await Yp(e,s);if(c(i))return a(i.message);let l=i.value,u=await tR(e,l,o);if(c(u))return a(u.message);let p=u.value,m=new Set(n.map(L=>L.sha)),f=new Set([...m,...r]),g=[...p.keys()].filter(L=>m.has(L)),b=[...p.keys()].filter(L=>f.has(L)),N=b.length===p.size,E=b.length>g.length,R=new Map;for(let L of g)for(let $ of p.get(L)??[])R.has($)||R.set($,L);let v=(L,$)=>d("Loaded squashed diff",{ref:t.trim().toUpperCase(),from:l,to:o,commits:g.length,files:L.map(B=>({...B,sha:R.get(B.path)??o})),contiguous:N,overlappingPaths:$}),I,M=[];if(!N||E){let L=zp(g.map(B=>p.get(B)??new Set)),$=zp([...p.entries()].filter(([B])=>!f.has(B)).map(([,B])=>B));if(L.size===0)return v([],[]);I=[...L],M=[...L].filter(B=>$.has(B)).sort()}let k=await Oc(e,l,o,I);if(c(k))return a(k.message);let P=await qp(e,k.value);return c(P)?a(P.message):v(P.value,M)};var Jp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,_c=e=>e.replace(Jp,""),aR=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,Xp=e=>e==="additions"||e==="deletions",Io=e=>{let t=Jp.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"||!Xp(r.side)||!Xp(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var Zp=/```\n([\s\S]*?)\n?```\s*$/,Qp=e=>Zp.exec(e)?.[1]??null,cR=/`[^`\n]+`[^\n]*\n?$/,ef=e=>_c(e).replace(Zp,"").replace(cR,"").trim(),tf=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})`},$c=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${tf(e)}`;var lR=e=>{let t=e.split(`
|
|
49
|
+
`),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(`
|
|
50
|
+
`):e},nf=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],aR({...t,note:n}),`\`${t.filePath}\` ${tf(t)}`,"```",lR(e),"```"].join(`
|
|
51
|
+
`)};var dR=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,qs=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+=`
|
|
52
|
+
`;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}},rf=e=>{let t=qs(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},Uc=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(`
|
|
53
|
+
`)){if(i.startsWith("diff --git ")){n=s();let m=i.slice(11),f=m.lastIndexOf(" b/");f!==-1&&(n.path=qs(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=rf(i.slice(4));m&&(l.oldPath=m);continue}if(u&&i.startsWith("+++ ")){let m=rf(i.slice(4));m&&(l.path=m);continue}if(u&&i.startsWith("rename from ")){l.oldPath=qs(i.slice(12));continue}if(u&&i.startsWith("rename to ")){l.path=qs(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=dR.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!=="")},Bc=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null;var jc=e=>e.flatMap(t=>[{kind:"file",text:`${Bc(t)?`${Bc(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),Ks=e=>{let t="",n=-1;return e.map(r=>(r.kind==="file"&&(t=r.file.path),r.kind==="hunk"&&n++,{file:t,hunk:n}))},Hc=(e,t,n)=>{let r=t.map(i=>Io(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(r.length===0)return new Set;let o=Ks(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},of=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,uR=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,sf=e=>{let t=uR.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)}},af=(e,t)=>Ks(e)[t]?.file??null,cf=(e,t,n,r)=>{let o=Ks(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`}:Wc(e,i,l)},Wc=(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=Ks(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(`
|
|
54
|
+
`)}}};import{existsSync as Kc}from"node:fs";import{chmod as Yc}from"node:fs/promises";import Xs from"node:path";import{spawn as mR,spawnSync as pR}from"node:child_process";import fR from"node:os";import lf from"node:path";import{ulid as gR}from"ulid";function Gc(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 hR(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Ys(){let{preferredEditor:e}=ee(),t=[e?hR(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function zc(e){let[t=""]=Gc(e);return/(^|\/)code(-insiders)?$/.test(t)}function df(e,t){let[n="",...r]=Gc(e);return{command:n,args:[...r,...t]}}function uf(e,t){return df(e,zc(e)?["--wait",t]:[t])}function yR(e,t,n,r="new"){return df(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function Vc(e){let t=lf.join(fR.tmpdir(),"epiq");Oe.mkDir(t);let n=lf.join(t,gR());Oe.writeToFile(n,e??"");let r=Ys();for(let o of r){let{command:s,args:i}=uf(o,n);if(!s)continue;let l=pR(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 bR=new Set(["vim","vi","nvim","nano","pico","ed"]);function vR(e){let[t=""]=Gc(e),n=t.split("/").pop()??t;return bR.has(n)}var xR=600;function mf({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=mR(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))},xR)})}function ER(e,t){return vR(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}`)):mf(uf(e,t),e)}function qc(e,t,n,r="new"){return mf(yR(e,t,n,r),e)}async function pf(e){let t=Ys();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 ER(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 RR,existsSync as SR,lstatSync as CR,mkdirSync as NR}from"node:fs";import IR from"node:os";import wR from"node:path";var wo=(...e)=>{let t=wR.join(IR.tmpdir(),"epiq",...e);try{return SR(t)&&CR(t).isSymbolicLink()?a(`Refusing to write through a symlink at ${t}`):(NR(t,{recursive:!0,mode:448}),RR(t,448),d("Prepared private temp dir",t))}catch(n){return a(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var AR=async(e,t)=>{let n=await _({cwd:e,args:["show","--no-ext-diff",t]});if(c(n))return a(n.message);let r=wo("commit-diffs");if(c(r))return a(r.message);let o=Xs.join(r.value,`${t}.diff`);return Kc(o)||(Oe.writeToFile(o,n.value.stdout),await Yc(o,292)),pf(o)},TR=12,MR=800,ff=async(e,t,n)=>{let r=await _({cwd:e,args:["show",`${t}:${n}`]});return c(r)?"":r.value.stdout},kR=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(`
|
|
55
|
+
`).map(o=>o.trim()).filter(Boolean);return r.length===0?a("No changed files found for this commit"):d("Listed changed files",r)},LR=async(e,t,n)=>{let r=await kR(e,t);if(c(r))return a(r.message);let o=r.value;if(o.length>TR)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=wo("commit-diffs",t);if(c(s))return a(s.message);let i=s.value,l=await Promise.all(o.map(async(g,b)=>{let[N,E]=await Promise.all([ff(e,`${t}~1`,g),ff(e,t,g)]),R=Xs.basename(g),v=Xs.join(i,String(b),"before",R),I=Xs.join(i,String(b),"after",R);return Kc(v)||(Oe.writeToFile(v,N),await Yc(v,292)),Kc(I)||(Oe.writeToFile(I,E),await Yc(I,292)),{beforePath:v,afterPath:I}})),[u,...p]=l;if(!u)return a("No changed files found for this commit");let m=await qc(n,u.beforePath,u.afterPath,"new");if(c(m)||p.length===0)return m;await new Promise(g=>setTimeout(g,MR));let f=await Promise.all(p.map(({beforePath:g,afterPath:b})=>qc(n,g,b,"reuse")));for(let g of f)c(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return m},Xc=async e=>{if(!kn(e.sha))return a("Invalid commit sha");let t=await Eo(e);if(c(t))return a(t.message);let n=t.value,r=Ys()[0];if(r&&zc(r)){let o=await LR(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 AR(n,e.sha)};var gf=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 Jc=["branches=default","branches=all","since=board","since=all","since=YYYY-MM-DD","label=<name>","confirm"],Zc=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"&&En(u))r.since=u;else if(l==="label"&&(u===""||Rn(u)))r.label=u;else return a(`${Jc.join(", ")}; not "${s}"`)}return d("Parsed",r)},hf=()=>{let e=Ct();if(c(e))return[];let t=rt(e.value);return c(t)?[]:[...t.value.live,...t.value.overLimit]},PR=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}`,gf(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 ")},hr=null,OR=e=>`${e.trim()} confirm`,yf=e=>hr&&hr.line===e.trim()?hr.summary:null,bf=async()=>{let e=Y().commandMeta.inputString,t=Zc(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=Ct();if(c(r))return r;let o=await Pc({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=OR(e);return hr={line:s,summary:PR(o.value.preview)},d(hr.summary,{followUp:`config repoConnect ${s}`})}return t.value.confirm&&(hr=null),d(o.value.kind==="connected"?`${o.message} \u2014 it syncs with the board; :sync fetches it`:o.message,null)},vf=()=>{let{userId:e}=ee();if(!e)return a("Set a username first with :config username");let t=Ct();if(c(t))return t;let n=Ic({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 xf=e=>e==="board"?4e3:2e3,Ef=e=>e.trim()?e:"";var Rf=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as DR}from"node:crypto";var FR="0123456789ABCDEFGHJKMNPQRSTVWXYZ",_R=e=>{let t=DR("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+=FR[Number(n>>s&31n)]}return r},Sf=new Map,pe=(e,t)=>{let n=`${e}:virtual:${t}`,r=Sf.get(n);if(r!==void 0)return r;let o=_R(n);return Sf.set(n,o),o};import Cf from"chalk";var de=e=>Cf.dim(e),fe=e=>Cf.hex(w.primary)(e),ve=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let m=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,g)=>ts(f)-ts(g)).slice(0,r).map(f=>ns(f)).join(" ");return m?`${de(e)}${m}${de(n)}`:""};var ln={None:"none",Invalid:"invalid",Valid:"valid"};var $R=["BOARD","TICKET","SWIMLANE"],Nf=()=>{let e=h().selectedNode;if(!e?.context)return W({message:de("Missing target context")});if($R.includes(e.context))return Q();if(e.parentNodeId){let t=h().nodes[e.parentNodeId];if(t?.id===pe(t?.parentNodeId??"","comments"))return Q()}return W({message:de("Command not available in this context")})},se="<ENTER> to confirm",BR=()=>{let{userId:e}=ee(),t=xe();return!e||c(t)?[]:Zn(t.value.emailLinks,e)},Q=(e="",t=[],n=!0)=>({message:n?de(e):e,validity:ln.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:ln.Invalid,message:e,completionWordList:t}),br=e=>e.length===0,If=(e,t)=>{let n=Qe(h().breadCrumb,"BOARD");if(c(n))return W({message:fe("Command is not applicable in this context")});let r=rd(n.value.id);return c(r)?W({message:fe(`Unable to ${t}: board id is not a valid ULID`)}):Pu({date:e,horizonDate:r.value})?null:W({message:fe(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Js=e=>` ${wf.hex("#000").bgHex(Be(e))(` ${e} `)} `,Qc=({modifier:e})=>{let t="confirm";return e===t?Q(se):W({message:br(e)?de("if you are certain, enter ")+ns(t):"",completionWordList:[t]})},UR=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?W({message:de(n)}):Q():W({message:br(r)?t:"",completionWordList:[...e]}),yr=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>br(n)&&br(r)?W({message:e,completionWordList:[]}):Q(t??se),jR=({modifier:e,inputString:t})=>{let n=Ma();return!br(e)||!br(t)?Q(se):W({message:n.length?de("number from the list, or a path"):de("path to an epiq project"),completionWordList:n})},HR=({modifier:e,inputString:t})=>{let n=Me(x.CONFIG);if(!n.includes(e))return W({message:ve({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case J.EDITOR:{let r=[..._u];return t.trim()?r.includes(t.trim())?Q(se):W({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):W({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case J.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?Q(se):W({message:ve({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?"":ve({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?u?Q(`${u} ${de(se)}`,o,!1):Q(se,o):W({message:u||fe("Enter a user name. Saved in ")+wf.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case J.EMAILS:{let r=ee().gitEmail,o=sr(),s=o.length>0||!r?o:[r],i=[...s,"none"],l=t.trim(),u=(N,E)=>W({message:ve({prefix:N,wordList:i,noOfHints:3,inputString:E,minLengthForHints:0}),completionWordList:i});if(!l)return Q(`${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())),b=p.filter(N=>!f(N)&&!g(N));return b.length>0?W({message:fe(`no address here matches ${b.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(m)?Q(se):u("",m)}case J.EMAILS_UNCLAIM:{let r=BR(),o=t.trim();return r.length===0?W({message:fe("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?Q(se):W({message:ve({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)?Q(se):W({message:ve({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=Tu(o);return W({message:ve({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return Q(se)}case J.ATTACHMENT_MAX_KB:{let r=ee().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<oo||o>so){let s=ve({prefix:" examples: ",wordList:Aa,minLengthForHints:0,inputString:t});return W({message:fe(`provide a size cap in KB (${oo}-${so}). current: ${r??Mn} KB.`)+s,completionWordList:Aa})}return Q(se)}case J.REPO_CLONE_MAX_MB:{let r=t.trim();if(!/^\d+$/.test(r)||!Fa(Number(r))){let o=ve({prefix:" examples: ",wordList:Ta,minLengthForHints:0,inputString:t});return W({message:fe(`provide a connected repo's clone cap in MB (${ar}-${cr}). current: ${lr()} MB.`)+o,completionWordList:Ta})}return Q(se)}case J.REPO_CONNECT:{let r=Zc(t);if(c(r))return W({message:fe(r.message),completionWordList:[]});let o=r.value.confirm?yf(t):null;return r.value.confirm&&!o?W({message:fe("preview it first: run the line without confirm"),completionWordList:[]}):Q(`${o??de(Jc.join(" "))} ${se}`,[],!1)}case J.REPO_DISCONNECT:{let r=hf(),o=ic(r),s=t.trim();return o.length===0?W({message:fe("no other repos are connected"),completionWordList:[]}):s&&!c(Ds(r,s))?Q(se):W({message:ve({prefix:"stop reading ",wordList:o,noOfHints:3,inputString:s,minLengthForHints:0}),completionWordList:o})}case J.SYNC_DEBOUNCE_MS:{let r=ee().autoSyncIntervalMs,o=er(t);if(!t.trim()||o===null){let s=ve({prefix:" examples: ",wordList:wa,minLengthForHints:0,inputString:t});return W({message:fe(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:wa})}return Q(se)}default:return W({message:fe("Unknown config option"),completionWordList:n})}},WR=({modifier:e,inputString:t})=>{let n=Me(x.EDIT);if(!n.length)return W({message:fe("Command not available in this context")});if(!n.includes(e)){let r=ve({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:r||fe("Unknown edit option"),completionWordList:n})}switch(e){case lt.COMMENT:return t.trim()?Q(se):W({message:de("write a comment...")});case lt.TITLE:return Q(se);case lt.DESCRIPTION:{let{preferredEditor:r}=ee();return r?Q(de("<ENTER> to edit in ")+r):W({message:"No editor selected"})}default:return W({message:fe("Unknown edit option"),completionWordList:n})}},GR=({modifier:e})=>{let t=Me(x.YANK);return t.length?t.includes(e)?Q(se+de(" and copy to clipboard")):W({message:ve({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:fe("Nothing selected to copy from")})},zR={[x.EXPORT]:()=>Q(se+de(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return Q(se);let n={message:de("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=wn(r);if(!r||!o)return W(n);let s=If(o,"peek");return s||Q(se)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=bs(e.modifier,e.inputString),r={message:de("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=wn(t);if(!t||!o)return W(r);let s=If(o,"replay");return s||(n&&ys(n)===null?W({message:fe("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):Q("<ENTER> to replay board history",n?Fu:[]))},[x.EXIT]:()=>Q(se+de(" and exit the application")),[x.INIT]:()=>Q(se),[x.OPEN]:jR,[x.PALETTE]:()=>Q(se),[x.FILTER]:e=>{if(e.modifier==="clear")return Q(se);let t=s=>Me(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:ve({wordList:Me(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Me(x.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:ve({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):Q():W({message:ve({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=Me(x.NONE);return W({message:ve({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>UR({list:Me(x.NEW),hint:ve({wordList:Me(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>Q(se),[x.EDIT]:WR,[x.COMMENT]:e=>{let t=yr({hint:de(`write a comment (max ${4e3} char)...`),onOk:de(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===ln.Invalid?t:e.inputString.length>4e3?Q(fe("max input exceeded")):t},[x.CONFIG]:HR,[x.YANK]:GR,[x.DELETE]:e=>{let t=Nf();return t.validity==="invalid"?t:Qc(e)},[x.CLOSE_ISSUE]:e=>Qc(e),[x.RE_OPEN_ISSUE]:e=>Qc(e),[x.MOVE]:e=>{let t=Nf();return t.validity==="invalid"?t:yr({hint:ve({prefix:"hey hacker! These commands are blocked for you... ",wordList:Me(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=C.getExistingTags().slice(0,10).map(Js).join("");return yr({hint:n.length?de("create tag or reuse:")+n+de(""):de("create tag ...")})(e)},[x.UNTAG]:e=>{let t=gs();if(c(t))return W({message:fe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Js).slice(0,10);return n.length?yr({hint:de(" ... ")+n.join("")})(e):W({message:fe("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=C.getExistingAssignees().map(Js).slice(0,10);return yr({hint:de("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=hs();if(c(t))return W({message:fe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Js).slice(0,10);return n.length?yr({hint:de("remove assignee... ")+n.join("")})(e):W({message:fe("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>Q(se)},Af=Object.fromEntries(Object.entries(zR).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Zs=["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 VR=3,qR=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"]),KR=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},YR=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=VR&&!qR.has(t)&&!/^\d+$/.test(t)),XR=e=>{let t=new Map;for(let s of KR(e))for(let i of YR(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=Zs.filter(s=>!r.has(s));return[...n,...o]},Tf=Zs,Mf=-1,kf=()=>{let e=xe();if(c(e))return Zs;let t=e.value,n=t.eventLog.length;return n!==Mf&&(Tf=XR(t),Mf=n),Tf};var Lf=e=>Object.values(x).includes(e),Pf=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:u}=Af[n].validate(n,r,s),p=n!==x.PEEK&&n!==x.REPLAY,m=o==="command"||o==="modifier"?Me(n):p?kf():[],{mode:f}=h(),g=f===y.COMMAND_LINE?i??"":"",b=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Nd(e,b,u):{hint:"",hints:[],remainder:"",overlap:0}}};var Of=e=>{let t=e.trimStart(),n=ZR(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=QR(e),l=Lf(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 b=s?"":i,N=JR(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:b,inputString:N}},JR=(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},ZR=e=>e.trim()?e.trim().split(/\s+/):[],QR=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as eS}from"react";var vr=e=>e===el||e===":",el=" ",To=40,xr={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:ln.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},tl=new Set,Df=()=>{for(let e of tl)e()},tS=e=>(tl.add(e),()=>tl.delete(e)),mt=e=>{let n=e(xr),r=Of(n.value),o=n.cursorPosition===n.value.length;xr={...n,commandMeta:Pf(r,o)},Df()},Mo=({message:e,status:t})=>{let n=structuredClone(xr);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,xr=n,Df(),d(e,null)},nl=e=>{mt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},rl=e=>{mt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&vr(n[o-1]);)o--;for(;o>0&&!vr(n[o-1]);)o--}else{for(;o<n.length&&!vr(n[o]);)o++;for(;o<n.length&&vr(n[o]);)o++}return{...t,cursorPosition:o}})},Ff=()=>{mt(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}})},_f=()=>{mt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&vr(t[r-1]);)r--;for(;r>0&&!vr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Qs=e=>{mt(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}})},$f=()=>{mt(e=>({...e,commandIsPending:!0}))},K=e=>{mt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Bf=({addToHistory:e=!0,line:t})=>{mt(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,To):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},Uf=e=>{mt(t=>({...t,commandHistory:e.slice(0,To),commandHistoryIndex:-1}))},jf=()=>{mt(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},Hf=()=>{mt(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}})},Wf=()=>{mt(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=()=>xr,WD=()=>eS(tS,Y,Y),ei=()=>{let[e,...t]=xr.value.split(el);return t.join(el).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"},nS=e=>e.shift===!0,rS={[S.NavPreviousItem]:S.NavPreviousItemJump,[S.NavNextItem]:S.NavNextItemJump,[S.MovePreviousItem]:S.MovePreviousItemJump,[S.MoveNextItem]:S.MoveNextItemJump};function oS(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function sS(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function iS(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 JD(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 yd(e,n.value);if(t===y.PALETTE)return bd(e,n.value);let r=oS(e)||sS(e);if(r)return aS(r,t,nS(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 aS(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=iS(h().contextNode.childRenderAxis,e,r);return!o||!n?o:rS[o]??o}import{ulid as dS}from"ulid";var ko=24n,cS=ko*4n,wt=(1n<<cS)-1n,lS=/^[0-9a-f]+$/;function Gf(e){return!e||!lS.test(e)?a(`Invalid hex rank: ${e}`):d("Converted rank to bigint",BigInt("0x"+e))}function st(e,t=ko){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(wt/2n,ko);let n=e?Gf(e):d("Resolved lower bound",0n);if(c(n))return n;let r=t?Gf(t):d("Resolved upper bound",wt);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,ko)}function zf(e){if(e<=0)return d("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=wt*BigInt(r+1)/(t+1n),s=st(o,ko);if(c(s))return s;n.push(s.value)}return d("Resolved evenly spaced ranks",n)}var ol=(e,t)=>{let n=ye(e),r=zf(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:dS(),action:"rebalance.children",payload:{parent:e,ranks:o},...ne(t)})};var Un=e=>e.trim().toLocaleLowerCase(),sl=(e,t)=>Un(e).includes(Un(t));var uS=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},mS=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Vf=null,qf=new Map,pS=()=>{let e=h().eventLog??[];if(e===Vf)return qf;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 Vf=e,qf=t,t},fS=e=>{let{contributors:t}=h(),n=pS().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},Kf=(e,t)=>{let n=Un(t.value);if(!n)return!0;switch(t.target){case"title":return sl(e.title??"",n);case"description":return sl(e.props.description??"",n);case"tag":return uS(e).map(Un).some(o=>o.includes(n));case"assignee":return mS(e).map(Un).some(o=>o.includes(n));case"actor":return fS(e).map(Un).some(o=>o.includes(n));case"ref":return Za(e.id,t.value);default:return!0}};var il=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,gS=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Yf=(e,t)=>Object.values(e).filter(n=>gS(n,t)).sort(il),Xf=(e,t)=>{let n={};for(let r of Object.values(e)){if(j(r)&&t.length>0&&!t.every(s=>Kf(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(il);return n},Jf=(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(il);return n};var Zf=e=>ti(ye(e),{at:"end"}),ti=(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=Qf(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=Qf(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))}}},ye=e=>{let t=h();if(!tg()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Yf(t.nodes,e)},Qf=(e,t)=>e.findIndex(n=>n.id===t),eg=(e,t,n={at:"end"})=>ti(ye(t).filter(r=>r.id!==e),n),ni=(e,t,n,r,o)=>{let s=eg(t,e,n);if(c(s))return s;if(!s.value.needsRebalance)return d("Resolved rank",s.value.rank);let i=ol(e,r);if(c(i))return i;let l=Z([i.value],o);if(c(l))return l;let u=eg(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)},ri=(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=ol(e,t);if(c(o))return o;let s=Z([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 Lo=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:()=>ng(1),navigateToPreviousItem:()=>ng(-1),jumpToNextItem:()=>rg(Lo),jumpToPreviousItem:()=>rg(-Lo),navigateToNextContainer:()=>og(1),navigateToPreviousContainer:()=>og(-1),navigate:({contextNode:e,selectedIndex:t})=>{A({contextNodeId:e.id,selectedIndex:t})}},ng=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})},rg=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})},og=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 ig=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),ag=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},hS=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&&Fe(t)&&t.childRenderAxis==="vertical"},oi=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=ye(r.id);return U.navigate({contextNode:r,selectedIndex:ig(t,o.length)}),!0},cg=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return oi(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=ye(o.id).findIndex(l=>l.id===n.id);return i>=0?(U.navigate({contextNode:o,selectedIndex:i}),!0):cg(o.id)},sg=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),cg(n))return!0;n=t[n]?.parentNodeId}return!1},yS=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},lg=e=>{let{nodes:t,rootNodeId:n}=h();if(hS(e.contextNodeId)&&oi(e.contextNodeId,e.selectedIndex))return d("Restored navigation inside text container",null);if(yS(e.selectedNodeId)&&e.selectedNodeId&&sg(e.selectedNodeId))return d("Restored navigation to selected node or ancestor",null);if(oi(e.contextNodeId,e.selectedIndex))return d("Restored navigation to previous container",null);if(e.parentNodeId&&oi(e.parentNodeId,e.selectedIndex))return d("Restored navigation to previous parent",null);if(sg(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=ye(r.id);return U.navigate({contextNode:r,selectedIndex:ig(e.selectedIndex,o.length)}),d("Restored navigation to root",null)};import{monotonicFactory as bS,ulid as _t}from"ulid";var Po=bS();function vS(){let e=xe();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 xS(){let e=vS();return c(e)?e:U.navigate(e.value)}function dg({userId:e,userName:t}){let n=Po(),r=Po(),o=Po(),s=Po(),i=Po(),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 b=He(void 0,void 0);return c(b)?b: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:fs,name:"Closed",parent:n,rank:p.value}},{id:_t(),userId:e,action:"add.swimlane",payload:{id:ct,name:"Closed",parent:fs,rank:b.value}},{id:_t(),userId:e,action:"lock.node",payload:{id:fs}},{id:_t(),userId:e,action:"lock.node",payload:{id:ct}}])}var ES=()=>{let e=xe();if(c(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},RS=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(", ");H.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(", ");H.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function Oo(e,t=[]){if(ES())return d("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ie.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=po(s);return c(i)?i:(A({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}=Dn(n);return r.length>0?a(`Materializing failed:
|
|
56
|
+
${r.map(s=>s.message).join(`
|
|
57
|
+
`)}`):(Fn(o),xS(),A({hasProjectDefinition:!0}),RS(t),d("State booted successfully",null))}import{WebSocket as SS}from"ws";var si=new Set,XF=e=>{si.add(e),e.on("close",()=>{si.delete(e)}),e.on("error",()=>{si.delete(e)})},ug=e=>{let t=JSON.stringify(e);for(let n of si)n.readyState===SS.OPEN&&n.send(t)};var ii=e=>{ut()&&(A({syncStatus:e}),ug({type:"sync-status",payload:e}))},ai=(e="Syncing...")=>{ii({status:"syncing",msg:e})},Do=(e="Synced")=>{ii({status:"synced",msg:e})},CS=e=>{ii({status:"failed",msg:e})},ci=e=>{ii({status:"offline",msg:e})},Ae=e=>(CS(e),a(e));var jn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),mg=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 Ag from"node:fs";import Vt from"node:fs";import qt from"node:path";import li from"node:fs";import pg from"node:path";var _e=".epiq/project.json",fg=e=>pg.join(e,_e),NS=e=>{if(!li.existsSync(fg(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)},al=(e,t)=>{try{let n=fg(e);return li.mkdirSync(pg.dirname(n),{recursive:!0}),li.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
58
|
+
`,"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")}},IS=({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(`
|
|
59
|
+
`);var gg=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!li.existsSync(rr(e)))return d("No project file to compare","no-checkout-file");let r=je(e);if(c(r))return a(r.message);let o=NS(t);if(c(o))return a(o.message);if(o.value===null){let s=al(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(IS({checkout:r.value,branch:o.value,stateBranch:n})):d("The checkout and the state branch agree","matched")};import $t from"node:fs";import Fo from"node:path";var Er=e=>e.split(`
|
|
60
|
+
`).filter(t=>t.trim().length>0),hg=e=>{let t=Fo.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=>Er($t.readFileSync(Fo.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)}`)}},yg=e=>Fo.join(e,Ue,Ht),bg=e=>{let t=yg(e),n=new Map;try{if(!$t.existsSync(t))return n;for(let r of $t.readdirSync(t))if(r.endsWith(".jsonl")&&!On(r))try{n.set(r,Er($t.readFileSync(Fo.join(t,r),"utf8")))}catch(o){if(!ao(o))throw o}}catch{return n}return n},wS=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},vg=(e,t)=>{if(t.size===0)return[];let n=yg(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Fo.join(n,o);try{let l=$t.existsSync(i)?$t.readFileSync(i,"utf8"):null,u=new Set(l===null?[]:Er(l)),p=s.filter(f=>!u.has(f)).filter(wS);if(p.length===0)continue;$t.mkdirSync(n,{recursive:!0});let m=l!==null&&l.length>0&&!l.endsWith(`
|
|
61
|
+
`);$t.appendFileSync(i,`${m?`
|
|
62
|
+
`:""}${p.join(`
|
|
63
|
+
`)}
|
|
64
|
+
`,"utf8"),r.push(`${o} (${p.length})`)}catch{continue}}return r},AS=(e,t)=>{let n=new Set(Er(t));return Er(e).filter(r=>!n.has(r))},TS=(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(`
|
|
65
|
+
`),xg=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Ce({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return d("No committed log to compare against",void 0);let o=AS(r.stdout,n);return o.length>0?a(TS(t,o,Er(r.stdout).length)):d("Event log only grew",void 0)};var MS="[epiq:init-repo]",Rg=async e=>{let t=await Ce({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(`
|
|
66
|
+
`));H.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",MS],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)},Eg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",kS=async e=>{let t=await ls(e);if(c(t))return a(t.message);let n=await Xd(e);return c(n)?a(n.message):d("Built sync commit message",`[sync|branch:${Eg(t.value)}:sha:${Eg(n.value)}]`)},cl=async({repoRoot:e,stateBranchName:t})=>{H.info(`Creating ${t}`);let n=await _({args:["commit-tree",au,"-m","[epiq:init-state-branch]"],cwd:e});if(c(n))return a(`Failed to create state branch commit
|
|
67
|
+
${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}
|
|
68
|
+
${o.message}`):d("Created state branch",!0)},ll=async({repoRoot:e,stateBranchName:t})=>{let n=await cs({repoRoot:e,branch:t});if(c(n))return a(`Ensure local state branch failed
|
|
69
|
+
`+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
|
|
70
|
+
`+r.message);let o=r.value,s=o?await Hr({repoRoot:e,branch:t}):d("No remote, no remote state branch",!1);if(c(s))return a(`Ensure local state branch failed
|
|
71
|
+
`+s.message);let i=s.value;if(o&&i){let l=await ue.fetch({cwd:e,remote:tt,branch:t});if(c(l))return a(`Failed to fetch ${t} from remote
|
|
72
|
+
${l.message}`)}if(i){let l=await _({args:["branch","--track",t,`${tt}/${t}`],cwd:e});return c(l)?a(`Failed to create local ${t} from remote
|
|
73
|
+
${l.message}`):d("Created local state branch from remote",!0)}return cl({repoRoot:e,stateBranchName:t})},LS=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(`
|
|
74
|
+
`),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)},PS=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=zr(qt.dirname(t));if(c(r))return a(`Failed to create state branch worktree
|
|
75
|
+
`+r.message);if(Vt.existsSync(t)&&!Vt.existsSync(qt.join(t,".git"))){let s=hg(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(`
|
|
76
|
+
`));H.info("Removing broken state branch worktree path"),uu(t)}H.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
|
|
77
|
+
${o.message}`):d("Created state branch worktree",!0)},Rr=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await DS({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(c(r))return r;let o=gg({repoRoot:e,stateBranchRoot:t,stateBranch:n});return c(o)?a(o.message):(o.value==="stamped"&&H.info("Stamped the state branch with this project\u2019s identity"),r)},OS=(e,t)=>{let n=tr(In());return qt.dirname(e)===n&&qt.dirname(t)===n},DS=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await LS({repoRoot:e,branch:n});if(c(r))return a(r.message);let o=tr(t),s=r.value?tr(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&&OS(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(`
|
|
78
|
+
`));if(s&&s!==o){let u=await nu(s);if(c(u))return a(u.message);if(u.value||mm(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(`
|
|
79
|
+
`));H.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
|
|
80
|
+
${p.message}`)}if(s&&!Vt.existsSync(s)){H.info("Pruning stale state branch worktree");let u=await ue.worktreePrune({cwd:e});if(c(u))return a(`Failed to prune stale worktrees
|
|
81
|
+
${u.message}`)}let i=await Yd({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){H.info("Pruning missing registered state branch worktree");let u=await ue.worktreePrune({cwd:e});if(c(u))return a(`Failed to prune stale worktrees
|
|
82
|
+
${u.message}`)}return PS({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},FS=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await ls(e);if(c(n))return a(n.message);if(n.value===t)return d("State branch already checked out",!1);(await Ce({cwd:e,args:["rebase","--abort"]})).exitCode===0&&H.info("Aborted stale state branch rebase");let o=await ue.checkout({cwd:e,branch:t});return c(o)?a(`Failed to checkout ${t}
|
|
83
|
+
${o.message}`):d("Checked out state branch",!0)},_S=async({repoRoot:e,stateBranchRoot:t})=>{let n=await fa(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=Rt(e);if(c(o))return o;let s=o.value,i=await Hr({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);H.info(`Configuring ${s} upstream`);let l=await ue.fetch({cwd:t,remote:tt,branch:s});if(c(l))return a(`Failed to fetch ${s}
|
|
84
|
+
${l.message}`);let u=await ue.setUpstream({cwd:t,branch:s,upstream:`${tt}/${s}`});return c(u)?a(`Failed to set state branch upstream
|
|
85
|
+
${u.message}`):d("Configured state branch upstream",!0)},di=async({stateBranchRoot:e,eventFileName:t})=>{let n=cu(t),r=qt.join(e,n);if(!Vt.existsSync(r))return d("No event file to stage",null);let o=await xg({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
|
|
86
|
+
${s.message}`):d("Staged state branch event file",n)},Sg=async({stateBranchRoot:e})=>{let t=lu(),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
|
|
87
|
+
${r.message}`):d("Staged state branch media files",t)},Cg=async({stateBranchRoot:e})=>{let t=[ha(),ya(),_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
|
|
88
|
+
${n.message}`):d("Staged event log config",t)},Ng=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await kS(e);return c(r)?a(`Create state branch sync commit failed
|
|
89
|
+
`+r.message):nr({cwd:t,message:r.value,pathspec:n})},_o=async({repoRoot:e,stateBranchRoot:t})=>{let n=await fa(t);if(c(n))return a(n.message);let r=Rt(e);if(c(r))return r;let o=r.value,s=n.value?await ue.push({cwd:t}):await ue.push({cwd:t,remote:tt,branch:o,setUpstream:!0});if(c(s))return a(`Failed during state branch push
|
|
90
|
+
${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)},Ig=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Rt(e);if(c(o))return o;let s=o.value,i=[Vr(),await ll({repoRoot:e,stateBranchName:s}),await Rr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await FS({stateBranchRoot:t,stateBranchName:s}),await pu(t),n?await _S({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 $S=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ie("getRepoRootDir",await St(t));if(c(r))return a(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ie("getStateBranchRoot",be({repoRoot:o}));if(c(s))return a(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&Ag.existsSync(i)){let m=await Qd(i,{preserve:[Bs]});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=Rt(o);if(c(f))return a(f.message);let g=await eu(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 b=ie("abortRebaseIfPresent(stateBranchRoot)",await ga(i));if(c(b))return a(b.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let l=ie("bootstrapStateBranchStorage",await Ig({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 pa(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",mu(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}))},BS=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 Im(Ve(t),n)){let m=ie("stageStateBranchOwnEventFile",await di({stateBranchRoot:t,eventFileName:p}));if(c(m))return a(m.message);r.push(m.value)}let o=ie("stageStateBranchMediaFiles",await Sg({stateBranchRoot:t}));if(c(o))return a(o.message);let s=ie("stageStateBranchEventConfig",await Cg({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 ru(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 Ng({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}))},dl=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return ci(n),d(n,{...e,pulled:!1,pushed:!1,offline:!0})},wg=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");ai();let r=ie("ensureSyncReady",await $S({claim:n,cwd:e,ensureUpstream:!0}));if(c(r))return Ae(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,l=ie("isDetachedHead(stateBranchRoot)",await ou(s));if(c(l))return Ae(l.message);if(logger.debug("[sync] detached state branch check result",{detached:l.value}),l.value)return Ae("Cannot run :sync while the state branch is in detached HEAD state");let u=!1,p,m=!1,f=!1,g=ie("getStateBranch",Rt(o));if(c(g))return Ae(g.message);let b=g.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:s});let N=ie("flushPendingLogs",Ns(s,t));c(N)&&logger.error(`[sync] ${N.message}`);let E=ie("commitOwnEventFileToStateBranch",await BS({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(c(E))return Ae(E.message);u=E.value.createdCommit,p=E.value.commitSha;let R=ie("hasRemote",await jt({repoRoot:s}));if(c(R))return Ae(R.message);if(!R.value)return dl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i},"no remote");let v=ie("pullBranchRebaseIfPresent",await Gr({cwd:s,branch:b}));if(c(v))return Wr(v.message)?dl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):Ae(v.message);m=v.value;let I=ie("isAheadOfUpstream",await tu(s));if(c(I))return Ae(I.message);if(u||i||I.value){logger.info("[sync] pushing state branch",{createdCommit:u,bootstrapped:i,stateBranchRoot:s});let M=ie("pushStateBranch",await _o({stateBranchRoot:s,repoRoot:o}));if(c(M)&&Jd(M.message)){let k=ie("pullBranchRebaseIfPresent(retry)",await Gr({cwd:s,branch:b}));if(c(k))return Ae(k.message);m=m||k.value,M=ie("pushStateBranch(retry)",await _o({stateBranchRoot:s,repoRoot:o}))}if(c(M))return Wr(M.message)?dl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):Ae(M.message);f=M.value}if(u){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let M=ie("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:s}));if(c(M))return Ae(M.message);p=M.value.stdout.trim(),logger.debug("[sync] final sync commit sha",p)}return Do(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})},ui=async(e,t)=>{let n=bg(e);try{return await t()}finally{let r=vg(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},Tg=async e=>{let t=e.cwd??process.cwd(),n=await St(t);if(c(n))return Ae(n.message);let r=be({repoRoot:n.value});if(c(r))return Ae(r.message);let o=r.value;if(!Ag.existsSync(o))return wg(e,"clean");let s=await xo({worktreeRoot:o,operation:"sync",fn:i=>ui(o,()=>wg(e,i))});return c(s)?Ae(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 Sr=null,mi=async({reposMinIntervalMs:e=0}={})=>(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Sr,currentStatus:h().syncStatus?.status,currentMessage:h().syncStatus?.msg}),Sr?(logger.debug("[sync] syncAndReloadState joining existing promise"),Sr):(logger.debug("[sync] syncAndReloadState creating promise"),Sr=US(e).finally(()=>{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:h().syncStatus?.status,statusMessageBeforeClear:h().syncStatus?.msg}),Sr=null}),Sr)),US=async e=>{let t;try{t=await jS(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=xe();return c(t)&&!c(n)&&n.value.syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),A({syncStatus:{msg:t.message,status:"failed"}})),t},jS=async e=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let t=Mg();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");A({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:h().syncStatus});let r=ur(n.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:r}),logger.debug("[sync] syncEpiqWithRemote:start");let o=ie("syncEpiqWithRemote",await Tg({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),A({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:h().syncStatus}),Ae(`Unable to sync state. ${o.message}`);let{stateBranchRoot:s,offline:i,repoRoot:l}=o.value,u=ul(s);return c(u)?u:(A({hasProjectDefinition:!0,syncStatus:i?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:h().syncStatus}),HS(l,e),d("Synced",!0))},HS=async(e,t)=>{let n=await zs({repoRoot:e,minIntervalMs:t}),r=c(n)?null:Ac(n.value),o=h().syncStatus;r&&o?.status==="synced"&&A({syncStatus:{msg:`Synced \xB7 ${r}`,status:"synced"}})},ul=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=Nt(e),n=ie("loadMergedEvents",go(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 A({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=Mg();if(r)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:r.message,syncStatus:h().syncStatus}),r;let o=ag(),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=xe(),u=!c(l)&&l.value.timeMode==="live",p=ie("bootStateFromEventLog",Oo(n.value.events,n.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!c(p),message:(c(p),p.message)}),c(p))return A({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&&Es(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"),A({filters:s}),logger.debug("[sync] restoreNavigationAnchor:start");let i=ie("restoreNavigationAnchor",lg(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)?(A({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)},Mg=()=>h().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:h().mode,syncStatus:h().syncStatus}),A({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var kg=0,ml,pl=!1,$o=!1,fl=()=>{if(pl)return!0;let e=xe();return c(e)?!1:e.value.syncStatus.status==="syncing"},WS=()=>{let e=os(ee().autoSyncIntervalMs),t=Date.now()-kg;return Math.max(0,e-t)},Lg=()=>{ml||(ml=setTimeout(async()=>{if(ml=void 0,!!ut()){if(fl()){$o=!0;return}$o=!1,await GS()}},WS()))},GS=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!ut())return a("Cannot auto-sync before state is initialized");if(fl())return $o=!0,a("Sync already in progress");pl=!0,kg=Date.now(),A({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await mi({reposMinIntervalMs:6e4})}finally{pl=!1,$o&&Lg()}},Pg=()=>{ut()&&($o=!0,!fl()&&Lg())};var Og=e=>{let{context:t}=h().contextNode;if(!t)return G.None;switch(e){case x.EXIT:return G.Exit;case x.EXPORT:return G.Export;case x.INIT:return G.Init;case x.OPEN:return G.OpenProject;case x.DELETE:return G.Delete;case x.EDIT:return G.Edit;case x.COMMENT:return G.Comment;case x.HELP:return G.ViewHelp;case x.RE_OPEN_ISSUE:return G.ReopenIssue;case x.CLOSE_ISSUE:return G.CloseIssue;case x.TAG:return G.TagTicket;case x.UNTAG:return G.UntagTicket;case x.ASSIGN:return G.AssignUserToTicket;case x.UNASSIGN:return G.UnassignUserFromTicket;case x.NEW:return G.NewItem;case x.FILTER:return G.Filter;case x.MOVE:return G.Move;case x.PEEK:return G.Peek;case x.REPLAY:return G.Replay;case x.CONFIG:return G.Config;case x.YANK:return G.Yank;case x.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 Sh from"node:fs";import tN from"node:path";import nN from"react";import{Box as QC}from"ink";import Ci from"react";import cC from"chalk";import{Box as yl,Text as lC}from"ink";import Bt from"react";import{Text as Dg}from"ink";import Fg,{useEffect as _g,useState as zS}from"react";var $g={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},pt=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Le(),r=$g[n]??$g.default,[o,s]=zS(0);if(_g(()=>{s(0)},[r]),_g(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Fg.createElement(Dg,null,t);let i=r[o]??r[0]??t;return Fg.createElement(Dg,{color:w.accent,dimColor:o===1},i)};import{Box as gl,Text as VS}from"ink";import pi from"react";var qS=(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}},ft=({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?qS(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},b=Math.max(1,g-f),N=e.slice(f,g),E=e.length>b,R=i,v=E?Math.max(1,Math.floor(b/e.length*R)):R,I=Math.max(0,R-v),M=Math.max(1,e.length-b),k=E?Math.floor(f/M*I):0;return pi.createElement(gl,{flexDirection:"row",height:i,width:"100%"},pi.createElement(gl,{flexDirection:"column",flexGrow:1,height:i},N),pi.createElement(gl,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((P,L)=>pi.createElement(VS,{key:L,color:E&&L>=k&&L<k+v?w.accent:w.secondary},E?"\u2502":" "))))};import{Box as Ir,Text as wr}from"ink";import Ye from"react";var Bg,hl,KS=()=>{let{eventLog:e=[]}=h();if(hl&&Bg===e)return hl;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Bg=e,hl=t,t},fi=e=>KS().has(e);import{Text as YS}from"ink";import XS from"react";var Cr=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Cn(o,n);return XS.createElement(YS,{underline:t,color:Be(o)},"@"+s,fi(e)?"":"\u2197")};import{Text as JS}from"ink";import ZS from"react";var gi=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getTag(e);if(!r)return;let o=n===void 0?r.name:Cn(r.name,n);return ZS.createElement(JS,{underline:t,backgroundColor:Be(r.name),color:w.secondary}," "+o+" ")};import{useEffect as QS,useState as eC}from"react";var tC=80,Ug=1400,hi=new Set,Bo=null,nC=e=>(hi.add(e),Bo||(Bo=setInterval(()=>{for(let t of hi)t()},tC)),()=>{hi.delete(e),hi.size===0&&Bo&&(clearInterval(Bo),Bo=null)}),rC=()=>{let e=Date.now()%Ug/Ug;return e<.5?e*2:(1-e)*2},Nr=e=>{let[,t]=eC(0);return QS(()=>{if(e)return nC(()=>t(n=>n+1))},[e]),cd(rC())};var oC=(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),Cn(e.slice(o).trim(),n)]},jg=3,sC=2,iC=(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}},Hg=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Nr(r),s=e-4,i=s-7-1,[l,u]=oC(Ut(t.title),i,s),p=u?null:Cn(Ut(t.props.description),s)||null,m=en(t),f=tn(t).map(v=>({...v,name:v.name})),g=Math.max(1,s-jg),b=C.getCommentsByIssue(t.id),N=b.length?String(b.length).length+2+1:0,{shown:E,hidden:R}=iC([...m.map(v=>({id:v.id,isTag:!0,width:Math.min(v.name.length,g)+jg})),...f.map(v=>({id:v.id,isTag:!1,width:Math.min(v.name.length,g)+sC+(fi(v.id)?0:1)}))],s-N);return Ye.createElement(Ir,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?w.accent:w.secondary,justifyContent:"space-between"},Ye.createElement(Ir,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Ye.createElement(Ir,{justifyContent:"space-between"},Ye.createElement(wr,{color:w.primary},l),Ye.createElement(wr,{color:w.secondary2,dimColor:!0},nt(t.id))),u&&Ye.createElement(wr,{color:w.primary},u),p&&Ye.createElement(wr,{color:w.secondary2,dimColor:!0},p)),Ye.createElement(Ir,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Ye.createElement(Ir,{flexDirection:"row"},E.map(v=>Ye.createElement(Ir,{paddingRight:1,key:v.id},v.isTag?Ye.createElement(gi,{id:v.id,maxWidth:g}):Ye.createElement(Cr,{id:v.id,maxWidth:g}))),R>0&&Ye.createElement(wr,{color:w.secondary2,dimColor:!0},"+",R)),b.length>0&&Ye.createElement(wr,{color:w.accent},"[",b.length,"]")))};import{Box as Hn,Text as Uo}from"ink";import it from"react";var aC=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Wg=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=Nr(s),u=(r.props.tags??[]).map(P=>C.getTag(P)).filter(P=>!!P),p=(r.props.assignees??[]).map(P=>C.getContributor(P)).map(P=>P&&{...P,name:P.name}).filter(P=>!!P),m=1,f=u.length*(1+m),g=p.length*(2+m),b=u.map(P=>it.createElement(Hn,{key:P.id,paddingRight:m},it.createElement(Uo,{color:Be(P.name)},"\u25A0"))),N=p.map(P=>it.createElement(Hn,{key:P.id,paddingRight:m},it.createElement(Uo,{color:Ki(P.name)},"@"+P.name.at(0)))),E=s?l:o?w.accent:i===y.MOVE?w.secondary:w.primary,R=C.getCommentsByIssue(r.id),v=R.length?String(R.length).length+2+m:0,I=R.length?it.createElement(Hn,{paddingRight:m},it.createElement(Uo,{color:w.accent},"[",R.length,"]")):null,M=f+g+v,k=Math.max(1,n-t-M-(M>0?1:0));return it.createElement(Hn,{justifyContent:"space-between"},it.createElement(Hn,null,it.createElement(Hn,{width:t},o?it.createElement(pt,{isSelected:!0}):it.createElement(Uo,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),it.createElement(Uo,{wrap:"truncate",color:E},aC(r.title,k))),it.createElement(Hn,null,b,N,I))};var dC=({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,b=Nr(g),N=`${e.title} ${cC.hex(w.secondary2).dim("("+m.length+")")}`,E=3,R=o?1:5,v=s&&i===-1,I=n-3-(o?1:0)-(v?2:0),M=Math.max(2,String(m.length).length+1),k=r-E-1,P=Bt.createElement(yl,{borderStyle:"round",borderColor:w.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Bt.createElement(pt,{isSelected:t}),Bt.createElement(lC,{bold:!0,color:g?b:t?w.accent:w.primary},N," ",e.readonly?"\u{1F512}":"")),L=($,B)=>{let ce=s&&i===B;if(!j($))return null;let O=f?.has($.id)??!1;return o?Bt.createElement(Wg,{key:$.id,index:B,labelWidth:M,width:I,ticket:$,isSelected:ce,isFlashing:O,mode:l}):Bt.createElement(Hg,{key:$.id,width:I,ticket:$,isSelected:ce,isFlashing:O})};return Bt.createElement(yl,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?w.accent:w.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},P,Bt.createElement(yl,null,m.length>0&&Bt.createElement(ft,{selectedIndex:i,height:k,itemHeight:R},m.map(L)),v&&Bt.createElement(pt,{isSelected:!0})))},Gg=Bt.memo(dC);import{Box as kr,Text as qC}from"ink";import Je,{useMemo as Lr}from"react";var zg=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},Vg=(e,t,n)=>Ie.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var qg=e=>e.action==="add.issue.comment";import{Box as Ar,Text as Kt}from"ink";import $e,{useEffect as uC,useMemo as mC,useRef as pC}from"react";import{decodeTime as Kg}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"},yi=e=>String(e).padStart(2,"0"),DB=e=>`${e.getFullYear()}-${yi(e.getMonth()+1)}-${yi(e.getDate())} ${yi(e.getHours())}:${yi(e.getMinutes())}`;var fC=e=>pe(e,"attachments"),gC=e=>C.getAttachmentsByIssue(e.id).sort((t,n)=>Kg(t.id)-Kg(n.id)),Yg=e=>{for(let t of e)C.deleteNode(t.id)},hC=(e,t,n)=>Ie.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),yC=(e,t)=>{let n=C.getNode(fC(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>hC(o,s,n.id)).map(o=>C.createNode(o)).filter(vt).map(({value:o})=>o).filter(Fe);return t.length>0&&h().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},bC=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Xg({ticket:e,width:t,height:n}){let r=mC(()=>gC(e),[e]),o=pC([]);uC(()=>(Yg(o.current),o.current=yC(e,r),()=>{Yg(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(Ar,{flexDirection:"column",width:t,height:n,padding:1},$e.createElement(Kt,{color:w.primary},"No attachments yet."),$e.createElement(Ar,{paddingTop:1},$e.createElement(Kt,{color:w.primary},"Attach images from the browser GUI"),$e.createElement(Kt,{color:w.accent}," epiq gui "),$e.createElement(Kt,{color:w.primary},"by dropping or pasting them."))):$e.createElement(Ar,{flexDirection:"column",width:t,height:n},$e.createElement(Ar,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:w.secondary,borderStyle:"single",paddingBottom:1},$e.createElement(Kt,{color:w.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),$e.createElement(ft,{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(Ar,{key:p.id,flexDirection:"row",paddingX:1,paddingBottom:1},$e.createElement(Kt,{color:w.accent},f?"\u276F ":" "),$e.createElement(Ar,{paddingLeft:1},$e.createElement(Kt,{color:w.secondary2},`#${m+1} `),$e.createElement(Kt,{color:f?w.accent:w.primary},g),$e.createElement(Kt,{color:w.secondary2}," "+bC(p.bytes)+" "+dn(Sn(p.id)))))})))}import{Box as un,Text as mn}from"ink";import ke,{useEffect as CC,useMemo as rh,useRef as NC}from"react";import{decodeTime as oh}from"ulid";var vC=(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},jo=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)},xC=/!\[([^\]]*)\]\([^)]*\)/g,EC=e=>e.replace(xC,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),RC=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),SC=4,bi=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(SC)),bl=e=>{let t=!1;return e.map(bi).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Io(n);if(r)return{kind:"caption",text:$c(r)};let o=EC(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:jo(s[1]??"")}:{kind:"text",spans:jo(o)}})},Zg=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Jg=(e,t)=>{let n=[];for(let r of bl(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 vC(RC(r.spans),t))n.push({kind:r.kind,spans:jo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Qg=(e,t)=>{let n=Io(e),r=n?Qp(e):null;if(!n||r===null)return Jg(_c(e).split(`
|
|
91
|
+
`),t);let o=ef(e),s=r.split(`
|
|
92
|
+
`).map(bi),i=n.side===n.endSide?n.start:void 0,l=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...Jg(o.split(`
|
|
93
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:$c(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 eh,Text as Wn}from"ink";import gt from"react";var th=({spans:e,bold:t,wrap:n})=>gt.createElement(Wn,{color:w.primary,bold:t,wrap:n},e.map((r,o)=>r.code?gt.createElement(Wn,{key:o,color:w.yellow},r.text):gt.createElement(Wn,{key:o},r.text))),vl=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return gt.createElement(Wn,null," ");case"fence":return gt.createElement(Wn,{color:w.secondary2},"```");case"caption":return gt.createElement(Wn,{color:w.accent,wrap:r},e.text);case"heading":return gt.createElement(th,{spans:e.spans,bold:!0,wrap:r});case"text":return gt.createElement(th,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return gt.createElement(Wn,{backgroundColor:w.secondary,color:w.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},nh=({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 gt.createElement(eh,{flexDirection:"column"},e.map((o,s)=>gt.createElement(eh,{key:s},gt.createElement(vl,{line:o,width:t,gutter:r}))))};var IC=4,wC=e=>pe(e,"comments"),AC=e=>C.getCommentsByIssue(e.id).sort((t,n)=>oh(t.id)-oh(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),sh=e=>{for(let t of e)C.deleteNode(t.id)},TC=(e,t)=>{let n=C.getNode(wC(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>Vg(o,s,n.id)).map(C.createNode).filter(vt).map(({value:o})=>o).filter(Ur);return t.length>0&&h().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r};function ih({ticket:e,width:t,height:n}){let r=rh(()=>AC(e),[e]),o=NC([]);CC(()=>(sh(o.current),o.current=TC(e,r),()=>{sh(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Le(),l=Math.max(1,n-4),u=Math.max(20,t-8),p=rh(()=>r.map(f=>{let g=Qg(f.md,u);return g.length>0?g:[{kind:"blank"}]}),[r,u]),m=p.map(f=>f.length+IC);return r.length===0?ke.createElement(un,{flexDirection:"column",width:t,height:n,padding:1},ke.createElement(mn,{color:w.primary},"No comments yet."),ke.createElement(un,{paddingTop:1},ke.createElement(mn,{color:w.primary},"Use"),ke.createElement(mn,{color:w.accent}," :comment "),ke.createElement(mn,{color:w.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:w.secondary,borderStyle:"single",paddingBottom:1},ke.createElement(mn,{color:w.secondary2},"Comments (",r.length,") ")),ke.createElement(ft,{height:l,itemHeights:m,selectedIndex:s},r.map((f,g)=>{let b=g===s;return ke.createElement(un,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:w.secondary,borderStyle:"single"},ke.createElement(un,{flexDirection:"row",paddingBottom:1},ke.createElement(mn,{color:w.accent},b?"\u276F ":" "),ke.createElement(un,{paddingLeft:1},ke.createElement(mn,{color:w.secondary2},`#${g+1} `),ke.createElement(Cr,{id:f.authorId}),ke.createElement(mn,{color:w.secondary2}," "+dn(Sn(f.id))))),ke.createElement(un,{paddingLeft:3,paddingBottom:1},ke.createElement(nh,{lines:p[g]??[],width:u})))})))}import{Box as fn,Text as Xe}from"ink";import ge,{useEffect as gh,useRef as _C,useState as $C}from"react";import{Box as At,Text as Yt}from"ink";import Re,{useEffect as Sl,useMemo as dh,useRef as LC,useState as PC}from"react";var vi=(e,t,n)=>{let r=[],o=ks(()=>{for(let s=0;s<t;s++){let i=st(BigInt(s+1));if(!vt(i))continue;let l=C.createNode(Ie.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));vt(l)&&r.push(l.value)}});return c(o)&&logger.error(`Line nodes: ${o.message}`),r},Tr=e=>{C.deleteNodes(e.map(t=>t.id))};import{useSyncExternalStore as MC}from"react";var Ei=null,xi=null,xl=new Set,ah=()=>{for(let e of xl)e()},El=e=>{Ei=e,ah()},Ri=()=>Ei,ch={mark:null},Gn=e=>{xi=e,ch={mark:e},ah()};var Rl=e=>xi&&xi.sha===e?xi.row:null,lh=()=>MC(e=>(xl.add(e),()=>{xl.delete(e)}),()=>ch),pn=()=>{let{contextNode:e}=h();return Ei&&Ei.sha===e.id?e.id:null};import OC from"string-width";var Cl=(e,t)=>`${e}::patch::${t}`,uh=e=>bi(e).replace(/[\x00-\x1f\x7f-\x9f]/g,"\uFFFD"),DC=e=>{switch(e){case"added":return w.green;case"removed":return w.red;case"hunk":return w.accent;case"file":return w.primary;default:return w.secondary2}},mh=(e,t)=>{let n=OC(e);return n>=t?e:e+"\xA0".repeat(t-n)},FC=e=>e==="added"?"+":e==="removed"?"-":" ",ph=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine);function fh({ticket:e,sha:t,repo:n,subject:r,width:o,height:s}){let[i,l]=PC({state:"loading"});Sl(()=>{let k=!0;return l({state:"loading"}),Fc({sha:t,repo:n}).then(P=>{k&&l(c(P)?{state:"failed",message:P.message}:{state:"loaded",rows:jc(Uc(P.value))})}),()=>{k=!1}},[t,n]);let u=i.state==="loaded"?i.rows:null,p=u!==null&&u.length>4e3,m=LC([]);Sl(()=>(Tr(m.current),m.current=u&&!p?vi(t,u.length,k=>Cl(t,k)):[],()=>{Tr(m.current),m.current=[]}),[t,u,p]),Sl(()=>(El(u?{sha:t,rows:u}:null),Gn(null),()=>{El(null),Gn(null)}),[t,u]);let{selectedIndex:f}=Le(),{mark:g}=lh(),b=dh(()=>u?Hc(u,C.getCommentsByIssue(e.id),t):new Set,[u,t,e]),N=g&&g.sha===t?g.row:null,E=k=>N!==null&&k>=Math.min(N,f)&&k<=Math.max(N,f),R=dh(()=>u?Math.max(5,u.reduce((k,P)=>Math.max(k,ph(P).length),0)+2):5,[u]),v=Math.max(1,s-4),I=Math.max(8,o-R-6);if(i.state!=="loaded")return Re.createElement(At,{flexDirection:"column",width:o,height:s,padding:1},Re.createElement(Yt,{color:w.primary},i.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${i.message}`));let M=k=>Re.createElement(At,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:w.secondary,borderStyle:"single",paddingBottom:1},Re.createElement(Yt,{color:w.secondary2,wrap:"truncate-end"},Nn(`${t.slice(0,7)} ${r} \u2014 ${k}`,Math.max(8,o-6))));return i.rows.length===0?Re.createElement(At,{flexDirection:"column",width:o,height:s},M("no changes"),Re.createElement(At,{paddingX:1},Re.createElement(Yt,{color:w.primary},"This commit changed no files."))):p?Re.createElement(At,{flexDirection:"column",width:o,height:s},M("too large to draw here"),Re.createElement(At,{paddingX:1,flexDirection:"column"},Re.createElement(Yt,{color:w.primary},`${i.rows.length.toLocaleString()} lines of diff.`),Re.createElement(Yt,{color:w.secondary2},"Press o to open it in your editor."))):Re.createElement(At,{flexDirection:"column",width:o,height:s},M(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"),Re.createElement(ft,{scrollByOne:!0,height:v,selectedIndex:f,itemHeight:1},i.rows.map((k,P)=>{let L=P===f,$=DC(k.kind);if(k.kind==="file")return Re.createElement(At,{key:Cl(t,P),paddingX:1},Re.createElement(Yt,{backgroundColor:w.secondary,color:L?w.accent:$,bold:!0,wrap:"truncate-end"},mh(` ${Nn(uh(k.text),I)}`,I+R+1)));let B=E(P),ce=`${FC(k.kind)}${Nn(uh(k.text),I)}`;return Re.createElement(At,{key:Cl(t,P),paddingX:1},Re.createElement(At,{flexShrink:0},Re.createElement(Yt,{color:L||B?w.accent:w.secondary2,dimColor:!L&&!B,wrap:"truncate-end"},`${L?"\u276F":"\xA0"}${B?"\u258C":"\xA0"}${ph(k).padStart(R-2,"\xA0")}`)),Re.createElement(At,{flexShrink:0},Re.createElement(Yt,{color:w.yellow,wrap:"truncate-end"},b.has(P)?"\u2502":"\xA0")),Re.createElement(Yt,{color:L?w.accent:$,backgroundColor:L||B?w.secondary:void 0,wrap:"truncate-end"},L||B?mh(ce,I+1):ce))})))}var BC=e=>pe(e,"diff"),hh=e=>{for(let t of e)C.deleteNode(t.id)},UC=(e,t,n)=>Ie.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),jC=(e,t)=>{let n=C.getNode(BC(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>UC(o,s,n.id)).map(o=>C.createNode(o)).filter(vt).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},HC=e=>`+${e.insertions} -${e.deletions}`;function yh({ticket:e,width:t,height:n}){let[r,o]=$C({state:"loading"}),s=nt(e.id);gh(()=>{let E=!0;return o({state:"loading"}),hc({ref:s}).then(R=>{if(!E)return;let v=Ct();o(c(R)?{state:"failed",message:R.message}:{state:"loaded",commits:R.value,labels:c(v)?new Map:sc(v.value)})}),()=>{E=!1}},[s]);let i=_C([]),l=r.state==="loaded"?r.commits:null,u=r.state==="loaded"?r.labels:null;gh(()=>(hh(i.current),i.current=l?jC(e,l):[],()=>{hh(i.current),i.current=[]}),[e,l]);let{selectedIndex:p,contextNode:m}=Le(),f=l?.find(E=>E.sha===m.id)??null,b=Math.max(1,n-4),N=Math.max(12,t-34);return r.state!=="loaded"?ge.createElement(fn,{flexDirection:"column",width:t,height:n,padding:1},ge.createElement(Xe,{color:w.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):f?ge.createElement(fh,{ticket:e,sha:f.sha,repo:f.repo,subject:f.subject,width:t,height:n}):r.commits.length===0?ge.createElement(fn,{flexDirection:"column",width:t,height:n,padding:1},ge.createElement(Xe,{color:w.primary},"No commits reference this ticket."),ge.createElement(fn,{paddingTop:1},ge.createElement(Xe,{color:w.primary},"Link one with an"),ge.createElement(Xe,{color:w.accent},` Epiq-Ref: ${s} `),ge.createElement(Xe,{color:w.primary},"line in its body,")),ge.createElement(fn,null,ge.createElement(Xe,{color:w.primary},"or a"),ge.createElement(Xe,{color:w.accent},` ${s} `),ge.createElement(Xe,{color:w.primary},"prefix on its subject."))):ge.createElement(fn,{flexDirection:"column",width:t,height:n},ge.createElement(fn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:w.secondary,borderStyle:"single",paddingBottom:1},ge.createElement(Xe,{color:w.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),ge.createElement(ft,{height:b,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 ge.createElement(fn,{key:E.sha,flexDirection:"row",paddingX:1,paddingBottom:1},ge.createElement(Xe,{color:w.accent},v?"\u276F ":" "),ge.createElement(fn,{paddingLeft:1},ge.createElement(Xe,{color:w.secondary2},`${E.sha.slice(0,7)} `),E.repo&&ge.createElement(Xe,{color:w.secondary2},`[${u?.get(E.repo)??_r(E.repo)}] `),ge.createElement(Xe,{color:v?w.accent:w.primary},I),ge.createElement(Xe,{color:w.secondary2},` ${HC(E)} ${dn(E.time)}`)))})))}import{Box as Si,Text as WC}from"ink";import Xt from"react";var bh=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Le(),{title:o}=t,s=t.parentNodeId?C.getNode(t.parentNodeId):void 0,i=s&&j(s)?o===me.ASSIGNEES?s.props.assignees??[]:o===me.TAGS?(s.props.tags??[]).filter(l=>C.getTag(l)):[]:[];return Xt.createElement(Si,{alignItems:"center",paddingTop:1},Xt.createElement(Si,{minWidth:12},Xt.createElement(pt,{isSelected:n}),Xt.createElement(WC,{color:n?w.accent:w.secondary2},o,":")),Xt.createElement(Si,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,u)=>{let p=r.id===t.id&&u===e;return Xt.createElement(Si,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Xt.createElement(pt,{isSelected:p}),o===me.ASSIGNEES?Xt.createElement(Cr,{isSelected:p,id:l}):o===me.TAGS?Xt.createElement(gi,{isSelected:p,id:l}):null)})))};import{Box as Mr,Text as wl}from"ink";import ht,{useEffect as GC,useMemo as Al,useRef as zC}from"react";var Nl=e=>Math.max(5,String(Math.max(e,1)).length+3),vh=(e,t)=>Math.max(0,e-6-Nl(t));var Il=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0));var VC="\u2029",xh=(e,t)=>`${e}::inline-line::${t}`,Tl=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=Le(),u=Al(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),p=Al(()=>u.join("\0"),[u]),m=zC([]);GC(()=>(Tr(m.current),m.current=vi(e,u.length,E=>xh(e,E)),()=>{Tr(m.current),m.current=[]}),[e,p]);let f=Nl(u.length),g=vh(s,u.length),N=Al(()=>bl(u).map(E=>{if(E.kind==="code"||E.kind==="caption")return{...E,text:Nn(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:jo(Nn(R,g))}}return E}),[u,g]).map((E,R)=>{let v=l.id===e&&i===R;return ht.createElement(Mr,{key:xh(e,R)},ht.createElement(Mr,{flexShrink:0},ht.createElement(wl,{color:v?w.primary:w.secondary2,dimColor:!v},`${R+1} `.padStart(f,"\xA0"))),E.kind==="blank"?ht.createElement(wl,{backgroundColor:v?"gray":void 0},VC):ht.createElement(Mr,null,ht.createElement(vl,{line:E,width:E.kind==="code"?g:0,wrap:"truncate-end"})))});return ht.createElement(Mr,{flexDirection:"column",paddingTop:1},ht.createElement(Mr,null,ht.createElement(pt,{isSelected:o}),ht.createElement(wl,{color:o?w.accent:w.secondary2},t)),ht.createElement(Mr,{flexDirection:"row",borderStyle:"round",borderColor:w.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},ht.createElement(ft,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},N)))};var KC=e=>pe(e,"description"),YC=e=>pe(e,"comments"),XC=e=>pe(e,"history"),JC=e=>pe(e,"diff"),ZC=e=>pe(e,"attachments"),Eh=({ticket:e,height:t})=>{let n=Lr(()=>zg(e),[e]),{selectedIndex:r,contextNode:o}=Le(),s=process.stdout.columns||120,i=Lr(()=>KC(e.id),[e.id]),l=Lr(()=>YC(e.id),[e.id]),u=Lr(()=>XC(e.id),[e.id]),p=Lr(()=>JC(e.id),[e.id]),m=Lr(()=>ZC(e.id),[e.id]),f=C.getAttachmentsByIssue(e.id).length,g=o.id===e.id,b=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(b){let V=t-3;return Je.createElement(kr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Je.createElement(ih,{ticket:e,width:s,height:V}))}if(E){let V=t-3;return Je.createElement(kr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Je.createElement(Xg,{ticket:e,width:s,height:V}))}if(R){let V=t-3;return Je.createElement(kr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Je.createElement(yh,{ticket:e,width:s,height:V}))}if(N){let O=C.getNode(u),V=O&&Fe(O)?O.props.value??"":"",Pe=Il(t);return Je.createElement(kr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},O?Je.createElement(Tl,{id:O.id,label:"Event log",text:V,selected:!1,maxWidth:s,rows:Pe}):null)}let I=[u,p,l,m],M=O=>I.includes(O),k=v.reduce((O,V)=>$r(V)?O+1:O,0),P=v.reduce((O,V)=>M(V.id)?O+1:O,0),L=v.findIndex(O=>M(O.id)),$=Il(t,k,P),B=(O,V,Pe,Dr)=>Je.createElement(kr,{key:O.id,paddingTop:V===L?1:0},Je.createElement(pt,{isSelected:Pe}),Je.createElement(qC,{backgroundColor:w.secondary,color:Pe?w.accent:w.primary},Dr)),ce=(O,V,Pe)=>O.id===i?Je.createElement(Tl,{key:O.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:V,maxWidth:s,rows:$}):$r(O)?Je.createElement(bh,{key:O.id,parent:O,selected:V,selectedIndex:r}):O.id===l?B(O,Pe,V,` Comments (${n}) \u203A\u203A `):O.id===m?B(O,Pe,V,` Attachments (${f}) \u203A\u203A `):O.id===u?B(O,Pe,V," History \u203A\u203A "):O.id===p?B(O,Pe,V," Diff \u203A\u203A "):null;return Je.createElement(kr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},v.map((O,V)=>ce(O,g&&r===V,V)))};var eN=({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),b=Math.floor(l/Math.max(e.length,1)),N=Math.min(b,g),E=s==="dense";return Ci.createElement(QC,{flexDirection:"row",height:i},m&&e.map((R,v)=>{let I=t.id===R.id,M=I?n:-1,k=t.context===te.BOARD&&n===v;return Ci.createElement(Gg,{key:R.id,height:i,width:N,swimlane:R,isSelected:k,isDense:E,isFocused:I,listSelectedIndex:M,mode:o})}),p&&f&&Ci.createElement(Eh,{height:i,ticket:f}))},Rh=Ci.memo(eN);import{render as rN}from"ink";import{Writable as oN}from"node:stream";var Ho=e=>String(e).padStart(2,"0"),sN=e=>{let t=e.getUTCFullYear(),n=Ho(e.getUTCMonth()+1),r=Ho(e.getUTCDate()),o=Ho(e.getUTCHours()),s=Ho(e.getUTCMinutes()),i=Ho(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},iN=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",aN=async(e,{width:t,height:n})=>{let r="",o=new oN({write(i,l,u){let p=cN(i.toString()).trimEnd();p.trim().length>0&&p.includes("\u256D")&&(r=p),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=rN(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},cN=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Ch=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 aN(nN.createElement(Rh,{height:u,width:l,swimlanes:(s[i.id]??[]).filter(v=>v!==void 0&&Qn(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=ss(process.cwd());if(c(m))return a("Unable to export, epiq root not found");let f=new Date,g=sN(f),b=`board_${iN(i.title)}_${g}.md`,N=fu(m.value);Sh.mkdirSync(N,{recursive:!0});let E=tN.join(N,b),R=`# Board - ${i.title}
|
|
94
|
+
Date: ${f.toISOString()}
|
|
95
|
+
|
|
96
|
+
\`\`\`text
|
|
97
|
+
${p}
|
|
98
|
+
\`\`\`
|
|
99
|
+
`;return Sh.writeFileSync(E,R,"utf8"),d("Exported board layout",E)};import{useSyncExternalStore as A1}from"react";var Ni,lN=new Set,Nh=()=>{for(let e of lN)e()};var Pr=()=>{if(!Ni)throw new Error("Ui state not initialized. Call initUiState() first.");return Ni};var k1=(e={})=>(Ni=e,Nh(),d("UX state initialized",null)),dN=e=>{let t=Pr();return Ni=e(t),Nh(),d("UX state updated",null)},gn=e=>dN(t=>({...t,...e}));import{ulid as Ii}from"ulid";var Ih=async e=>{let{contextNode:t,selectedIndex:n}=h(),r=ae(t.id)[n];if(e.modifier===lt.DESCRIPTION){let{breadCrumb:o,selectedNode:s}=h();return[...o,s].some(l=>l&&j(l))?mN():pN()}if(r&&Ur(r))return uN(e);if(e.modifier===lt.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:Z([{id:Ii(),action:"edit.title",payload:{id:s.id,name:i},...ne(o.value)}],l.value)}return a("Unknown edit command")},uN=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||!Ur(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||!j(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 Z([{id:Ii(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:p},...ne(t.value)}],f)},mN=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=Qe([...r,o],"TICKET");if(c(s))return a("Edit target must be an issue");let i=s.value;if(!j(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=Vc(u);if(c(p))return a("Failed to edit field");let m=p.value;return m===u?d("No changes made",null):Z([{id:Ii(),action:"edit.description",payload:{id:i.id,md:m},...ne(e.value)}],n)},pN=async()=>{let e=oe();if(c(e))return a("Unable to resolve user ID");let{selectedNode:t}=h();if(!t||!(Br(t)||Qn(t)))return a("Edit target must be an issue, swimlane or board");if(t.readonly)return a("Cannot edit readonly node");let n=t.props?.description??"",r=Vc(n);if(c(r))return a("Failed to edit field");let o=Ef(r.value);if(o===n)return d("No changes made",null);let s=Br(t)?"board":"swimlane",i=Rf(s==="board"?"Board description":"Swimlane description",o,xf(s));if(i)return a(i);let l=await le();return c(l)?l:Z([{id:Ii(),action:"edit.description",payload:{id:t.id,md:o},...ne(e.value)}],l.value)};import gN from"node:fs";import kl from"node:path";import Ml from"node:fs";import fN from"node:path";var wh=async e=>{let t=fN.join(e,".gitignore"),n=Ml.existsSync(t)?Ml.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
100
|
+
`).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(`
|
|
101
|
+
`);return n=n.trimEnd()+`
|
|
102
|
+
|
|
103
|
+
${l}
|
|
104
|
+
`,Ml.writeFileSync(t,n,"utf8"),H.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),d("Local epiq paths ignored",!0)};var hN=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return c(t)?t:d("Checked git diff",t.value.stdout.split(`
|
|
105
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},re=(e,t)=>a(`[${e}] ${t}`),Ah=async({cwd:e,user:t})=>{let n=us(),r=await St(e);if(c(r))return re(1,r.message);let o=r.value,s=await Kd(o);if(c(s))return re(2,s.message);if(s.value)return re(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await hN(o);if(c(i))return re(2.5,i.message);if(i.value.length>0)return re(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(Xr(o))return re(4,"Epiq project already initialized");let{userId:l,userName:u}=t;if(!l||!u)return re(5,"Missing Epiq user id");let p=await Rg(o);if(c(p))return re(6,p.message);let m=n.stateBranch,f=await cs({repoRoot:o,branch:m});if(c(f))return re(6,f.message);if(f.value)return re(6,`State branch already exists: ${m}`);let g=await yN({repoRoot:o,stateBranch:m});if(c(g))return re(6,g.message);if(g.value)return bN({repoRoot:o,stateBranch:m});let b=await cl({repoRoot:o,stateBranchName:m});if(c(b))return re(6,b.message);let N=Vr();if(c(N))return re(7,N.message);let E=kl.join(In(),n.projectId),R=await Rr({repoRoot:o,stateBranchRoot:E,stateBranchName:m});if(c(R))return re(8,R.message);let v=kl.join(E,".epiq");gN.mkdirSync(v,{recursive:!0});let I=dg({userId:l,userName:u});if(c(I))return re(9,I.message);for(let nb of I.value){let zl=Um({event:nb,rootDir:E});if(c(zl))return re(9,zl.message)}let M=ur({userId:l}),k=Ns(E,M);if(c(k))return re(9,k.message);let P=al(E,n);if(c(P))return re(9,P.message);let L=await di({stateBranchRoot:E,eventFileName:M});if(c(L))return re(10,L.message);let $=await ue.stage({cwd:E,pathspec:[_e]});if(c($))return re(10,$.message);let B=await nr({cwd:E,message:"[epiq:init]"});if(c(B))return re(10,B.message);let ce=await wh(o);if(c(ce))return re(11,ce.message);let O=xa({repoRoot:o,fileContents:n});if(c(O))return re(12,O.message);let V=await ue.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(c(V))return re(13,V.message);let Pe=await ue.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(c(Pe))return re(13,Pe.message);let Dr=[],Wl=await _({cwd:o,args:["push","-u","origin","HEAD"]});c(Wl)&&Dr.push(`[init:14] ${Wl.message}`);let Gl=await _o({repoRoot:o,stateBranchRoot:E});return c(Gl)&&Dr.push(`[init:15] ${Gl.message}`),d("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:m,stateBranchRoot:E,defaultEvents:I.value,warnings:Dr})},yN=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 Hr({repoRoot:e,branch:t});return c(r)?a(`Could not ask origin whether ${t} exists: ${r.message}`):r},bN=async({repoRoot:e,stateBranch:t})=>{let n=await _({cwd:e,args:["fetch","origin",t]});if(c(n))return re(6,n.message);let r=await _({cwd:e,args:["show",`origin/${t}:${_e}`]});if(c(r))return re(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(`
|
|
106
|
+
`));let o;try{o=JSON.parse(r.value.stdout)}catch(N){return re(6,`The identity on origin/${t} is not readable: ${N instanceof Error?N.message:String(N)}`)}let s=xa({repoRoot:e,fileContents:o});if(c(s))return re(12,s.message);let i=await ue.stage({cwd:e,pathspec:[_e]});if(c(i))return re(13,i.message);let l=await ue.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[_e]});if(c(l))return re(13,l.message);let u=Vr();if(c(u))return re(7,u.message);let p=kl.join(In(),o.projectId),m=await ll({repoRoot:e,stateBranchName:t});if(c(m))return re(8,m.message);let f=await Rr({repoRoot:e,stateBranchRoot:p,stateBranchName:t});if(c(f))return re(8,f.message);let g=[],b=await _({cwd:e,args:["push","-u","origin","HEAD"]});return c(b)&&g.push(`[init:14] ${b.message}`),d("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:p,defaultEvents:[],warnings:g})};var Wo=(e,t)=>a(`[${e}] ${t}`),Th=async()=>{K("");let e=to();if(!e.isSetupDone||!e.userName)return Wo(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=ee(),n=t.userName,r=t.userId;if(!r||!n)return Wo(5,"Missing Epiq user id");let o=await Ah({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 Wo(16,l.map(g=>g.message).join(`
|
|
107
|
+
`));let u=xe();if(c(u))return Wo(16,u.message);let{rootNodeId:p,nodes:m}=u.value,f=m[p];return f?(U.navigate({contextNode:f,selectedIndex:0}),A({hasProjectDefinition:!0}),d(s,null)):Wo(16,"Unable to resolve initialized root node")};import{ulid as xN}from"ulid";import{ulid as vN}from"ulid";var Mh=null,Tt=()=>structuredClone(Mh),Go=e=>{Mh=e},kh=()=>{let{contextNode:e,selectedIndex:t}=h(),r=ye(e.id)[t];return r?d("Resolved selected child",r):a("Target node not found")},Ll=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ye(t).filter(o=>o.id!==e);return ti(r,n)},Lh=({id:e,parentId:t,position:n={at:"end"}})=>{let r=oe();if(c(r))return a("Unable to resolve user ID");let o=Ll({parentId:t,id:e,position:n});return c(o)?o:d("Created pending move state",{id:vN(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Ph=e=>{Go(e);let t=fo(e,!0);return c(t)?t:d("Node moved successfully",t.value)};function Pl(e){let t=kh();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=ye(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=Lh({id:t.value.id,parentId:l.id,position:{at:"end"}});return c(u)?u:Ph(u.value)}function zo(e,t=1){let n=kh();if(c(n))return n;let{contextNode:r,selectedIndex:o}=h(),s=ye(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=Lh({id:n.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:l.id}});return c(u)?u:Ph(u.value)}var Oh=()=>{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=ye(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))},Or=(e,t="Moved preview")=>{if(c(e))return Tt()&&A({mode:y.MOVE}),e;let n=Oh();return c(n)?n:(A({mode:y.MOVE}),d(t,null))},Dh=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=ye(n.id)[r];if(!o)return A({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=ye(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=Ll({parentId:o.parentNodeId,id:o.id,position:p});return c(m)?m:(Go({id:xN(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:m.value.rank},...ne(e.value)}),A({mode:y.MOVE}),d("Move initialized",null))}if(t==="next")return Or(zo(1));if(t==="previous")return Or(zo(-1));if(t==="jump-next")return Or(zo(1,Lo));if(t==="jump-previous")return Or(zo(-1,Lo));if(t==="to-next")return Or(Pl(1));if(t==="to-previous")return Or(Pl(-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=Z([s],i.value);if(c(l))return l;let u=Oh();return c(u)?u:(Go(null),A({mode:y.DEFAULT}),d("Moved item",null))}return t==="cancel"?(Go(null),A({mode:y.DEFAULT}),d("Cancelling move",null)):a("Invalid move modifier")};import{ulid as wi}from"ulid";import{monotonicFactory as EN,ulid as RN}from"ulid";var SN=EN(),Fh=({name:e,parent:t,rank:n,user:{userId:r}})=>{let o=SN();return d("Created issue events",[{id:RN(),userId:r,action:"add.issue",payload:{id:o,parent:t,name:e,rank:n}}])};var _h=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=Z([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:b})=>b===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=ri(m.id,n.value,o);return c(f)?f:u({id:wi(),action:"add.board",payload:{id:wi(),name:t.inputString,parent:m.id,rank:f.value},...ne(n.value)})}if(t.modifier==="swimlane"){let p=Qe(s,"BOARD");if(c(p))return a("Unable to add swimlane in this context");let m=ri(p.value.id,n.value,o);return c(m)?m:u({id:wi(),action:"add.swimlane",payload:{id:wi(),name:t.inputString,parent:p.value.id,rank:m.value},...ne(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=Qe(s,"SWIMLANE");return c(I)?null:I.value})();if(!m)return a("Unable to add issue in this context");let f=ri(m.id,n.value,o);if(c(f))return f;let g=Fh({name:t.inputString,parent:m.id,rank:f.value,user:n.value});if(c(g))return g;let b=g.value,N=Z([...b],o);if(c(N))return N;if(!N.value[0])return a("Issue creation failed");let v=b.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 PN from"node:os";import zh from"node:path";import Vo from"node:fs";import CN from"node:path";import{z as zn}from"zod";var qo="command-history.json",NN=20,IN=zn.object({projectId:zn.string().min(1),commands:zn.array(zn.string()),lastUsedAt:zn.number().finite()}),wN=zn.object({projects:zn.array(IN)}),$h=()=>{let e=wo();return c(e)?e:d("Resolved command history path",CN.join(e.value,qo))},AN=()=>{try{let e=Ee(process.cwd());return c(e)?null:e.value}catch{return null}},Bh=e=>{if(!Vo.existsSync(e))return d("No command history recorded",{state:"read",projects:[]});let t;try{t=Vo.readFileSync(e,"utf8")}catch(o){return a(`Unable to read ${qo}: ${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 ${qo}: ${o instanceof Error?o.message:String(o)}`})}let r=wN.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 ${qo} shape: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`})},Uh=({root:e})=>{let t=kt(e);if(c(t))return a(t.message);let n=$h();if(c(n))return n;let r=Bh(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,To)??[])},jh=({commands:e,root:t=AN(),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=$h();if(c(o))return o;let s=o.value,i=Bh(s);if(c(i))return i;let l=i.value,u=l.state==="read"?l.projects:[],p=[{projectId:r.value,commands:e.slice(0,To),lastUsedAt:n},...u.filter(f=>f.projectId!==r.value)].sort((f,g)=>g.lastUsedAt-f.lastUsedAt).slice(0,NN),m=`${s}.${process.pid}.tmp`;try{Vo.writeFileSync(m,JSON.stringify({projects:p},null,2)+`
|
|
108
|
+
`,"utf8"),Vo.renameSync(m,s)}catch(f){try{Vo.rmSync(m,{force:!0})}catch{}return a(`Unable to write ${qo}: ${f instanceof Error?f.message:String(f)}`)}return d("Stored command history",null)};var TN=e=>e.some(t=>t.action==="init.workspace"),Hh=async(e,t)=>{let n=Rt(e);return c(n)?a(n.message):Gr({cwd:t,branch:n.value})},MN=e=>{let t=Ee(process.cwd());if(c(t))return!1;let n=be({repoRoot:t.value});return!c(n)&&n.value===e},Ol=!1,VW=()=>Ol,Wh=async e=>{Ol=!0;try{return await kN(e)}finally{Ol=!1}},kN=async e=>{let t=be({repoRoot:e});if(c(t))return jn(3,t.message);let n=t.value,r=await Rr({repoRoot:e,stateBranchRoot:n,stateBranchName:us().stateBranch});if(c(r))return jn(3,r.message);let o=Nt(n),s=go(n);if(c(s))return jn(3,s.message);if(!TN(s.value.events)){let f=await xo({worktreeRoot:n,operation:"boot pull",fn:()=>ui(n,()=>Hh(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=Nt(n),s=go(n),c(s))return jn(3,s.message)}let{events:i,unreadable:l}=s.value,u=Oo(i,l);if(c(u))return jn(4,u.message);Es(n,o),A({hasProjectDefinition:!0,hasInitializingEvents:!!i.length});let p=Ru({root:e});c(p)&&logger.info(p.message);let m=Uh({root:e});return c(m)&&logger.info(m.message),Uf(c(m)?[]:m.value),d("Loaded project",void 0)},LN=async e=>{let t=be({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 xo({worktreeRoot:n,operation:"boot pull",fn:()=>ui(n,()=>(ai("Pulling"),Hh(e,n)))});if(c(o))return Ae(o.message);if(o.value===null)return d("Another process holds the state worktree",void 0);let s=o.value;if(c(s))return Wr(s.message)?(ci("Offline"),d("Offline",void 0)):Ae(s.message);if(!s.value)return Do("Already synced"),d("Already synced",void 0);if(!MN(n))return d("Project changed during the pull",void 0);let i=ul(n);return c(i)?i:(Do("Pulled"),d("Pulled and reloaded",void 0))},Gh=e=>{LN(e).then(t=>{c(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${mg(t)}`)})},qW=()=>{let e=Oo([]);return c(e)?jn(4,e.message):(A({hasProjectDefinition:!1,hasInitializingEvents:!1}),d("Booted without a project",void 0))};var ON=e=>e==="~"||e.startsWith("~/")?zh.join(PN.homedir(),e.slice(1)):e,DN=(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=Ee(zh.resolve(ON(n)));return c(r)?a(`No epiq project at ${n}`):d("Resolved project path",r.value)},Vh=async()=>{let e=ei();if(K(""),h().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=ps({exclude:process.cwd()}),n=c(t)?[]:t.value,r=DN(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 Wh(o);return c(i)?(process.chdir(s),a(i.message)):(Gh(o),d(`Opened ${bu(o)}`,null))};var Ai=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=$m(n,t);if(c(s))return a(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,u=hn();if(c(u))return u;let p=sn(i),{fatal:m,skipped:f}=Dn(p);if(m.length>0)return hn(),A(o),a(m.map(b=>b.message).join(", "));Fn(f);let g=h().nodes[e];return g?(U.navigate({contextNode:g,selectedIndex:r}),d("",{unappliedEvents:l})):(hn(),A(o),a("Board did not exist at that date"))};var qh=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 FN=20,_N=16,$N=150,Ti=null,Mi=null;var Vn=()=>{Ti!==null&&(clearInterval(Ti),Ti=null),Mi!==null&&(clearTimeout(Mi),Mi=null)},Kh=()=>{Vn(),A({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Yh=({events:e,startTime:t,durationMs:n})=>{Vn();let r=e.length,o=Zo(e.map(f=>Qo(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=qh(o),l=Math.max(1,Math.round(n*FN/1e3)),u=Math.max(Math.round(n/l),_N),p=0,m=0;A({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Ti=setInterval(()=>{p++;let f=p/l,g=[],b,N;for(;m<r&&i[m]<=f;){let R=e[m],v=fo(R);if(c(v)){if(dr(v)){m++;continue}Kh();return}g.push(...ec(R)),b=R,N=o[m],m++}if(m>=r||p>=l){for(;m<r;m++){let v=fo(e[m]);if(c(v)&&!dr(v))break}let R=h().replay;A({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),Vn(),Mi=setTimeout(Kh,$N);return}let E=h().replay;A({unappliedEvents:e.slice(m),replay:{progress:Math.min(1,f),appliedCount:m,totalCount:r,startTime:t,endTime:s,currentTime:b?N??E?.currentTime??t:E?.currentTime??t,currentLabel:b?Xh(b):E?.currentLabel??"",flashNodeIds:b?[...new Set(g)]:E?.flashNodeIds??[]}})},u)};var Jh=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(c(e))return e;let t=await St(process.cwd());if(c(t))return a("Unable to locate repo root");let n=be({repoRoot:t.value});if(c(n))return n;let{modifier:r,inputString:o}=Y().commandMeta;if(Vn(),r==="now"){let l=Ls(n.value);if(c(l))return a(l.message);let u=hn();if(c(u))return u;let p=sn(l.value),{fatal:m,skipped:f}=Dn(p);return m.length>0?a(m.map(g=>g.message).join(", ")):(Fn(f),A({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=Bm(n.value);if(c(l))return l;let u=r==="prev"?h().eventLog.at(-1):h().unappliedEvents.at(0),p=u===void 0?null:Qo(u),m=(u===void 0?null:l.value.get(u.id)??null)??(p===null?null:Wi(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=wn(r||o.trim());if(!l)return a("Invalid peek date");s=l.getTime()}let i=Ai({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return c(i)?i:(A({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),d("Peeking",!0))};var Zh=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(c(e))return e;let t=await St(process.cwd());if(c(t))return a("Unable to locate repo root");let n=be({repoRoot:t.value});if(c(n))return n;let{modifier:r,inputString:o}=Y().commandMeta,{dateInput:s,durationInput:i}=bs(r,o);if(Vn(),h().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let l=wn(s);if(!l)return a("Invalid replay date");let u=i?ys(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let p=l.getTime(),m=h(),f=Ai({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?(hn(),A(m),d("Nothing to replay from that point",!0)):(Yh({events:g,startTime:p,durationMs:u}),d("Replaying board history",!0))};import{spawn as UN}from"node:child_process";var jN=()=>{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"]}}},Qh=async e=>new Promise(t=>{let{command:n,args:r}=jN();try{let o=UN(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 Ko=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await Qh(e);return c(n)?n:d(`Copied ${t} to clipboard`,null)},ey=async e=>{let{breadCrumb:t,selectedNode:n}=h(),r=no({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case Te.REF:return Ko(nt(o.id),"ref");case Te.TITLE:return Ko(o.title,"title");case Te.DESCRIPTION:return r?Ko(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 Ko(s.join(", "),"tags")}case Te.ASSIGNEES:{if(!r)return a("No issue in scope");let s=tn(r).map(({name:i})=>i);return Ko(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var ty=async()=>{K(""),A({mode:y.DEFAULT});let e=xe();if(c(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");A({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await mi();return c(t)?(A({syncStatus:{msg:t.message,status:"failed"}}),t):(A({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as ny}from"ulid";var ry=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=j(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let l=h().nodes[i];if(!l||!j(l))return a("Unable to resolve comment issue");let u=l.log?.filter(qg).find(p=>p.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):Z([{id:ny(),action:"delete.issue.comment",payload:{id:s,issue:i},...ne(e.value)}],o.value):a("Unable to resolve comment")}return Z([{id:ny(),action:"delete.node",payload:{id:r.id},...ne(e.value)}],o.value)};import{ulid as HN}from"ulid";var oy=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(!j(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=ni(o.id,r.id,{at:"end"},e.value,i);if(c(l))return l;let u=Z([{id:HN(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...ne(e.value)}],i);return c(u)?u:d("Issue closed",null)};import{ulid as WN}from"ulid";var sy=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 iy=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):yt(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(!j(s))return a("Target node is not issue");let l=sy(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=ni(u.id,s.id,{at:"end"},e.value,m);if(c(f))return f;let g=Z([{id:WN(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...ne(e.value)}],m);return c(g)?g:d("Issue reopened",null)};import{ulid as GN}from"ulid";var ay=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=ei();if(!o)return a("Provide a title");let s=await le();return c(s)?s:Z([{id:GN(),action:"edit.title",payload:{id:r.id,name:o},...ne(e.value)}],s.value)};import{ulid as zN}from"ulid";var cy=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=yt(s.id,"TICKET");if(c(i))return a("Unable to untag issue in this context");let l=i.value;if(!j(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:Z([{id:zN(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...ne(e.value)}],p.value)};import{ulid as Dl}from"ulid";var ly=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=yt(o.id,"TICKET");if(c(s))return a("Unable to tag issue in this context");let i=s.value;if(!j(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??Dl();return(i.props.tags??[]).includes(p)?a("Already tagged with that tag"):Z([...u?[]:[{id:Dl(),action:"create.tag",payload:{id:p,name:r},...ne(e.value)}],{id:Dl(),action:"add.issue.tag",payload:{id:i.id,tag:p},...ne(e.value)}],l.value)};import{ulid as Fl}from"ulid";var dy=({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)}))},C2=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=et(t),s=n.get(o),i=s?r[s]:void 0;return s?{...Xi(s,i?.name),resolved:!0}:{...Xi(o||e,e),resolved:!1}};var ki=e=>{let{eventLog:t=[],contributors:n}=h();return dy({events:t,registry:n,logFileNames:_m(e)})};var uy=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=yt(u.id,"TICKET");if(c(p))return a("Unable to assign issue in this context");let m=p.value;if(!j(m))return a("Target node is not issue");let f=await le();if(c(f))return f;let g=ki(f.value),b=!o&&s.toLowerCase()==="me",N,E;if(b)N=e.value.userId,E=g.find(I=>I.id===N)?.name??e.value.userName;else{let I=g.filter(k=>k.name===s);if(I.length>1)return a(`"${s}" matches ${I.length} contributors (${I.map(k=>k.id).join(", ")}). Assign from the GUI to choose by id.`);let M=I[0];if(!M&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);N=M?.id??Fl(),E=M?.name??s}if((m.props.assignees??[]).includes(N))return a("Assignee already assigned");let v=!!h().contributors[N];return Z([...v?[]:[{id:Fl(),action:"create.contributor",payload:{id:N,name:E},...ne(e.value)}],{id:Fl(),action:"add.issue.assignee",payload:{id:m.id,assignee:N},...ne(e.value)}],f.value)};import{ulid as VN}from"ulid";var my=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=yt(o.id,"TICKET");if(c(s))return a("Unable to unassign in this context");let i=s.value;if(!j(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):ki(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?Z([{id:VN(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...ne(e.value)}],p.value):a(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)};import{ulid as py}from"ulid";var qN=e=>{let t=e.trim(),n=pn(),r=n?sf(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=Ri();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=af(o.rows,Math.max(0,h().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=cf(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:nf({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}},fy=async e=>{let t=qN(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=Qe([...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):yt(u.id,"TICKET");if(c(p))return a("Unable to comment on issue in this context");let m=p.value;if(!j(m))return a("Target node is not issue");let f=await le();if(c(f))return f;let g=await Z([{id:py(),action:"add.issue.comment",payload:{id:py(),issue:m.id,author:o.value.userId,md:n},...ne(o.value)}],f.value);return r&&!c(g)&&Gn(null),g};import{ulid as eI}from"ulid";var gy=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",KN=e=>{let t=zu();return c(t)?gy({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:gy(t.value)},hy=()=>{let e=Pt();return c(e)?a(e.message):d("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:os(e.value.autoSyncDebounceMs),blockedReason:KN(e.value)})},Li=e=>{let t=e.intervalMs===void 0?void 0:er(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=hy();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=hy();return c(o)?d("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o};var yy=()=>{let e=Y().commandMeta.inputString,t=er(e);if(t===null)return a(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=Li({intervalMs:t});return c(n)?n:d(`Auto sync interval set to ${t}ms`,null)};import YN from"zod";var by=()=>{let e=YN.coerce.number().int().min(ar).max(cr).safeParse(Y().commandMeta.inputString);if(!e.success)return a(`A connected repo's clone cap must be ${ar}-${cr} MB (default ${Da})`);let t=qe({repoCloneMaxMb:e.data});return c(t)?t:d(`Connected repo clone cap set to ${e.data} MB`,null)};var vy=()=>{let e=Y().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Mu(e),n=Li({enabled:t===!0});return c(n)?n:d(`Auto sync set to "${e}"`,null)};import{ulid as ZN}from"ulid";var _l=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),xy="",Ey=new Map,XN=15e3;var JN=async(e,t)=>{let n=`${e} ${t??""}`,r=Ey.get(n);if(r&&Date.now()-r.at<Us(XN))return d("Cached author scan",r.authors);let o=await Ce({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${xy}%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(`
|
|
109
|
+
`)){let l=i.lastIndexOf(xy);if(l===-1)continue;let u=i.slice(0,l),p=et(i.slice(l+1));if(!Jn(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 Ey.set(n,{at:Date.now(),authors:s}),d("Scanned repository authors",s)},Ry=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await JN(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=>_l(u??"")));return d("Found candidates",[...s.entries()].map(([u,p])=>({email:u,names:[...p.names],commits:p.commits,looksLikeYours:[...p.names].some(m=>_l(m).some(f=>l.has(f)))||_l(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)))},Sy=e=>e.filter(t=>t.claimedBy.length===0);var Cy=()=>{let e=Sa();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))},Ny=async()=>{let e=Y().commandMeta.inputString.trim();if(e==="none"){let R=Cy();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=xe();if(c(o))return a("Board is not loaded");let s=Ee(process.cwd());if(c(s))return a(s.message);let i=Rt(s.value),l=await Ry({repoRoot:s.value,stateBranch:c(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(c(l))return l;let p=Sy(l.value);if(Iu(p.map(R=>R.email)),p.length===0){if(!Au()){let R=Cy();if(c(R))return R}return d("No unclaimed addresses in this history.",null)}if(!e)return A({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===et(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 b=be({repoRoot:s.value});if(c(b))return b;let N=f.map(R=>({id:ZN(),action:"link.contributor.email",payload:{contributor:t,email:R.email},userId:t})),E=Z(N,b.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 QN}from"ulid";var Iy=()=>{let e=Y().commandMeta.inputString.trim(),{userId:t}=ee();if(!t)return a("Set a username first with :config username");let n=xe();if(c(n))return a("Board is not loaded");let r=Zn(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===et(e));if(!o)return a(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=Ee(process.cwd());if(c(s))return s;let i=be({repoRoot:s.value});if(c(i))return i;let l=Z([{id:QN(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return c(l)?a(l.message):d(`Unclaimed ${o}`,null)};var wy=()=>{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 Ay=e=>{let t=e.inputString.trim();switch(e.modifier){case J.USERNAME:{if(process.env[Fi])return a(`Cannot change the configured user while ${Fi} 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||eI();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 Ny();case J.EMAILS_UNCLAIM:return Iy();case J.AUTOSYNC:return vy();case J.LOG_LEVEL:return wy();case J.SYNC_DEBOUNCE_MS:return yy();case J.ATTACHMENT_MAX_KB:return Ju();case J.REPO_CLONE_MAX_MB:return by();case J.REPO_CONNECT:return bf();case J.REPO_DISCONNECT:return vf();default:return a("Unknown config command")}};var $l=()=>{let e=ku(),t=h().mode;if(!(t!==y.COMMAND_LINE&&t!==y.DEFAULT)){if(!e){A({mode:y.DEFAULT});return}A({mode:y.COMMAND_LINE}),K(e)}};var Ty=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:Dh},{intent:G.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:ry,onSuccess:()=>A({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(x.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return he(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode: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 gn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),A({mode:y.HELP}),d("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:oy,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:iy,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:Th,onSuccess:$l},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:y.COMMAND_LINE,action:Vh,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:_h,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:ay,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:cy,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:ly,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:uy,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:my,onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>fy(t),onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:ty},{intent:G.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:Jh},{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 Ch();return c(e)?e:(A({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)=>Ih(t),onSuccess:()=>A({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)=>ey(t),onSuccess:()=>A({mode:y.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>Ay(t),onSuccess:$l}];var tI=e=>{let t=e.value;return t&&typeof t=="object"&&typeof t.followUp=="string"?t.followUp:null},nI=new Set(["peek","replay","filter","view-help","yank"]),bt=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=Og(n);$f();let{readOnly:l}=h();if(l&&!nI.has(i))return Mo({status:Yn.Fail,message:"Command not available in readonly state",value:null});let u=Ty.filter(g=>e||g.systemOnly!==!0).find(g=>g.intent===i);if(!u)return Mo({status:Yn.Fail,message:"Command not found",value:null});let p;try{p=await u.action(u,{command:n,inputString:s,modifier:o})}catch(g){return Mo({status:Yn.Fail,message:g instanceof Error?g.message:"Command failed",value:null})}if(c(p))return Mo(p);let m=!e;if(Bf({addToHistory:m,line:t}),m){let g=jh({commands:Y().commandHistory});c(g)&&logger.info(g.message)}let f=tI(p);return f!==null?(K(f),p):(u.onSuccess?.(),ee().autoSync&&Pg(),p)};var Pi=[{intent:S.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(A({mode:y.COMMAND_LINE}),K("move cancel"),bt({isForceExecutedBySystem:!0}))},{intent:S.InitMove,mode:y.DEFAULT,description:"[m] move",action:()=>(A({mode:y.COMMAND_LINE}),K("move start"),bt({isForceExecutedBySystem:!0}))},{intent:S.ConfirmMove,mode:y.MOVE,description:"[m] confirm move",action:()=>(A({mode:y.COMMAND_LINE}),K("move confirm"),bt({isForceExecutedBySystem:!0}))}],Oi=[{intent:S.MovePreviousItem,mode:y.MOVE,action:()=>Tt()?(A({mode:y.COMMAND_LINE}),K("move previous"),bt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveNextItem,mode:y.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>Tt()?(A({mode:y.COMMAND_LINE}),K("move next"),bt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MovePreviousItemJump,mode:y.MOVE,action:()=>Tt()?(A({mode:y.COMMAND_LINE}),K("move jump-previous"),bt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveNextItemJump,mode:y.MOVE,action:()=>Tt()?(A({mode:y.COMMAND_LINE}),K("move jump-next"),bt({isForceExecutedBySystem:!0})):a("No pending move")}],My=[{intent:S.MoveToNextContainer,mode:y.MOVE,action:()=>Tt()?(A({mode:y.COMMAND_LINE}),K("move to-next"),bt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveToPreviousContainer,mode:y.MOVE,action:()=>Tt()?(A({mode:y.COMMAND_LINE}),K("move to-previous"),bt({isForceExecutedBySystem:!0})):a("No pending move")}];var ky={[te.WORKSPACE]:[...Pi,...Oi],[te.BOARD]:[...Pi,...Oi],[te.SWIMLANE]:[...Pi,...Oi,...My],[te.TICKET]:[],[te.FIELD]:[],[te.FIELD_LIST]:[],[te.TEXT]:[],[te.COMMENT]:[]};import oI from"node:fs";import sI from"node:path";import{spawn as rI}from"node:child_process";function Ly(e){let t=process.platform,o=rI(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 Py=e=>{let t=Ee(process.cwd());if(c(t))return a("Unable to resolve project root");let n=be({repoRoot:t.value});if(c(n))return a(n.message);let r=Oa(e.hash,e.ext),o=sI.join(Yr(n.value),r);return oI.existsSync(o)?(Ly(o),d(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var Oy=()=>{K("");let{pendingNavTarget:e}=Pr();A({mode:y.DEFAULT}),e&&U.navigate(e),gn({pendingNavTarget:void 0})},Dy=[{intent:S.ExitCommandLine,mode:y.HELP,action:()=>(Oy(),d("Exiting help",null))},{intent:S.Exit,mode:y.HELP,action:()=>(Oy(),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 Fy=()=>{K(""),A({mode:y.DEFAULT})},_y=[{intent:S.Confirm,mode:y.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=sr();return e?(A({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:()=>(Fy(),d("Closed identity",null))},{intent:S.Exit,mode:y.IDENTITY,description:"[esc] close",action:()=>(Fy(),d("Closed identity",null))}];var iI=e=>{A({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=Pr();t&&U.navigate(t),gn({pendingNavTarget:void 0}),K(`${e} `)},$y=()=>{K("");let{pendingNavTarget:e}=Pr();e&&U.navigate(e),gn({pendingNavTarget:void 0}),A({mode:y.DEFAULT})},By=[{intent:S.InitCommandPalette,mode:y.DEFAULT,description:"[?] command palette",action:()=>{K("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return gn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),A({mode:y.PALETTE}),d("Opening command palette",null)}},{intent:S.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=h();if(!e||!pd(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?(iI(t),d("Selected command",t)):d("No command selected",null)}},{intent:S.ExitCommandLine,mode:y.PALETTE,action:()=>($y(),d("Exiting palette",null))},{intent:S.Exit,mode:y.PALETTE,action:()=>($y(),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 Uy=()=>{let e=pn();if(!e)return d("Nothing to comment on here",null);let t=Ri();if(!t||t.sha!==e)return a("The diff is still loading");let{selectedIndex:n}=h(),r=Math.max(0,n),o=Wc(t.rows,Rl(e)??r,r);return o.ok?(A({mode:y.COMMAND_LINE}),K(`${x.COMMENT} ${of(o.value.start,o.value.end)} `),d("Commenting on a diff line",null)):a(o.reason)},jy=[{intent:S.InitCommandLine,mode:y.DEFAULT,description:"[:] write command",action:()=>(A({mode:y.COMMAND_LINE}),K(""),d("Entering command line mode",null))},...Dy,..._y,...By,{intent:S.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(A({mode:y.COMMAND_LINE}),K(`${x.NEW} `),d("Adding new item",null))},{intent:S.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(A({mode:y.COMMAND_LINE}),K(`${x.DELETE} `),d("Deleting item",null))},{intent:S.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=h();if(!ye(e?.id??"")?.length){let r=e?C.getAttachment(e.id):void 0;if(r)return Py(r);if(pn())return Uy();if(e?.title===me.DESCRIPTION)return A({mode:y.COMMAND_LINE}),K(`${x.EDIT} description `),d("Propose command",!0);if(e?.title===me.ASSIGNEES)return A({mode:y.COMMAND_LINE}),K(`${x.ASSIGN} `),d("Propose command",!0);if(e?.title===me.TAGS)return A({mode:y.COMMAND_LINE}),K(`${x.TAG} `),d("Propose command",!0);if(t.title===me.DESCRIPTION&&e?.context==="TEXT")return A({mode:y.COMMAND_LINE}),K(`${x.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?Xc({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=Rl(e);return Gn(n===t?null:{sha:e,row:Math.max(0,t)}),d("Marked diff line",null)}},{intent:S.CommentOnDiffLine,mode:y.DEFAULT,action:()=>pn()?Uy():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(x.YANK).includes(t)?t:Te.REF;return A({mode:y.COMMAND_LINE}),K(`${x.YANK} ${r}`),d("Propose command",!0)}},{intent:S.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(A({mode:y.COMMAND_LINE}),K(`${x.EDIT} title ${h().selectedNode?.title}`),d("Exiting context",null))},{intent:S.EditDescription,mode:y.DEFAULT,description:"[e] edit desc",action:()=>(A({mode:y.COMMAND_LINE}),K(`${x.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 aI=500,cI=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Hy=e=>{let t=cI(e);t&&Qs(n=>(n+t).slice(0,aI))};var lI=[y.COMMAND_LINE,y.PALETTE],dI=e=>e==="edit title "?h().selectedNode?.title??"":"",uI=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>(nl(-1),d("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>(nl(1),d("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(rl("left"),d("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(rl("right"),d("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(Qs((t,{remainder:n})=>{let r=n?t+n:t;return r+dI(r)}),d("Auto-completing command",null))},{intent:S.CaptureInput,mode:e,action:(t,{sequence:n})=>(Hy(n??""),d("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(Ff(),d("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(_f(),d("Erasing input word",null))}],Wy=[{intent:S.Confirm,mode:y.COMMAND_LINE,action:()=>(bt(),d("Executing command",null))},{intent:S.ViewHelp,mode:y.DEFAULT,action:()=>(A({mode:y.HELP}),d("Viewing help",null))},...lI.flatMap(uI),{intent:S.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(jf(),A({mode:y.DEFAULT}),d("Exiting command line",null))},{intent:S.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Hf(),d("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Wf(),d("Getting next command from history",null))}];var mI=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Gy=({keys:e})=>e.length===1?0:1,zy=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(mI).filter(r=>r!==null).sort((r,o)=>Gy(r)-Gy(o))};function Vy(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 qy=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 Ze,Bl,Ul=new Set,jl=()=>{for(let e of Ul)e()},fI=e=>(Ul.add(e),()=>Ul.delete(e));function Hl(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=Vy(t,o,r);if(c(u))return logger.error(u.message),u;let p=u.value,{context:m}=l,f=[...jy,...ky[m]??[],...Wy],g=zy(f,n),b=qy(f),N=gI(o,s),E=N[t]?.[e.selectedIndex]??null;return d("Derived successfully",{...e,contextNode:l,breadCrumb:p,availableHints:g,availableActions:f,actionIndex:b,selectedNode:E,renderedChildrenIndex:N})}var h=()=>{if(!Ze)throw new Error("State not initialized. Call initWorkspaceState() first.");return Ze},xe=()=>Ze?d("Retrieved state",Ze):a("State not initialized. Call initWorkspaceState() first.");Su(e=>Ze?Zn(Ze.emailLinks,e):[]);function po(e){Bl=e;let t=Ee(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:$i(),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=Hl(r);return c(o)?o:(Ze=o.value,jl(),d("State initialized",null))}var qn=!1,Yo=null;function he(e){let t=h(),n=e(t);if(qn)return n.nodes!==t.nodes&&(yn=null),Yo=n,Ze={...t,...n},d("State updated",null);let r=Hl(n);return c(r)?a(r.message??"Unable to update state"):(Ze=r.value,jl(),d("State updated",null))}function ks(e){if(qn)return d("Joined batch",e());qn=!0,Yo=null,yn=new Set;let t=()=>{let n=Yo;if(qn=!1,Yo=null,n===null)return null;let r=Hl(n);return c(r)?a(r.message??"Unable to update state"):(Ze=r.value,jl(),d("State updated",null))};try{let n=e(),r=t();return r&&c(r)?a(r.message):d("State updated",n)}finally{qn&&t()}}var tg=()=>qn,A=e=>he(t=>({...t,...e}));function Kn(e,t,n){if(!qn)return he(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=h(),o=r[e]??{};if(e==="nodes"){let i=o[t],l=n;i?.parentNodeId&&yn?.add(i.parentNodeId),l.parentNodeId&&yn?.add(l.parentNodeId)}o[t]=n;let s={...r,[e]:o};return Yo=s,Ze={...r,...s},d("State updated",null)}var Le=()=>pI(fI,h,h),yn=null,Ky=null,gI=(e,t)=>{let n=Ze?.renderedChildrenIndex,r=n!==void 0&&yn!==null&&e===Ky&&t.length===0&&Ze?.filters.length===0,o;if(r){o={...n};let s=Jf(e,yn);for(let i of yn){let l=s[i];l?o[i]=l:delete o[i]}}else o=Xf(e,t);return Ky=e,yn=new Set,o},ae=e=>h()?.renderedChildrenIndex[e]??[],hn=()=>Bl?po(Bl):a("Cannot reset state: no initial workspace found"),ut=()=>Ze!==void 0;var yt=(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}`)},hI=(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},bn=(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=he(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&&he(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(!j(t))return a("Can only comment on issues");let n=Kn("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(!j(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Kn("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=Kn("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(!j(t))return a("Can only attach to issues");let n=he(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=he(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=bn(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=bn(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 ye(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=bn(o,"move");if(i)return i;if(hI(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=bn(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 ye(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?(A({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:dd,tombstoned:!0},r=he(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=he(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=he(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:et(e),contributor:t,authorId:n},o=Ji(r.email,t),s=h().emailLinks[o];if(s&&!s.tombstoned)return d("Email already linked",s);let i=he(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=Ji(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(!md(n,o))return a("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=he(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=he(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=bn(r,"edit");if(o)return o;if(!j(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=bn(r,"edit");if(o)return o;if(!j(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=bn(r,"edit");if(o)return o;if(!j(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=bn(r,"edit");if(o)return o;if(!j(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=he(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=he(s=>({...s,tags:{...s.tags,[e]:r}}));return c(o)?a("Unable to restore tag"):d("Restored tag",r)},createTag(e){let t=he(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?a("Could not create tag"):d("Tag created",e)},createNode(e){let t=Kn("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=Kn("nodes",e,n);return c(r)?a(r.message):d("Locked node",n)},updateNode(e){let t=Kn("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 ye(e)}};var yI=(e,t)=>e+" ".repeat(Math.max(0,t-Yy(e))),bI=(e,t)=>" ".repeat(Math.max(0,t-Yy(e)))+e,Xy=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`),vI=(e,t)=>t?e<t?"up":e>t?"down":null:null,xI=(e,t)=>{let n=C.getNode(e.payload.parent),r=n?vn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=vI(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Jy=e=>`${Math.max(1,Math.round(e/1024))} KB`,Zy=e=>C.getAttachment(e)?.name??"",EI=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?vn.bgHex(Be(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?vn.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?vn.hex(Be(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?vn.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 Hi(e);case"add.issue.attachment":return`"${e.payload.name}" ${vn.dim(`(${Jy(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Zy(e.payload.id);return t?`"${t}"`:""}default:return""}},RI=e=>{let t=dn(Sn(e));return vn.gray(bI(t,8))},SI=12,CI=e=>yI(`${e}`,SI),NI=e=>{let t=xe();return c(t)?e:Yi(e,t.value.contributors[e]?.name)},II=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 Hi(e);case"move.node":{let t=C.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Jy(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Zy(e.payload.id);return t?`"${t}"`:""}default:return""}},Xh=e=>[Xy(e.action),II(e)].filter(Boolean).join(" "),Qy=(e,t)=>{let n=RI(e.id),r=CI(NI(e.userId)),o=vn.dim("\u203A"),s=e.action==="move.node"?xI(e,t):[Xy(e.action),EI(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var wI=e=>pe(e,"comments"),AI=e=>pe(e,"description"),TI=e=>pe(e,"assignees"),MI=e=>pe(e,"tags"),kI=e=>pe(e,"history"),LI=e=>pe(e,"diff"),PI=e=>pe(e,"attachments"),Xo=({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({...Ie.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)},eb=({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({...Ie.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(!$r(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)},Di=null,OI=()=>{if(Di)return d("Virtual field ranks",Di);let e=st(wt/4n),t=st(wt/2n),n=st(wt*3n/4n),r=st(wt*7n/8n),o=st(wt*15n/16n),s=st(wt*13n/16n),i=st(wt*27n/32n);return c(e)?e:c(t)?t:c(n)?n:c(r)?r:c(o)?o:c(s)?s:c(i)?i:(Di={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",Di))},tc=e=>{let t=OI();if(c(t))return t;let n=t.value,r=Xo({id:AI(e.id),name:me.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(c(r))return r;let o=eb({id:TI(e.id),name:me.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(c(o))return o;let s=eb({id:MI(e.id),name:me.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(c(s))return s;let i=Xo({id:wI(e.id),name:me.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(c(i))return i;let l=Xo({id:PI(e.id),name:me.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(c(l))return l;let u=Xo({id:kI(e.id),name:me.HISTORY,parentNodeId:e.id,rank:n.log,value:DI(e),readonly:!0,childRenderAxis:"vertical"});if(c(u))return u;let p=Xo({id:LI(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)},DI=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=>Qy(r,n.get(r.action)??[])).join(`
|
|
110
|
+
`)},tb=!0,y4=e=>{tb=e},nc=()=>tb,b4=()=>{let{nodes:e}=h();for(let t of Object.values(e)){if(!j(t))continue;let n=tc(t);if(c(n))return n}return d("Virtual nodes materialized",void 0)};export{os as a,H as b,Rt as c,_ as d,Ce as e,qd as f,be as g,St as h,Kr as i,rv as j,Ee as k,Pt as l,qe as m,zu as n,ee as o,DA as p,at as q,w as r,Be as s,ad as t,JI as u,cd as v,ZI as w,ib as x,Xl as y,xn as z,Zt as A,gb as B,Hi as C,Wi as D,Sn as E,Zo as F,rd as G,Qo as H,Yi as I,Xi as J,dd as K,Qe as L,et as M,Jn as N,Ji as O,sw as P,Zn as Q,iw as R,md as S,j as T,pd as U,Qn as V,Br as W,y as X,Cn as Y,Nn as Z,Ut as _,pw as $,bu as aa,ps as ba,Ru as ca,Iu as da,to as ea,ct as fa,en as ga,tn as ha,x as ia,Me as ja,Uv as ka,Mn as la,Oa as ma,HT as na,WT as oa,Ct as pa,Nt as qa,em as ra,Es as sa,Dn as ta,Fn as ua,ne as va,ur as wa,nt as xa,Za as ya,Ie as za,sn as Aa,go as Ba,ML as Ca,_m as Da,Ls as Ea,$m as Fa,Bm as Ga,Z as Ha,rc as Ia,Ps as Ja,rt as Ka,yP as La,_n as Ma,uc as Na,uE as Oa,hc as Pa,Ec as Qa,Ic as Ra,zs as Sa,Ac as Ta,jE as Ua,jp as Va,Pc as Wa,zE as Xa,XE as Ya,QE as Za,sR as _a,Xc as $a,xf as ab,Ef as bb,Rf as cb,ln as db,se as eb,xr as fb,tS as gb,WD as hb,S as ib,JD as jb,ye as kb,ni as lb,ri as mb,U as nb,Oo as ob,XF as pb,ug as qb,ai as rb,Do as sb,CS as tb,jn as ub,mg as vb,ll as wb,Rr as xb,Tg as yb,ul as zb,Pg as Ab,Og as Bb,pt as Cb,ft as Db,Cr as Eb,gi as Fb,DB as Gb,Rh as Hb,Pr as Ib,k1 as Jb,Ah as Kb,Fh as Lb,VW as Mb,Wh as Nb,Gh as Ob,qW as Pb,sy as Qb,dy as Rb,C2 as Sb,gy as Tb,hy as Ub,Li as Vb,Ry as Wb,Sy as Xb,Ty as Yb,mI as Zb,h as _b,xe as $b,A as ac,Le as bc,ae as cc,hn as dc,ut as ec,yt as fc,hI as gc,C as hc,Xy as ic,Xh as jc,Xo as kc,eb as lc,tc as mc,y4 as nc,nc as oc,b4 as pc};
|