task-pipeliner 0.3.14 → 0.3.15

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/README.ko.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > 조건 기반 실행과 아름다운 CLI 출력을 제공하는 강력한 워크플로우 오케스트레이션 도구
4
4
 
5
- **버전:** 0.3.14
5
+ **버전:** 0.3.15
6
6
 
7
7
  ![fox2](https://github.com/user-attachments/assets/fdf8d786-6a91-4d2d-9dc1-72be6f3ccd98)
8
8
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > A powerful workflow orchestration tool with condition-based execution and beautiful CLI output
4
4
 
5
- **Version:** 0.3.14
5
+ **Version:** 0.3.15
6
6
 
7
7
  ![fox2](https://github.com/user-attachments/assets/fdf8d786-6a91-4d2d-9dc1-72be6f3ccd98)
8
8
 
package/dist/index.cjs CHANGED
@@ -1,35 +1,37 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Rr=Object.create;var ct=Object.defineProperty;var Er=Object.getOwnPropertyDescriptor;var Pr=Object.getOwnPropertyNames;var Cr=Object.getPrototypeOf,Dr=Object.prototype.hasOwnProperty;var Tr=(o,e)=>()=>(o&&(e=o(o=0)),e);var Ir=(o,e)=>{for(var t in e)ct(o,t,{get:e[t],enumerable:!0})},Mr=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pr(e))!Dr.call(o,s)&&s!==t&&ct(o,s,{get:()=>e[s],enumerable:!(r=Er(e,s))||r.enumerable});return o};var x=(o,e,t)=>(t=o!=null?Rr(Cr(o)):{},Mr(e||!o||!o.__esModule?ct(t,"default",{value:o,enumerable:!0}):t,o));var _t={};Ir(_t,{DAEMON_DIR:()=>he,getDaemonErrorLogPath:()=>dt,getDaemonPid:()=>ut,getDaemonStartTime:()=>Ht,getDaemonStatus:()=>N,isDaemonRunning:()=>Y,readDaemonErrorLog:()=>mt,removeDaemonPid:()=>Ce,saveDaemonPid:()=>jr,writeDaemonError:()=>pt});function Nr(o){try{return process.kill(o,0),!0}catch{return!1}}async function ut(){try{if(!(0,ce.existsSync)(z))return null;let o=await(0,M.readFile)(z,"utf-8"),e=parseInt(o.trim(),10);return isNaN(e)?(await(0,M.unlink)(z),null):Nr(e)?e:(await(0,M.unlink)(z),null)}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return null;throw o}}async function Y(){return await ut()!==null}async function jr(){await(0,M.mkdir)(he,{recursive:!0}),await(0,M.writeFile)(z,process.pid.toString(),"utf-8");let o=new Date().toISOString();await(0,M.writeFile)(Ee,o,"utf-8")}async function pt(o){try{await(0,M.mkdir)(he,{recursive:!0});let e=`${new Date().toISOString()} ${o.message}
2
+ "use strict";var Rr=Object.create;var ct=Object.defineProperty;var Er=Object.getOwnPropertyDescriptor;var Pr=Object.getOwnPropertyNames;var Cr=Object.getPrototypeOf,Dr=Object.prototype.hasOwnProperty;var Tr=(o,e)=>()=>(o&&(e=o(o=0)),e);var Ir=(o,e)=>{for(var t in e)ct(o,t,{get:e[t],enumerable:!0})},Mr=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pr(e))!Dr.call(o,s)&&s!==t&&ct(o,s,{get:()=>e[s],enumerable:!(r=Er(e,s))||r.enumerable});return o};var x=(o,e,t)=>(t=o!=null?Rr(Cr(o)):{},Mr(e||!o||!o.__esModule?ct(t,"default",{value:o,enumerable:!0}):t,o));var _t={};Ir(_t,{DAEMON_DIR:()=>he,getDaemonErrorLogPath:()=>dt,getDaemonPid:()=>ut,getDaemonStartTime:()=>Ht,getDaemonStatus:()=>j,isDaemonRunning:()=>Y,readDaemonErrorLog:()=>mt,removeDaemonPid:()=>Ce,saveDaemonPid:()=>jr,writeDaemonError:()=>pt});function Nr(o){try{return process.kill(o,0),!0}catch{return!1}}async function ut(){try{if(!(0,ce.existsSync)(z))return null;let o=await(0,N.readFile)(z,"utf-8"),e=parseInt(o.trim(),10);return isNaN(e)?(await(0,N.unlink)(z),null):Nr(e)?e:(await(0,N.unlink)(z),null)}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return null;throw o}}async function Y(){return await ut()!==null}async function jr(){await(0,N.mkdir)(he,{recursive:!0}),await(0,N.writeFile)(z,process.pid.toString(),"utf-8");let o=new Date().toISOString();await(0,N.writeFile)(Ee,o,"utf-8")}async function pt(o){try{await(0,N.mkdir)(he,{recursive:!0});let e=`${new Date().toISOString()} ${o.message}
3
3
  ${o.stack??""}
4
- `;await(0,M.writeFile)(We,e,"utf-8")}catch{}}async function Ce(){try{(0,ce.existsSync)(z)&&await(0,M.unlink)(z),(0,ce.existsSync)(Ee)&&await(0,M.unlink)(Ee)}catch{}}async function Ht(){try{if((0,ce.existsSync)(Ee)){let e=(await(0,M.readFile)(Ee,"utf-8")).trim();if(e)return e}if((0,ce.existsSync)(z)){let o=await(0,M.stat)(z);return new Date(o.mtime).toISOString()}return null}catch{return null}}function dt(){return We}async function mt(){try{return(0,ce.existsSync)(We)&&(await(0,M.readFile)(We,"utf-8")).trim()||null}catch{return null}}async function N(){let o=await ut(),e=o?await Ht():null;return{running:o!==null,pid:o,startTime:e}}var ce,M,Vt,Pe,he,z,Ee,We,ge=Tr(()=>{"use strict";ce=require("fs"),M=require("fs/promises"),Vt=require("os"),Pe=require("path"),he=(0,Pe.join)((0,Vt.homedir)(),".pipeliner","daemon"),z=(0,Pe.join)(he,"scheduler.pid"),Ee=(0,Pe.join)(he,"scheduler.started");We=(0,Pe.join)(he,"error.log")});var ir=require("child_process"),te=require("fs"),oe=require("fs/promises"),ar=require("os"),G=require("path"),lr=require("util"),w=x(require("chalk"),1),cr=require("commander");ge();var K=require("path"),uo=x(require("chalk"),1);var zt=x(require("readline"),1),F=x(require("chalk"),1),ft=x(require("inquirer"),1),Ut=15,B=class{searchable;constructor(e=!1){this.searchable=e}async prompt(e,t){if(this.searchable)return this.promptWithSearch(e,t);let{choice:r}=await ft.default.prompt([{type:"list",name:"choice",message:F.default.cyan(e),choices:t.map(i=>({name:i.label,value:i.id})),pageSize:Ut}]),s=t.find(i=>i.id===r);if(!s)throw new Error(`Invalid choice: ${r}`);return s}async promptWithSearch(e,t){return new Promise(r=>{let s="",i=0,n=[...t],a=0,l=zt.createInterface({input:process.stdin,output:process.stdout,terminal:!1});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdout.write("\x1B[?25l");let c=()=>{let p=Ut,h=0,g=n.length;if(n.length>p){let S=Math.floor(p/2);h=Math.max(0,i-S),g=Math.min(n.length,h+p),g===n.length&&(h=Math.max(0,g-p))}let k=3+(n.length===0?1:(h>0?1:0)+(g-h)+(g<n.length?1:0));a>0&&process.stdout.write(`\x1B[${a}A\x1B[0J`),console.log(F.default.cyan(`? ${e}`));let y=s?F.default.gray(` Filter: ${s}`)+F.default.gray(` (${n.length}/${t.length})`):F.default.gray(" Type to filter, \u2191\u2193 to navigate, Enter to select");if(console.log(y),console.log(),n.length===0)console.log(F.default.yellow(" No matches found"));else{h>0&&console.log(F.default.gray(` \u2191 ${h} more above`));for(let S=h;S<g;S++){let T=n[S];console.log(S===i?F.default.cyan(`\u276F ${T.label}`):F.default.white(` ${T.label}`))}g<n.length&&console.log(F.default.gray(` \u2193 ${n.length-g} more below`))}a=k},d=()=>{let p=s.toLowerCase();n=p?t.filter(h=>h.label.toLowerCase().includes(p)):[...t],i>=n.length&&(i=Math.max(0,n.length-1))},f=p=>{let h=p.toString();if(h===""&&(m(),process.exit(0)),h==="\r"||h===`
5
- `){n.length>0&&(m(),r(n[i]));return}if(h==="\x1B"&&p.length===1){s&&(s="",d(),c());return}if(h==="\x1B[A"){n.length>0&&(i=i>0?i-1:n.length-1,c());return}if(h==="\x1B[B"){n.length>0&&(i=i<n.length-1?i+1:0,c());return}if(h==="\x7F"||h==="\b"){s.length>0&&(s=s.slice(0,-1),d(),c());return}h.length===1&&h>=" "&&h<="~"&&(s+=h,d(),c())},m=()=>{process.stdin.removeListener("data",f),process.stdin.isTTY&&process.stdin.setRawMode(!1),l.close(),process.stdout.write("\x1B[?25h")};c(),process.stdin.on("data",f)})}},Ve=class{async prompt(e,t){let{value:r}=await ft.default.prompt([{type:"input",name:"value",message:F.default.cyan(e),default:t}]);return r}};var Zt=x(require("boxen"),1),C=x(require("chalk"),1),ht=x(require("string-width"),1);function He(o){if(o.records.length===0)return"";let e=Ar(o.records),t=0;for(let m of e)m.length>1?t+=Math.max(...m.map(p=>p.duration)):t+=m[0].duration;let r=(t/1e3).toFixed(1),s=o.records.reduce((m,p)=>p.duration>m.duration?p:m),i=o.records.indexOf(s)+1,n=(s.duration/1e3).toFixed(1),a=[],l=0;for(let m=0;m<e.length;m++){let p=e[m];if(p.some(b=>b.context.branchIndex!==void 0&&b.context.stepIndex>=1e3)&&p.length>=1&&p.length>0){let b=p,k=b.map(S=>({name:Yt(S),startTime:l,duration:S.duration})),y=Math.max(...b.map(S=>S.duration));a.push({stepNumber:m+1,name:"Parallel",startTime:l,duration:y,isParallel:!0,parallelBranches:k}),l+=y}else{let b=p[0],y=Yt(b)||"Unknown";a.push({stepNumber:m+1,name:y,startTime:l,duration:b.duration,isParallel:!1}),l+=b.duration}}let c=Br(a,t,s.duration),f=`${`${C.default.bold("Workflow Summary")}
4
+ `;await(0,N.writeFile)(We,e,"utf-8")}catch{}}async function Ce(){try{(0,ce.existsSync)(z)&&await(0,N.unlink)(z),(0,ce.existsSync)(Ee)&&await(0,N.unlink)(Ee)}catch{}}async function Ht(){try{if((0,ce.existsSync)(Ee)){let e=(await(0,N.readFile)(Ee,"utf-8")).trim();if(e)return e}if((0,ce.existsSync)(z)){let o=await(0,N.stat)(z);return new Date(o.mtime).toISOString()}return null}catch{return null}}function dt(){return We}async function mt(){try{return(0,ce.existsSync)(We)&&(await(0,N.readFile)(We,"utf-8")).trim()||null}catch{return null}}async function j(){let o=await ut(),e=o?await Ht():null;return{running:o!==null,pid:o,startTime:e}}var ce,N,Vt,Pe,he,z,Ee,We,ge=Tr(()=>{"use strict";ce=require("fs"),N=require("fs/promises"),Vt=require("os"),Pe=require("path"),he=(0,Pe.join)((0,Vt.homedir)(),".pipeliner","daemon"),z=(0,Pe.join)(he,"scheduler.pid"),Ee=(0,Pe.join)(he,"scheduler.started");We=(0,Pe.join)(he,"error.log")});var ir=require("child_process"),te=require("fs"),oe=require("fs/promises"),ar=require("os"),G=require("path"),lr=require("util"),w=x(require("chalk"),1),cr=require("commander");ge();var K=require("path"),uo=x(require("chalk"),1);var zt=x(require("readline"),1),W=x(require("chalk"),1),ft=x(require("inquirer"),1),Ut=15,O=class{searchable;constructor(e=!1){this.searchable=e}async prompt(e,t){if(this.searchable)return this.promptWithSearch(e,t);let{choice:r}=await ft.default.prompt([{type:"list",name:"choice",message:W.default.cyan(e),choices:t.map(i=>({name:i.label,value:i.id})),pageSize:Ut}]),s=t.find(i=>i.id===r);if(!s)throw new Error(`Invalid choice: ${r}`);return s}async promptWithSearch(e,t){return new Promise(r=>{let s="",i=0,n=[...t],a=0,l=zt.createInterface({input:process.stdin,output:process.stdout,terminal:!1});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdout.write("\x1B[?25l");let c=()=>{let p=Ut,h=0,g=n.length;if(n.length>p){let M=Math.floor(p/2);h=Math.max(0,i-M),g=Math.min(n.length,h+p),g===n.length&&(h=Math.max(0,g-p))}let b=s?W.default.gray(` Filter: ${s}`)+W.default.gray(` (${n.length}/${t.length})`):W.default.gray(" Type to filter, \u2191\u2193 to navigate, Enter to select"),y=[W.default.cyan(`? ${e}`),b,""];if(n.length===0)y.push(W.default.yellow(" No matches found"));else{h>0&&y.push(W.default.gray(` \u2191 ${h} more above`));for(let M=h;M<g;M++){let A=n[M];y.push(M===i?W.default.cyan(`\u276F ${A.label}`):W.default.white(` ${A.label}`))}g<n.length&&y.push(W.default.gray(` \u2193 ${n.length-g} more below`))}let S=y.length,k=a>0?a:0,I=k>0?`\x1B[${k}A\x1B[0J`:"";process.stdout.write(`${I}${y.join(`
5
+ `)}
6
+ `),a=S},d=()=>{let p=s.toLowerCase();n=p?t.filter(h=>h.label.toLowerCase().includes(p)):[...t],i>=n.length&&(i=Math.max(0,n.length-1))},f=p=>{let h=p.toString();if(h===""&&(m(),process.exit(0)),h==="\r"||h===`
7
+ `){n.length>0&&(m(),r(n[i]));return}if(h==="\x1B"&&p.length===1){s&&(s="",d(),c());return}if(h==="\x1B[A"){n.length>0&&(i=i>0?i-1:n.length-1,c());return}if(h==="\x1B[B"){n.length>0&&(i=i<n.length-1?i+1:0,c());return}if(h==="\x7F"||h==="\b"){s.length>0&&(s=s.slice(0,-1),d(),c());return}h.length===1&&h>=" "&&h<="~"&&(s+=h,d(),c())},m=()=>{process.stdin.removeListener("data",f),process.stdin.isTTY&&process.stdin.setRawMode(!1),l.close(),process.stdout.write("\x1B[?25h")};c(),process.stdin.on("data",f)})}},Ve=class{async prompt(e,t){let{value:r}=await ft.default.prompt([{type:"input",name:"value",message:W.default.cyan(e),default:t}]);return r}};var Zt=x(require("boxen"),1),C=x(require("chalk"),1),ht=x(require("string-width"),1);function He(o){if(o.records.length===0)return"";let e=Ar(o.records),t=0;for(let m of e)m.length>1?t+=Math.max(...m.map(p=>p.duration)):t+=m[0].duration;let r=(t/1e3).toFixed(1),s=o.records.reduce((m,p)=>p.duration>m.duration?p:m),i=o.records.indexOf(s)+1,n=(s.duration/1e3).toFixed(1),a=[],l=0;for(let m=0;m<e.length;m++){let p=e[m];if(p.some(b=>b.context.branchIndex!==void 0&&b.context.stepIndex>=1e3)&&p.length>=1&&p.length>0){let b=p,y=b.map(k=>({name:Yt(k),startTime:l,duration:k.duration})),S=Math.max(...b.map(k=>k.duration));a.push({stepNumber:m+1,name:"Parallel",startTime:l,duration:S,isParallel:!0,parallelBranches:y}),l+=S}else{let b=p[0],S=Yt(b)||"Unknown";a.push({stepNumber:m+1,name:S,startTime:l,duration:b.duration,isParallel:!1}),l+=b.duration}}let c=Br(a,t,s.duration),f=`${`${C.default.bold("Workflow Summary")}
6
8
  ${C.default.cyan(`Workflow finished in ${r}s`)}
7
9
  ${C.default.yellow(`Slowest step: Step ${i} (${n}s)`)}`}
8
10
 
9
11
  ${c}`;return`
10
- ${(0,Zt.default)(f,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"cyan"})}`}function Ar(o){let e=[],t=new Map,r=1e3;for(let i of o){let n;i.context.branchIndex!==void 0&&i.context.stepIndex>=r?n=Math.floor(i.context.stepIndex/r):n=i.context.stepIndex,t.has(n)||t.set(n,[]);let a=t.get(n);a&&a.push(i)}let s=Array.from(t.keys()).sort((i,n)=>i-n);for(let i of s){let n=t.get(i);if(n){let a=n.filter(l=>l.context.branchIndex!==void 0&&l.context.stepIndex>=r);if(a.length>0){a.sort((c,d)=>{let f=c.context.branchIndex??-1,m=d.context.branchIndex??-1;return f-m}),e.push(a);let l=n.filter(c=>(c.context.branchIndex===void 0||c.context.stepIndex<r)&&!("parallel"in c.step));l.length>0&&(l.sort((c,d)=>c.context.stepIndex-d.context.stepIndex),e.push(l))}else n.sort((l,c)=>l.context.stepIndex-c.context.stepIndex),e.push(n)}}return e}function Yt(o){let e=o.step,t=28;if("run"in e){let r=o.resolvedCommand??e.run;return r.length>t?`${r.substring(0,t-2)}..`:r}else if("choose"in e){let r=e.choose.message;return r.length>t?`${r.substring(0,t-2)}..`:r}else if("prompt"in e){let r=e.prompt.message;return r.length>t?`${r.substring(0,t-2)}..`:r}else{if("parallel"in e)return"Parallel";if("fail"in e){let r=e.fail.message;return r.length>t?`${r.substring(0,t-2)}..`:r}}return"Unknown"}function Jt(o,e){return Te(o)<=e}function Br(o,e,t){let r=process.stdout.columns||80,s=36,i=4,n=36,a=8,l=8,d=n+a+l+9,m=r-s-i-d,g=Math.max(40,Math.max(0,m-5)),b=[],k=2+n+3+a+3+l+3+g+2,y=r-s-8,S=(R,P,Z=!1)=>{let Re=Te(R);if(Re===P)return R;if(Re>P)return De(R,P);let ne=P-Re;if(Z){let se=R.lastIndexOf("\u2524"),fe=R.lastIndexOf("\u253C",se-1);if(fe>0&&se>fe){let Le=R.slice(0,fe+1),at=R.slice(fe+1,se),Fe=R.slice(se);return Le+at+"\u2500".repeat(ne)+Fe}return R.slice(0,-1)+"\u2500".repeat(ne)+R.slice(-1)}let Oe=R.lastIndexOf("\u2502");return Oe>0?R.slice(0,Oe)+" ".repeat(ne)+R.slice(Oe):R+" ".repeat(ne)},T="\u2500".repeat(n),V="\u2500".repeat(a),A="\u2500".repeat(l),ot="\u2500".repeat(g),rt=`\u250C\u2500${T}\u2500\u252C\u2500${V}\u2500\u252C\u2500${A}\u2500\u252C\u2500${ot}\u2500\u2510`;rt=S(rt,k,!0),b.push(rt);let ur=ue("Step / Task",n),pr=J("Start",a),dr=ue("Duration",l),mr=ue("Timeline",g),nt=`\u2502 ${C.default.bold(ur)} \u2502 ${C.default.bold(pr)} \u2502 ${C.default.bold(dr)} \u2502 ${C.default.bold(mr)} \u2502`;nt=S(nt,k),b.push(nt);let fr="\u2500".repeat(n),hr="\u2500".repeat(a),gr="\u2500".repeat(l),wr="\u2500".repeat(g),st=`\u251C\u2500${fr}\u2500\u253C\u2500${hr}\u2500\u253C\u2500${gr}\u2500\u253C\u2500${wr}\u2500\u2524`;st=S(st,k,!0),b.push(st);let Be=new Map;for(let R=0;R<o.length;R++){let P=o[R],Z=Math.round(P.startTime);Be.has(Z)||Be.set(Z,[]),Be.get(Z)?.push(R)}for(let R=0;R<o.length;R++){let P=o[R],Z=(P.startTime/1e3).toFixed(1),Re=(P.duration/1e3).toFixed(1),ne=`${C.default.cyan(`Step ${P.stepNumber}`)}: ${P.name}`,se=qt(P.duration,t)(`${Re}s`),fe=Math.round(P.startTime),Le=Be.get(fe)??[],at=Le.indexOf(R),Fe=Gt(P.startTime,P.duration,e,g,P.duration,t,!1,at,Le.length,P.isParallel),ie=`\u2502 ${ue(ne,n)} \u2502 ${J(`${Z}s`,a)} \u2502 ${J(se,l)} \u2502 ${Fe} \u2502`;if(ie=S(ie,k),!Jt(ie,y)){let ae=De(ne,n);ie=`\u2502 ${ue(ae,n)} \u2502 ${J(`${Z}s`,a)} \u2502 ${J(se,l)} \u2502 ${Fe} \u2502`,ie=S(ie,k)}if(b.push(ie),P.isParallel&&P.parallelBranches&&P.parallelBranches.length>0)for(let ae=0;ae<P.parallelBranches.length;ae++){let X=P.parallelBranches[ae],Ot=(X.startTime/1e3).toFixed(1),vr=(X.duration/1e3).toFixed(1),Lt=Gt(X.startTime,X.duration,e,g,X.duration,t,!0,0,1,!1),Ft=ae===0?"\u2502 \u23A7 ":ae===P.parallelBranches.length-1?"\u2502 \u23A9 ":"\u2502 \u251C ",lt=n-3,kr=ue(C.default.blue(X.name),lt),Wt=qt(X.duration,t)(`${vr}s`),le=`${Ft}${kr} \u2502 ${J(`${Ot}s`,a)} \u2502 ${J(Wt,l)} \u2502 ${Lt} \u2502`;if(le=S(le,k),!Jt(le,y)){let $r=De(C.default.blue(X.name),lt-3);le=`${Ft}${ue($r,lt)} \u2502 ${J(`${Ot}s`,a)} \u2502 ${J(Wt,l)} \u2502 ${Lt} \u2502`,le=S(le,k)}b.push(le)}}let br="\u2500".repeat(n),yr="\u2500".repeat(a),Sr="\u2500".repeat(l),xr="\u2500".repeat(g),it=`\u2514\u2500${br}\u2500\u2534\u2500${yr}\u2500\u2534\u2500${Sr}\u2500\u2534\u2500${xr}\u2500\u2518`;return it=S(it,k,!0),b.push(it),b.join(`
11
- `)}function qt(o,e){if(o===0)return C.default.gray;let t=o/e;return t>=.8?C.default.red:t>=.5?C.default.yellow:C.default.green}function Gt(o,e,t,r,s,i,n=!1,a=0,l=1,c=!1){let d=o/t,m=(o+e)/t,p=Math.round(d*r),h=Math.round(m*r);if(l>1&&e===0){let A=a*1e-4;p=Math.round((d+A)*r),h=p+1}else h<=p&&(h=p+1);p=Math.max(0,Math.min(p,r-1)),h=Math.max(p+1,Math.min(h,r));let g;if(n)g=C.default.cyan;else if(c)g=C.default.blue;else if(s===0)g=C.default.gray;else{let A=s/i;A>=.8?g=C.default.red:A>=.5?g=C.default.yellow:g=C.default.green}let k=m>=.99||h>=r?r:h,y="";for(let A=0;A<p;A++)y+=C.default.gray("\u2591");let S=k-p,T="\u2588".repeat(S);y+=g(T);let V=r-k;for(let A=0;A<V;A++)y+=C.default.gray("\u2591");return y}function Te(o){return(0,ht.default)(o)}function De(o,e){if(Te(o)<=e)return o;let s=e-2;if(s<1)return"..";let i=/\u001b\[[0-9;]*m/g,n=[],a;for(;(a=i.exec(o))!==null;)n.push(a[0]);let l=o.replace(i,""),c="",d=0;for(let f=0;f<l.length;f++){let m=l[f],p=(0,ht.default)(m);if(d+p>s)break;c+=m,d+=p}return c+="..",n.length>0&&c.length>0?n[0]+c+(n[n.length-1]??""):c}function ue(o,e){let t=Te(o);return t>=e?De(o,e):o+" ".repeat(e-t)}function J(o,e){let t=Te(o);return t>=e?De(o,e):" ".repeat(e-t)+o}var _e=x(require("boxen"),1),we=x(require("chalk"),1);function gt(o,e,t,r={}){let{borderColor:s="cyan",isNested:i=!1}=r,n;e!==void 0&&(t?n=`line ${e} in ${t}`:n=`line ${e}`);let a=i?`\u2502 ${o}`:`> ${o}`;return(0,_e.default)(a,{title:n,borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:s})}function be(o,e=!1,t){let r=o?"\u2713 Completed":"\u2717 Failed",s=o?we.default.green(r):we.default.red(r);if(t!==void 0){let i=ye(t);return`${s} ${we.default.gray(`(${i})`)}`}return s}function Ie(o){return(0,_e.default)(`\u2717 ${o}`,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"red"})}function Xt(o){return(0,_e.default)(`> Starting parallel execution (${o} branches)`,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"yellow"})}function Kt(o){let e=o?"\u2713 All parallel branches completed":"\u2717 Some parallel branches failed";return o?we.default.green(e):we.default.red(e)}function wt(o,e=!1){return`${e?"| \u2502 ":"\u2502 "}${o}`}function ye(o){return`${(o/1e3).toFixed(3)}s`}var Qt=require("fs"),eo=require("path"),pe=class{constructor(e){this.workspace=e}evaluate(e){return"var"in e||"has"in e?this.evaluateVarExists(e):"file"in e?this.evaluateFileExists(e):"choice"in e?this.evaluateChoice(e):"all"in e?this.evaluateAll(e):"any"in e?this.evaluateAny(e):"not"in e?this.evaluateNot(e):!1}evaluateVarExists(e){if(e.has)return this.workspace.hasVariable(e.has)||this.workspace.hasFact(e.has);if(!e.var)return!1;if(typeof e.var=="object"){for(let[r,s]of Object.entries(e.var)){let i=this.workspace.getVariable(r),n=this.workspace.getFact(r),a=i??(n!==void 0?n.toString():void 0);if(a===void 0||a!==s)return!1}return!0}let t=e.var;return this.workspace.hasVariable(t)||this.workspace.hasFact(t)}evaluateFileExists(e){try{let t=e.file.trim(),r=(0,eo.resolve)(process.cwd(),t);return(0,Qt.existsSync)(r)}catch{return!1}}evaluateChoice(e){return this.workspace.hasChoice(e.choice)}evaluateAll(e){return e.all.every(t=>this.evaluate(t))}evaluateAny(e){return e.any.some(t=>this.evaluate(t))}evaluateNot(e){return!this.evaluate(e.not)}};var bt=x(require("log-update"),1);var yt=1e3;function Or(o,e,t){return e.parallel.map((r,s)=>({workspace:o.workspace.clone(),stepIndex:t.stepIndex*yt+s,branchIndex:s,lineNumber:t.lineNumber,fileName:t.fileName}))}function to(o,e){return"run"in o?o.run:"choose"in o?`Choose: ${o.choose.message}`:"prompt"in o?`Prompt: ${o.prompt.message}`:"fail"in o?`Fail: ${o.fail.message}`:`Branch ${e+1}`}function Lr(o,e){let t=0;for(let r=0;r<o.length;r++){let s=o[r],i=e[r];s.when&&!new pe(i.workspace).evaluate(s.when)||t++}return t}function Ue(o,e,t=!1){let r=o.map(s=>{let i=s.index+1,n="",a="";switch(s.status){case"pending":n="\u25CB",a=`Branch ${i}: ${s.name} - Pending`;break;case"running":n=e,a=`Branch ${i}: ${s.name} - Running...`;break;case"success":n="\u2713",a=`Branch ${i}: ${s.name} - Completed`;break;case"failed":n="\u2717",a=`Branch ${i}: ${s.name} - Failed${s.error?`: ${s.error}`:""}`;break}return`${n} ${a}`});(0,bt.default)(r.join(`
12
+ ${(0,Zt.default)(f,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"cyan"})}`}function Ar(o){let e=[],t=new Map,r=1e3;for(let i of o){let n;i.context.branchIndex!==void 0&&i.context.stepIndex>=r?n=Math.floor(i.context.stepIndex/r):n=i.context.stepIndex,t.has(n)||t.set(n,[]);let a=t.get(n);a&&a.push(i)}let s=Array.from(t.keys()).sort((i,n)=>i-n);for(let i of s){let n=t.get(i);if(n){let a=n.filter(l=>l.context.branchIndex!==void 0&&l.context.stepIndex>=r);if(a.length>0){a.sort((c,d)=>{let f=c.context.branchIndex??-1,m=d.context.branchIndex??-1;return f-m}),e.push(a);let l=n.filter(c=>(c.context.branchIndex===void 0||c.context.stepIndex<r)&&!("parallel"in c.step));l.length>0&&(l.sort((c,d)=>c.context.stepIndex-d.context.stepIndex),e.push(l))}else n.sort((l,c)=>l.context.stepIndex-c.context.stepIndex),e.push(n)}}return e}function Yt(o){let e=o.step,t=28;if("run"in e){let r=o.resolvedCommand??e.run;return r.length>t?`${r.substring(0,t-2)}..`:r}else if("choose"in e){let r=e.choose.message;return r.length>t?`${r.substring(0,t-2)}..`:r}else if("prompt"in e){let r=e.prompt.message;return r.length>t?`${r.substring(0,t-2)}..`:r}else{if("parallel"in e)return"Parallel";if("fail"in e){let r=e.fail.message;return r.length>t?`${r.substring(0,t-2)}..`:r}}return"Unknown"}function Jt(o,e){return Te(o)<=e}function Br(o,e,t){let r=process.stdout.columns||80,s=36,i=4,n=36,a=8,l=8,d=n+a+l+9,m=r-s-i-d,g=Math.max(40,Math.max(0,m-5)),b=[],y=2+n+3+a+3+l+3+g+2,S=r-s-8,k=(R,P,Z=!1)=>{let Re=Te(R);if(Re===P)return R;if(Re>P)return De(R,P);let ne=P-Re;if(Z){let se=R.lastIndexOf("\u2524"),fe=R.lastIndexOf("\u253C",se-1);if(fe>0&&se>fe){let Le=R.slice(0,fe+1),at=R.slice(fe+1,se),Fe=R.slice(se);return Le+at+"\u2500".repeat(ne)+Fe}return R.slice(0,-1)+"\u2500".repeat(ne)+R.slice(-1)}let Oe=R.lastIndexOf("\u2502");return Oe>0?R.slice(0,Oe)+" ".repeat(ne)+R.slice(Oe):R+" ".repeat(ne)},I="\u2500".repeat(n),M="\u2500".repeat(a),A="\u2500".repeat(l),ot="\u2500".repeat(g),rt=`\u250C\u2500${I}\u2500\u252C\u2500${M}\u2500\u252C\u2500${A}\u2500\u252C\u2500${ot}\u2500\u2510`;rt=k(rt,y,!0),b.push(rt);let ur=ue("Step / Task",n),pr=J("Start",a),dr=ue("Duration",l),mr=ue("Timeline",g),nt=`\u2502 ${C.default.bold(ur)} \u2502 ${C.default.bold(pr)} \u2502 ${C.default.bold(dr)} \u2502 ${C.default.bold(mr)} \u2502`;nt=k(nt,y),b.push(nt);let fr="\u2500".repeat(n),hr="\u2500".repeat(a),gr="\u2500".repeat(l),wr="\u2500".repeat(g),st=`\u251C\u2500${fr}\u2500\u253C\u2500${hr}\u2500\u253C\u2500${gr}\u2500\u253C\u2500${wr}\u2500\u2524`;st=k(st,y,!0),b.push(st);let Be=new Map;for(let R=0;R<o.length;R++){let P=o[R],Z=Math.round(P.startTime);Be.has(Z)||Be.set(Z,[]),Be.get(Z)?.push(R)}for(let R=0;R<o.length;R++){let P=o[R],Z=(P.startTime/1e3).toFixed(1),Re=(P.duration/1e3).toFixed(1),ne=`${C.default.cyan(`Step ${P.stepNumber}`)}: ${P.name}`,se=qt(P.duration,t)(`${Re}s`),fe=Math.round(P.startTime),Le=Be.get(fe)??[],at=Le.indexOf(R),Fe=Gt(P.startTime,P.duration,e,g,P.duration,t,!1,at,Le.length,P.isParallel),ie=`\u2502 ${ue(ne,n)} \u2502 ${J(`${Z}s`,a)} \u2502 ${J(se,l)} \u2502 ${Fe} \u2502`;if(ie=k(ie,y),!Jt(ie,S)){let ae=De(ne,n);ie=`\u2502 ${ue(ae,n)} \u2502 ${J(`${Z}s`,a)} \u2502 ${J(se,l)} \u2502 ${Fe} \u2502`,ie=k(ie,y)}if(b.push(ie),P.isParallel&&P.parallelBranches&&P.parallelBranches.length>0)for(let ae=0;ae<P.parallelBranches.length;ae++){let X=P.parallelBranches[ae],Ot=(X.startTime/1e3).toFixed(1),vr=(X.duration/1e3).toFixed(1),Lt=Gt(X.startTime,X.duration,e,g,X.duration,t,!0,0,1,!1),Ft=ae===0?"\u2502 \u23A7 ":ae===P.parallelBranches.length-1?"\u2502 \u23A9 ":"\u2502 \u251C ",lt=n-3,kr=ue(C.default.blue(X.name),lt),Wt=qt(X.duration,t)(`${vr}s`),le=`${Ft}${kr} \u2502 ${J(`${Ot}s`,a)} \u2502 ${J(Wt,l)} \u2502 ${Lt} \u2502`;if(le=k(le,y),!Jt(le,S)){let $r=De(C.default.blue(X.name),lt-3);le=`${Ft}${ue($r,lt)} \u2502 ${J(`${Ot}s`,a)} \u2502 ${J(Wt,l)} \u2502 ${Lt} \u2502`,le=k(le,y)}b.push(le)}}let br="\u2500".repeat(n),yr="\u2500".repeat(a),Sr="\u2500".repeat(l),xr="\u2500".repeat(g),it=`\u2514\u2500${br}\u2500\u2534\u2500${yr}\u2500\u2534\u2500${Sr}\u2500\u2534\u2500${xr}\u2500\u2518`;return it=k(it,y,!0),b.push(it),b.join(`
13
+ `)}function qt(o,e){if(o===0)return C.default.gray;let t=o/e;return t>=.8?C.default.red:t>=.5?C.default.yellow:C.default.green}function Gt(o,e,t,r,s,i,n=!1,a=0,l=1,c=!1){let d=o/t,m=(o+e)/t,p=Math.round(d*r),h=Math.round(m*r);if(l>1&&e===0){let A=a*1e-4;p=Math.round((d+A)*r),h=p+1}else h<=p&&(h=p+1);p=Math.max(0,Math.min(p,r-1)),h=Math.max(p+1,Math.min(h,r));let g;if(n)g=C.default.cyan;else if(c)g=C.default.blue;else if(s===0)g=C.default.gray;else{let A=s/i;A>=.8?g=C.default.red:A>=.5?g=C.default.yellow:g=C.default.green}let y=m>=.99||h>=r?r:h,S="";for(let A=0;A<p;A++)S+=C.default.gray("\u2591");let k=y-p,I="\u2588".repeat(k);S+=g(I);let M=r-y;for(let A=0;A<M;A++)S+=C.default.gray("\u2591");return S}function Te(o){return(0,ht.default)(o)}function De(o,e){if(Te(o)<=e)return o;let s=e-2;if(s<1)return"..";let i=/\u001b\[[0-9;]*m/g,n=[],a;for(;(a=i.exec(o))!==null;)n.push(a[0]);let l=o.replace(i,""),c="",d=0;for(let f=0;f<l.length;f++){let m=l[f],p=(0,ht.default)(m);if(d+p>s)break;c+=m,d+=p}return c+="..",n.length>0&&c.length>0?n[0]+c+(n[n.length-1]??""):c}function ue(o,e){let t=Te(o);return t>=e?De(o,e):o+" ".repeat(e-t)}function J(o,e){let t=Te(o);return t>=e?De(o,e):" ".repeat(e-t)+o}var _e=x(require("boxen"),1),we=x(require("chalk"),1);function gt(o,e,t,r={}){let{borderColor:s="cyan",isNested:i=!1}=r,n;e!==void 0&&(t?n=`line ${e} in ${t}`:n=`line ${e}`);let a=i?`\u2502 ${o}`:`> ${o}`;return(0,_e.default)(a,{title:n,borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:s})}function be(o,e=!1,t){let r=o?"\u2713 Completed":"\u2717 Failed",s=o?we.default.green(r):we.default.red(r);if(t!==void 0){let i=ye(t);return`${s} ${we.default.gray(`(${i})`)}`}return s}function Ie(o){return(0,_e.default)(`\u2717 ${o}`,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"red"})}function Xt(o){return(0,_e.default)(`> Starting parallel execution (${o} branches)`,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"yellow"})}function Kt(o){let e=o?"\u2713 All parallel branches completed":"\u2717 Some parallel branches failed";return o?we.default.green(e):we.default.red(e)}function wt(o,e=!1){return`${e?"| \u2502 ":"\u2502 "}${o}`}function ye(o){return`${(o/1e3).toFixed(3)}s`}var Qt=require("fs"),eo=require("path"),pe=class{constructor(e){this.workspace=e}evaluate(e){return"var"in e||"has"in e?this.evaluateVarExists(e):"file"in e?this.evaluateFileExists(e):"choice"in e?this.evaluateChoice(e):"all"in e?this.evaluateAll(e):"any"in e?this.evaluateAny(e):"not"in e?this.evaluateNot(e):!1}evaluateVarExists(e){if(e.has)return this.workspace.hasVariable(e.has)||this.workspace.hasFact(e.has);if(!e.var)return!1;if(typeof e.var=="object"){for(let[r,s]of Object.entries(e.var)){let i=this.workspace.getVariable(r),n=this.workspace.getFact(r),a=i??(n!==void 0?n.toString():void 0);if(a===void 0||a!==s)return!1}return!0}let t=e.var;return this.workspace.hasVariable(t)||this.workspace.hasFact(t)}evaluateFileExists(e){try{let t=e.file.trim(),r=(0,eo.resolve)(process.cwd(),t);return(0,Qt.existsSync)(r)}catch{return!1}}evaluateChoice(e){return this.workspace.hasChoice(e.choice)}evaluateAll(e){return e.all.every(t=>this.evaluate(t))}evaluateAny(e){return e.any.some(t=>this.evaluate(t))}evaluateNot(e){return!this.evaluate(e.not)}};var bt=x(require("log-update"),1);var yt=1e3;function Or(o,e,t){return e.parallel.map((r,s)=>({workspace:o.workspace.clone(),stepIndex:t.stepIndex*yt+s,branchIndex:s,lineNumber:t.lineNumber,fileName:t.fileName}))}function to(o,e){return"run"in o?o.run:"choose"in o?`Choose: ${o.choose.message}`:"prompt"in o?`Prompt: ${o.prompt.message}`:"fail"in o?`Fail: ${o.fail.message}`:`Branch ${e+1}`}function Lr(o,e){let t=0;for(let r=0;r<o.length;r++){let s=o[r],i=e[r];s.when&&!new pe(i.workspace).evaluate(s.when)||t++}return t}function Ue(o,e,t=!1){let r=o.map(s=>{let i=s.index+1,n="",a="";switch(s.status){case"pending":n="\u25CB",a=`Branch ${i}: ${s.name} - Pending`;break;case"running":n=e,a=`Branch ${i}: ${s.name} - Running...`;break;case"success":n="\u2713",a=`Branch ${i}: ${s.name} - Completed`;break;case"failed":n="\u2717",a=`Branch ${i}: ${s.name} - Failed${s.error?`: ${s.error}`:""}`;break}return`${n} ${a}`});(0,bt.default)(r.join(`
12
14
  `))}async function Fr(o,e,t,r){let s=[],i=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],n=0;for(let d=0;d<t.length;d++){let f=t[d],m=r[d];if(f.when&&!new pe(m.workspace).evaluate(f.when))continue;let p=e(f,d);s.push({index:d,name:p,status:"pending"})}let a=setInterval(()=>{n=(n+1)%i.length,Ue(s,i[n])},100),l=s.map(async d=>{let{index:f}=d,m=t[f],p=r[f];d.status="running";try{let h=await o.executeStep(m,p,!0);if(d.status="success",Ue(s,i[n]),o.recordBranch){let g="run"in m?{resolvedCommand:m.run}:void 0;o.recordBranch(m,p,h,"success",g)}return{index:f,result:h,context:p}}catch(h){p.workspace.setStepResult(p.stepIndex,!1);let g=h instanceof Error?h.message:String(h);if(d.status="failed",d.error=g,Ue(s,i[n]),o.recordBranch){let b="run"in m?{resolvedCommand:m.run}:void 0;o.recordBranch(m,p,void 0,"failure",b)}return{index:f,error:h,context:p}}}),c=await Promise.all(l);return clearInterval(a),Ue(s,"",!0),bt.default.done(),c}function Wr(o,e,t,r,s){let i=!0,n=!1;console.log("");for(let l of t){if(!l)continue;n=!0;let{index:c,result:d,error:f,context:m}=l;if(f){i=!1;let p=`Branch ${c+1} failed: ${f instanceof Error?f.message:String(f)}`,h=Ie(p);console.error(h)}else if(d&&typeof d=="object"&&"stdout"in d){let p=d;if(i=i&&p.success,p.stdout.length>0||p.stderr.length>0||!p.success){let h=r[c],g=e(h,c);o.taskRunner.displayBufferedOutput(p,g,!1,m.lineNumber,m.fileName)}}}n||console.log("\u26A0\uFE0F All parallel branches were skipped (conditions not met)");let a=Kt(i);return console.log(a),i}function Vr(o,e){for(let t of e){let r=t.workspace.getAllFacts(),s=t.workspace.getAllVariables();for(let[i,n]of r)o.workspace.setFact(i,n);for(let[i,n]of s)o.workspace.setVariable(i,n)}}async function oo(o,e,t){let r=Or(o,e,t),s=Lr(e.parallel,r),i=Xt(s);console.log(i);let n=await Fr(o,to,e.parallel,r),a=Wr(o,to,n,e.parallel,t);if(o.setStepResult(t.stepIndex,a),!a){let l=t.lineNumber?` (line ${t.lineNumber})`:"";throw new Error(`Parallel step ${t.stepIndex}${l} failed: one or more branches failed`)}Vr(o,r)}var St=require("jsonpath-plus"),ro=require("yaml");function no(o,e){try{let t=e.join(`
13
15
  `);if(!("regex"in o)&&!("json"in o)&&!("yaml"in o)&&!("yml"in o)&&!("kv"in o)&&!("after"in o)&&!("before"in o)&&!("line"in o))return t;if("regex"in o){let r=new RegExp(o.regex),s=t.match(r);return s&&s[1]?s[1]:null}if("json"in o)try{let r=JSON.parse(t),s=(0,St.JSONPath)({path:o.json,json:r});if(s&&s.length>0){let i=s[0];return typeof i=="string"?i:JSON.stringify(i)}return null}catch{return null}if("yaml"in o||"yml"in o)try{let r=(0,ro.parse)(t),s="yaml"in o?o.yaml:o.yml,i=(0,St.JSONPath)({path:s,json:r});if(i&&i.length>0){let n=i[0];return typeof n=="string"?n:JSON.stringify(n)}return null}catch{return null}if("kv"in o&&typeof o.kv=="string"){let r=o.kv.trim();if(!r)return null;for(let s of e){let i=s.trim();if(!i||i.startsWith("#"))continue;let n=`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*=\\s*(.+)$`,a=i.match(new RegExp(n));if(a&&a[1])return a[1].trim().replace(/^["']|["']$/g,"")}return null}if("after"in o||"before"in o){let r="after"in o?o.after:"",s="before"in o?o.before:void 0;if(r){let i=t.indexOf(r);if(i===-1)return null;let n=i+r.length,a=t.length;if(s){let l=t.indexOf(s,n);if(l===-1)return null;a=l}return t.substring(n,a).trim()}if(s){let i=t.indexOf(s);return i===-1?null:t.substring(0,i).trim()}}if("line"in o){let{from:r,to:s}=o.line,i=Math.max(0,r-1),n=Math.min(e.length,s);return i>=e.length||n<=i||i<0||s<r?null:e.slice(i,n).join(`
14
- `)}return null}catch{return null}}function Hr(o,e,t){if(e.hasVariable(o))return e.getVariable(o)??t;if(e.hasFact(o)){let r=e.getFact(o);return typeof r=="string"?r:String(r)}return e.hasChoice(o)?e.getChoice(o)??t:t}function de(o,e){let t=/\{\{\s*(\w+)\s*\}\}/g;return o.replace(t,(r,s)=>Hr(s,e,r))}async function so(o,e,t,r,s){let{workspace:i,taskRunner:n,baseDir:a,globalShell:l,calculateBaseStepIndex:c}=o,d=c(t),f=de(e.run.trim(),i),m=e.shell??l,p=e.retry??0,h=p==="Infinity"||p===1/0,g=typeof p=="number"?p:0,b=e.timeout,k=!1,y=0,S=e.run.trim()!==f?`${f}
15
- (template: ${e.run})`:f;for(;h||y<=g;){let T=await n.run(f,d,S,t.branchIndex,r,s,t.lineNumber,t.fileName,a,b,m),V=typeof T=="boolean"?T:T.success;if(k=T,V||!h&&y>=g)break;if(y++,h||y<=g){let A=Math.min(1e3*Math.pow(2,y-1),1e4);await new Promise(ot=>setTimeout(ot,A))}}return k}async function io(o,e,t,r,s){let i=await so(o,{run:e.run,timeout:e.timeout,retry:e.retry,shell:void 0},t,r,s);return(typeof i=="boolean"?i:i.success)||!e.onError?i:io(o,e.onError,t,r,s)}async function ao(o,e,t,r=!1,s=!1){let{workspace:i}=o,n=!!(r===!0||e.captures&&e.captures.length>0),a=await so(o,{run:e.run,timeout:e.timeout,retry:e.retry,shell:e.shell},t,n,s),l=typeof a=="boolean"?a:a.success;if(i.setStepResult(t.stepIndex,l),n&&typeof a=="object"&&"stdout"in a){let f=de(e.run.trim(),i),m=e.run.trim()!==f?`${f}
16
- (template: ${e.run})`:f;o.taskRunner.displayBufferedOutput(a,m,!1,t.lineNumber,t.fileName)}if(e.captures&&typeof a=="object"&&"stdout"in a){let f=a.stdout||[];for(let m of e.captures){let p=no(m,f);p!==null&&m.as&&i.setVariable(m.as,p)}}if(l||!e.onError)return a;let c={run:e.onError.run,timeout:e.onError.timeout,retry:e.onError.retry,onError:e.onError.onError??void 0};return await io(o,c,t,r,s)}var H=require("fs/promises"),lo=require("os"),me=require("path"),co=x(require("dayjs"),1),Se=(0,me.join)((0,lo.homedir)(),".pipeliner","workflow-history"),xe=class{constructor(){}async saveHistory(e){await(0,H.mkdir)(Se,{recursive:!0});let t=(0,co.default)().format("YYYY-MM-DD_HH-mm-ss"),r=Math.random().toString(36).slice(2,6),s=(0,me.join)(Se,`workflow-${t}-${r}.json`);return await(0,H.writeFile)(s,JSON.stringify(e,null,2),{encoding:"utf8"}),s}async clearAllHistories(){await(0,H.rm)(Se,{recursive:!0,force:!0})}async removeHistory(e){await(0,H.rm)((0,me.join)(Se,e),{force:!0})}async getHistoryNames(){try{let t=(await(0,H.readdir)(Se)).map(r=>(0,me.basename)(r));return t.sort((r,s)=>{let i=l=>{let c=l.match(/workflow-(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})-/);return c?c[1]:""},n=i(r),a=i(s);return n===a?s.localeCompare(r):a.localeCompare(n)}),t}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return[];throw e}}async getHistory(e){let t=await(0,H.readFile)((0,me.join)(Se,e),{encoding:"utf8"});return JSON.parse(t)}};var ze=class{records=[];initialTimestamp=Date.now();recordStartTimestamp=Date.now();constructor(){this.records=[]}recordStart(){this.recordStartTimestamp=Date.now()}recordEnd(e,t,r,s,i){let n=this.getDuration();return this.records.push({step:e,context:t,output:r,duration:n,status:s,...i}),n}reset(){this.records=[],this.initialTimestamp=Date.now()}async save(){let e=new xe,t={initialTimestamp:this.initialTimestamp,records:this.records};return await e.saveHistory(t)}getDuration(){return Date.now()-this.recordStartTimestamp}getHistory(){return{initialTimestamp:this.initialTimestamp,records:this.records}}};var xt=require("child_process");var Ye=class{async run(e,t,r,s,i=!1,n=!1,a,l,c,d,f){return i?this.runBuffered(e,c,d,f):this.runRealtime(e,r??e,n,a,l,c,d,f)}async runBuffered(e,t,r,s){return new Promise((i,n)=>{let a=this.spawnWithShell(e,t,s),l=[],c=[],d="",f="",m=null;r&&r>0&&(m=setTimeout(()=>{a.kill("SIGTERM");let p=`Command timed out after ${r} seconds`;c.push(p),i({success:!1,stdout:l,stderr:c})},r*1e3)),a.stdout?.on("data",p=>{let h=p.toString(),{lines:g,remaining:b}=this.processStreamBuffer(h,d);l.push(...g),d=b}),a.stderr?.on("data",p=>{let h=p.toString(),{lines:g,remaining:b}=this.processStreamBuffer(h,f);c.push(...g),f=b}),a.on("close",p=>{m&&clearTimeout(m),d.trim()&&l.push(d),f.trim()&&c.push(f),i({success:p===0,stdout:l,stderr:c})}),a.on("error",p=>{m&&clearTimeout(m);let h=`Error: ${p.message}`;i({success:!1,stdout:l,stderr:[...c,h]})})})}async runRealtime(e,t,r,s,i,n,a,l){let d=gt(t,s,i,{borderColor:r?"green":"cyan"});console.log(d);let f=Date.now();return new Promise(m=>{let p=this.spawnWithShell(e,n,l),h="",g="",b=null;a&&a>0&&(b=setTimeout(()=>{p.kill("SIGTERM");let k=`Command timed out after ${a} seconds`,y=Ie(k);console.error(y);let S=Date.now()-f,T=be(!1,!1,S);console.log(T),m(!1)},a*1e3)),p.stdout?.on("data",k=>{let y=k.toString(),{lines:S,remaining:T}=this.processStreamBuffer(y,h);S.forEach(V=>process.stdout.write(`\u2502 ${V}
17
- `)),h=T}),p.stderr?.on("data",k=>{let y=k.toString(),{lines:S,remaining:T}=this.processStreamBuffer(y,g);S.forEach(V=>process.stderr.write(`\u2502 ${V}
18
- `)),g=T}),p.on("close",k=>{b&&clearTimeout(b),h.trim()&&process.stdout.write(`\u2502 ${h}
16
+ `)}return null}catch{return null}}function Hr(o,e,t){if(e.hasVariable(o))return e.getVariable(o)??t;if(e.hasFact(o)){let r=e.getFact(o);return typeof r=="string"?r:String(r)}return e.hasChoice(o)?e.getChoice(o)??t:t}function de(o,e){let t=/\{\{\s*(\w+)\s*\}\}/g;return o.replace(t,(r,s)=>Hr(s,e,r))}async function so(o,e,t,r,s){let{workspace:i,taskRunner:n,baseDir:a,globalShell:l,calculateBaseStepIndex:c}=o,d=c(t),f=de(e.run.trim(),i),m=e.shell??l,p=e.retry??0,h=p==="Infinity"||p===1/0,g=typeof p=="number"?p:0,b=e.timeout,y=!1,S=0,k=e.run.trim()!==f?`${f}
17
+ (template: ${e.run})`:f;for(;h||S<=g;){let I=await n.run(f,d,k,t.branchIndex,r,s,t.lineNumber,t.fileName,a,b,m),M=typeof I=="boolean"?I:I.success;if(y=I,M||!h&&S>=g)break;if(S++,h||S<=g){let A=Math.min(1e3*Math.pow(2,S-1),1e4);await new Promise(ot=>setTimeout(ot,A))}}return y}async function io(o,e,t,r,s){let i=await so(o,{run:e.run,timeout:e.timeout,retry:e.retry,shell:void 0},t,r,s);return(typeof i=="boolean"?i:i.success)||!e.onError?i:io(o,e.onError,t,r,s)}async function ao(o,e,t,r=!1,s=!1){let{workspace:i}=o,n=!!(r===!0||e.captures&&e.captures.length>0),a=await so(o,{run:e.run,timeout:e.timeout,retry:e.retry,shell:e.shell},t,n,s),l=typeof a=="boolean"?a:a.success;if(i.setStepResult(t.stepIndex,l),n&&typeof a=="object"&&"stdout"in a){let f=de(e.run.trim(),i),m=e.run.trim()!==f?`${f}
18
+ (template: ${e.run})`:f;o.taskRunner.displayBufferedOutput(a,m,!1,t.lineNumber,t.fileName)}if(e.captures&&typeof a=="object"&&"stdout"in a){let f=a.stdout||[];for(let m of e.captures){let p=no(m,f);p!==null&&m.as&&i.setVariable(m.as,p)}}if(l||!e.onError)return a;let c={run:e.onError.run,timeout:e.onError.timeout,retry:e.onError.retry,onError:e.onError.onError??void 0};return await io(o,c,t,r,s)}var H=require("fs/promises"),lo=require("os"),me=require("path"),co=x(require("dayjs"),1),Se=(0,me.join)((0,lo.homedir)(),".pipeliner","workflow-history"),xe=class{constructor(){}async saveHistory(e){await(0,H.mkdir)(Se,{recursive:!0});let t=(0,co.default)().format("YYYY-MM-DD_HH-mm-ss"),r=Math.random().toString(36).slice(2,6),s=(0,me.join)(Se,`workflow-${t}-${r}.json`);return await(0,H.writeFile)(s,JSON.stringify(e,null,2),{encoding:"utf8"}),s}async clearAllHistories(){await(0,H.rm)(Se,{recursive:!0,force:!0})}async removeHistory(e){await(0,H.rm)((0,me.join)(Se,e),{force:!0})}async getHistoryNames(){try{let t=(await(0,H.readdir)(Se)).map(r=>(0,me.basename)(r));return t.sort((r,s)=>{let i=l=>{let c=l.match(/workflow-(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})-/);return c?c[1]:""},n=i(r),a=i(s);return n===a?s.localeCompare(r):a.localeCompare(n)}),t}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return[];throw e}}async getHistory(e){let t=await(0,H.readFile)((0,me.join)(Se,e),{encoding:"utf8"});return JSON.parse(t)}};var ze=class{records=[];initialTimestamp=Date.now();recordStartTimestamp=Date.now();constructor(){this.records=[]}recordStart(){this.recordStartTimestamp=Date.now()}recordEnd(e,t,r,s,i){let n=this.getDuration();return this.records.push({step:e,context:t,output:r,duration:n,status:s,...i}),n}reset(){this.records=[],this.initialTimestamp=Date.now()}async save(){let e=new xe,t={initialTimestamp:this.initialTimestamp,records:this.records};return await e.saveHistory(t)}getDuration(){return Date.now()-this.recordStartTimestamp}getHistory(){return{initialTimestamp:this.initialTimestamp,records:this.records}}};var xt=require("child_process");var Ye=class{async run(e,t,r,s,i=!1,n=!1,a,l,c,d,f){return i?this.runBuffered(e,c,d,f):this.runRealtime(e,r??e,n,a,l,c,d,f)}async runBuffered(e,t,r,s){return new Promise((i,n)=>{let a=this.spawnWithShell(e,t,s),l=[],c=[],d="",f="",m=null;r&&r>0&&(m=setTimeout(()=>{a.kill("SIGTERM");let p=`Command timed out after ${r} seconds`;c.push(p),i({success:!1,stdout:l,stderr:c})},r*1e3)),a.stdout?.on("data",p=>{let h=p.toString(),{lines:g,remaining:b}=this.processStreamBuffer(h,d);l.push(...g),d=b}),a.stderr?.on("data",p=>{let h=p.toString(),{lines:g,remaining:b}=this.processStreamBuffer(h,f);c.push(...g),f=b}),a.on("close",p=>{m&&clearTimeout(m),d.trim()&&l.push(d),f.trim()&&c.push(f),i({success:p===0,stdout:l,stderr:c})}),a.on("error",p=>{m&&clearTimeout(m);let h=`Error: ${p.message}`;i({success:!1,stdout:l,stderr:[...c,h]})})})}async runRealtime(e,t,r,s,i,n,a,l){let d=gt(t,s,i,{borderColor:r?"green":"cyan"});console.log(d);let f=Date.now();return new Promise(m=>{let p=this.spawnWithShell(e,n,l),h="",g="",b=null;a&&a>0&&(b=setTimeout(()=>{p.kill("SIGTERM");let y=`Command timed out after ${a} seconds`,S=Ie(y);console.error(S);let k=Date.now()-f,I=be(!1,!1,k);console.log(I),m(!1)},a*1e3)),p.stdout?.on("data",y=>{let S=y.toString(),{lines:k,remaining:I}=this.processStreamBuffer(S,h);k.forEach(M=>process.stdout.write(`\u2502 ${M}
19
+ `)),h=I}),p.stderr?.on("data",y=>{let S=y.toString(),{lines:k,remaining:I}=this.processStreamBuffer(S,g);k.forEach(M=>process.stderr.write(`\u2502 ${M}
20
+ `)),g=I}),p.on("close",y=>{b&&clearTimeout(b),h.trim()&&process.stdout.write(`\u2502 ${h}
19
21
  `),g.trim()&&process.stderr.write(`\u2502 ${g}
20
- `);let y=k===0,S=Date.now()-f,T=be(y,!1,S);console.log(T),m(y)}),p.on("error",k=>{b&&clearTimeout(b);let y=Ie(`Error: ${k.message}`);console.error(y),m(!1)})})}createSpawnOptions(e){let t={stdio:["inherit","pipe","pipe"],shell:!0};return e&&(t.cwd=e),t}spawnWithShell(e,t,r){if(r&&r.length>0){let s=r[0],i=[...r.slice(1),e],n={stdio:["inherit","pipe","pipe"]};return t&&(n.cwd=t),(0,xt.spawn)(s,i,n)}else{let s=process.env.SHELL??(process.platform==="win32"?"cmd.exe":"/bin/sh"),i=process.platform==="win32"?"/c":"-c",n={stdio:["inherit","pipe","pipe"]};return t&&(n.cwd=t),(0,xt.spawn)(s,[i,e],n)}}processStreamBuffer(e,t){let r=t+e,s=[],i=r;for(;i.includes(`
22
+ `);let S=y===0,k=Date.now()-f,I=be(S,!1,k);console.log(I),m(S)}),p.on("error",y=>{b&&clearTimeout(b);let S=Ie(`Error: ${y.message}`);console.error(S),m(!1)})})}createSpawnOptions(e){let t={stdio:["inherit","pipe","pipe"],shell:!0};return e&&(t.cwd=e),t}spawnWithShell(e,t,r){if(r&&r.length>0){let s=r[0],i=[...r.slice(1),e],n={stdio:["inherit","pipe","pipe"]};return t&&(n.cwd=t),(0,xt.spawn)(s,i,n)}else{let s=process.env.SHELL??(process.platform==="win32"?"cmd.exe":"/bin/sh"),i=process.platform==="win32"?"/c":"-c",n={stdio:["inherit","pipe","pipe"]};return t&&(n.cwd=t),(0,xt.spawn)(s,[i,e],n)}}processStreamBuffer(e,t){let r=t+e,s=[],i=r;for(;i.includes(`
21
23
  `);){let n=i.indexOf(`
22
24
  `),a=i.substring(0,n);i=i.substring(n+1),s.push(a)}return{lines:s,remaining:i}}formatNestedOutput(e,t){t?e.split(`
23
25
  `).forEach(r=>{r.trim()&&console.log(`| ${r}`)}):console.log(e)}displayBufferedOutput(e,t,r=!1,s,i){let n=gt(t,s,i,{borderColor:"cyan",isNested:r});this.formatNestedOutput(n,r),e.stdout.forEach(l=>{let c=wt(l,r);process.stdout.write(`${c}
24
26
  `)}),e.stderr.forEach(l=>{let c=wt(l,r);process.stderr.write(`${c}
25
- `)});let a=be(e.success,r);console.log(a)}};var Je=class o{state;constructor(){this.state={facts:new Map,choices:new Map,variables:new Map,stepResults:new Map,lastStepIndex:-1}}hasFact(e){return this.state.facts.has(e)}getFact(e){return this.state.facts.get(e)}setFact(e,t){this.state.facts.set(e,t)}getFactStatus(e){if(!this.hasFact(e))return"pending";let t=this.getFact(e);return t===!1||t==="failed"?"failed":"ready"}getAllFacts(){return new Map(this.state.facts)}hasChoice(e){return this.state.choices.has(e)}getChoice(e){return this.state.choices.get(e)}setChoice(e,t){this.state.choices.set(e,t)}hasVariable(e){return this.state.variables.has(e)}getVariable(e){return this.state.variables.get(e)}setVariable(e,t){this.state.variables.set(e,t)}getAllVariables(){return new Map(this.state.variables)}setStepResult(e,t,r){this.state.stepResults.set(e,{success:t,exitCode:r}),this.state.lastStepIndex=e}getStepResult(e){return this.state.stepResults.get(e)}getLastStepResult(){if(this.state.lastStepIndex!==-1)return this.state.stepResults.get(this.state.lastStepIndex)}clone(){let e=new o;return e.state.facts=new Map(this.state.facts),e.state.choices=new Map(this.state.choices),e.state.variables=new Map(this.state.variables),e.state.stepResults=new Map(this.state.stepResults),e.state.lastStepIndex=this.state.lastStepIndex,e}};var ve=class{workspace;taskRunner;choicePrompt;textPrompt;baseDir;globalShell;constructor(){this.workspace=new Je,this.taskRunner=new Ye,this.choicePrompt=new B,this.textPrompt=new Ve}resolveBaseDir(e){if(!e.baseDir){e._filePath&&(this.baseDir=(0,K.dirname)(e._filePath));return}if((0,K.isAbsolute)(e.baseDir))this.baseDir=e.baseDir;else if(e._filePath){let t=(0,K.dirname)(e._filePath);this.baseDir=(0,K.resolve)(t,e.baseDir)}else this.baseDir=(0,K.resolve)(process.cwd(),e.baseDir)}createStepContext(e,t){let r={workspace:this.workspace,stepIndex:e};return t._lineNumbers&&(r.lineNumber=t._lineNumbers.get(e)),t._fileName&&(r.fileName=t._fileName),r}evaluateStepCondition(e){return e.when?new pe(this.workspace).evaluate(e.when):!0}calculateBaseStepIndex(e){return e.branchIndex===void 0?e.stepIndex:Math.floor(e.stepIndex/yt)}isRunStep(e){return"run"in e}getRecordResolved(e){if("run"in e)return{resolvedCommand:de(e.run.trim(),this.workspace)};if("choose"in e){let t=e.choose.as&&this.workspace.hasVariable(e.choose.as)?this.workspace.getVariable(e.choose.as):e.choose.options.find(r=>this.workspace.getChoice(r.id))?.id;return t!==void 0?{choiceValue:t}:void 0}if("prompt"in e){let t=this.workspace.getFact(e.prompt.as);return t!==void 0?{promptValue:t}:void 0}}async execute(e,t){if(t?.executionVars&&Object.keys(t.executionVars).length>0)for(let[c,d]of Object.entries(t.executionVars))this.workspace.setVariable(c,d);this.resolveBaseDir(e),this.globalShell=e.shell;let r=new ze,s=Date.now();for(let c=0;c<e.steps.length;c++){let d=e.steps[c],f=this.createStepContext(c,e),m=!!d.when;if(this.evaluateStepCondition(d)){r.recordStart();try{let p=await this.executeStep(d,f,!1,m,r);"parallel"in d||this.handleStepResult(d,f,c,p,r)}catch(p){throw"parallel"in d||this.handleStepError(d,f,c,p,r),p}}}let i=Date.now()-s,n=ye(i);console.log(uo.default.cyan(`
26
- Total execution time: ${n}`));let a=r.getHistory(),l=He(a);l&&console.log(l),await r.save(),r.reset()}isStepSuccessful(e,t){return"run"in t?typeof e=="boolean"?e:e&&typeof e=="object"&&"success"in e?e.success:!1:!0}handleStepResult(e,t,r,s,i){let n=this.isRunStep(e)?(()=>{let d=this.workspace.getStepResult(r);return d?d.success:!0})():this.isStepSuccessful(s,e),a=n?"success":"failure",l=this.getRecordResolved(e),c=i.recordEnd(e,t,s,a,l);if(!this.isRunStep(e)){let d=be(n,!1,c);console.log(d)}if(this.isRunStep(e)){if(e.continue===!1){let d=t.lineNumber?` (line ${t.lineNumber})`:"",f=n?`Step ${r}${d} completed, but workflow stopped due to continue: false`:`Step ${r}${d} failed`;throw new Error(f)}if(!n&&e.continue!==!0){let d=t.lineNumber?` (line ${t.lineNumber})`:"";throw new Error(`Step ${r}${d} failed`)}}}handleStepError(e,t,r,s,i){this.workspace.setStepResult(r,!1);let n=s instanceof Error?s.message:String(s),a={success:!1,stdout:[],stderr:[n]},l=this.getRecordResolved(e);i.recordEnd(e,t,a,"failure",l)}fixMalformedStep(e){let r=e;return"choose"in e&&r.choose===null&&"message"in e&&"options"in e?{choose:{message:r.message,options:r.options,as:r.as},when:r.when}:"prompt"in e&&r.prompt===null&&"message"in e&&"as"in e?{prompt:{message:r.message,as:r.as,default:r.default},when:r.when}:e}async executeStep(e,t,r=!1,s=!1,i){if(e=this.fixMalformedStep(e),"run"in e){let n=await ao({workspace:this.workspace,taskRunner:this.taskRunner,baseDir:this.baseDir,globalShell:this.globalShell,calculateBaseStepIndex:a=>this.calculateBaseStepIndex(a)},e,t,r,s);return r&&typeof n=="object"&&"stdout"in n,n}if("choose"in e){await this.executeChooseStep(e,t);return}if("prompt"in e){await this.executePromptStep(e,t);return}if("parallel"in e){await oo({workspace:this.workspace,taskRunner:this.taskRunner,executeStep:(n,a,l)=>this.executeStep(n,a,l,!!n.when,i),setStepResult:(n,a)=>this.workspace.setStepResult(n,a),recordBranch:i?(n,a,l,c,d)=>{i.recordStart();let f=d||this.getRecordResolved(n);i.recordEnd(n,a,l,c,f)}:void 0},e,t);return}if("fail"in e){await this.executeFailStep(e,t);return}}async executeChooseStep(e,t){let r=e.choose.as,s=e.choose.options.map(a=>a.id);if(r&&this.workspace.hasVariable(r)){let a=this.workspace.getVariable(r)??"";if(s.includes(a)){this.workspace.setChoice(a,a),this.workspace.setStepResult(t.stepIndex,!0);return}}let i=await this.choicePrompt.prompt(e.choose.message,e.choose.options);if(!i?.id)throw new Error(`Invalid choice result: ${JSON.stringify(i)}`);let n=r??i.id;this.workspace.setChoice(i.id,i.id),this.workspace.setVariable(n,i.id),this.workspace.setStepResult(t.stepIndex,!0)}async executePromptStep(e,t){let r=e.prompt.as;if(this.workspace.hasVariable(r)){let a=this.workspace.getVariable(r)??"";this.workspace.setFact(r,a),this.workspace.setStepResult(t.stepIndex,!0);return}let s=de(e.prompt.message,this.workspace),i=e.prompt.default?de(e.prompt.default,this.workspace):void 0,n=await this.textPrompt.prompt(s,i);this.workspace.setVariable(r,n),this.workspace.setFact(r,n),this.workspace.setStepResult(t.stepIndex,!0)}async executeFailStep(e,t){let r=new Error(e.fail.message);throw r.stack=void 0,r}};var go=require("yaml"),Rt=require("zod");var u=require("zod"),_r=u.z.object({file:u.z.string()}),Ur=u.z.object({var:u.z.union([u.z.string(),u.z.record(u.z.string(),u.z.string())]).optional(),has:u.z.string().optional()}),zr=u.z.object({status:u.z.object({fact:u.z.string(),is:u.z.enum(["ready","failed","pending"])})}),Yr=u.z.object({step:u.z.object({success:u.z.boolean()}).optional(),last_step:u.z.enum(["success","failure"]).optional()}),Jr=u.z.object({choice:u.z.string()}),qr=u.z.union([_r,Jr,Ur,zr,Yr]),_=u.z.lazy(()=>u.z.union([qr,u.z.object({all:u.z.array(_)}),u.z.object({any:u.z.array(_)}),u.z.object({not:_})])),po=u.z.lazy(()=>u.z.object({run:u.z.string(),timeout:u.z.number().optional(),retry:u.z.union([u.z.number(),u.z.literal("Infinity")]).optional(),onError:po.optional()})),Gr=u.z.object({as:u.z.string()}),Zr=u.z.object({regex:u.z.string(),as:u.z.string()}),Xr=u.z.object({json:u.z.string(),as:u.z.string()}),Kr=u.z.object({yaml:u.z.string(),as:u.z.string()}),Qr=u.z.object({yml:u.z.string(),as:u.z.string()}),en=u.z.object({kv:u.z.string(),as:u.z.string()}),tn=u.z.object({after:u.z.string(),as:u.z.string()}),on=u.z.object({before:u.z.string(),as:u.z.string()}),rn=u.z.object({after:u.z.string(),before:u.z.string(),as:u.z.string()}),nn=u.z.object({line:u.z.object({from:u.z.number(),to:u.z.number()}),as:u.z.string()}),sn=u.z.union([Zr,Xr,Kr,Qr,en,rn,tn,on,nn,Gr]),mo=u.z.object({run:u.z.string(),when:_.optional(),timeout:u.z.number().optional(),retry:u.z.union([u.z.number(),u.z.literal("Infinity")]).optional(),shell:u.z.array(u.z.string()).min(1,"shell must have at least one element").optional(),continue:u.z.boolean().optional(),onError:po.optional(),captures:u.z.array(sn).optional()}),an=u.z.object({choose:u.z.object({message:u.z.string(),options:u.z.array(u.z.object({id:u.z.string(),label:u.z.string()})),as:u.z.string().optional()}),when:_.optional()}),ln=u.z.object({prompt:u.z.object({message:u.z.string(),as:u.z.string(),default:u.z.string().optional(),validate:u.z.string().optional()}),when:_.optional()});function fo(o){if(!o||typeof o!="object")return{found:!1};let e=o;if("choose"in e)return{found:!0,type:"choose"};if("prompt"in e)return{found:!0,type:"prompt"};if("parallel"in e&&Array.isArray(e.parallel))for(let t of e.parallel){let r=fo(t);if(r.found)return r}return{found:!1}}var ho=u.z.lazy(()=>u.z.union([mo,u.z.object({parallel:u.z.array(u.z.lazy(()=>ho)),when:_.optional()}),u.z.object({fail:u.z.object({message:u.z.string()}),when:_.optional()})]).superRefine((o,e)=>{let t=fo(o);t.found&&e.addIssue({code:u.z.ZodIssueCode.custom,message:`'${t.type}' step is not allowed inside 'parallel' block (user input cannot run in parallel)`})})),cn=u.z.lazy(()=>u.z.union([mo,an,ln,u.z.object({parallel:u.z.array(ho),when:_.optional()}),u.z.object({fail:u.z.object({message:u.z.string()}),when:_.optional()})])),un=u.z.object({name:u.z.string().min(1,"Profile name must be non-empty"),var:u.z.record(u.z.string(),u.z.union([u.z.string(),u.z.number(),u.z.boolean()]).transform(String))}),pn=u.z.object({name:u.z.string().optional(),baseDir:u.z.string().optional(),shell:u.z.array(u.z.string()).min(1,"shell must have at least one element").optional(),profiles:u.z.array(un).optional(),steps:u.z.array(cn).min(1,"Workflow must have at least one step")});function vt(o){return pn.parse(o)}function wo(o,e){let t=o.path;if(o.code==="custom"){let s=kt(t);return` - ${o.message}${s}`}if(o.message==="Invalid input"){let s=kt(t),i=dn(t,e);return i?` - ${i}${s}`:` - Invalid step type${s}`}let r=kt(t);return` - ${o.message}${r}`}function kt(o){if(o.length===0)return"";let e=[];for(let t=0;t<o.length;t++){let r=o[t],s=o[t+1];r==="steps"&&typeof s=="number"?(e.push(`step ${s+1}`),t++):r==="parallel"&&typeof s=="number"?(e.push(`parallel branch ${s+1}`),t++):typeof r=="string"&&r!=="steps"&&r!=="parallel"&&e.push(r)}return e.length>0?` (${e.join(" \u2192 ")})`:""}function I(o,e,t){let r=t?`
27
+ `)});let a=be(e.success,r);console.log(a)}};var Je=class o{state;constructor(){this.state={facts:new Map,choices:new Map,variables:new Map,stepResults:new Map,lastStepIndex:-1}}hasFact(e){return this.state.facts.has(e)}getFact(e){return this.state.facts.get(e)}setFact(e,t){this.state.facts.set(e,t)}getFactStatus(e){if(!this.hasFact(e))return"pending";let t=this.getFact(e);return t===!1||t==="failed"?"failed":"ready"}getAllFacts(){return new Map(this.state.facts)}hasChoice(e){return this.state.choices.has(e)}getChoice(e){return this.state.choices.get(e)}setChoice(e,t){this.state.choices.set(e,t)}hasVariable(e){return this.state.variables.has(e)}getVariable(e){return this.state.variables.get(e)}setVariable(e,t){this.state.variables.set(e,t)}getAllVariables(){return new Map(this.state.variables)}setStepResult(e,t,r){this.state.stepResults.set(e,{success:t,exitCode:r}),this.state.lastStepIndex=e}getStepResult(e){return this.state.stepResults.get(e)}getLastStepResult(){if(this.state.lastStepIndex!==-1)return this.state.stepResults.get(this.state.lastStepIndex)}clone(){let e=new o;return e.state.facts=new Map(this.state.facts),e.state.choices=new Map(this.state.choices),e.state.variables=new Map(this.state.variables),e.state.stepResults=new Map(this.state.stepResults),e.state.lastStepIndex=this.state.lastStepIndex,e}};var ve=class{workspace;taskRunner;choicePrompt;textPrompt;baseDir;globalShell;constructor(){this.workspace=new Je,this.taskRunner=new Ye,this.choicePrompt=new O,this.textPrompt=new Ve}resolveBaseDir(e){if(!e.baseDir){e._filePath&&(this.baseDir=(0,K.dirname)(e._filePath));return}if((0,K.isAbsolute)(e.baseDir))this.baseDir=e.baseDir;else if(e._filePath){let t=(0,K.dirname)(e._filePath);this.baseDir=(0,K.resolve)(t,e.baseDir)}else this.baseDir=(0,K.resolve)(process.cwd(),e.baseDir)}createStepContext(e,t){let r={workspace:this.workspace,stepIndex:e};return t._lineNumbers&&(r.lineNumber=t._lineNumbers.get(e)),t._fileName&&(r.fileName=t._fileName),r}evaluateStepCondition(e){return e.when?new pe(this.workspace).evaluate(e.when):!0}calculateBaseStepIndex(e){return e.branchIndex===void 0?e.stepIndex:Math.floor(e.stepIndex/yt)}isRunStep(e){return"run"in e}getRecordResolved(e){if("run"in e)return{resolvedCommand:de(e.run.trim(),this.workspace)};if("choose"in e){let t=e.choose.as&&this.workspace.hasVariable(e.choose.as)?this.workspace.getVariable(e.choose.as):e.choose.options.find(r=>this.workspace.getChoice(r.id))?.id;return t!==void 0?{choiceValue:t}:void 0}if("prompt"in e){let t=this.workspace.getFact(e.prompt.as);return t!==void 0?{promptValue:t}:void 0}}async execute(e,t){if(t?.executionVars&&Object.keys(t.executionVars).length>0)for(let[c,d]of Object.entries(t.executionVars))this.workspace.setVariable(c,d);this.resolveBaseDir(e),this.globalShell=e.shell;let r=new ze,s=Date.now();for(let c=0;c<e.steps.length;c++){let d=e.steps[c],f=this.createStepContext(c,e),m=!!d.when;if(this.evaluateStepCondition(d)){r.recordStart();try{let p=await this.executeStep(d,f,!1,m,r);"parallel"in d||this.handleStepResult(d,f,c,p,r)}catch(p){throw"parallel"in d||this.handleStepError(d,f,c,p,r),p}}}let i=Date.now()-s,n=ye(i);console.log(uo.default.cyan(`
28
+ Total execution time: ${n}`));let a=r.getHistory(),l=He(a);l&&console.log(l),await r.save(),r.reset()}isStepSuccessful(e,t){return"run"in t?typeof e=="boolean"?e:e&&typeof e=="object"&&"success"in e?e.success:!1:!0}handleStepResult(e,t,r,s,i){let n=this.isRunStep(e)?(()=>{let d=this.workspace.getStepResult(r);return d?d.success:!0})():this.isStepSuccessful(s,e),a=n?"success":"failure",l=this.getRecordResolved(e),c=i.recordEnd(e,t,s,a,l);if(!this.isRunStep(e)){let d=be(n,!1,c);console.log(d)}if(this.isRunStep(e)){if(e.continue===!1){let d=t.lineNumber?` (line ${t.lineNumber})`:"",f=n?`Step ${r}${d} completed, but workflow stopped due to continue: false`:`Step ${r}${d} failed`;throw new Error(f)}if(!n&&e.continue!==!0){let d=t.lineNumber?` (line ${t.lineNumber})`:"";throw new Error(`Step ${r}${d} failed`)}}}handleStepError(e,t,r,s,i){this.workspace.setStepResult(r,!1);let n=s instanceof Error?s.message:String(s),a={success:!1,stdout:[],stderr:[n]},l=this.getRecordResolved(e);i.recordEnd(e,t,a,"failure",l)}fixMalformedStep(e){let r=e;return"choose"in e&&r.choose===null&&"message"in e&&"options"in e?{choose:{message:r.message,options:r.options,as:r.as},when:r.when}:"prompt"in e&&r.prompt===null&&"message"in e&&"as"in e?{prompt:{message:r.message,as:r.as,default:r.default},when:r.when}:e}async executeStep(e,t,r=!1,s=!1,i){if(e=this.fixMalformedStep(e),"run"in e){let n=await ao({workspace:this.workspace,taskRunner:this.taskRunner,baseDir:this.baseDir,globalShell:this.globalShell,calculateBaseStepIndex:a=>this.calculateBaseStepIndex(a)},e,t,r,s);return r&&typeof n=="object"&&"stdout"in n,n}if("choose"in e){await this.executeChooseStep(e,t);return}if("prompt"in e){await this.executePromptStep(e,t);return}if("parallel"in e){await oo({workspace:this.workspace,taskRunner:this.taskRunner,executeStep:(n,a,l)=>this.executeStep(n,a,l,!!n.when,i),setStepResult:(n,a)=>this.workspace.setStepResult(n,a),recordBranch:i?(n,a,l,c,d)=>{i.recordStart();let f=d??this.getRecordResolved(n);i.recordEnd(n,a,l,c,f)}:void 0},e,t);return}if("fail"in e){await this.executeFailStep(e,t);return}}async executeChooseStep(e,t){let r=e.choose.as,s=e.choose.options.map(a=>a.id);if(r&&this.workspace.hasVariable(r)){let a=this.workspace.getVariable(r)??"";if(s.includes(a)){this.workspace.setChoice(a,a),this.workspace.setStepResult(t.stepIndex,!0);return}}let i=await this.choicePrompt.prompt(e.choose.message,e.choose.options);if(!i?.id)throw new Error(`Invalid choice result: ${JSON.stringify(i)}`);let n=r??i.id;this.workspace.setChoice(i.id,i.id),this.workspace.setVariable(n,i.id),this.workspace.setStepResult(t.stepIndex,!0)}async executePromptStep(e,t){let r=e.prompt.as;if(this.workspace.hasVariable(r)){let a=this.workspace.getVariable(r)??"";this.workspace.setFact(r,a),this.workspace.setStepResult(t.stepIndex,!0);return}let s=de(e.prompt.message,this.workspace),i=e.prompt.default?de(e.prompt.default,this.workspace):void 0,n=await this.textPrompt.prompt(s,i);this.workspace.setVariable(r,n),this.workspace.setFact(r,n),this.workspace.setStepResult(t.stepIndex,!0)}async executeFailStep(e,t){let r=new Error(e.fail.message);throw r.stack=void 0,r}};var go=require("yaml"),Rt=require("zod");var u=require("zod"),_r=u.z.object({file:u.z.string()}),Ur=u.z.object({var:u.z.union([u.z.string(),u.z.record(u.z.string(),u.z.string())]).optional(),has:u.z.string().optional()}),zr=u.z.object({status:u.z.object({fact:u.z.string(),is:u.z.enum(["ready","failed","pending"])})}),Yr=u.z.object({step:u.z.object({success:u.z.boolean()}).optional(),last_step:u.z.enum(["success","failure"]).optional()}),Jr=u.z.object({choice:u.z.string()}),qr=u.z.union([_r,Jr,Ur,zr,Yr]),_=u.z.lazy(()=>u.z.union([qr,u.z.object({all:u.z.array(_)}),u.z.object({any:u.z.array(_)}),u.z.object({not:_})])),po=u.z.lazy(()=>u.z.object({run:u.z.string(),timeout:u.z.number().optional(),retry:u.z.union([u.z.number(),u.z.literal("Infinity")]).optional(),onError:po.optional()})),Gr=u.z.object({as:u.z.string()}),Zr=u.z.object({regex:u.z.string(),as:u.z.string()}),Xr=u.z.object({json:u.z.string(),as:u.z.string()}),Kr=u.z.object({yaml:u.z.string(),as:u.z.string()}),Qr=u.z.object({yml:u.z.string(),as:u.z.string()}),en=u.z.object({kv:u.z.string(),as:u.z.string()}),tn=u.z.object({after:u.z.string(),as:u.z.string()}),on=u.z.object({before:u.z.string(),as:u.z.string()}),rn=u.z.object({after:u.z.string(),before:u.z.string(),as:u.z.string()}),nn=u.z.object({line:u.z.object({from:u.z.number(),to:u.z.number()}),as:u.z.string()}),sn=u.z.union([Zr,Xr,Kr,Qr,en,rn,tn,on,nn,Gr]),mo=u.z.object({run:u.z.string(),when:_.optional(),timeout:u.z.number().optional(),retry:u.z.union([u.z.number(),u.z.literal("Infinity")]).optional(),shell:u.z.array(u.z.string()).min(1,"shell must have at least one element").optional(),continue:u.z.boolean().optional(),onError:po.optional(),captures:u.z.array(sn).optional()}),an=u.z.object({choose:u.z.object({message:u.z.string(),options:u.z.array(u.z.object({id:u.z.string(),label:u.z.string()})),as:u.z.string().optional()}),when:_.optional()}),ln=u.z.object({prompt:u.z.object({message:u.z.string(),as:u.z.string(),default:u.z.string().optional(),validate:u.z.string().optional()}),when:_.optional()});function fo(o){if(!o||typeof o!="object")return{found:!1};let e=o;if("choose"in e)return{found:!0,type:"choose"};if("prompt"in e)return{found:!0,type:"prompt"};if("parallel"in e&&Array.isArray(e.parallel))for(let t of e.parallel){let r=fo(t);if(r.found)return r}return{found:!1}}var ho=u.z.lazy(()=>u.z.union([mo,u.z.object({parallel:u.z.array(u.z.lazy(()=>ho)),when:_.optional()}),u.z.object({fail:u.z.object({message:u.z.string()}),when:_.optional()})]).superRefine((o,e)=>{let t=fo(o);t.found&&e.addIssue({code:u.z.ZodIssueCode.custom,message:`'${t.type}' step is not allowed inside 'parallel' block (user input cannot run in parallel)`})})),cn=u.z.lazy(()=>u.z.union([mo,an,ln,u.z.object({parallel:u.z.array(ho),when:_.optional()}),u.z.object({fail:u.z.object({message:u.z.string()}),when:_.optional()})])),un=u.z.object({name:u.z.string().min(1,"Profile name must be non-empty"),var:u.z.record(u.z.string(),u.z.union([u.z.string(),u.z.number(),u.z.boolean()]).transform(String))}),pn=u.z.object({name:u.z.string().optional(),baseDir:u.z.string().optional(),shell:u.z.array(u.z.string()).min(1,"shell must have at least one element").optional(),profiles:u.z.array(un).optional(),steps:u.z.array(cn).min(1,"Workflow must have at least one step")});function vt(o){return pn.parse(o)}function wo(o,e){let t=o.path;if(o.code==="custom"){let s=kt(t);return` - ${o.message}${s}`}if(o.message==="Invalid input"){let s=kt(t),i=dn(t,e);return i?` - ${i}${s}`:` - Invalid step type${s}`}let r=kt(t);return` - ${o.message}${r}`}function kt(o){if(o.length===0)return"";let e=[];for(let t=0;t<o.length;t++){let r=o[t],s=o[t+1];r==="steps"&&typeof s=="number"?(e.push(`step ${s+1}`),t++):r==="parallel"&&typeof s=="number"?(e.push(`parallel branch ${s+1}`),t++):typeof r=="string"&&r!=="steps"&&r!=="parallel"&&e.push(r)}return e.length>0?` (${e.join(" \u2192 ")})`:""}function T(o,e,t){let r=t?`
27
29
  Reason: ${t}`:"";throw new Error(`Invalid workflow structure:
28
- - ${e} (step ${o+1})${r}`)}function bo(o,e,t=!1,r=[]){let s=["run","choose","prompt","parallel","fail"],i=s.find(n=>n in o);if(!i){let n=Object.keys(o).filter(a=>a!=="when");I(e,`Unknown step type. Found keys: [${n.join(", ")}]. Valid types: ${s.join(", ")}`)}if(i==="run"){let n=o.run;if(typeof n!="string"&&I(e,"'run' must be a string command"),n===""&&I(e,"'run' command cannot be empty"),"shell"in o&&o.shell!==void 0){Array.isArray(o.shell)||I(e,"'shell' must be an array");let a=o.shell;a.length===0&&I(e,"'shell' cannot be empty","Shell configuration must have at least one element (program name)");for(let l=0;l<a.length;l++)typeof a[l]!="string"&&I(e,`'shell[${l}]' must be a string`)}}if(i==="choose"){if(t){let l=r.join(" \u2192 ");throw new Error(`Invalid workflow structure:
30
+ - ${e} (step ${o+1})${r}`)}function bo(o,e,t=!1,r=[]){let s=["run","choose","prompt","parallel","fail"],i=s.find(n=>n in o);if(!i){let n=Object.keys(o).filter(a=>a!=="when");T(e,`Unknown step type. Found keys: [${n.join(", ")}]. Valid types: ${s.join(", ")}`)}if(i==="run"){let n=o.run;if(typeof n!="string"&&T(e,"'run' must be a string command"),n===""&&T(e,"'run' command cannot be empty"),"shell"in o&&o.shell!==void 0){Array.isArray(o.shell)||T(e,"'shell' must be an array");let a=o.shell;a.length===0&&T(e,"'shell' cannot be empty","Shell configuration must have at least one element (program name)");for(let l=0;l<a.length;l++)typeof a[l]!="string"&&T(e,`'shell[${l}]' must be a string`)}}if(i==="choose"){if(t){let l=r.join(" \u2192 ");throw new Error(`Invalid workflow structure:
29
31
  - 'choose' step is not allowed inside 'parallel' block (step ${e+1}, ${l})
30
- Reason: User input prompts cannot run in parallel`)}let n=o.choose;(!n||typeof n!="object")&&I(e,"'choose' must be an object with 'message' and 'options'");let a=n;(!a.message||typeof a.message!="string")&&I(e,"'choose.message' is required and must be a string"),Array.isArray(a.options)||I(e,"'choose.options' is required and must be an array"),a.options.length===0&&I(e,"'choose.options' cannot be empty","At least one option is required");for(let l=0;l<a.options.length;l++){let c=a.options[l];(!c||typeof c!="object")&&I(e,`'choose.options[${l}]' must be an object with 'id' and 'label'`),(!c.id||typeof c.id!="string")&&I(e,`'choose.options[${l}].id' is required and must be a string`),(!c.label||typeof c.label!="string")&&I(e,`'choose.options[${l}].label' is required and must be a string`)}}if(i==="prompt"){if(t){let l=r.join(" \u2192 ");throw new Error(`Invalid workflow structure:
32
+ Reason: User input prompts cannot run in parallel`)}let n=o.choose;(!n||typeof n!="object")&&T(e,"'choose' must be an object with 'message' and 'options'");let a=n;(!a.message||typeof a.message!="string")&&T(e,"'choose.message' is required and must be a string"),Array.isArray(a.options)||T(e,"'choose.options' is required and must be an array"),a.options.length===0&&T(e,"'choose.options' cannot be empty","At least one option is required");for(let l=0;l<a.options.length;l++){let c=a.options[l];(!c||typeof c!="object")&&T(e,`'choose.options[${l}]' must be an object with 'id' and 'label'`),(!c.id||typeof c.id!="string")&&T(e,`'choose.options[${l}].id' is required and must be a string`),(!c.label||typeof c.label!="string")&&T(e,`'choose.options[${l}].label' is required and must be a string`)}}if(i==="prompt"){if(t){let l=r.join(" \u2192 ");throw new Error(`Invalid workflow structure:
31
33
  - 'prompt' step is not allowed inside 'parallel' block (step ${e+1}, ${l})
32
- Reason: User input prompts cannot run in parallel`)}let n=o.prompt;(!n||typeof n!="object")&&I(e,"'prompt' must be an object with 'message' and 'as'");let a=n;(!a.message||typeof a.message!="string")&&I(e,"'prompt.message' is required and must be a string"),(!a.as||typeof a.as!="string")&&I(e,"'prompt.as' is required and must be a string","The 'as' field specifies the variable name to store the user's input")}if(i==="parallel"){let n=o.parallel;Array.isArray(n)||I(e,"'parallel' must be an array of steps"),n.length===0&&I(e,"'parallel' cannot be empty","At least one step is required");for(let a=0;a<n.length;a++){let l=n[a];(!l||typeof l!="object")&&I(e,`'parallel[${a}]' must be a valid step object`);let c=[...r,`branch ${a+1}`];bo(l,e,!0,c)}}if(i==="fail"){let n=o.fail;(!n||typeof n!="object")&&I(e,"'fail' must be an object with 'message'");let a=n;(!a.message||typeof a.message!="string")&&I(e,"'fail.message' is required and must be a string")}}function yo(o){if(!o||typeof o!="object")throw new Error(`Invalid workflow structure:
34
+ Reason: User input prompts cannot run in parallel`)}let n=o.prompt;(!n||typeof n!="object")&&T(e,"'prompt' must be an object with 'message' and 'as'");let a=n;(!a.message||typeof a.message!="string")&&T(e,"'prompt.message' is required and must be a string"),(!a.as||typeof a.as!="string")&&T(e,"'prompt.as' is required and must be a string","The 'as' field specifies the variable name to store the user's input")}if(i==="parallel"){let n=o.parallel;Array.isArray(n)||T(e,"'parallel' must be an array of steps"),n.length===0&&T(e,"'parallel' cannot be empty","At least one step is required");for(let a=0;a<n.length;a++){let l=n[a];(!l||typeof l!="object")&&T(e,`'parallel[${a}]' must be a valid step object`);let c=[...r,`branch ${a+1}`];bo(l,e,!0,c)}}if(i==="fail"){let n=o.fail;(!n||typeof n!="object")&&T(e,"'fail' must be an object with 'message'");let a=n;(!a.message||typeof a.message!="string")&&T(e,"'fail.message' is required and must be a string")}}function yo(o){if(!o||typeof o!="object")throw new Error(`Invalid workflow structure:
33
35
  - Workflow must be an object`);let e=o;if("name"in e&&e.name!==void 0&&typeof e.name!="string")throw new Error(`Invalid workflow structure:
34
36
  - 'name' must be a string`);if("shell"in e&&e.shell!==void 0){if(!Array.isArray(e.shell))throw new Error(`Invalid workflow structure:
35
37
  - 'shell' must be an array`);if(e.shell.length===0)throw new Error(`Invalid workflow structure:
@@ -46,51 +48,51 @@ ${s}`)}throw r}}extractStepLineNumbers(e){let t=new Map,r=e.split(`
46
48
  `),s=0,i=!1;for(let n=0;n<r.length;n++){let a=r[n].trim();if(a==="steps:"||a.startsWith("steps:")){i=!0;continue}i&&a.startsWith("-")&&t.set(s++,n+1)}return t}},$t=class{parse(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON format: ${r instanceof Error?r.message:String(r)}`)}if(t&&typeof t=="object"&&"steps"in t){let r=t;Array.isArray(r.steps)&&(r.steps=r.steps.map(s=>Et(s)))}yo(t);try{return vt(t)}catch(r){if(r instanceof Rt.ZodError){let s=r.issues.map(i=>wo(i,t)).filter(i=>i!==null).join(`
47
49
  `);throw new Error(`Invalid workflow structure:
48
50
  ${s}`)}throw r}}extractStepLineNumbers(e){let t=new Map,r=e.split(`
49
- `),s=0,i=!1,n=!1;for(let a=0;a<r.length;a++){let c=r[a].trim();if(c.startsWith('"steps"')||c.startsWith("'steps'")){i=!0,c.includes("[")&&(n=!0);continue}if(i&&c==="["){n=!0;continue}if(n&&c==="]"){n=!1,i=!1;continue}n&&c.startsWith("{")&&t.set(s++,a+1)}return t}};function ke(o){switch(o.toLowerCase().split(".").pop()){case"yaml":case"yml":return new qe;case"json":return new $t;default:return new qe}}var ko=require("fs/promises"),$o=require("path"),Ze=x(require("boxen"),1),U=x(require("chalk"),1),Ct=x(require("node-cron"),1);ge();var $e=require("fs/promises"),xo=require("os"),Pt=require("path"),vo=(0,Pt.join)((0,xo.homedir)(),".pipeliner","schedules"),So=(0,Pt.join)(vo,"schedules.json"),W=class{async loadSchedules(){try{let e=await(0,$e.readFile)(So,"utf-8");return JSON.parse(e).schedules||[]}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return[];throw e}}async saveSchedules(e){await(0,$e.mkdir)(vo,{recursive:!0}),await(0,$e.writeFile)(So,JSON.stringify({schedules:e},null,2),"utf-8")}async addSchedule(e){let t=await this.loadSchedules(),r=Math.random().toString(36).slice(2,10),s=new Date().toISOString(),i={id:r,createdAt:s,...e};return t.push(i),await this.saveSchedules(t),i}async removeSchedule(e){let t=await this.loadSchedules(),r=t.length,s=t.filter(i=>i.id!==e);return s.length===r?!1:(await this.saveSchedules(s),!0)}async updateLastRun(e){let t=await this.loadSchedules(),r=t.find(s=>s.id===e);r&&(r.lastRun=new Date().toISOString(),await this.saveSchedules(t))}async toggleSchedule(e,t){let r=await this.loadSchedules(),s=r.find(i=>i.id===e);return s?(s.enabled=t,await this.saveSchedules(r),!0):!1}async getSchedule(e){return(await this.loadSchedules()).find(r=>r.id===e)}};var mn=/^([+-])?(\d{1,2})(?::(\d{2}))?$/;function fn(o){let e=o.trim();if(e===""||e==="0"||e==="+0"||e==="-0")return 0;let t=e.match(mn);if(!t)return null;let r=t[1],s=parseInt(t[2],10);if(s>14)return null;let n=r==="-"?-s:s;return n<-12||n>14?null:n}function hn(o){if(o===0)return"UTC";let e=o>0?"-":"+",t=Math.abs(o);return`Etc/GMT${e}${t}`}function Ge(o){if(!o?.trim())return;let e=fn(o);if(e!==null)return hn(e)}var Q=class{scheduleManager;tasks=new Map;startOptions;constructor(){this.scheduleManager=new W}async start(e=!1,t){if(this.startOptions=t,!e&&await Y()){let s=await N();throw new Error(`Scheduler daemon is already running (PID: ${s.pid}). Use "tp schedule stop" to stop it first.`)}if(e)console.log("\u{1F680} Starting scheduler daemon in background...");else{let s=U.default.bold("\u{1F680} Starting workflow scheduler...");console.log((0,Ze.default)(s,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"cyan"}))}if(await this.reload(),e){if(!process.env.TP_DAEMON_MODE){let s=[U.default.green("\u2713 Scheduler daemon started"),"",U.default.gray(`PID: ${process.pid}`),U.default.dim(" tp schedule stop stop daemon"),U.default.dim(" tp schedule status check status")].join(`
51
+ `),s=0,i=!1,n=!1;for(let a=0;a<r.length;a++){let c=r[a].trim();if(c.startsWith('"steps"')||c.startsWith("'steps'")){i=!0,c.includes("[")&&(n=!0);continue}if(i&&c==="["){n=!0;continue}if(n&&c==="]"){n=!1,i=!1;continue}n&&c.startsWith("{")&&t.set(s++,a+1)}return t}};function ke(o){switch(o.toLowerCase().split(".").pop()){case"yaml":case"yml":return new qe;case"json":return new $t;default:return new qe}}var ko=require("fs/promises"),$o=require("path"),Ze=x(require("boxen"),1),U=x(require("chalk"),1),Ct=x(require("node-cron"),1);ge();var $e=require("fs/promises"),xo=require("os"),Pt=require("path"),vo=(0,Pt.join)((0,xo.homedir)(),".pipeliner","schedules"),So=(0,Pt.join)(vo,"schedules.json"),V=class{async loadSchedules(){try{let e=await(0,$e.readFile)(So,"utf-8");return JSON.parse(e).schedules||[]}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return[];throw e}}async saveSchedules(e){await(0,$e.mkdir)(vo,{recursive:!0}),await(0,$e.writeFile)(So,JSON.stringify({schedules:e},null,2),"utf-8")}async addSchedule(e){let t=await this.loadSchedules(),r=Math.random().toString(36).slice(2,10),s=new Date().toISOString(),i={id:r,createdAt:s,...e};return t.push(i),await this.saveSchedules(t),i}async removeSchedule(e){let t=await this.loadSchedules(),r=t.length,s=t.filter(i=>i.id!==e);return s.length===r?!1:(await this.saveSchedules(s),!0)}async updateLastRun(e){let t=await this.loadSchedules(),r=t.find(s=>s.id===e);r&&(r.lastRun=new Date().toISOString(),await this.saveSchedules(t))}async toggleSchedule(e,t){let r=await this.loadSchedules(),s=r.find(i=>i.id===e);return s?(s.enabled=t,await this.saveSchedules(r),!0):!1}async getSchedule(e){return(await this.loadSchedules()).find(r=>r.id===e)}};var mn=/^([+-])?(\d{1,2})(?::(\d{2}))?$/;function fn(o){let e=o.trim();if(e===""||e==="0"||e==="+0"||e==="-0")return 0;let t=e.match(mn);if(!t)return null;let r=t[1],s=parseInt(t[2],10);if(s>14)return null;let n=r==="-"?-s:s;return n<-12||n>14?null:n}function hn(o){if(o===0)return"UTC";let e=o>0?"-":"+",t=Math.abs(o);return`Etc/GMT${e}${t}`}function Ge(o){if(!o?.trim())return;let e=fn(o);if(e!==null)return hn(e)}var Q=class{scheduleManager;tasks=new Map;startOptions;constructor(){this.scheduleManager=new V}async start(e=!1,t){if(this.startOptions=t,!e&&await Y()){let s=await j();throw new Error(`Scheduler daemon is already running (PID: ${s.pid}). Use "tp schedule stop" to stop it first.`)}if(e)console.log("\u{1F680} Starting scheduler daemon in background...");else{let s=U.default.bold("\u{1F680} Starting workflow scheduler...");console.log((0,Ze.default)(s,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"cyan"}))}if(await this.reload(),e){if(!process.env.TP_DAEMON_MODE){let s=[U.default.green("\u2713 Scheduler daemon started"),"",U.default.gray(`PID: ${process.pid}`),U.default.dim(" tp schedule stop stop daemon"),U.default.dim(" tp schedule status check status")].join(`
50
52
  `);console.log(`${(0,Ze.default)(s,{borderStyle:"round",padding:{top:1,bottom:1,left:2,right:2},borderColor:"green"})}
51
53
  `)}}else{let s=[U.default.green("\u2713 Scheduler is running"),U.default.dim(" Press Ctrl+C to stop")].join(`
52
54
  `);console.log((0,Ze.default)(s,{borderStyle:"round",padding:{top:0,bottom:0,left:2,right:2},margin:{top:0,bottom:0,left:0,right:0},borderColor:"green"}))}let r=async()=>{e||console.log(`
53
55
  \u23F9 Stopping scheduler...`),this.stop(),await Ce(),e||process.exit(0)};process.on("SIGINT",r),process.on("SIGTERM",r),e&&process.stdin.destroy()}async reload(){this.stop();let t=(await this.scheduleManager.loadSchedules()).filter(r=>r.enabled);if(t.length===0){console.log(U.default.gray(` No enabled schedules to load.
54
56
  `));return}for(let r of t)try{this.startSchedule(r)}catch(s){console.error(U.default.red(` \u2717 Failed to start schedule ${r.id}:`),s)}}startSchedule(e){if(!Ct.default.validate(e.cron)){console.error(` \u2717 Invalid cron expression for schedule ${e.id}: ${e.cron}`);return}let t={},r=Ge(e.timezone);r&&(t.timezone=r);let s;try{s=Ct.default.schedule(e.cron,async()=>{await this.executeSchedule(e)},t)}catch(i){throw console.error(` \u2717 Cron schedule failed for ${e.id} (timezone: ${r??"local"}).`,i instanceof Error?i.message:i),i}this.tasks.set(e.id,s),this.startOptions?.onScheduleStarted?.(e)}async executeSchedule(e){let t=e.name??e.workflowPath;e.silent||(console.log(`
55
- \u23F0 Running scheduled workflow: ${t}`),console.log(` Time: ${new Date().toISOString()}`),e.profile&&console.log(` Profile: ${e.profile}`));try{let r=(0,$o.resolve)(e.workflowPath),s=ke(r),i=await(0,ko.readFile)(r,"utf-8"),n=s.parse(i);n._filePath=r,n._fileName=r.split(/[/\\]/).pop()||"workflow";let a=new ve,l={};if(e.profile){if(!n.profiles)throw new Error(`Profile "${e.profile}" not found: no profiles defined in workflow`);let c=n.profiles.find(d=>d.name===e.profile);if(!c)throw new Error(`Profile "${e.profile}" not found. Available profiles: ${n.profiles.map(d=>d.name).join(", ")}`);l.executionVars={...c.var}}await a.execute(n,l),await this.scheduleManager.updateLastRun(e.id),e.silent||console.log(`\u2713 Scheduled workflow completed: ${t}
57
+ \u23F0 Running scheduled workflow: ${t}`),console.log(` Time: ${new Date().toISOString()}`),e.profile&&console.log(` Profile: ${e.profile}`));try{let r=(0,$o.resolve)(e.workflowPath),s=ke(r),i=await(0,ko.readFile)(r,"utf-8"),n=s.parse(i);n._filePath=r,n._fileName=r.split(/[/\\]/).pop()??"workflow";let a=new ve,l={};if(e.profile){if(!n.profiles)throw new Error(`Profile "${e.profile}" not found: no profiles defined in workflow`);let c=n.profiles.find(d=>d.name===e.profile);if(!c)throw new Error(`Profile "${e.profile}" not found. Available profiles: ${n.profiles.map(d=>d.name).join(", ")}`);l.executionVars={...c.var}}await a.execute(n,l),await this.scheduleManager.updateLastRun(e.id),e.silent||console.log(`\u2713 Scheduled workflow completed: ${t}
56
58
  `)}catch(r){e.silent||(console.error(`\u2717 Scheduled workflow failed: ${t}`),console.error(` Error: ${r instanceof Error?r.message:String(r)}
57
- `))}}stop(){for(let e of this.tasks.values())e.stop();this.tasks.clear()}async stopDaemon(){let e=await N();if(!e.running||!e.pid)return!1;let t=e.pid;try{if(process.kill(t,"SIGTERM"),await new Promise(r=>setTimeout(r,1e3)),await Y()){try{process.kill(t,"SIGKILL")}catch{}await new Promise(r=>setTimeout(r,500))}return await Ce(),!0}catch{return await Ce(),!1}}};var Dt=x(require("boxen"),1),v=x(require("chalk"),1),Ro=x(require("dayjs"),1);function Eo(o,e){console.log();let t=o.records.reduce((c,d)=>c+d.duration,0),r=o.records.filter(c=>c.status==="success").length,s=o.records.filter(c=>c.status==="failure").length,i=(0,Ro.default)(o.initialTimestamp).format("YYYY-MM-DD HH:mm:ss"),n=ye(t),a=[v.default.bold("Workflow Execution History"),"",`${v.default.cyan("File:")} ${e}`,`${v.default.cyan("Started:")} ${i}`,`${v.default.cyan("Total Duration:")} ${n}`,`${v.default.cyan("Total Steps:")} ${o.records.length}`,`${v.default.green("\u2713 Successful:")} ${r}`,s>0?`${v.default.red("\u2717 Failed:")} ${s}`:""].filter(Boolean).join(`
59
+ `))}}stop(){for(let e of this.tasks.values())e.stop();this.tasks.clear()}async stopDaemon(){let e=await j();if(!e.running||!e.pid)return!1;let t=e.pid;try{if(process.kill(t,"SIGTERM"),await new Promise(r=>setTimeout(r,1e3)),await Y()){try{process.kill(t,"SIGKILL")}catch{}await new Promise(r=>setTimeout(r,500))}return await Ce(),!0}catch{return await Ce(),!1}}};var Dt=x(require("boxen"),1),v=x(require("chalk"),1),Ro=x(require("dayjs"),1);function Eo(o,e){console.log();let t=o.records.reduce((c,d)=>c+d.duration,0),r=o.records.filter(c=>c.status==="success").length,s=o.records.filter(c=>c.status==="failure").length,i=(0,Ro.default)(o.initialTimestamp).format("YYYY-MM-DD HH:mm:ss"),n=ye(t),a=[v.default.bold("Workflow Execution History"),"",`${v.default.cyan("File:")} ${e}`,`${v.default.cyan("Started:")} ${i}`,`${v.default.cyan("Total Duration:")} ${n}`,`${v.default.cyan("Total Steps:")} ${o.records.length}`,`${v.default.green("\u2713 Successful:")} ${r}`,s>0?`${v.default.red("\u2717 Failed:")} ${s}`:""].filter(Boolean).join(`
58
60
  `);console.log((0,Dt.default)(a,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"cyan"})),o.records.forEach((c,d)=>{gn(c,d+1,o.records.length)});let l=He(o);l&&console.log(l),console.log()}function gn(o,e,t){let r=wn(o.step),s=bn(o),i=o.status==="success"?v.default.green("\u2713"):v.default.red("\u2717"),n=o.status==="success"?v.default.green("Success"):v.default.red("Failed"),a=ye(o.duration),l=[`${i} ${v.default.bold(`Step ${e}/${t}`)} - ${v.default.cyan(r)}`,`${v.default.gray("Duration:")} ${a} | ${v.default.gray("Status:")} ${n}`,"",v.default.white(s)].join(`
59
61
  `);console.log((0,Dt.default)(l,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:o.status==="success"?"green":"red"})),yn(o.output)&&Sn(o.output)}function wn(o){return"run"in o?"Run":"choose"in o?"Choose":"prompt"in o?"Prompt":"parallel"in o?"Parallel":"fail"in o?"Fail":"Unknown"}function bn(o){let e=o.step,t=[];if("run"in e){let r=o.resolvedCommand,s=r??e.run;t.push(`Command: ${v.default.yellow(s)}`),r&&r!==e.run&&t.push(`${v.default.gray("Template:")} ${v.default.gray(e.run)}`)}else if("choose"in e){if(t.push(`Message: ${v.default.yellow(e.choose.message)}`),o.choiceValue!==void 0){let r=e.choose.options.find(s=>s.id===o.choiceValue)?.label??o.choiceValue;t.push(`${v.default.gray("Selected:")} ${v.default.cyan(o.choiceValue)}${r!==o.choiceValue?` (${r})`:""}`)}}else"prompt"in e?(t.push(`Message: ${v.default.yellow(e.prompt.message)} | Variable: ${v.default.cyan(e.prompt.as)}`),o.promptValue!==void 0&&t.push(`${v.default.gray("Entered:")} ${v.default.cyan(String(o.promptValue))}`)):"parallel"in e?t.push(`Parallel execution with ${e.parallel.length} branches`):"fail"in e?t.push(`Error: ${v.default.red(e.fail.message)}`):t.push("Unknown step type");return t.join(`
60
62
  `)}function yn(o){return typeof o=="object"&&o!==null&&"success"in o&&"stdout"in o&&"stderr"in o}function Sn(o){if(o.stdout.length>0){let e=o.stdout.map(t=>v.default.gray(` ${t}`)).join(`
61
63
  `);console.log(v.default.green(" Output:")),console.log(e)}if(o.stderr.length>0){let e=o.stderr.map(t=>v.default.gray(` ${t}`)).join(`
62
- `);console.log(v.default.red(" Errors:")),console.log(e)}}var Qo=require("commander");var Fo=require("child_process"),Ke=require("fs"),Wo=require("fs/promises"),j=require("path"),Vo=x(require("boxen"),1),D=x(require("chalk"),1),Qe=x(require("inquirer"),1),Ho=x(require("node-cron"),1);ge();var Co=require("fs/promises"),Do=require("path"),To=require("yaml"),Io=require("zod");var L=require("zod"),xn=L.z.object({name:L.z.string().min(1,"Schedule name must be non-empty"),cron:L.z.string().min(1,"Cron expression is required"),workflow:L.z.string().min(1,"Workflow path is required"),baseDir:L.z.string().optional(),timezone:L.z.union([L.z.string(),L.z.number()]).transform(String).optional(),silent:L.z.boolean().optional(),profile:L.z.string().optional()}),vn=L.z.object({schedules:L.z.array(xn).min(1,"Schedule file must have at least one schedule")});function Po(o){return vn.parse(o)}async function Mo(o){let e=await(0,Co.readFile)(o,"utf-8"),t=(0,Do.extname)(o).toLowerCase(),r;try{if(t===".yaml"||t===".yml")r=(0,To.parse)(e);else if(t===".json")r=JSON.parse(e);else throw new Error(`Unsupported file format: ${t}. Use .yaml, .yml, or .json`)}catch(s){if(s instanceof Error&&s.message.startsWith("Unsupported"))throw s;let i=t===".json"?"JSON":"YAML";throw new Error(`Invalid ${i} format: ${s instanceof Error?s.message:String(s)}`)}try{return Po(r)}catch(s){if(s instanceof Io.ZodError){let i=s.issues.map(n=>` - ${n.message} (${n.path.join(".")})`).join(`
64
+ `);console.log(v.default.red(" Errors:")),console.log(e)}}var Qo=require("commander");var Fo=require("child_process"),Ke=require("fs"),Wo=require("fs/promises"),B=require("path"),Vo=x(require("boxen"),1),D=x(require("chalk"),1),Qe=x(require("inquirer"),1),Ho=x(require("node-cron"),1);ge();var Co=require("fs/promises"),Do=require("path"),To=require("yaml"),Io=require("zod");var F=require("zod"),xn=F.z.object({name:F.z.string().min(1,"Schedule name must be non-empty"),cron:F.z.string().min(1,"Cron expression is required"),workflow:F.z.string().min(1,"Workflow path is required"),baseDir:F.z.string().optional(),timezone:F.z.union([F.z.string(),F.z.number()]).transform(String).optional(),silent:F.z.boolean().optional(),profile:F.z.string().optional()}),vn=F.z.object({schedules:F.z.array(xn).min(1,"Schedule file must have at least one schedule")});function Po(o){return vn.parse(o)}async function Mo(o){let e=await(0,Co.readFile)(o,"utf-8"),t=(0,Do.extname)(o).toLowerCase(),r;try{if(t===".yaml"||t===".yml")r=(0,To.parse)(e);else if(t===".json")r=JSON.parse(e);else throw new Error(`Unsupported file format: ${t}. Use .yaml, .yml, or .json`)}catch(s){if(s instanceof Error&&s.message.startsWith("Unsupported"))throw s;let i=t===".json"?"JSON":"YAML";throw new Error(`Invalid ${i} format: ${s instanceof Error?s.message:String(s)}`)}try{return Po(r)}catch(s){if(s instanceof Io.ZodError){let i=s.issues.map(n=>` - ${n.message} (${n.path.join(".")})`).join(`
63
65
  `);throw new Error(`Invalid schedule file structure:
64
- ${i}`)}throw s}}var No=x(require("boxen"),1),E=x(require("chalk"),1),jo=x(require("cronstrue"),1),Tt=x(require("dayjs"),1),It=x(require("node-cron"),1);function Mt(o){try{return jo.default.toString(o)}catch{return null}}function kn(o){if(!It.default.validate(o.cron))return null;try{let e={},t=Ge(o.timezone);t&&(e.timezone=t);let r=It.default.createTask(o.cron,()=>{},e),s=r.getNextRun();return r.destroy(),s}catch{return null}}function ee(o,e){let t=o,{daemonRunning:r,emphasizeState:s}=e,i=t.enabled?s?E.default.bold.green("ENABLED"):E.default.green("enabled"):s?E.default.bold.gray("DISABLED"):E.default.gray("disabled"),n=r&&t.enabled,a=n?E.default.green("\u25CF active"):E.default.gray("\u25CB inactive"),l=s?t.enabled?E.default.bold.green(" [ENABLED]"):E.default.bold.gray(" [DISABLED]"):"",c=E.default.bold(t.name??t.workflowPath),d=kn(t),f=d?(0,Tt.default)(d).format("YYYY-MM-DD HH:mm:ss"):E.default.dim("\u2014"),m=t.lastRun?(0,Tt.default)(t.lastRun).format("YYYY-MM-DD HH:mm:ss"):E.default.dim("never"),p=Mt(t.cron),h=t.timezone?t.timezone.startsWith("+")||t.timezone.startsWith("-")?`UTC${t.timezone}`:`UTC+${t.timezone}`:null,g=h??"local",b=p?`${t.cron} ${E.default.dim(`\u2192 ${p} (${g})`)}`:t.cron,k=[[E.default.gray("Enabled"),i],[E.default.gray("Cron"),b],[E.default.gray("Timezone"),h??E.default.dim("local")],[E.default.gray("Workflow"),t.workflowPath],...t.profile?[[E.default.gray("Profile"),E.default.cyan(t.profile)]]:[],...t.silent?[[E.default.gray("Silent"),E.default.yellow("yes")]]:[],[E.default.gray("Last run"),m],[E.default.gray("Next run"),f]],y=[`${c} ${a}${l}`,...k.map(([T,V])=>` ${T.padEnd(10)} ${V}`)].join(`
65
- `);return(0,No.default)(y,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:n?"green":"gray"})}var q=require("fs"),O=require("path"),Nt=require("url"),Ao={};function Bo(){console.log=()=>{},console.error=()=>{},console.warn=()=>{},console.info=()=>{},process.stdout.write=()=>!0,process.stderr.write=()=>!0}function Oo(){return"0.3.14"}function Xe(o){let e=o?(0,O.resolve)(o):process.cwd(),t=50,r=0;for(;r<t;){let s=(0,O.resolve)(e,"tp");try{if((0,q.existsSync)(s)&&(0,q.statSync)(s).isDirectory())return s}catch{}let i=(0,O.dirname)(e);if(i===e)break;e=i,r++}return null}function Lo(o){let e={};for(let t of o){let r=t.indexOf("=");if(r===-1)throw new Error(`Invalid -v/--var format: "${t}". Use key=value (e.g. -v version=1.0.0).`);let s=t.slice(0,r).trim(),i=t.slice(r+1).trim();if(!s)throw new Error(`Invalid -v/--var format: key is empty in "${t}". Use key=value.`);e[s]=i}return e}function jt(o,e){let t=e.workflow;if((0,j.isAbsolute)(t))return t;let r=e.baseDir?(0,j.resolve)(e.baseDir):(0,j.dirname)(o);return(0,j.resolve)(r,t)}function _o(o,e="plain"){let t=o.name??"(no alias)",r=(0,j.basename)(o.workflowPath),s=Mt(o.cron)??o.cron,i=e==="color"?o.enabled?D.default.green("Enabled"):D.default.dim("Disabled"):o.enabled?"\u2713":"\u2717";return`${t} \xB7 ${r} \xB7 ${o.cron} \xB7 ${s} \xB7 ${i}`}async function Uo(o){let e=new W;if(!o){let l=Xe();l||(console.error(D.default.red(`
66
- \u2717 No tp directory found`)),process.exit(1));let c=(0,j.join)(l,"schedules");(0,Ke.existsSync)(c)||(console.error(D.default.red(`
67
- \u2717 No schedules directory found at ${c}`)),process.exit(1));let f=(await(0,Wo.readdir)(c)).filter(g=>{let b=(0,j.extname)(g).toLowerCase();return[".yaml",".yml",".json"].includes(b)});f.length===0&&(console.error(D.default.red(`
68
- \u2717 No schedule files found in ${c}`)),process.exit(1));let m=f.map(g=>({id:(0,j.join)(c,g),label:g}));o=(await new B(!0).prompt("Select a schedule file to add",m)).id}let t=(0,j.resolve)(o);(0,Ke.existsSync)(t)||(console.error(`\u2717 File not found: ${t}`),process.exit(1));let r;try{r=await Mo(t)}catch(l){console.error(`\u2717 Failed to parse schedule file: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}let s=r.schedules.filter(l=>!Ho.default.validate(l.cron));if(s.length>0){console.error("\u2717 Invalid cron expression(s):");for(let l of s)console.error(` - ${l.name}: "${l.cron}"`);process.exit(1)}let i=r.schedules.filter(l=>{let c=jt(t,l);return!(0,Ke.existsSync)(c)});if(i.length>0){console.error("\u2717 Workflow file(s) not found:");for(let l of i){let c=jt(t,l);console.error(` - ${l.name}: ${l.workflow} (resolved: ${c})`)}process.exit(1)}console.log(`
66
+ ${i}`)}throw s}}var No=x(require("boxen"),1),E=x(require("chalk"),1),jo=x(require("cronstrue"),1),Tt=x(require("dayjs"),1),It=x(require("node-cron"),1);function Mt(o){try{return jo.default.toString(o)}catch{return null}}function kn(o){if(!It.default.validate(o.cron))return null;try{let e={},t=Ge(o.timezone);t&&(e.timezone=t);let r=It.default.createTask(o.cron,()=>{},e),s=r.getNextRun();return r.destroy(),s}catch{return null}}function ee(o,e){let t=o,{daemonRunning:r,emphasizeState:s}=e,i=t.enabled?s?E.default.bold.green("ENABLED"):E.default.green("enabled"):s?E.default.bold.gray("DISABLED"):E.default.gray("disabled"),n=r&&t.enabled,a=n?E.default.green("\u25CF active"):E.default.gray("\u25CB inactive"),l=s?t.enabled?E.default.bold.green(" [ENABLED]"):E.default.bold.gray(" [DISABLED]"):"",c=E.default.bold(t.name??t.workflowPath),d=kn(t),f=d?(0,Tt.default)(d).format("YYYY-MM-DD HH:mm:ss"):E.default.dim("\u2014"),m=t.lastRun?(0,Tt.default)(t.lastRun).format("YYYY-MM-DD HH:mm:ss"):E.default.dim("never"),p=Mt(t.cron),h=t.timezone?t.timezone.startsWith("+")||t.timezone.startsWith("-")?`UTC${t.timezone}`:`UTC+${t.timezone}`:null,g=h??"local",b=p?`${t.cron} ${E.default.dim(`\u2192 ${p} (${g})`)}`:t.cron,y=[[E.default.gray("Enabled"),i],[E.default.gray("Cron"),b],[E.default.gray("Timezone"),h??E.default.dim("local")],[E.default.gray("Workflow"),t.workflowPath],...t.profile?[[E.default.gray("Profile"),E.default.cyan(t.profile)]]:[],...t.silent?[[E.default.gray("Silent"),E.default.yellow("yes")]]:[],[E.default.gray("Last run"),m],[E.default.gray("Next run"),f]],S=[`${c} ${a}${l}`,...y.map(([I,M])=>` ${I.padEnd(10)} ${M}`)].join(`
67
+ `);return(0,No.default)(S,{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:n?"green":"gray"})}var q=require("fs"),L=require("path"),Nt=require("url"),Ao={};function Bo(){console.log=()=>{},console.error=()=>{},console.warn=()=>{},console.info=()=>{},process.stdout.write=()=>!0,process.stderr.write=()=>!0}function Oo(){return"0.3.15"}function Xe(o){let e=o?(0,L.resolve)(o):process.cwd(),t=50,r=0;for(;r<t;){let s=(0,L.resolve)(e,"tp");try{if((0,q.existsSync)(s)&&(0,q.statSync)(s).isDirectory())return s}catch{}let i=(0,L.dirname)(e);if(i===e)break;e=i,r++}return null}function Lo(o){let e={};for(let t of o){let r=t.indexOf("=");if(r===-1)throw new Error(`Invalid -v/--var format: "${t}". Use key=value (e.g. -v version=1.0.0).`);let s=t.slice(0,r).trim(),i=t.slice(r+1).trim();if(!s)throw new Error(`Invalid -v/--var format: key is empty in "${t}". Use key=value.`);e[s]=i}return e}function jt(o,e){let t=e.workflow;if((0,B.isAbsolute)(t))return t;let r=e.baseDir?(0,B.resolve)(e.baseDir):(0,B.dirname)(o);return(0,B.resolve)(r,t)}function _o(o,e="plain"){let t=o.name??"(no alias)",r=(0,B.basename)(o.workflowPath),s=Mt(o.cron)??o.cron,i=e==="color"?o.enabled?D.default.green("Enabled"):D.default.dim("Disabled"):o.enabled?"\u2713":"\u2717";return`${t} \xB7 ${r} \xB7 ${o.cron} \xB7 ${s} \xB7 ${i}`}async function Uo(o){let e=new V;if(!o){let l=Xe();l||(console.error(D.default.red(`
68
+ \u2717 No tp directory found`)),process.exit(1));let c=(0,B.join)(l,"schedules");(0,Ke.existsSync)(c)||(console.error(D.default.red(`
69
+ \u2717 No schedules directory found at ${c}`)),process.exit(1));let f=(await(0,Wo.readdir)(c)).filter(g=>{let b=(0,B.extname)(g).toLowerCase();return[".yaml",".yml",".json"].includes(b)});f.length===0&&(console.error(D.default.red(`
70
+ \u2717 No schedule files found in ${c}`)),process.exit(1));let m=f.map(g=>({id:(0,B.join)(c,g),label:g}));o=(await new O(!0).prompt("Select a schedule file to add",m)).id}let t=(0,B.resolve)(o);(0,Ke.existsSync)(t)||(console.error(`\u2717 File not found: ${t}`),process.exit(1));let r;try{r=await Mo(t)}catch(l){console.error(`\u2717 Failed to parse schedule file: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}let s=r.schedules.filter(l=>!Ho.default.validate(l.cron));if(s.length>0){console.error("\u2717 Invalid cron expression(s):");for(let l of s)console.error(` - ${l.name}: "${l.cron}"`);process.exit(1)}let i=r.schedules.filter(l=>{let c=jt(t,l);return!(0,Ke.existsSync)(c)});if(i.length>0){console.error("\u2717 Workflow file(s) not found:");for(let l of i){let c=jt(t,l);console.error(` - ${l.name}: ${l.workflow} (resolved: ${c})`)}process.exit(1)}console.log(`
69
71
  Found ${r.schedules.length} schedule(s) in file.
70
- `);let n=[];for(let l of r.schedules){let{alias:c}=await Qe.default.prompt([{type:"input",name:"alias",message:`Alias for "${l.name}" (press Enter to use as-is):`,default:l.name}]),d=await e.addSchedule({name:c,workflowPath:jt(t,l),cron:l.cron,enabled:!0,timezone:l.timezone,silent:l.silent,profile:l.profile});n.push(d)}let a=await N();console.log(`
72
+ `);let n=[];for(let l of r.schedules){let{alias:c}=await Qe.default.prompt([{type:"input",name:"alias",message:`Alias for "${l.name}" (press Enter to use as-is):`,default:l.name}]),d=await e.addSchedule({name:c,workflowPath:jt(t,l),cron:l.cron,enabled:!0,timezone:l.timezone,silent:l.silent,profile:l.profile});n.push(d)}let a=await j();console.log(`
71
73
  \u2713 Added ${n.length} schedule(s) successfully
72
- `);for(let l of n)console.log(ee(l,{daemonRunning:a.running}));console.log(D.default.dim(' Tip: Run "tp schedule start" to start the scheduler daemon'))}async function zo(){let o=new W,e=await o.loadSchedules();if(e.length===0){console.log("No schedules found");return}let t=e.map(c=>({id:c.id,label:_o(c)})),i=(await new B(!0).prompt("Select schedule to remove:",t)).id,n=e.find(c=>c.id===i),{confirm:a}=await Qe.default.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to remove this schedule?",default:!1}]);if(!a){console.log("Cancelled");return}let l=await o.removeSchedule(i);if(l&&n){let c=await N();console.log(`
74
+ `);for(let l of n)console.log(ee(l,{daemonRunning:a.running}));console.log(D.default.dim(' Tip: Run "tp schedule start" to start the scheduler daemon'))}async function zo(){let o=new V,e=await o.loadSchedules();if(e.length===0){console.log("No schedules found");return}let t=e.map(c=>({id:c.id,label:_o(c)})),i=(await new O(!0).prompt("Select schedule to remove:",t)).id,n=e.find(c=>c.id===i),{confirm:a}=await Qe.default.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to remove this schedule?",default:!1}]);if(!a){console.log("Cancelled");return}let l=await o.removeSchedule(i);if(l&&n){let c=await j();console.log(`
73
75
  \u2713 Schedule removed
74
- `),console.log(ee(n,{daemonRunning:c.running}))}else console.log(l?"\u2713 Schedule removed successfully":"\u2717 Schedule not found")}async function At(){let e=await new W().loadSchedules();if(e.length===0){let n=[D.default.gray("No schedules registered."),"",D.default.dim(" tp schedule add <schedule.yaml> add from a schedule file")].join(`
76
+ `),console.log(ee(n,{daemonRunning:c.running}))}else console.log(l?"\u2713 Schedule removed successfully":"\u2717 Schedule not found")}async function At(){let e=await new V().loadSchedules();if(e.length===0){let n=[D.default.gray("No schedules registered."),"",D.default.dim(" tp schedule add <schedule.yaml> add from a schedule file")].join(`
75
77
  `);console.log(`
76
78
  ${(0,Vo.default)(n,{borderStyle:"round",padding:{top:1,bottom:1,left:2,right:2},margin:{top:0,bottom:0,left:0,right:0},borderColor:"gray"})}
77
- `);return}let t=await N(),r=t.running?D.default.green("\u25CF running"):D.default.gray("\u25CB stopped"),s=e.filter(n=>n.enabled).length,i=D.default.bold("\u{1F4C5} Workflow Schedules");console.log(i),console.log([D.default.gray(" Daemon: "),r,D.default.gray(` \xB7 Schedules: ${s}/${e.length} enabled`)].join(""));for(let n of e)console.log(ee(n,{daemonRunning:t.running}));console.log(D.default.dim(" Tip: tp schedule start \u2014 run scheduler daemon; tp schedule status \u2014 view live status"))}async function Yo(o){if(await Y()){let e=await N();console.error(`\u2717 Scheduler daemon is already running (PID: ${e.pid})`),console.error(' Run "tp schedule stop" to stop it first'),process.exit(1)}if(o)if(process.env.TP_DAEMON_MODE==="true")try{let{saveDaemonPid:e}=await Promise.resolve().then(()=>(ge(),_t));await e(),await new Q().start(!0),await new Promise(()=>{})}catch(e){await pt(e instanceof Error?e:new Error(String(e))),process.exit(1)}else{let e=process.argv.slice(1);(0,Fo.spawn)(process.argv[0],e,{detached:!0,stdio:"ignore",env:{...process.env,TP_DAEMON_MODE:"true"}}).unref();let r=3,s=800,i=!1;for(let n=0;n<r;n++)if(await new Promise(a=>setTimeout(a,s)),await Y()){i=!0;break}if(i){let n=await N();console.log(`\u2713 Scheduler daemon started in background (PID: ${n.pid})`),console.log(' Run "tp schedule stop" to stop the daemon'),console.log(' Run "tp schedule status" to check daemon status')}else{console.error("\u2717 Failed to start scheduler daemon");let n=await mt();n?(console.error(D.default.dim(" Last error from daemon:")),console.error(D.default.red(n.split(`
79
+ `);return}let t=await j(),r=t.running?D.default.green("\u25CF running"):D.default.gray("\u25CB stopped"),s=e.filter(n=>n.enabled).length,i=D.default.bold("\u{1F4C5} Workflow Schedules");console.log(i),console.log([D.default.gray(" Daemon: "),r,D.default.gray(` \xB7 Schedules: ${s}/${e.length} enabled`)].join(""));for(let n of e)console.log(ee(n,{daemonRunning:t.running}));console.log(D.default.dim(" Tip: tp schedule start \u2014 run scheduler daemon; tp schedule status \u2014 view live status"))}async function Yo(o){if(await Y()){let e=await j();console.error(`\u2717 Scheduler daemon is already running (PID: ${e.pid})`),console.error(' Run "tp schedule stop" to stop it first'),process.exit(1)}if(o)if(process.env.TP_DAEMON_MODE==="true")try{let{saveDaemonPid:e}=await Promise.resolve().then(()=>(ge(),_t));await e(),await new Q().start(!0),await new Promise(()=>{})}catch(e){await pt(e instanceof Error?e:new Error(String(e))),process.exit(1)}else{let e=process.argv.slice(1);(0,Fo.spawn)(process.argv[0],e,{detached:!0,stdio:"ignore",env:{...process.env,TP_DAEMON_MODE:"true"}}).unref();let r=3,s=800,i=!1;for(let n=0;n<r;n++)if(await new Promise(a=>setTimeout(a,s)),await Y()){i=!0;break}if(i){let n=await j();console.log(`\u2713 Scheduler daemon started in background (PID: ${n.pid})`),console.log(' Run "tp schedule stop" to stop the daemon'),console.log(' Run "tp schedule status" to check daemon status')}else{console.error("\u2717 Failed to start scheduler daemon");let n=await mt();n?(console.error(D.default.dim(" Last error from daemon:")),console.error(D.default.red(n.split(`
78
80
  `).map(a=>` ${a}`).join(`
79
- `)))):console.error(D.default.dim(` Check ${dt()} for details`)),process.exit(1)}process.exit(0)}else await new Q().start(!1,{onScheduleStarted:t=>console.log(ee(t,{daemonRunning:!0}))}),await new Promise(()=>{})}async function Jo(){let o=await N();if(!o.running){console.log("Scheduler daemon is not running");return}console.log(`Stopping scheduler daemon (PID: ${o.pid})...`);let t=await new Q().stopDaemon();console.log(t?"\u2713 Scheduler daemon stopped":"\u2717 Failed to stop scheduler daemon (process may have already exited)")}async function qo(){let o=new W,e=await o.loadSchedules();if(e.length===0){console.log("No schedules found");return}let t=e.map(m=>({id:m.id,label:_o(m,"color")})),i=(await new B(!0).prompt("Select schedule to toggle:",t)).id,n=e.find(m=>m.id===i);if(!n){console.log("\u2717 Schedule not found");return}let a=!n.enabled;await o.toggleSchedule(i,a);let l=await N(),c={...n,enabled:a},d=a?D.default.bold.green("ENABLED"):D.default.bold.gray("DISABLED"),f=a?D.default.dim(" (will run at the times shown below)"):D.default.dim(" (will not run until you enable it again)");console.log(`
81
+ `)))):console.error(D.default.dim(` Check ${dt()} for details`)),process.exit(1)}process.exit(0)}else await new Q().start(!1,{onScheduleStarted:t=>console.log(ee(t,{daemonRunning:!0}))}),await new Promise(()=>{})}async function Jo(){let o=await j();if(!o.running){console.log("Scheduler daemon is not running");return}console.log(`Stopping scheduler daemon (PID: ${o.pid})...`);let t=await new Q().stopDaemon();console.log(t?"\u2713 Scheduler daemon stopped":"\u2717 Failed to stop scheduler daemon (process may have already exited)")}async function qo(){let o=new V,e=await o.loadSchedules();if(e.length===0){console.log("No schedules found");return}let t=e.map(m=>({id:m.id,label:_o(m,"color")})),i=(await new O(!0).prompt("Select schedule to toggle:",t)).id,n=e.find(m=>m.id===i);if(!n){console.log("\u2717 Schedule not found");return}let a=!n.enabled;await o.toggleSchedule(i,a);let l=await j(),c={...n,enabled:a},d=a?D.default.bold.green("ENABLED"):D.default.bold.gray("DISABLED"),f=a?D.default.dim(" (will run at the times shown below)"):D.default.dim(" (will not run until you enable it again)");console.log(`
80
82
  \u2713 Schedule is now ${d}${f}
81
- `),console.log(ee(c,{daemonRunning:l.running,emphasizeState:!0}))}async function Go(){let o=new W,e=await o.loadSchedules();if(e.length===0){console.log("No schedules found");return}let{confirm:t}=await Qe.default.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to remove all ${e.length} schedule(s)?`,default:!1}]);if(!t){console.log("Cancelled");return}await o.saveSchedules([]),console.log(`\u2713 Removed all ${e.length} schedule(s)`)}var Bt=x(require("boxen"),1),$=x(require("chalk"),1),et=x(require("dayjs"),1),Me=x(require("log-update"),1);ge();function $n(o){if(!o)return"Unknown";let e=(0,et.default)(o),r=(0,et.default)().diff(e,"second"),s=Math.floor(r/86400),i=Math.floor(r%86400/3600),n=Math.floor(r%3600/60),a=r%60,l=[];return s>0&&l.push(`${s}d`),i>0&&l.push(`${i}h`),n>0&&l.push(`${n}m`),(a>0||l.length===0)&&l.push(`${a}s`),l.join(" ")}function Rn(o,e){return ee(o,{daemonRunning:e})}async function Zo(){let o=await N(),t=await new W().loadSchedules(),r=[],s;if(o.running&&o.pid){let n=$n(o.startTime),a=o.startTime?(0,et.default)(o.startTime).format("YYYY-MM-DD HH:mm:ss"):"Unknown";s=[`${$.default.green("\u25CF")} ${$.default.green("active")} ${$.default.gray("(running)")}`,"",`${$.default.gray("Loaded:")} ${$.default.white(a)}`,`${$.default.gray("Active:")} ${$.default.green("active (running)")} since ${$.default.white(a)}`,`${$.default.gray("PID:")} ${$.default.white(o.pid.toString())}`,`${$.default.gray("Uptime:")} ${$.default.white(n)}`].join(`
83
+ `),console.log(ee(c,{daemonRunning:l.running,emphasizeState:!0}))}async function Go(){let o=new V,e=await o.loadSchedules();if(e.length===0){console.log("No schedules found");return}let{confirm:t}=await Qe.default.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to remove all ${e.length} schedule(s)?`,default:!1}]);if(!t){console.log("Cancelled");return}await o.saveSchedules([]),console.log(`\u2713 Removed all ${e.length} schedule(s)`)}var Bt=x(require("boxen"),1),$=x(require("chalk"),1),et=x(require("dayjs"),1),Me=x(require("log-update"),1);ge();function $n(o){if(!o)return"Unknown";let e=(0,et.default)(o),r=(0,et.default)().diff(e,"second"),s=Math.floor(r/86400),i=Math.floor(r%86400/3600),n=Math.floor(r%3600/60),a=r%60,l=[];return s>0&&l.push(`${s}d`),i>0&&l.push(`${i}h`),n>0&&l.push(`${n}m`),(a>0||l.length===0)&&l.push(`${a}s`),l.join(" ")}function Rn(o,e){return ee(o,{daemonRunning:e})}async function Zo(){let o=await j(),t=await new V().loadSchedules(),r=[],s;if(o.running&&o.pid){let n=$n(o.startTime),a=o.startTime?(0,et.default)(o.startTime).format("YYYY-MM-DD HH:mm:ss"):"Unknown";s=[`${$.default.green("\u25CF")} ${$.default.green("active")} ${$.default.gray("(running)")}`,"",`${$.default.gray("Loaded:")} ${$.default.white(a)}`,`${$.default.gray("Active:")} ${$.default.green("active (running)")} since ${$.default.white(a)}`,`${$.default.gray("PID:")} ${$.default.white(o.pid.toString())}`,`${$.default.gray("Uptime:")} ${$.default.white(n)}`].join(`
82
84
  `)}else s=[`${$.default.red("\u25CF")} ${$.default.red("inactive")} ${$.default.gray("(dead)")}`,"",`${$.default.gray("Loaded:")} ${$.default.gray("not found")}`,`${$.default.gray("Active:")} ${$.default.red("inactive (dead)")}`].join(`
83
85
  `);let i=(0,Bt.default)(s,{title:$.default.bold("task-pipeliner-scheduler.service"),titleAlignment:"left",borderStyle:"round",padding:{top:1,bottom:1,left:2,right:2},margin:{top:1,bottom:0,left:0,right:0},borderColor:o.running?"green":"red"});if(r.push(i),t.length>0){let n=t.filter(l=>l.enabled).length,a=$.default.bold(`Schedules: ${n}/${t.length} enabled`);r.push(a);for(let l of t)r.push(Rn(l,o.running))}else{let n=(0,Bt.default)($.default.gray("No schedules configured"),{borderStyle:"round",padding:{top:0,bottom:0,left:1,right:1},margin:{top:0,bottom:0,left:0,right:0},borderColor:"gray"});r.push(n)}return`
84
86
 
85
87
  ${r.join(`
86
88
  `)}`}function Xo(){process.stdout.write("\x1B[2J\x1B[H")}var En=2,Pn=24;function Cn(){let o=typeof process.stdout.rows=="number"?process.stdout.rows:Pn;return Math.max(5,o-En)}function Dn(o){let e=o.toString("utf8");return e==="\x1B[A"?"up":e==="\x1B[B"?"down":e==="\x1B[5~"?"pageup":e==="\x1B[6~"?"pagedown":e==="\x1B[H"||e==="\x1B[1~"?"home":e==="\x1B[4~"||e==="\x1B[F"?"end":null}async function Ko(o){if(o){let e=process.stdin.isTTY&&process.stdout.isTTY,t=Cn(),r=!0,s=[],i="",n=0,a=()=>{let f=s.length,m=Math.max(0,f-t);n=Math.min(n,m);let h=s.slice(n,n+t).join(`
87
89
  `),g=f>t?$.default.dim(` [${n+1}-${Math.min(n+t,f)}/${f}] \u2191/\u2193 PgUp/PgDn: scroll`):"";(0,Me.default)(`${h}
88
- ${i}${g}`)},l=()=>{r=!1,e&&process.stdin.isTTY&&(process.stdin.setRawMode(!1),process.stdin.pause()),Me.default.done(),process.exit(0)};process.on("SIGINT",l),process.on("SIGTERM",l),e&&process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{let m=typeof f=="string"?Buffer.from(f,"utf8"):f;if(m.length===1&&m[0]===3){l();return}let p=Dn(m);if(!p||s.length<=t){p&&a();return}let h=Math.max(0,s.length-t);switch(p){case"up":n=Math.max(0,n-1);break;case"down":n=Math.min(h,n+1);break;case"pageup":n=Math.max(0,n-t);break;case"pagedown":n=Math.min(h,n+t);break;case"home":n=0;break;case"end":n=h;break}a()}));let c=async()=>{try{let f=await Zo(),m=await N();if(i=m.running?$.default.gray(`
90
+ ${i}${g}`)},l=()=>{r=!1,e&&process.stdin.isTTY&&(process.stdin.setRawMode(!1),process.stdin.pause()),Me.default.done(),process.exit(0)};process.on("SIGINT",l),process.on("SIGTERM",l),e&&process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{let m=typeof f=="string"?Buffer.from(f,"utf8"):f;if(m.length===1&&m[0]===3){l();return}let p=Dn(m);if(!p||s.length<=t){p&&a();return}let h=Math.max(0,s.length-t);switch(p){case"up":n=Math.max(0,n-1);break;case"down":n=Math.min(h,n+1);break;case"pageup":n=Math.max(0,n-t);break;case"pagedown":n=Math.min(h,n+t);break;case"home":n=0;break;case"end":n=h;break}a()}));let c=async()=>{try{let f=await Zo(),m=await j();if(i=m.running?$.default.gray(`
89
91
  Ctrl+C: exit (daemon keeps running)`):$.default.gray(`
90
92
  Tip: tp schedule start -d to start daemon. Ctrl+C: exit.`),s=f.split(`
91
93
  `),e)a();else{let p=m.running?$.default.gray(`
92
94
  Press Ctrl+C to exit (daemon keeps running in background)`):$.default.gray(`
93
- Tip: To start the daemon, run: tp schedule start -d. Press Ctrl+C to exit.`);(0,Me.default)(`${f}${p}`)}}catch(f){Me.default.done(),console.error("Error updating status:",f),process.exit(1)}},d=setInterval(async()=>{if(!r){clearInterval(d);return}await c()},1e3);Xo(),await c(),await new Promise(()=>{})}else{Xo();let e=await Zo(),r=(await N()).running?"":$.default.gray(`
95
+ Tip: To start the daemon, run: tp schedule start -d. Press Ctrl+C to exit.`);(0,Me.default)(`${f}${p}`)}}catch(f){Me.default.done(),console.error("Error updating status:",f),process.exit(1)}},d=setInterval(async()=>{if(!r){clearInterval(d);return}await c()},1e3);Xo(),await c(),await new Promise(()=>{})}else{Xo();let e=await Zo(),r=(await j()).running?"":$.default.gray(`
94
96
  Tip: To start the daemon, run: tp schedule start -d`);console.log(`${e}${r}
95
97
  `)}}function er(){let o=new Qo.Command("schedule").description("Manage workflow schedules").action(async()=>{await At()});return o.command("add [scheduleFile]").description("Add schedules from a schedule file (YAML or JSON). If no file given, select from nearest tp/schedules directory.").action(async e=>{await Uo(e)}),o.command("remove").alias("rm").description("Remove a workflow schedule").action(async()=>{await zo()}),o.command("remove-all").description("Remove all workflow schedules").action(async()=>{await Go()}),o.command("list").alias("ls").description("List all workflow schedules").action(async()=>{await At()}),o.command("start").description("Start the scheduler daemon").option("-d, --daemon","Run in background daemon mode").action(async e=>{await Yo(e.daemon??!1)}),o.command("stop").description("Stop the scheduler daemon").action(async()=>{await Jo()}),o.command("status").description('View daemon and schedule status (does not start the daemon). In live mode, Ctrl+C only exits the status view; the daemon keeps running if it was started with "tp schedule start -d".').option("-n, --no-follow","Show status once and exit (no live refresh)").action(async e=>{let t=e.follow!==!1;await Ko(t)}),o.command("toggle").description("Enable or disable a schedule").action(async()=>{await qo()}),o}var tr=[{filename:"example-hello.yaml",content:`name: Hello World (with choose)
96
98
 
@@ -171,7 +173,7 @@ steps:
171
173
  `}];var tt=require("fs"),rr=require("fs/promises"),je=require("path"),Ne=x(require("chalk"),1);async function nr(){let o=Xe();if(!o)return console.error(Ne.default.red(`
172
174
  \u2717 No tp directory found`)),null;let e=(0,je.join)(o,"workflows");if(!(0,tt.existsSync)(e))return console.error(Ne.default.red(`
173
175
  \u2717 No workflows directory found at ${e}`)),null;try{let r=(await(0,rr.readdir)(e)).filter(a=>{let l=(0,je.extname)(a).toLowerCase();return[".yaml",".yml",".json"].includes(l)});if(r.length===0)return console.error(Ne.default.red(`
174
- \u2717 No workflow files found in tp/workflows`)),null;let s=await Promise.all(r.map(async a=>{let l=(0,je.join)(e,a);try{let c=ke(l),d=(0,tt.readFileSync)(l,"utf-8"),m=c.parse(d).name??"Untitled";return{id:l,label:`${a} - ${m}`}}catch{return{id:l,label:a}}}));return(await new B(!0).prompt("Select a workflow to run",s))?.id??null}catch(t){let r=t instanceof Error?t.message:String(t);return console.error(Ne.default.red(`
176
+ \u2717 No workflow files found in tp/workflows`)),null;let s=await Promise.all(r.map(async a=>{let l=(0,je.join)(e,a);try{let c=ke(l),d=(0,tt.readFileSync)(l,"utf-8"),m=c.parse(d).name??"Untitled";return{id:l,label:`${a} - ${m}`}}catch{return{id:l,label:a}}}));return(await new O(!0).prompt("Select a workflow to run",s))?.id??null}catch(t){let r=t instanceof Error?t.message:String(t);return console.error(Ne.default.red(`
175
177
  \u2717 Failed to read tp directory: ${r}`)),null}}function sr(o){return o.split("/").pop()??o}var Ae=(0,G.join)((0,ar.homedir)(),".pipeliner"),Tn=(0,lr.promisify)(ir.exec),re=new cr.Command;re.name("task-pipeliner").description(`A powerful task pipeline runner with condition-based workflow execution.
176
178
 
177
179
  Define workflows in YAML or JSON files with conditional execution, parallel tasks,
@@ -299,7 +301,7 @@ Please visit manually: ${t}`)),process.exit(1)}});re.addCommand(er());re.command
299
301
  tp directory already exists at ${e}`)):(await(0,oe.mkdir)(e,{recursive:!0}),console.log(w.default.green(`
300
302
  \u2713 Created ${e}`)));let s=async(n,a)=>{(0,te.existsSync)(n)?console.log(w.default.gray(` ${a} already exists`)):(await(0,oe.mkdir)(n,{recursive:!0}),console.log(w.default.green(`\u2713 Created ${a}`)))};await s(t,"tp/workflows"),await s(r,"tp/schedules");let i=[];for(let{filename:n,content:a}of tr){let l=(0,G.join)(t,n);(0,te.existsSync)(l)?console.log(w.default.gray(` Skipped (exists): tp/workflows/${n}`)):(await(0,oe.writeFile)(l,a,"utf-8"),i.push(`tp/workflows/${n}`))}for(let{filename:n,content:a}of or){let l=(0,G.join)(r,n);(0,te.existsSync)(l)?console.log(w.default.gray(` Skipped (exists): tp/schedules/${n}`)):(await(0,oe.writeFile)(l,a,"utf-8"),i.push(`tp/schedules/${n}`))}i.length>0&&(console.log(w.default.green(`
301
303
  \u2713 Added ${i.length} example file(s):`)),i.forEach(n=>console.log(w.default.dim(` ${n}`)))),console.log(w.default.dim(`
302
- Next: tp run tp/workflows/example-hello.yaml | tp schedule add tp/schedules/example-daily.yaml | tp schedule list`)),console.log()});var In=re.command("history").description("Manage workflow execution history");In.action(async()=>{let o=new B,e=new B(!0),t=await o.prompt("Select an action",[{id:"show",label:"Show - View and select a history to view"},{id:"remove",label:"Remove - Delete a specific history file"},{id:"remove-all",label:"Remove All - Delete all history files"}]);t?.id||(console.error(w.default.red(`
304
+ Next: tp run tp/workflows/example-hello.yaml | tp schedule add tp/schedules/example-daily.yaml | tp schedule list`)),console.log()});var In=re.command("history").description("Manage workflow execution history");In.action(async()=>{let o=new O,e=new O(!0),t=await o.prompt("Select an action",[{id:"show",label:"Show - View and select a history to view"},{id:"remove",label:"Remove - Delete a specific history file"},{id:"remove-all",label:"Remove All - Delete all history files"}]);t?.id||(console.error(w.default.red(`
303
305
  \u2717 Invalid choice`)),process.exit(1));let r=new xe;switch(t.id){case"show":{let s=await r.getHistoryNames();if(s.length===0){console.log(w.default.yellow(`
304
306
  \u26A0 No history found`));return}let i=await e.prompt("Select a history to view",s.map(n=>({id:n,label:n})));i?.id||(console.error(w.default.red(`
305
307
  \u2717 Invalid choice`)),process.exit(1));try{let n=await r.getHistory(i.id);Eo(n,i.id)}catch(n){let a=n instanceof Error?n.message:String(n);console.error(w.default.red(`
@@ -311,8 +313,8 @@ Please visit manually: ${t}`)),process.exit(1)}});re.addCommand(er());re.command
311
313
  \u2717 Cancelled`));return}try{await r.clearAllHistories(),console.log(w.default.green(`
312
314
  \u2713 All histories removed`))}catch(i){let n=i instanceof Error?i.message:String(i);console.error(w.default.red(`
313
315
  \u2717 Failed to remove histories: ${n}`)),process.exit(1)}break}default:console.error(w.default.red(`
314
- \u2717 Unknown action: ${t.id}`)),process.exit(1)}});re.command("clean").description("Remove all data in ~/.pipeliner (schedules, daemon state, workflow history). Use after upgrades if data is incompatible.").action(async()=>{if((await new B().prompt(`This will remove all data in ${w.default.yellow(Ae)} (schedules, daemon PID, workflow history). Continue?`,[{id:"yes",label:"Yes, remove all"},{id:"no",label:"No, cancel"}]))?.id!=="yes"){console.log(w.default.yellow(`
315
- \u2717 Cancelled`));return}try{if(await Y()){let t=await N();console.log(w.default.gray(`Stopping scheduler daemon (PID: ${t.pid})...`)),await new Q().stopDaemon(),console.log(w.default.gray(" Daemon stopped"))}(0,te.existsSync)(Ae)?(await(0,oe.rm)(Ae,{recursive:!0}),console.log(w.default.green(`
316
+ \u2717 Unknown action: ${t.id}`)),process.exit(1)}});re.command("clean").description("Remove all data in ~/.pipeliner (schedules, daemon state, workflow history). Use after upgrades if data is incompatible.").action(async()=>{if((await new O().prompt(`This will remove all data in ${w.default.yellow(Ae)} (schedules, daemon PID, workflow history). Continue?`,[{id:"yes",label:"Yes, remove all"},{id:"no",label:"No, cancel"}]))?.id!=="yes"){console.log(w.default.yellow(`
317
+ \u2717 Cancelled`));return}try{if(await Y()){let t=await j();console.log(w.default.gray(`Stopping scheduler daemon (PID: ${t.pid})...`)),await new Q().stopDaemon(),console.log(w.default.gray(" Daemon stopped"))}(0,te.existsSync)(Ae)?(await(0,oe.rm)(Ae,{recursive:!0}),console.log(w.default.green(`
316
318
  \u2713 Removed ${Ae}`))):console.log(w.default.gray(`
317
319
  ${Ae} does not exist (already clean)`))}catch(t){let r=t instanceof Error?t.message:String(t);console.error(w.default.red(`
318
320
  \u2717 Clean failed: ${r}`)),process.exit(1)}});re.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "task-pipeliner",
3
- "version": "0.3.14",
3
+ "version": "0.3.15",
4
4
  "description": "A task pipeline runner with condition-based workflow execution",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",