infra-kit 0.1.79 → 0.1.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,38 +1,37 @@
1
- import{Command as Ht}from"commander";import{z as _}from"zod";import{$ as hr}from"zx";import dr from"node:process";import ur from"pino";import fr from"pino-pretty";var gr=()=>{let e=dr.argv.includes("--debug")?"debug":"info",o=["time","pid","hostname"];return e==="debug"&&o.push("level"),ur({level:e},fr({destination:2,ignore:o.join(","),colorize:!0}))},r=gr();var Z=async(e,o,t,n)=>{try{return await hr`${o}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:n}}},ee=async()=>{let e=await Promise.all([Z("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),Z("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),Z("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),Z("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login")]);r.info(`Doctor check results:
2
- `);for(let t of e){let n=t.status==="pass"?"[PASS]":"[FAIL]";r.info(` ${n} ${t.name}: ${t.message}`)}let o={checks:e.map(t=>({name:t.name,status:t.status,message:t.message})),allPassed:e.every(t=>t.status==="pass")};return{content:[{type:"text",text:JSON.stringify(o,null,2)}],structuredContent:o}},vr={name:"doctor",description:"Check installation and authentication status of gh and doppler CLIs",inputSchema:{},outputSchema:{checks:_.array(_.object({name:_.string().describe("Name of the check"),status:_.enum(["pass","fail"]).describe("Check result"),message:_.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:_.boolean().describe("Whether all checks passed")},handler:ee};import te from"node:fs";import Ke from"node:path";import Rr from"node:process";import{z as oe}from"zod";import Ge from"node:fs";import yr from"node:path";import wr from"node:process";var R=["dev","arthur","renana","roman","eliran","oriana"],$e={"hulyo-monorepo":"hulyo","travelist-monorepo":"travelist"},br="./node_modules/.cache/infra-kit",O="env-load.sh",ze="env-clear.sh",Se="INFRA_KIT_SESSION",D="INFRA_KIT_ENV_CONFIG",J="INFRA_KIT_ENV_PROJECT",L="INFRA_KIT_ENV_LOADED_AT",re=e=>Ge.existsSync(e)?Ge.readFileSync(e,"utf-8").split(`
3
- `).filter(t=>t.includes("=")&&!t.startsWith("set ")).map(t=>t.split("=")[0]):[],j=()=>{let e=wr.env[Se];if(!e)throw new Error("INFRA_KIT_SESSION is not set. Run `source ~/.zshrc` or `infra-kit env-init` first.");return yr.join(br,e)},V="-worktrees";var se=async()=>{let e=j(),o=Ke.join(e,O);if(!te.existsSync(o))return r.error("No loaded environment found. Run `env-load` first."),{content:[{type:"text",text:"No loaded environment found. Run `env-load` first."}]};let t=re(o),n=[...t.map(l=>`unset ${l}`),`unset ${D}`,`unset ${J}`,`unset ${L}`],s=Ke.resolve(e,ze);te.mkdirSync(e,{recursive:!0}),te.writeFileSync(s,`${n.join(`
1
+ import{Command as ao,Option as Cr}from"commander";import{z as B}from"zod";import{$ as Ir}from"zx";import $r from"node:process";import Tr from"pino";import Sr from"pino-pretty";var Er=()=>{let e=$r.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Tr({level:e},Sr({destination:2,ignore:r.join(","),colorize:!0}))},o=Er();var me=async(e,r,t,s)=>{try{return await Ir`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:s}}},ue=async()=>{let e=await Promise.all([me("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),me("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),me("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),me("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login")]);o.info(`Doctor check results:
2
+ `);for(let t of e){let s=t.status==="pass"?"[PASS]":"[FAIL]";o.info(` ${s} ${t.name}: ${t.message}`)}let r={checks:e.map(t=>({name:t.name,status:t.status,message:t.message})),allPassed:e.every(t=>t.status==="pass")};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},Ar={name:"doctor",description:"Check installation and authentication status of gh and doppler CLIs",inputSchema:{},outputSchema:{checks:B.array(B.object({name:B.string().describe("Name of the check"),status:B.enum(["pass","fail"]).describe("Check result"),message:B.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:B.boolean().describe("Whether all checks passed")},handler:ue};import fe from"node:fs";import cr from"node:path";import Or from"node:process";import{z as ge}from"zod";import ir from"node:fs";import Pr from"node:path";import Nr from"node:process";var T=["dev","arthur","renana","roman","eliran","oriana"],We={"hulyo-monorepo":"hulyo","travelist-monorepo":"travelist"},Dr="./node_modules/.cache/infra-kit",W="env-load.sh",ar="env-clear.sh",Fe="INFRA_KIT_SESSION",F="INFRA_KIT_ENV_CONFIG",M="INFRA_KIT_ENV_PROJECT",q="INFRA_KIT_ENV_LOADED_AT",de=e=>ir.existsSync(e)?ir.readFileSync(e,"utf-8").split(`
3
+ `).filter(t=>t.includes("=")&&!t.startsWith("set ")).map(t=>t.split("=")[0]):[],U=()=>{let e=Nr.env[Fe];if(!e)throw new Error("INFRA_KIT_SESSION is not set. Run `source ~/.zshrc` or `infra-kit env-init` first.");return Pr.join(Dr,e)},G="-worktrees";var he=async()=>{let e=U(),r=cr.join(e,W);if(!fe.existsSync(r))return o.error("No loaded environment found. Run `env-load` first."),{content:[{type:"text",text:"No loaded environment found. Run `env-load` first."}]};let t=de(r),s=[...t.map(a=>`unset ${a}`),`unset ${F}`,`unset ${M}`,`unset ${q}`],n=cr.resolve(e,ar);fe.mkdirSync(e,{recursive:!0}),fe.writeFileSync(n,`${s.join(`
4
4
  `)}
5
- `),Rr.stdout.write(`${s}
6
- `),te.unlinkSync(o);let i={variableCount:t.length,unsetStatements:n};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}},kr={name:"env-clear",description:"Clear loaded env vars. Returns a file path that must be sourced (source <path>) to apply. The env-clear shell alias does this automatically.",inputSchema:{},outputSchema:{filePath:oe.string().describe("Path to the file that must be sourced to apply"),variableCount:oe.number().describe("Number of variables cleared"),unsetStatements:oe.array(oe.string()).describe("Unset statements generated")},handler:se};import ne from"node:fs";import xr from"node:os";import Cr from"node:path";var He="# infra-kit shell functions",Ee=async()=>{let e=Cr.join(xr.homedir(),".zshrc"),o=Er();if(ne.existsSync(e)){let t=ne.readFileSync(e,"utf-8"),n=Sr(t);ne.writeFileSync(e,n)}ne.appendFileSync(e,`
7
- ${o}
8
- `),r.info(`Added infra-kit shell functions to ${e}`),r.info("Run `source ~/.zshrc` or open a new terminal to activate.")},$r=e=>e.startsWith("#")||e.startsWith("env-load")||e.startsWith("env-clear")||e.startsWith("env-status")||e.startsWith("if ")||e.startsWith(" export INFRA_KIT_SESSION")||e.startsWith("fi"),Sr=e=>{let o=e.indexOf(He);if(o===-1)return e;let t=e.slice(0,o).replace(/\n+$/,""),n=e.slice(o).split(`
9
- `),s=0;for(;s<n.length&&$r(n[s]);)s++;let i=n.slice(s).join(`
5
+ `),Or.stdout.write(`${n}
6
+ `),fe.unlinkSync(r);let i={variableCount:t.length,unsetStatements:s};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}},_r={name:"env-clear",description:"Clear loaded env vars. Returns a file path that must be sourced (source <path>) to apply. The env-clear shell alias does this automatically.",inputSchema:{},outputSchema:{filePath:ge.string().describe("Path to the file that must be sourced to apply"),variableCount:ge.number().describe("Number of variables cleared"),unsetStatements:ge.array(ge.string()).describe("Unset statements generated")},handler:he};import ve from"node:fs";import Jr from"node:os";import Lr from"node:path";var lr="# infra-kit shell functions",Me=async()=>{let e=Lr.join(Jr.homedir(),".zshrc"),r=Br();if(ve.existsSync(e)){let t=ve.readFileSync(e,"utf-8"),s=Vr(t);ve.writeFileSync(e,s)}ve.appendFileSync(e,`
7
+ ${r}
8
+ `),o.info(`Added infra-kit shell functions to ${e}`),o.info("Run `source ~/.zshrc` or open a new terminal to activate.")},jr=e=>e.startsWith("#")||e.startsWith("env-load")||e.startsWith("env-clear")||e.startsWith("env-status")||e.startsWith("if ")||e.startsWith(" export INFRA_KIT_SESSION")||e.startsWith("fi"),Vr=e=>{let r=e.indexOf(lr);if(r===-1)return e;let t=e.slice(0,r).replace(/\n+$/,""),s=e.slice(r).split(`
9
+ `),n=0;for(;n<s.length&&jr(s[n]);)n++;let i=s.slice(n).join(`
10
10
  `);return t+(i?`
11
- ${i}`:"")},Er=()=>{let e="pnpm exec infra-kit";return[He,'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",`env-load() { local f; f=$(${e} env-load "$@") && source "$f" && ${e} env-status; }`,`env-clear() { local f; f=$(${e} env-clear) && source "$f" && ${e} env-status; }`,`env-status() { ${e} env-status; }`].join(`
12
- `)};import{z as Te}from"zod";import Xe from"node:process";import{$ as Ye}from"zx";var N=async()=>{try{await Ye`doppler --version`}catch(e){r.error({error:e},"Error: Doppler CLI is not installed."),r.error("Please install it from: https://docs.doppler.com/docs/install-cli"),Xe.exit(1)}try{await Ye`doppler me`}catch(e){r.error({error:e},"Error: Doppler CLI is not authenticated."),r.error("Please authenticate by running: doppler login"),Xe.exit(1)}};import Ir from"node:path";import{$ as Qe}from"zx";var S=async e=>{let t=(await Qe`git worktree list`).stdout.split(`
13
- `).filter(Boolean),n={release:Tr,feature:Ar};return t.map(n[e]).filter(s=>s!==null)},Tr=e=>{let o=e.split(" ").filter(Boolean);return o.length<3||!o[0]?.includes("release/v")?null:`release/${o[0]?.split("/").pop()||""}`},Ar=e=>{let o=e.split(" ").filter(Boolean);return o.length<3||!o[0]?.includes("feature/")?null:`feature/${o[0]?.split("/").pop()||""}`},b=async()=>(await Qe`git rev-parse --show-toplevel`).stdout.trim();var U=async()=>{let e=await b(),o=Ir.basename(e),t=$e[o];if(!t)throw new Error(`Could not determine Doppler project for directory "${o}". Expected one of: ${Object.keys($e).join(", ")}`);return t};var ie=async()=>{await N();let e=await U();r.info(`Doppler Project: ${e}
14
- `),r.info("Available Configs:");for(let t of R)r.info(` - ${t}`);let o={project:e,configs:R};return{content:[{type:"text",text:JSON.stringify(o,null,2)}],structuredContent:o}},Pr={name:"env-list",description:"List available Doppler configs for the detected project",inputSchema:{},outputSchema:{project:Te.string().describe("Detected Doppler project name"),configs:Te.array(Te.string()).describe("Available environment configs")},handler:ie};import _r from"@inquirer/select";import Ze from"node:fs";import Or from"node:path";import er from"node:process";import{z as q}from"zod";import{$ as Ae}from"zx";var Nr=()=>{let e="",o=[],t=!1;return{start(n){e=n,o=[],t=!1},setInteractive(){t=!0},addOption(n,s){o.push({flag:n,value:s})},print(){if(!t||o.length===0)return;let n=o.map(s=>typeof s.value=="boolean"?s.value?s.flag:"":Array.isArray(s.value)?`${s.flag} "${s.value.join(", ")}"`:`${s.flag} ${s.value}`).filter(Boolean).join(" ");r.info(""),r.info("# Equivalent command:"),r.info(`pnpm exec infra-kit ${e} ${n}`)},reset(){e="",o=[],t=!1}}},a=Nr();var ae=async e=>{await N();let{config:o}=e;a.start("env-load");let t="";o?t=o:(a.setInteractive(),t=await _r({message:"Select environment config",choices:R.map(h=>({name:h,value:h}))},{output:er.stderr})),a.addOption("--config",t);let n=await U();Ae.quiet=!0;let s=await Ae`doppler secrets download --no-file --format env --project ${n} --config ${t}`;Ae.quiet=!1;let i=s.stdout.trim(),l=new Date().toISOString(),c=["set -a",i,`${D}=${t}`,`${J}=${n}`,`${L}=${l}`,"set +a"],m=j(),p=Or.resolve(m,O);Ze.mkdirSync(m,{recursive:!0}),Ze.writeFileSync(p,`${c.join(`
11
+ ${i}`:"")},Br=()=>{let e="pnpm exec infra-kit";return[lr,'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",`env-load() { local f; f=$(${e} env-load "$@") && source "$f" && ${e} env-status; }`,`env-clear() { local f; f=$(${e} env-clear) && source "$f" && ${e} env-status; }`,`env-status() { ${e} env-status; }`].join(`
12
+ `)};import{z as qe}from"zod";import pr from"node:process";import{$ as mr}from"zx";var j=async()=>{try{await mr`doppler --version`}catch(e){o.error({error:e},"Error: Doppler CLI is not installed."),o.error("Please install it from: https://docs.doppler.com/docs/install-cli"),pr.exit(1)}try{await mr`doppler me`}catch(e){o.error({error:e},"Error: Doppler CLI is not authenticated."),o.error("Please authenticate by running: doppler login"),pr.exit(1)}};import Mr from"node:path";import{$ as ur}from"zx";var D=async e=>{let t=(await ur`git worktree list`).stdout.split(`
13
+ `).filter(Boolean),s={release:Wr,feature:Fr};return t.map(s[e]).filter(n=>n!==null)},Wr=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("release/v")?null:`release/${r[0]?.split("/").pop()||""}`},Fr=e=>{let r=e.split(" ").filter(Boolean);return r.length<3||!r[0]?.includes("feature/")?null:`feature/${r[0]?.split("/").pop()||""}`},x=async()=>(await ur`git rev-parse --show-toplevel`).stdout.trim();var Q=async()=>{let e=await x(),r=Mr.basename(e),t=We[r];if(!t)throw new Error(`Could not determine Doppler project for directory "${r}". Expected one of: ${Object.keys(We).join(", ")}`);return t};var ye=async()=>{await j();let e=await Q();o.info(`Doppler Project: ${e}
14
+ `),o.info("Available Configs:");for(let t of T)o.info(` - ${t}`);let r={project:e,configs:T};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}},qr={name:"env-list",description:"List available Doppler configs for the detected project",inputSchema:{},outputSchema:{project:qe.string().describe("Detected Doppler project name"),configs:qe.array(qe.string()).describe("Available environment configs")},handler:ye};import Gr from"@inquirer/select";import dr from"node:fs";import zr from"node:path";import fr from"node:process";import{z as ee}from"zod";import{$ as Ue}from"zx";var Ur=()=>{let e="",r=[],t=!1;return{start(s){e=s,r=[],t=!1},setInteractive(){t=!0},addOption(s,n){r.push({flag:s,value:n})},print(){if(!t||r.length===0)return;let s=r.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} ${n.value}`).filter(Boolean).join(" ");o.info(`\u{1F4DF} Equivalent command:
15
+ pnpm exec infra-kit ${e} ${s}`),o.info("")},reset(){e="",r=[],t=!1}}},c=Ur();var be=async e=>{await j();let{config:r}=e;c.start("env-load");let t="";r?t=r:(c.setInteractive(),t=await Gr({message:"Select environment config",choices:T.map(f=>({name:f,value:f}))},{output:fr.stderr})),c.addOption("--config",t);let s=await Q();Ue.quiet=!0;let n=await Ue`doppler secrets download --no-file --format env --project ${s} --config ${t}`;Ue.quiet=!1;let i=n.stdout.trim(),a=new Date().toISOString(),p=["set -a",i,`${F}=${t}`,`${M}=${s}`,`${q}=${a}`,"set +a"],l=U(),m=zr.resolve(l,W);dr.mkdirSync(l,{recursive:!0}),dr.writeFileSync(m,`${p.join(`
15
16
  `)}
16
- `),er.stdout.write(`${p}
17
- `);let d={variableCount:i.split(`
18
- `).filter(h=>h.includes("=")).length,project:n,config:t};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}},Dr={name:"env-load",description:"Load Doppler env vars for a config. Returns a file path that must be sourced (source <path>) to apply variables. The env-load shell alias does this automatically.",inputSchema:{config:q.string().describe("Environment config name to load (e.g. dev, arthur, renana)")},outputSchema:{filePath:q.string().describe("Path to the file that must be sourced to apply variables"),variableCount:q.number().describe("Number of variables loaded"),project:q.string().describe("Doppler project name"),config:q.string().describe("Doppler config name")},handler:ae};import Jr from"node:path";import G from"node:process";import{z as F}from"zod";var ce=async()=>{await N(),r.info(`Environment Session Status:
19
- `);let e=j(),o=G.env[Se],t=Jr.join(e,O),n=0,s=0,i=G.env[D]??null,l=G.env[J]??null,c=G.env[L]??null;if(i){let p=re(t);p.length>0&&(s=p.length,n=p.filter(u=>u in G.env).length),r.info(` Session: ${n} of ${s} vars loaded (project: ${l}, config: ${i}, loaded at: ${c})`)}else r.info(" Session: no env loaded");r.info(` Session ID: ${o}`);let m={sessionId:o,sessionLoadedCount:n,sessionTotalCount:s,sessionConfig:i,sessionProject:l,sessionLoadedAt:c};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}},Lr={name:"env-status",description:"Show Doppler authentication status and detected project info",inputSchema:{},outputSchema:{sessionId:F.string().describe("Current terminal session ID"),sessionLoadedCount:F.number().describe("Number of cached vars active in the current session"),sessionTotalCount:F.number().describe("Total number of cached var names"),sessionConfig:F.string().nullable().describe("Doppler config name of the loaded session"),sessionProject:F.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:F.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:ce};import Vr from"@inquirer/checkbox";import Fr from"@inquirer/confirm";import Wr from"node:process";import{z as W}from"zod";import{$}from"zx";import{$ as xs}from"zx";import rr from"node:process";import{$ as C}from"zx";var Ie=e=>e.replace("release/","").slice(1).split(".").map(Number),Pe=e=>[...e].sort((o,t)=>{let[n,s,i]=Ie(o),[l,c,m]=Ie(t);return n!==l?(n??0)-(l??0):s!==c?(s??0)-(c??0):(i??0)-(m??0)});var y=async()=>{try{let e=await C`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,o=JSON.parse(e.stdout);o.length===0&&(r.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),rr.exit(1));let t=o.map(n=>n.headRefName);return Pe(t)}catch(e){r.error({error:e},"\u274C Error fetching release PRs"),rr.exit(1)}},le=async e=>{let{version:o,jiraVersionUrl:t}=e,n=`release/v${o}`;try{C.quiet=!0,await C`git switch dev`,await C`git pull origin dev`,await C`git checkout -b ${n}`,await C`git push -u origin ${n}`,await C`git commit --allow-empty-message --allow-empty --message ''`,await C`git push origin ${n}`;let i=(await C`gh pr create --title "Release v${o}" --body "${t} \n" --base dev --head ${n}`).stdout.trim();return await C`git switch dev`,C.quiet=!1,{branchName:n,prUrl:i}}catch(s){throw r.error({error:s,branchName:n},`Error creating release branch ${n}`),s}};var pe=async e=>{let{all:o,confirmedCommand:t}=e;a.start("merge-dev");let n=await y();if(n.length===0)return r.info("\u2139\uFE0F No open release branches found"),a.print(),{content:[{type:"text",text:JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)}],structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let s=[];o?s=n:(a.setInteractive(),s=await Vr({required:!0,message:"\u{1F33F} Select release branches",choices:n.map(p=>({name:p.replace("release/v",""),value:p}))}));let i=s.length===n.length;i?a.addOption("--all",!0):a.addOption("--branches",s);let l=t?!0:await Fr({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||a.setInteractive(),l||(r.info("Operation cancelled. Exiting..."),Wr.exit(0)),i&&a.addOption("--yes",!0),$.quiet=!0,await $`git fetch origin`,await $`git switch dev`,await $`git pull origin dev`;let c=[];for(let p of s)await Mr(p)||c.push(p);if($.quiet=!1,c.length>0){r.info(`
20
- \u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
21
- `),r.info(`\u{1F4CB} Manual merge script for failed branches:
22
- `),r.info("```bash");for(let p of c)r.info(`# Phase #1: Merge dev into ${p}`),r.info(`git switch ${p} && git pull origin ${p} && git merge origin/dev`),r.info("# Phase #2:Resolve conflicts if any, then:"),r.info(`git push origin ${p} && git switch dev`);r.info(`\u2705 ${s.length-c.length}/${s.length} merges completed successfully.`)}else r.info("\u2705 All merges completed successfully!");a.print();let m={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}},Mr=async e=>{try{return await $`git switch ${e}`,await $`git pull origin ${e}`,await $`git merge origin/dev --no-edit`,await $`git push origin ${e}`,await $`git switch dev`,r.info(`Successfully merged dev into ${e}`),!0}catch(o){return r.error({error:o,branch:e},`Error merging dev into ${e}`),await $`git reset --merge HEAD~1`,!1}},Br={name:"gh-merge-dev",description:"Merge dev branch into selected release branches",inputSchema:{all:W.boolean().describe("Merge dev into all release branches without prompting")},outputSchema:{successfulMerges:W.number().describe("Number of successful merges"),failedMerges:W.number().describe("Number of failed merges"),failedBranches:W.array(W.string()).describe("List of branches that failed to merge"),totalBranches:W.number().describe("Total number of branches processed")},handler:pe};import zr from"@inquirer/confirm";import Kr from"@inquirer/select";import De from"node:process";import{z as me}from"zod";import{$ as T}from"zx";import z from"node:process";var Ne=async(e,o)=>{try{let{baseUrl:t,token:n,email:s,projectId:i}=o,l={name:e.name,projectId:e.projectId||i,description:e.description||"",released:e.released||!1,archived:e.archived||!1},c=`${t}/rest/api/3/version`,m=btoa(`${s}:${n}`),p=await fetch(c,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${m}`},body:JSON.stringify(l)});if(!p.ok){let d=await p.text();throw r.error({status:p.status,statusText:p.statusText,error:d},"Failed to create Jira version"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return{success:!0,version:await p.json()}}catch(t){throw r.error({error:t},"Error creating Jira version"),t}},Ur=async e=>{try{let{baseUrl:o,token:t,email:n,projectId:s}=e,i=`${o}/rest/api/3/project/${s}/versions`,l=btoa(`${n}:${t}`),c=await fetch(i,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${l}`}});if(!c.ok){let p=await c.text();throw r.error({status:c.status,statusText:c.statusText,error:p},"Failed to get Jira project versions"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return await c.json()}catch(o){throw r.error({error:o},"Error getting Jira project versions"),o}},qr=async(e,o)=>{try{return(await Ur(o)).find(s=>s.name===e)||null}catch(t){throw r.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Gr=async(e,o)=>{try{let{baseUrl:t,token:n,email:s}=o,i={released:e.released??!0,archived:e.archived??!1};e.releaseDate?i.releaseDate=e.releaseDate:e.released!==!1&&(i.releaseDate=new Date().toISOString().split("T")[0]),e.description!==void 0&&(i.description=e.description);let l=`${t}/rest/api/3/version/${e.versionId}`,c=btoa(`${s}:${n}`),m=await fetch(l,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});if(!m.ok){let u=await m.text();throw r.error({status:m.status,statusText:m.statusText,error:u},"Failed to update Jira version"),new Error(`HTTP ${m.status}: ${m.statusText}`)}return{success:!0,version:await m.json()}}catch(t){throw r.error({error:t},"Error updating Jira version"),t}},_e=async(e,o)=>{try{let{versionName:t}=e,n=await qr(t,o);if(!n)throw r.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Gr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},o)}catch(t){throw r.error({error:t},"Error delivering Jira release"),t}},M=async()=>{let e=z.env.JIRA_BASE_URL,o=z.env.JIRA_TOKEN||z.env.JIRA_API_TOKEN,t=z.env.JIRA_PROJECT_ID,n=z.env.JIRA_EMAIL,s=[];if(e||s.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),o||s.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||s.push("JIRA_PROJECT_ID (numeric project ID)"),n||s.push("JIRA_EMAIL (your Jira email address)"),s.length>0){let l=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...s.map(c=>` - ${c}`),"","You can set these in your .env file or as environment variables."].join(`
23
- `);throw new Error(l)}let i=Number.parseInt(t,10);if(Number.isNaN(i))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:o,projectId:i,email:n}},Oe=async()=>{try{return await M()}catch(e){return r.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var de=async e=>{let{version:o,confirmedCommand:t}=e;a.start("release-deliver");let n=await y(),s="";o?s=`release/v${o}`:(a.setInteractive(),s=await Kr({message:"\u{1F33F} Select release branch",choices:n.map(c=>({name:c.replace("release/v",""),value:c}))}));let i=s.replace("release/v","");a.addOption("--version",i),n.includes(s)||(r.error(`\u274C Release branch ${s} not found in open PRs. Exiting...`),De.exit(1));let l=t?!0:await zr({message:`Are you sure you want to deliver version ${s} to production?`});t||a.setInteractive(),l||(r.info("Operation cancelled. Exiting..."),De.exit(0)),a.addOption("--yes",!0);try{T.quiet=!0,await T`gh pr merge ${s} --squash --admin --delete-branch`,await T`gh pr create --base main --head dev --title "Release v${s.replace("release/v","")} (RC)" --body ""`,await T`gh pr merge dev --squash --admin`,T.quiet=!1,await T`gh workflow run deploy-all.yml --ref main -f environment=prod`,T.quiet=!0,await T`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`,T.quiet=!1;let c=await Oe();if(c)try{let p=s.replace("release/","");await _e({versionName:p},c)}catch(p){r.error({error:p},"Failed to deliver Jira release (non-blocking)")}else r.info("\u{1F514} Jira is not configured, skipping Jira release delivery");r.info(`Successfully delivered ${s} to production!`),a.print();let m={releaseBranch:s,version:s.replace("release/v",""),success:!0};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}}catch(c){r.error({error:c},"\u274C Error merging release branch into dev"),De.exit(1)}},Hr={name:"gh-release-deliver",description:"Deliver a release branch to production",inputSchema:{version:me.string().describe('Version to deliver to production (e.g., "1.2.5")')},outputSchema:{releaseBranch:me.string().describe("The release branch that was delivered"),version:me.string().describe("The version that was delivered"),success:me.boolean().describe("Whether the delivery was successful")},handler:de};import tr from"@inquirer/select";import Je from"node:process";import{z as I}from"zod";import{$ as Le}from"zx";var ue=async e=>{let{version:o,env:t,skipTerraform:n}=e;a.start("release-deploy-all");let s=["dev"],i=await y();s.push(...i);let l="";o?l=o==="dev"?"dev":`release/v${o}`:(a.setInteractive(),l=await tr({message:"\u{1F33F} Select release branch",choices:s.map(u=>({name:u.replace("release/v",""),value:u}))}));let c=l==="dev"?"dev":l.replace("release/v","");a.addOption("--version",c),s.includes(l)||(r.error(`\u274C Release branch ${l} not found in open PRs. Exiting...`),Je.exit(1));let m="";t?m=t:(a.setInteractive(),m=await tr({message:"\u{1F9EA} Select environment",choices:R.map(u=>({name:u,value:u}))})),a.addOption("--env",m),R.includes(m)||(r.error(`\u274C Invalid environment: ${m}. Exiting...`),Je.exit(1));let p=n??!1;p&&a.addOption("--skip-terraform",!0);try{Le.quiet=!0,await Le`gh workflow run deploy-all.yml --ref ${l} -f environment=${m} ${p?["-f","skip_terraform_deploy=true"]:[]}`,Le.quiet=!1,r.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${l} and environment: ${m}`),a.print();let d={releaseBranch:l,version:l.replace("release/v",""),environment:m,skipTerraformDeploy:p,success:!0};return{content:[{type:"text",text:JSON.stringify(d,null,2)}],structuredContent:d}}catch(u){r.error({error:u},"\u274C Error launching workflow"),Je.exit(1)}},Xr={name:"gh-release-deploy-all",description:"Deploy a release branch to a specified environment",inputSchema:{version:I.string().describe('Version to deploy (e.g., "1.2.5")'),env:I.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),skipTerraform:I.boolean().optional().describe("Skip terraform deployment step")},outputSchema:{releaseBranch:I.string().describe("The release branch that was deployed"),version:I.string().describe("The version that was deployed"),environment:I.string().describe("The environment deployed to"),skipTerraformDeploy:I.boolean().describe("Whether terraform deployment was skipped"),success:I.boolean().describe("Whether the deployment was successful")},handler:ue};import Yr from"@inquirer/checkbox";import or from"@inquirer/select";import Qr from"node:fs/promises";import{resolve as Zr}from"node:path";import B from"node:process";import et from"yaml";import{z as x}from"zod";import{$ as je}from"zx";var fe=async e=>{let{version:o,env:t,services:n,skipTerraform:s}=e;a.start("release-deploy-selected");let i=["dev"],l=await y();i.push(...l);let c="";o?c=o==="dev"?"dev":`release/v${o}`:(a.setInteractive(),c=await or({message:"\u{1F33F} Select release branch",choices:i.map(g=>({name:g.replace("release/v",""),value:g}))}));let m=c==="dev"?"dev":c.replace("release/v","");a.addOption("--version",m),i.includes(c)||(r.error(`\u274C Release branch ${c} not found in open PRs. Exiting...`),B.exit(1));let p="";t?p=t:(a.setInteractive(),p=await or({message:"\u{1F9EA} Select environment",choices:R.map(g=>({name:g,value:g}))})),a.addOption("--env",p),R.includes(p)||(r.error(`\u274C Invalid environment: ${p}. Exiting...`),B.exit(1));let u=await rt();u.length===0&&(r.error("\u274C No services found in workflow file. Exiting..."),B.exit(1));let d=[];n&&n.length>0?d=n:(a.setInteractive(),d=await Yr({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:u.map(g=>({name:g,value:g}))})),a.addOption("--services",d),d.length===0&&(r.error("\u274C No services selected. Exiting..."),B.exit(1));let h=d.filter(g=>!u.includes(g));h.length>0&&(r.error(`\u274C Invalid services: ${h.join(", ")}. Available services: ${u.join(", ")}`),B.exit(1));let f=s??!1;f&&a.addOption("--skip-terraform",!0);try{je.quiet=!0;let g=d.flatMap(mr=>["-f",`${mr}=true`]);await je`gh workflow run deploy-selected-services.yml --ref ${c} -f environment=${p} ${g} ${f?["-f","skip_terraform_deploy=true"]:[]}`,je.quiet=!1,r.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${c}, environment: ${p}, services: ${d.join(", ")}`),a.print();let qe={releaseBranch:c,version:c.replace("release/v",""),environment:p,services:d,skipTerraformDeploy:f,success:!0};return{content:[{type:"text",text:JSON.stringify(qe,null,2)}],structuredContent:qe}}catch(g){r.error({error:g},"\u274C Error launching workflow"),B.exit(1)}},rt=async()=>{let e=await b(),o=Zr(e,".github/workflows/deploy-selected-services.yml"),t=await Qr.readFile(o,"utf-8"),s=et.parse(t).on.workflow_dispatch.inputs,i=[];for(let[l,c]of Object.entries(s))c.type==="boolean"&&l!=="skip_terraform_deploy"&&i.push(l);return i},tt={name:"gh-release-deploy-selected",description:"Deploy selected services from a release branch to a specified environment",inputSchema:{version:x.string().describe('Version to deploy (e.g., "1.2.5")'),env:x.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),services:x.array(x.string()).describe('List of services to deploy (e.g., ["client-be", "client-fe"])'),skipTerraform:x.boolean().optional().describe("Skip terraform deployment step")},outputSchema:{releaseBranch:x.string().describe("The release branch that was deployed"),version:x.string().describe("The version that was deployed"),environment:x.string().describe("The environment deployed to"),services:x.array(x.string()).describe("The services that were deployed"),skipTerraformDeploy:x.boolean().describe("Whether terraform deployment was skipped"),success:x.boolean().describe("Whether the deployment was successful")},handler:fe};import Ve from"@inquirer/select";import ot from"node:fs/promises";import{resolve as st}from"node:path";import ge from"node:process";import nt from"yaml";import{z as E}from"zod";import{$ as Fe}from"zx";var he=async e=>{let{version:o,env:t,service:n,skipTerraform:s}=e;a.start("release-deploy-service");let i=["dev"],l=await y();i.push(...l);let c="";o?c=o==="dev"?"dev":`release/v${o}`:(a.setInteractive(),c=await Ve({message:"\u{1F33F} Select release branch",choices:i.map(f=>({name:f.replace("release/v",""),value:f}))}));let m=c==="dev"?"dev":c.replace("release/v","");a.addOption("--version",m),i.includes(c)||(r.error(`\u274C Release branch ${c} not found in open PRs. Exiting...`),ge.exit(1));let p="";t?p=t:(a.setInteractive(),p=await Ve({message:"\u{1F9EA} Select environment",choices:R.map(f=>({name:f,value:f}))})),a.addOption("--env",p),R.includes(p)||(r.error(`\u274C Invalid environment: ${p}. Exiting...`),ge.exit(1));let u=await it(),d="";n?d=n:(a.setInteractive(),d=await Ve({message:"\u{1F680} Select service to deploy",choices:u.map(f=>({name:f,value:f}))})),a.addOption("--service",d),u.includes(d)||(r.error(`\u274C Invalid service: ${d}. Available services: ${u.join(", ")}`),ge.exit(1));let h=s??!1;h&&a.addOption("--skip-terraform",!0);try{Fe.quiet=!0,await Fe`gh workflow run deploy-single-service.yml --ref ${c} -f environment=${p} -f service=${d} ${h?["-f","skip_terraform_deploy=true"]:[]}`,Fe.quiet=!1,r.info(`Successfully launched deploy-single-service workflow_dispatch for release branch: ${c}, environment: ${p}, service: ${d}`),a.print();let g={releaseBranch:c,version:c.replace("release/v",""),environment:p,service:d,skipTerraformDeploy:h,success:!0};return{content:[{type:"text",text:JSON.stringify(g,null,2)}],structuredContent:g}}catch(f){r.error({error:f},"\u274C Error launching workflow"),ge.exit(1)}},it=async()=>{let e=await b(),o=st(e,".github/workflows/deploy-single-service.yml"),t=await ot.readFile(o,"utf-8");return nt.parse(t).on.workflow_dispatch.inputs.service.options},at={name:"gh-release-deploy-service",description:"Deploy a specific service in a release branch to a specified environment",inputSchema:{version:E.string().describe('Version to deploy (e.g., "1.2.5")'),env:E.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),service:E.string().describe('Service to deploy (e.g., "client-be", "client-fe")'),skipTerraform:E.boolean().optional().describe("Skip terraform deployment step")},outputSchema:{releaseBranch:E.string().describe("The release branch that was deployed"),version:E.string().describe("The version that was deployed"),environment:E.string().describe("The environment deployed to"),service:E.string().describe("The service that was deployed"),skipTerraformDeploy:E.boolean().describe("Whether terraform deployment was skipped"),success:E.boolean().describe("Whether the deployment was successful")},handler:he};import{z as We}from"zod";var ve=async()=>{let o=(await y()).map(n=>n.replace("release/",""));r.info(`All release branches:
24
- `),r.info(`
25
- ${o.join(`
26
- `)}`);let t={releases:o,count:o.length};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},ct={name:"gh-release-list",description:"List all open release branches",inputSchema:{},outputSchema:{releases:We.array(We.string()).describe("List of all release branches"),count:We.number().describe("Number of release branches")},handler:ve};import sr from"@inquirer/confirm";import nr from"node:process";import{z as P}from"zod";import{$ as Me,question as ir}from"zx";import{$ as K}from"zx";var H=async()=>{K.quiet=!0,await K`git fetch origin`,await K`git switch dev`,await K`git pull origin dev`,K.quiet=!1},X=async(e,o,t)=>{let n=`v${e}`,s=await Ne({name:n,projectId:o.projectId,description:t||"",released:!1,archived:!1},o),i=`${o.baseUrl}/projects/${s.version.projectId}/versions/${s.version.id}/tab/release-report-all-issues`,l=await le({version:e,jiraVersionUrl:i});return{version:e,branchName:l.branchName,prUrl:l.prUrl,jiraVersionUrl:i}};var ye=async e=>{let{version:o,description:t,confirmedCommand:n,checkout:s}=e;a.start("release-create");let i=o,l=t,c=s,m=await M();i||(a.setInteractive(),i=await ir("Enter version (e.g. 1.2.5): ")),(!i||i.trim()==="")&&(r.error("No version provided. Exiting..."),nr.exit(1));let p=i.trim();a.addOption("--version",p),l===void 0&&(a.setInteractive(),l=await ir("Enter description (optional, press Enter to skip): "),l.trim()===""&&(l="")),l&&a.addOption("--description",l);let u=n?!0:await sr({message:`Are you sure you want to create release branch for version ${p}?`});n||a.setInteractive(),u||(r.info("Operation cancelled. Exiting..."),nr.exit(0)),a.addOption("--yes",!0),await H();let d=await X(p,m,l);r.info(`\u2705 Successfully created release: v${p}`),r.info(`\u{1F517} GitHub PR: ${d.prUrl}`),r.info(`\u{1F517} Jira Version: ${d.jiraVersionUrl}`),c===void 0&&(a.setInteractive(),c=await sr({message:`Do you want to checkout to the created branch ${d.branchName}?`,default:!0})),c||a.addOption("--no-checkout",!0),c&&(Me.quiet=!0,await Me`git switch ${d.branchName}`,Me.quiet=!1,r.info(`\u{1F504} Switched to branch ${d.branchName}`)),a.print();let h={version:p,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:d.jiraVersionUrl,isCheckedOut:c};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],structuredContent:h}},lt={name:"release-create",description:"Create a single release branch for specified version with Jira version creation",inputSchema:{version:P.string().describe('Version to create (e.g., "1.2.5")'),description:P.string().optional().describe("Optional description for the Jira version"),checkout:P.boolean().optional().default(!0).describe("Checkout to the created branch (default: true)")},outputSchema:{version:P.string().describe("Version number"),branchName:P.string().describe("Release branch name"),prUrl:P.string().describe("GitHub PR URL"),jiraVersionUrl:P.string().describe("Jira version URL"),isCheckedOut:P.boolean().describe("Whether the branch was checked out")},handler:ye};import pt from"@inquirer/confirm";import ar from"node:process";import{z as w}from"zod";import{question as mt}from"zx";var we=async e=>{let{versions:o,description:t,confirmedCommand:n}=e;a.start("release-create-batch");let s=o,i=await M();s||(a.setInteractive(),s=await mt("Enter versions by comma (e.g. 1.2.5, 1.2.6): "));let l=s.split(",").map(f=>f.trim());a.addOption("--versions",l.join(", ")),l.length===0&&(r.error("No versions provided. Exiting..."),ar.exit(1)),l.length===1&&r.warn('\u{1F4A1} You are creating only one release. Consider using "create-release" command for single releases.');let c=n?!0:await pt({message:`Are you sure you want to create release branches for these versions: ${l.join(", ")}?`});n||a.setInteractive(),c||(r.info("Operation cancelled. Exiting..."),ar.exit(0)),a.addOption("--yes",!0),t&&a.addOption("--description",t),await H();let m=[],p=[];for(let f of l)try{let g=await X(f,i,t);m.push(g),r.info(`\u2705 Successfully created release: v${f}`),r.info(`\u{1F517} GitHub PR: ${g.prUrl}`),r.info(`\u{1F517} Jira Version: ${g.jiraVersionUrl}
27
- `)}catch(g){let A=g instanceof Error?g.message:String(g);p.push({version:f,error:A}),r.error(`\u274C Failed to create release: v${f}`),r.error(` Error: ${A}
28
- `)}let u=m.length,d=p.length;u===l.length?r.info(`\u2705 All ${l.length} release branches were created successfully.`):u>0?(r.warn(`\u26A0\uFE0F ${u} of ${l.length} release branches were created successfully.`),r.warn(`\u274C ${d} release(s) failed.`)):r.error(`\u274C All ${l.length} release branches failed to create.`),a.print();let h={createdBranches:m.map(f=>f.branchName),successCount:u,failureCount:d,releases:m,failedReleases:p};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],structuredContent:h}},dt={name:"release-create-batch",description:"Create multiple release branches for specified versions with Jira version creation (batch operation)",inputSchema:{versions:w.string().describe('Comma-separated list of versions to create (e.g., "1.2.5, 1.2.6")'),description:w.string().optional().describe("Optional description for the Jira versions")},outputSchema:{createdBranches:w.array(w.string()).describe("List of created release branches"),successCount:w.number().describe("Number of releases created successfully"),failureCount:w.number().describe("Number of releases that failed"),releases:w.array(w.object({version:w.string().describe("Version number"),branchName:w.string().describe("Release branch name"),prUrl:w.string().describe("GitHub PR URL"),jiraVersionUrl:w.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:w.array(w.object({version:w.string().describe("Version number that failed"),error:w.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:we};import ut from"@inquirer/checkbox";import cr from"@inquirer/confirm";import{copyFileSync as ft,existsSync as gt}from"node:fs";import ht from"node:process";import{z as Y}from"zod";import{$ as Be}from"zx";var vt="feature",yt="release",wt="release/v",be=async e=>{let{confirmedCommand:o,all:t,cursor:n}=e;a.start("worktrees-add");try{let s=await S("release"),i=await b(),l=`${i}${V}`;await lr(`${l}/${yt}`),await lr(`${l}/${vt}`);let c=await y();if(c.length===0)return r.info("\u2139\uFE0F No open release branches found"),a.print(),{content:[{type:"text",text:JSON.stringify({createdWorktrees:[],count:0},null,2)}],structuredContent:{createdWorktrees:[],count:0}};let m=[];t?m=c:(a.setInteractive(),m=await ut({required:!0,message:"\u{1F33F} Select release branches",choices:c.map(A=>({name:A.replace("release/v",""),value:A}))}));let p=m.length===c.length;p?a.addOption("--all",!0):a.addOption("--branches",m);let u=o?!0:await cr({message:"Are you sure you want to proceed with these worktree changes?"});o||a.setInteractive(),u||(r.info("Operation cancelled. Exiting..."),ht.exit(0)),p&&a.addOption("--yes",!0);let d=n?!0:await cr({message:"Open created worktrees in Cursor?"});d||a.setInteractive(),d&&a.addOption("--cursor",!0);let{branchesToCreate:h}=bt({selectedReleaseBranches:m,currentWorktrees:s}),f=await Rt(h,l,i);if(kt(f),d)for(let A of f)await Be`cursor ${l}/${A}`;a.print();let g={createdWorktrees:f,count:f.length};return{content:[{type:"text",text:JSON.stringify(g,null,2)}],structuredContent:g}}catch(s){throw r.error({error:s},"\u274C Error managing worktrees"),s}},lr=async e=>{await Be`mkdir -p ${e}`},bt=e=>{let{selectedReleaseBranches:o,currentWorktrees:t}=e,n=t.filter(i=>i.startsWith(wt));return{branchesToCreate:o.filter(i=>!n.includes(i))}},Rt=async(e,o,t)=>{let n=[];for(let s of e)try{let i=`${o}/${s}`;await Be`git worktree add ${i} ${s}`;let l=`${t}/.env`;gt(l)&&(ft(l,`${i}/.env`),r.info("\u{1F4CB} Copied .env to worktree")),n.push(s)}catch(i){r.error({error:i,branch:s},`\u274C Failed to create worktree for ${s}`)}return n},kt=e=>{e.length>0?(r.info(`
29
- `),r.info("\u2705 Created worktrees:"),r.info(e.join(`
30
- `)),r.info("")):r.info("\u2139\uFE0F No new worktrees to create")},xt={name:"worktrees-add",description:"Create worktrees for selected release branches",inputSchema:{all:Y.boolean().describe("Add worktrees for all release branches without prompting"),cursor:Y.boolean().optional().describe("Open created worktrees in Cursor")},outputSchema:{createdWorktrees:Y.array(Y.string()).describe("List of created worktree branches"),count:Y.number().describe("Number of worktrees created")},handler:be};import{z as k}from"zod";import{$ as Q}from"zx";var Re=async()=>{try{let[e,o]=await Promise.all([S("release"),S("feature")]),t=await b(),n=await Ct(e,o,t);It(n);let s={worktrees:n,totalCount:n.length,releaseCount:e.length,featureCount:o.length};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}}catch(e){throw r.error({error:e},"\u274C Error listing worktrees"),e}},Ct=async(e,o,t)=>{let n=[...e.map(i=>({branch:i,type:"release"})),...o.map(i=>({branch:i,type:"feature"}))],s=[];for(let{branch:i,type:l}of n)try{let c=`${t}/${i}`,m=await $t(i),p=await St(c),u=await Et(c),d=await Tt(c),h=await At(c);s.push({branch:i,path:c,commit:p.substring(0,8),isCurrent:m,type:l,status:u,lastCommitMessage:d.substring(0,60)+(d.length>60?"...":""),aheadBehind:h})}catch(c){r.warn({error:c,branch:i},`\u26A0\uFE0F Could not process worktree ${i}`)}return s.sort((i,l)=>i.type!==l.type?i.type==="release"?-1:1:i.branch.localeCompare(l.branch))},$t=async e=>{try{return(await Q`git branch --show-current`).stdout.trim()===e}catch{return!1}},St=async e=>{try{return(await Q`cd ${e} && git rev-parse HEAD`).stdout.trim()}catch{return"unknown"}},Et=async e=>{try{let t=(await Q`cd ${e} && git status --porcelain`).stdout.trim().split(`
31
- `).filter(Boolean);return t.length===0?"clean":t.length<=3?"modified":"dirty"}catch{return"unknown"}},Tt=async e=>{try{return(await Q`cd ${e} && git log -1 --pretty=format:"%s"`).stdout.trim()}catch{return"No commit message available"}},At=async e=>{try{let t=(await Q`cd ${e} && git rev-list --count --left-right @{u}...HEAD 2>/dev/null || echo "0 0"`).stdout.trim().split(" ").map(Number),n=t[0]||0,s=t[1]||0;return s===0&&n===0?"up to date":s>0&&n===0?`\u2191${s} ahead`:n>0&&s===0?`\u2193${n} behind`:`\u2191${s} \u2193${n}`}catch{return"unknown"}},It=e=>{if(e.length===0){r.info(`
32
- \u{1F33F} Git Worktrees`),r.info("\u2500".repeat(80)),r.info("\u2139\uFE0F No worktrees found"),r.info("\u2500".repeat(80));return}r.info(`
33
- \u{1F33F} Git Worktrees`),r.info("\u2550".repeat(100));let o=e.filter(s=>s.type==="release"),t=e.filter(s=>s.type==="feature");pr("\u{1F680} Releases",o),t.length>0&&o.length>0&&r.info(""),pr("\u2728 Features",t);let n=e.find(s=>s.isCurrent);r.info(`
34
- ${"\u2550".repeat(100)}`),r.info(`\u{1F4CA} Summary: ${e.length} total worktrees (${o.length} releases, ${t.length} features)`),n&&r.info(`\u{1F4CD} Currently on: ${n.branch}`),r.info("")},pr=(e,o)=>{if(o.length!==0){r.info(`
35
- ${e}`),r.info("\u2500".repeat(50));for(let[t,n]of o.entries())Pt(n),t<o.length-1&&r.info("")}},Pt=e=>{let o=e.isCurrent?"\u{1F4CD}":" ",t=Nt(e.status),s=`${e.type==="release"?"\u{1F680}":"\u2728"} ${e.branch}`;r.info(`${o} ${t} ${s}`);let i=e.aheadBehind!=="unknown"?` | ${e.aheadBehind}`:"";r.info(` \u{1F4DD} ${e.commit}${i}`),r.info(` \u{1F4AC} ${e.lastCommitMessage}`);let l=e.path.split("/").slice(-2).join("/");r.info(` \u{1F4C1} ${l}`)},Nt=e=>{switch(e){case"clean":return"\u2705";case"modified":return"\u26A0\uFE0F ";case"dirty":return"\u{1F534}";default:return"\u2753"}},_t={name:"worktrees-list",description:"List all git worktrees with detailed information",inputSchema:{},outputSchema:{worktrees:k.array(k.object({branch:k.string(),path:k.string(),commit:k.string(),isCurrent:k.boolean(),type:k.enum(["release","feature"]),status:k.string(),lastCommitMessage:k.string(),aheadBehind:k.string()})).describe("List of all worktrees with details"),totalCount:k.number().describe("Total number of worktrees"),releaseCount:k.number().describe("Number of release worktrees"),featureCount:k.number().describe("Number of feature worktrees")},handler:Re};import Ot from"@inquirer/checkbox";import Dt from"@inquirer/confirm";import Jt from"node:process";import{z as ke}from"zod";import{$ as Lt}from"zx";var xe=async e=>{let{confirmedCommand:o,all:t}=e;a.start("worktrees-remove");try{let n=await S("release");if(n.length===0)return r.info("\u2139\uFE0F No active worktrees to remove"),a.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let i=`${await b()}${V}`,l=[];t?l=n:(a.setInteractive(),l=await Ot({required:!0,message:"\u{1F33F} Select release branches",choices:n.map(d=>({name:d.replace("release/v",""),value:d}))}));let c=l.length===n.length;c?a.addOption("--all",!0):a.addOption("--branches",l);let m=o?!0:await Dt({message:"Are you sure you want to proceed with these worktree changes?"});o||a.setInteractive(),m||(r.info("Operation cancelled. Exiting..."),Jt.exit(0)),c&&a.addOption("--yes",!0);let p=await jt(l,i);Vt(p),a.print();let u={removedWorktrees:p,count:p.length};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}}catch(n){throw r.error({error:n},"\u274C Error managing worktrees"),n}},jt=async(e,o)=>{let t=[];for(let n of e)try{let s=`${o}/${n}`;await Lt`git worktree remove ${s}`,t.push(n)}catch(s){r.error({error:s,branch:n},`\u274C Failed to remove worktree for ${n}`)}return t},Vt=e=>{e.length>0?(r.info("\u274C Removed worktrees:"),r.info(e.join(`
36
- `)),r.info("")):r.info("\u2139\uFE0F No unused worktrees to remove")},Ft={name:"worktrees-remove",description:"Remove selected worktrees",inputSchema:{all:ke.boolean().describe("Remove all worktrees without prompting")},outputSchema:{removedWorktrees:ke.array(ke.string()).describe("List of removed worktree branches"),count:ke.number().describe("Number of worktrees removed")},handler:xe};import Wt from"@inquirer/confirm";import Mt from"node:process";import{z as Ue}from"zod";import{$ as Bt}from"zx";var Ut="release/v",Ce=async e=>{let{confirmedCommand:o}=e;a.start("worktrees-sync");try{let t=await S("release"),s=`${await b()}${V}`,i=await y(),l=o?!0:await Wt({message:"Are you sure you want to proceed with these worktree changes?"});o||a.setInteractive(),l||(r.info("Operation cancelled. Exiting..."),Mt.exit(0)),o||a.addOption("--yes",!0);let{branchesToRemove:c}=qt({releasePRsList:i,currentWorktrees:t}),m=await Gt(c,s);zt(m),a.print();let p={removedWorktrees:m,count:m.length};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],structuredContent:p}}catch(t){throw r.error({error:t},"\u274C Error managing worktrees"),t}},qt=e=>{let{releasePRsList:o,currentWorktrees:t}=e;return{branchesToRemove:t.filter(i=>i.startsWith(Ut)).filter(i=>!o.includes(i))}},Gt=async(e,o)=>{let t=[];for(let n of e)try{let s=`${o}/${n}`;await Bt`git worktree remove ${s}`,t.push(n)}catch(s){r.error({error:s,branch:n},`\u274C Failed to remove worktree for ${n}`)}return t},zt=e=>{e.length>0?(r.info("\u274C Removed worktrees:"),r.info(e.join(`
37
- `)),r.info("")):r.info("\u2139\uFE0F No unused worktrees to remove")},Kt={name:"worktrees-sync",description:"Synchronize worktrees with active release branches",inputSchema:{},outputSchema:{removedWorktrees:Ue.array(Ue.string()).describe("List of removed worktree branches"),count:Ue.number().describe("Number of worktrees removed during sync")},handler:Ce};var v=new Ht;v.command("merge-dev").description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async e=>{await pe({all:e.all,confirmedCommand:e.yes})});v.command("release-list").description("List all release branches").action(async()=>{await ve()});v.command("release-create").description("Create a single release branch").option("-v, --version <version>","Specify the version to create, e.g. 1.2.5").option("-d, --description <description>","Optional description for the Jira version").option("-y, --yes","Skip confirmation prompt").option("--no-checkout","Do not checkout the created branch after creation (checkout is default)").action(async e=>{await ye({version:e.version,description:e.description,confirmedCommand:e.yes,checkout:e.checkout})});v.command("release-create-batch").description("Create multiple release branches (batch operation)").option("-v, --versions <versions>","Specify the versions to create by comma, e.g. 1.2.5, 1.2.6").option("-d, --description <description>","Optional description for the Jira versions").option("-y, --yes","Skip confirmation prompt").action(async e=>{await we({versions:e.versions,description:e.description,confirmedCommand:e.yes})});v.command("release-deploy-all").description("Deploy any release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await ue({version:e.version,env:e.env,skipTerraform:e.skipTerraform})});v.command("release-deploy-service").description("Deploy specific service in release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --service <service>","Specify the service to deploy, e.g. client-be").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await he({version:e.version,env:e.env,service:e.service,skipTerraform:e.skipTerraform})});v.command("release-deploy-selected").description("Deploy selected services from release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await fe({version:e.version,env:e.env,services:e.services,skipTerraform:e.skipTerraform})});v.command("release-deliver").description("Release a new version to production").option("-v, --version <version>","Specify the version to release, e.g. 1.2.5").option("-y, --yes","Skip confirmation prompt").action(async e=>{await de({version:e.version,confirmedCommand:e.yes})});v.command("worktrees-sync").description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Ce({confirmedCommand:e.yes})});v.command("worktrees-add").description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-c, --cursor","Open created worktrees in Cursor").action(async e=>{await be({confirmedCommand:e.yes,all:e.all,cursor:e.cursor})});v.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await Re()});v.command("worktrees-remove").description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").action(async e=>{await xe({confirmedCommand:e.yes,all:e.all})});v.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await ee()});v.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await ce()});v.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await ie()});v.command("env-init").description("Set up shell functions for env-load/env-clear in .zshrc").action(async()=>{await Ee()});v.command("env-load").description("Load Doppler env vars for a config. Prints a file path to stdout \u2014 auto-sourced by the env-load shell alias, or run source <path> manually").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async e=>{await ae({config:e.config})});v.command("env-clear").description("Clear loaded env vars. Prints a file path to stdout \u2014 auto-sourced by the env-clear shell alias, or run source <path> manually").action(async()=>{await se()});v.parse();
17
+ `),fr.stdout.write(`${m}
18
+ `);let u={variableCount:i.split(`
19
+ `).filter(f=>f.includes("=")).length,project:s,config:t};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}},Kr={name:"env-load",description:"Load Doppler env vars for a config. Returns a file path that must be sourced (source <path>) to apply variables. The env-load shell alias does this automatically.",inputSchema:{config:ee.string().describe("Environment config name to load (e.g. dev, arthur, renana)")},outputSchema:{filePath:ee.string().describe("Path to the file that must be sourced to apply variables"),variableCount:ee.number().describe("Number of variables loaded"),project:ee.string().describe("Doppler project name"),config:ee.string().describe("Doppler config name")},handler:be};import Hr from"node:path";import re from"node:process";import{z}from"zod";var we=async()=>{await j(),o.info("Environment session status:");let e=U(),r=re.env[Fe],t=Hr.join(e,W),s=0,n=0,i=re.env[F]??null,a=re.env[M]??null,p=re.env[q]??null;if(i){let m=de(t);m.length>0&&(n=m.length,s=m.filter(u=>u in re.env).length);let d=p?.replace(/\.\d{3}Z$/,"")??null;o.info(` ${i}: ${s} of ${n} vars loaded (project: ${a}, loadedAt: ${d}, session: ${r})
20
+ `)}else o.info(` Session ${r}: no env loaded
21
+ `);let l={sessionId:r,sessionLoadedCount:s,sessionTotalCount:n,sessionConfig:i,sessionProject:a,sessionLoadedAt:p};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],structuredContent:l}},Xr={name:"env-status",description:"Show Doppler authentication status and detected project info",inputSchema:{},outputSchema:{sessionId:z.string().describe("Current terminal session ID"),sessionLoadedCount:z.number().describe("Number of cached vars active in the current session"),sessionTotalCount:z.number().describe("Total number of cached var names"),sessionConfig:z.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:z.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:z.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:we};import et from"@inquirer/checkbox";import rt from"@inquirer/confirm";import tt from"node:process";import{z as H}from"zod";import{$ as N}from"zx";import{$ as _s}from"zx";import Te from"node:process";import{$ as A}from"zx";import{$ as se}from"zx";import te from"node:process";var Ge=async(e,r)=>{try{let{baseUrl:t,token:s,email:n,projectId:i}=r,a={name:e.name,projectId:e.projectId||i,description:e.description||"",released:e.released||!1,archived:e.archived||!1},p=`${t}/rest/api/3/version`,l=btoa(`${n}:${s}`),m=await fetch(p,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(a)});if(!m.ok){let u=await m.text();throw o.error({status:m.status,statusText:m.statusText,error:u},"Failed to create Jira version"),new Error(`HTTP ${m.status}: ${m.statusText}`)}return{success:!0,version:await m.json()}}catch(t){throw o.error({error:t},"Error creating Jira version"),t}},Re=async e=>{try{let{baseUrl:r,token:t,email:s,projectId:n}=e,i=`${r}/rest/api/3/project/${n}/versions`,a=btoa(`${s}:${t}`),p=await fetch(i,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${a}`}});if(!p.ok){let m=await p.text();throw o.error({status:p.status,statusText:p.statusText,error:m},"Failed to get Jira project versions"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return await p.json()}catch(r){throw o.error({error:r},"Error getting Jira project versions"),r}},Zr=async(e,r)=>{try{return(await Re(r)).find(n=>n.name===e)||null}catch(t){throw o.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Qr=async(e,r)=>{try{let{baseUrl:t,token:s,email:n}=r,i={released:e.released??!0,archived:e.archived??!1};e.releaseDate?i.releaseDate=e.releaseDate:e.released!==!1&&(i.releaseDate=new Date().toISOString().split("T")[0]),e.description!==void 0&&(i.description=e.description);let a=`${t}/rest/api/3/version/${e.versionId}`,p=btoa(`${n}:${s}`),l=await fetch(a,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${p}`},body:JSON.stringify(i)});if(!l.ok){let d=await l.text();throw o.error({status:l.status,statusText:l.statusText,error:d},"Failed to update Jira version"),new Error(`HTTP ${l.status}: ${l.statusText}`)}return{success:!0,version:await l.json()}}catch(t){throw o.error({error:t},"Error updating Jira version"),t}},ze=async(e,r)=>{try{let{versionName:t}=e,s=await Zr(t,r);if(!s)throw o.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Qr({versionId:s.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw o.error({error:t},"Error delivering Jira release"),t}},K=async()=>{let e=te.env.JIRA_BASE_URL,r=te.env.JIRA_TOKEN||te.env.JIRA_API_TOKEN,t=te.env.JIRA_PROJECT_ID,s=te.env.JIRA_EMAIL,n=[];if(e||n.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||n.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||n.push("JIRA_PROJECT_ID (numeric project ID)"),s||n.push("JIRA_EMAIL (your Jira email address)"),n.length>0){let a=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...n.map(p=>` - ${p}`),"","You can set these in your .env file or as environment variables."].join(`
22
+ `);throw new Error(a)}let i=Number.parseInt(t,10);if(Number.isNaN(i))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:i,email:s}},oe=async()=>{try{return await K()}catch(e){return o.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var ke=e=>e==="hotfix"?"main":"dev",ne=async(e="regular")=>{let r=ke(e);se.quiet=!0,await se`git fetch origin`,await se`git switch ${r}`,await se`git pull origin ${r}`,se.quiet=!1},ie=async e=>{let{version:r,jiraConfig:t,description:s,type:n="regular"}=e,i=`v${r}`,a=await Ge({name:i,projectId:t.projectId,description:s||"",released:!1,archived:!1},t),p=`${t.baseUrl}/projects/${a.version.projectId}/versions/${a.version.id}/tab/release-report-all-issues`,l=await Ce({version:r,jiraVersionUrl:p,type:n});return{version:r,type:n,branchName:l.branchName,prUrl:l.prUrl,jiraVersionUrl:p}},R=async()=>{let e=new Map,r=await oe();if(!r)return e;try{let t=await Re(r);for(let s of t)s.description&&e.set(s.name,s.description)}catch{}return e},xe=(e,r,t)=>{let s=t?" ".repeat(t-e.length+3):" ";return`${e}${s}[${r}]`},b=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",C=e=>{let{branches:r,descriptions:t,types:s}=e,n=r.map(a=>a.replace("release/v","")),i=Math.max(...n.map(a=>a.length));return r.map((a,p)=>{let l=n[p],m=s?s.get(a)||"regular":void 0,d=t.get(`v${l}`),u=" ".repeat(i-l.length+3),f=m?xe(l,m,i):l;return d&&(f=m?`${f} ${d}`:`${l}${u}${d}`),{name:f,value:a}})};var Ke=e=>e.replace("release/","").slice(1).split(".").map(Number),$e=e=>[...e].sort((r,t)=>{let[s,n,i]=Ke(r),[a,p,l]=Ke(t);return s!==a?(s??0)-(a??0):n!==p?(n??0)-(p??0):(i??0)-(l??0)});var gr=async()=>{let e=await A`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await A`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],s=new Set;return t.filter(n=>s.has(n.headRefName)?!1:(s.add(n.headRefName),!0))},Se=async()=>{try{let e=await gr();return e.length===0&&(o.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Te.exit(1)),$e(e.map(r=>r.headRefName))}catch(e){o.error({error:e},"\u274C Error fetching release PRs"),Te.exit(1)}},w=async()=>{try{let e=await gr();e.length===0&&(o.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Te.exit(1));let r=$e(e.map(s=>s.headRefName)),t=new Map(e.map(s=>[s.headRefName,s]));return r.map(s=>({branch:s,title:t.get(s).title}))}catch(e){o.error({error:e},"\u274C Error fetching release PRs"),Te.exit(1)}},Ce=async e=>{let{version:r,jiraVersionUrl:t,type:s}=e,n=s==="hotfix"?"Hotfix":"Release",i=ke(s),a=`release/v${r}`;try{A.quiet=!0,await A`git switch ${i}`,await A`git pull origin ${i}`,await A`git checkout -b ${a}`,await A`git push -u origin ${a}`,await A`git commit --allow-empty-message --allow-empty --message ''`,await A`git push origin ${a}`;let l=(await A`gh pr create --title "${n} v${r}" --body "${t} \n" --base ${i} --head ${a}`).stdout.trim();return await A`git switch ${i}`,A.quiet=!1,{branchName:a,prUrl:l}}catch(p){throw o.error({error:p,branchName:a},`Error creating release branch ${a}`),p}};var Ee=async e=>{let{all:r,confirmedCommand:t}=e;c.start("merge-dev");let n=(await w()).filter(d=>b(d.title)==="regular").map(d=>d.branch);if(n.length===0)return o.info("\u2139\uFE0F No open release branches found"),c.print(),{content:[{type:"text",text:JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)}],structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let i=[];if(r)i=n;else{c.setInteractive();let d=await R();i=await et({required:!0,message:"\u{1F33F} Select release branches",choices:C({branches:n,descriptions:d})})}let a=i.length===n.length;a?c.addOption("--all",!0):c.addOption("--versions",i.map(d=>d.replace("release/v","")));let p=t?!0:await rt({message:`Are you sure you want to merge dev into these branches: ${i.join(", ")}?`});t||c.setInteractive(),p||(o.info("Operation cancelled. Exiting..."),tt.exit(0)),a&&c.addOption("--yes",!0),N.quiet=!0,await N`git fetch origin`,await N`git switch dev`,await N`git pull origin dev`;let l=[];for(let d of i)await ot(d)||l.push(d);if(N.quiet=!1,l.length>0){o.info(`
23
+ \u26A0\uFE0F ${l.length} branch(es) failed to merge automatically.
24
+ `),o.info(`\u{1F4CB} Manual merge script for failed branches:
25
+ `),o.info("```bash");for(let d of l)o.info(`# Phase #1: Merge dev into ${d}`),o.info(`git switch ${d} && git pull origin ${d} && git merge origin/dev`),o.info("# Phase #2:Resolve conflicts if any, then:"),o.info(`git push origin ${d} && git switch dev`);o.info(`\u2705 ${i.length-l.length}/${i.length} merges completed successfully.`)}else o.info("\u2705 All merges completed successfully!");c.print();let m={successfulMerges:i.length-l.length,failedMerges:l.length,failedBranches:l,totalBranches:i.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}},ot=async e=>{try{return await N`git switch ${e}`,await N`git pull origin ${e}`,await N`git merge origin/dev --no-edit`,await N`git push origin ${e}`,await N`git switch dev`,o.info(`Successfully merged dev into ${e}`),!0}catch(r){return o.error({error:r,branch:e},`Error merging dev into ${e}`),await N`git reset --merge HEAD~1`,!1}},st={name:"gh-merge-dev",description:"Merge dev branch into selected release branches",inputSchema:{all:H.boolean().describe("Merge dev into all release branches without prompting")},outputSchema:{successfulMerges:H.number().describe("Number of successful merges"),failedMerges:H.number().describe("Number of failed merges"),failedBranches:H.array(H.string()).describe("List of branches that failed to merge"),totalBranches:H.number().describe("Total number of branches processed")},handler:Ee};import nt from"@inquirer/confirm";import it from"@inquirer/select";import He from"node:process";import{z as ae}from"zod";import{$ as S}from"zx";var Ie=async e=>{let{version:r,confirmedCommand:t}=e;c.start("release-deliver");let s=await w(),n=s.map(u=>u.branch),i=new Map(s.map(u=>[u.branch,b(u.title)])),a="";if(r)a=`release/v${r}`;else{c.setInteractive();let u=await R();a=await it({message:"\u{1F33F} Select release branch",choices:C({branches:n,descriptions:u,types:i})})}let p=a.replace("release/v","");c.addOption("--version",p);let l=s.find(u=>u.branch===a);l||(o.error(`\u274C Release branch ${a} not found in open PRs. Exiting...`),He.exit(1));let m=b(l.title),d=t?!0:await nt({message:`Are you sure you want to deliver version ${a} to production?`});t||c.setInteractive(),d||(o.info("Operation cancelled. Exiting..."),He.exit(0)),c.addOption("--yes",!0);try{S.quiet=!0,m==="hotfix"?(await S`gh pr merge ${a} --squash --admin --delete-branch`,S.quiet=!1,await S`gh workflow run deploy-all.yml --ref main -f environment=prod`,S.quiet=!0,await S`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`):(await S`gh pr merge ${a} --squash --admin --delete-branch`,await S`gh pr create --base main --head dev --title "Release v${p} (RC)" --body ""`,await S`gh pr merge dev --squash --admin`,S.quiet=!1,await S`gh workflow run deploy-all.yml --ref main -f environment=prod`,S.quiet=!0,await S`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`),S.quiet=!1;let u=await oe();if(u)try{let g=a.replace("release/","");await ze({versionName:g},u)}catch(g){o.error({error:g},"Failed to deliver Jira release (non-blocking)")}else o.info("\u{1F514} Jira is not configured, skipping Jira release delivery");o.info(`Successfully delivered ${a} to production!`),c.print();let f={releaseBranch:a,version:a.replace("release/v",""),type:m,success:!0};return{content:[{type:"text",text:JSON.stringify(f,null,2)}],structuredContent:f}}catch(u){o.error({error:u},"\u274C Error merging release branch into dev"),He.exit(1)}},at={name:"gh-release-deliver",description:"Deliver a release branch to production",inputSchema:{version:ae.string().describe('Version to deliver to production (e.g., "1.2.5")')},outputSchema:{releaseBranch:ae.string().describe("The release branch that was delivered"),version:ae.string().describe("The version that was delivered"),type:ae.enum(["regular","hotfix"]).describe("Release type"),success:ae.boolean().describe("Whether the delivery was successful")},handler:Ie};import hr from"@inquirer/select";import Xe from"node:process";import{z as L}from"zod";import{$ as Ye}from"zx";var Ae=async e=>{let{version:r,env:t,skipTerraform:s}=e;c.start("release-deploy-all");let n=await w(),i=n.map(f=>f.branch),a=new Map(n.map(f=>[f.branch,b(f.title)])),p=["dev",...i],l="";if(r)l=r==="dev"?"dev":`release/v${r}`;else{c.setInteractive();let f=await R();l=await hr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...C({branches:i,descriptions:f,types:a})]})}let m=l==="dev"?"dev":l.replace("release/v","");c.addOption("--version",m),p.includes(l)||(o.error(`\u274C Release branch ${l} not found in open PRs. Exiting...`),Xe.exit(1));let d="";t?d=t:(c.setInteractive(),d=await hr({message:"\u{1F9EA} Select environment",choices:T.map(f=>({name:f,value:f}))})),c.addOption("--env",d),T.includes(d)||(o.error(`\u274C Invalid environment: ${d}. Exiting...`),Xe.exit(1));let u=s??!1;u&&c.addOption("--skip-terraform",!0);try{Ye.quiet=!0,await Ye`gh workflow run deploy-all.yml --ref ${l} -f environment=${d} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Ye.quiet=!1,o.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${l} and environment: ${d}`),c.print();let g={releaseBranch:l,version:l.replace("release/v",""),environment:d,skipTerraformDeploy:u,success:!0};return{content:[{type:"text",text:JSON.stringify(g,null,2)}],structuredContent:g}}catch(f){o.error({error:f},"\u274C Error launching workflow"),Xe.exit(1)}},ct={name:"gh-release-deploy-all",description:"Deploy a release branch to a specified environment",inputSchema:{version:L.string().describe('Version to deploy (e.g., "1.2.5")'),env:L.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),skipTerraform:L.boolean().optional().describe("Skip terraform deployment step")},outputSchema:{releaseBranch:L.string().describe("The release branch that was deployed"),version:L.string().describe("The version that was deployed"),environment:L.string().describe("The environment deployed to"),skipTerraformDeploy:L.boolean().describe("Whether terraform deployment was skipped"),success:L.boolean().describe("Whether the deployment was successful")},handler:Ae};import lt from"@inquirer/checkbox";import vr from"@inquirer/select";import pt from"node:fs/promises";import{resolve as mt}from"node:path";import X from"node:process";import ut from"yaml";import{z as P}from"zod";import{$ as Ze}from"zx";var Pe=async e=>{let{version:r,env:t,services:s,skipTerraform:n}=e;c.start("release-deploy-selected");let i=await w(),a=i.map(v=>v.branch),p=new Map(i.map(v=>[v.branch,b(v.title)])),l=["dev",...a],m="";if(r)m=r==="dev"?"dev":`release/v${r}`;else{c.setInteractive();let v=await R();m=await vr({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...C({branches:a,descriptions:v,types:p})]})}let d=m==="dev"?"dev":m.replace("release/v","");c.addOption("--version",d),l.includes(m)||(o.error(`\u274C Release branch ${m} not found in open PRs. Exiting...`),X.exit(1));let u="";t?u=t:(c.setInteractive(),u=await vr({message:"\u{1F9EA} Select environment",choices:T.map(v=>({name:v,value:v}))})),c.addOption("--env",u),T.includes(u)||(o.error(`\u274C Invalid environment: ${u}. Exiting...`),X.exit(1));let f=await dt();f.length===0&&(o.error("\u274C No services found in workflow file. Exiting..."),X.exit(1));let g=[];s&&s.length>0?g=s:(c.setInteractive(),g=await lt({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:f.map(v=>({name:v,value:v}))})),c.addOption("--services",g),g.length===0&&(o.error("\u274C No services selected. Exiting..."),X.exit(1));let E=g.filter(v=>!f.includes(v));E.length>0&&(o.error(`\u274C Invalid services: ${E.join(", ")}. Available services: ${f.join(", ")}`),X.exit(1));let h=n??!1;h&&c.addOption("--skip-terraform",!0);try{Ze.quiet=!0;let v=g.flatMap(pe=>["-f",`${pe}=true`]);await Ze`gh workflow run deploy-selected-services.yml --ref ${m} -f environment=${u} ${v} ${h?["-f","skip_terraform_deploy=true"]:[]}`,Ze.quiet=!1,o.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${m}, environment: ${u}, services: ${g.join(", ")}`),c.print();let J={releaseBranch:m,version:m.replace("release/v",""),environment:u,services:g,skipTerraformDeploy:h,success:!0};return{content:[{type:"text",text:JSON.stringify(J,null,2)}],structuredContent:J}}catch(v){o.error({error:v},"\u274C Error launching workflow"),X.exit(1)}},dt=async()=>{let e=await x(),r=mt(e,".github/workflows/deploy-selected-services.yml"),t=await pt.readFile(r,"utf-8"),n=ut.parse(t).on.workflow_dispatch.inputs,i=[];for(let[a,p]of Object.entries(n))p.type==="boolean"&&a!=="skip_terraform_deploy"&&i.push(a);return i},ft={name:"gh-release-deploy-selected",description:"Deploy selected services from a release branch to a specified environment",inputSchema:{version:P.string().describe('Version to deploy (e.g., "1.2.5")'),env:P.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),services:P.array(P.string()).describe('List of services to deploy (e.g., ["client-be", "client-fe"])'),skipTerraform:P.boolean().optional().describe("Skip terraform deployment step")},outputSchema:{releaseBranch:P.string().describe("The release branch that was deployed"),version:P.string().describe("The version that was deployed"),environment:P.string().describe("The environment deployed to"),services:P.array(P.string()).describe("The services that were deployed"),skipTerraformDeploy:P.boolean().describe("Whether terraform deployment was skipped"),success:P.boolean().describe("Whether the deployment was successful")},handler:Pe};import Qe from"@inquirer/select";import gt from"node:fs/promises";import{resolve as ht}from"node:path";import Ne from"node:process";import vt from"yaml";import{z as O}from"zod";import{$ as er}from"zx";var De=async e=>{let{version:r,env:t,service:s,skipTerraform:n}=e;c.start("release-deploy-service");let i=await w(),a=i.map(h=>h.branch),p=new Map(i.map(h=>[h.branch,b(h.title)])),l=["dev",...a],m="";if(r)m=r==="dev"?"dev":`release/v${r}`;else{c.setInteractive();let h=await R();m=await Qe({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...C({branches:a,descriptions:h,types:p})]})}let d=m==="dev"?"dev":m.replace("release/v","");c.addOption("--version",d),l.includes(m)||(o.error(`\u274C Release branch ${m} not found in open PRs. Exiting...`),Ne.exit(1));let u="";t?u=t:(c.setInteractive(),u=await Qe({message:"\u{1F9EA} Select environment",choices:T.map(h=>({name:h,value:h}))})),c.addOption("--env",u),T.includes(u)||(o.error(`\u274C Invalid environment: ${u}. Exiting...`),Ne.exit(1));let f=await yt(),g="";s?g=s:(c.setInteractive(),g=await Qe({message:"\u{1F680} Select service to deploy",choices:f.map(h=>({name:h,value:h}))})),c.addOption("--service",g),f.includes(g)||(o.error(`\u274C Invalid service: ${g}. Available services: ${f.join(", ")}`),Ne.exit(1));let E=n??!1;E&&c.addOption("--skip-terraform",!0);try{er.quiet=!0,await er`gh workflow run deploy-single-service.yml --ref ${m} -f environment=${u} -f service=${g} ${E?["-f","skip_terraform_deploy=true"]:[]}`,er.quiet=!1,o.info(`Successfully launched deploy-single-service workflow_dispatch for release branch: ${m}, environment: ${u}, service: ${g}`),c.print();let v={releaseBranch:m,version:m.replace("release/v",""),environment:u,service:g,skipTerraformDeploy:E,success:!0};return{content:[{type:"text",text:JSON.stringify(v,null,2)}],structuredContent:v}}catch(h){o.error({error:h},"\u274C Error launching workflow"),Ne.exit(1)}},yt=async()=>{let e=await x(),r=ht(e,".github/workflows/deploy-single-service.yml"),t=await gt.readFile(r,"utf-8");return vt.parse(t).on.workflow_dispatch.inputs.service.options},bt={name:"gh-release-deploy-service",description:"Deploy a specific service in a release branch to a specified environment",inputSchema:{version:O.string().describe('Version to deploy (e.g., "1.2.5")'),env:O.string().describe('Environment to deploy to (e.g., "dev", "renana", "oriana")'),service:O.string().describe('Service to deploy (e.g., "client-be", "client-fe")'),skipTerraform:O.boolean().optional().describe("Skip terraform deployment step")},outputSchema:{releaseBranch:O.string().describe("The release branch that was deployed"),version:O.string().describe("The version that was deployed"),environment:O.string().describe("The environment deployed to"),service:O.string().describe("The service that was deployed"),skipTerraformDeploy:O.boolean().describe("Whether terraform deployment was skipped"),success:O.boolean().describe("Whether the deployment was successful")},handler:De};import{z as Y}from"zod";var Oe=async()=>{let r=(await w()).map(a=>({version:a.branch.replace("release/",""),type:b(a.title)})),t=await R(),s=Math.max(...r.map(a=>a.version.length)),n=r.map(a=>{let p=xe(a.version,a.type,s),l=t.get(a.version);return l?`${p} ${l}`:p});o.info(`All release branches:
26
+ `),o.info(`
27
+ ${n.join(`
28
+ `)}
29
+ `);let i={releases:r.map(a=>({version:a.version,type:a.type,description:t.get(a.version)||null})),count:r.length};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}},wt={name:"gh-release-list",description:"List all open release branches",inputSchema:{},outputSchema:{releases:Y.array(Y.object({version:Y.string().describe("Release version"),type:Y.enum(["regular","hotfix"]).describe("Release type"),description:Y.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:Y.number().describe("Number of release branches")},handler:Oe};import yr from"@inquirer/confirm";import Rt from"@inquirer/select";import br from"node:process";import{z as _}from"zod";import{$ as rr,question as wr}from"zx";var _e=async e=>{let{version:r,description:t,type:s,confirmedCommand:n,checkout:i}=e;c.start("release-create");let a=r,p=t,l=s||"regular",m=i,d=await K();a||(c.setInteractive(),a=await wr("Enter version (e.g. 1.2.5): ")),(!a||a.trim()==="")&&(o.error("No version provided. Exiting..."),br.exit(1));let u=a.trim();c.addOption("--version",u),s||(c.setInteractive(),l=await Rt({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),c.addOption("--type",l),p===void 0&&(c.setInteractive(),p=await wr("Enter description (optional, press Enter to skip): "),p.trim()===""&&(p="")),p&&c.addOption("--description",p);let f=n?!0:await yr({message:`Are you sure you want to create release branch for version ${u}?`});n||c.setInteractive(),f||(o.info("Operation cancelled. Exiting..."),br.exit(0)),c.addOption("--yes",!0),await ne(l);let g=await ie({version:u,jiraConfig:d,description:p,type:l});o.info(`\u2705 Successfully created release: v${u}`),o.info(`\u{1F517} GitHub PR: ${g.prUrl}`),o.info(`\u{1F517} Jira Version: ${g.jiraVersionUrl}`),m===void 0&&(c.setInteractive(),m=await yr({message:`Do you want to checkout to the created branch ${g.branchName}?`,default:!0})),m||c.addOption("--no-checkout",!0),m&&(rr.quiet=!0,await rr`git switch ${g.branchName}`,rr.quiet=!1,o.info(`\u{1F504} Switched to branch ${g.branchName}`)),c.print();let E={version:u,type:l,branchName:g.branchName,prUrl:g.prUrl,jiraVersionUrl:g.jiraVersionUrl,isCheckedOut:m};return{content:[{type:"text",text:JSON.stringify(E,null,2)}],structuredContent:E}},kt={name:"release-create",description:"Create a single release branch for specified version with Jira version creation",inputSchema:{version:_.string().describe('Version to create (e.g., "1.2.5")'),description:_.string().optional().describe("Optional description for the Jira version"),type:_.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")'),checkout:_.boolean().optional().default(!0).describe("Checkout to the created branch (default: true)")},outputSchema:{version:_.string().describe("Version number"),type:_.enum(["regular","hotfix"]).describe("Release type"),branchName:_.string().describe("Release branch name"),prUrl:_.string().describe("GitHub PR URL"),jiraVersionUrl:_.string().describe("Jira version URL"),isCheckedOut:_.boolean().describe("Whether the branch was checked out")},handler:_e};import xt from"@inquirer/confirm";import Ct from"@inquirer/select";import Rr from"node:process";import{z as k}from"zod";import{question as $t}from"zx";var Tt=async e=>{let{versions:r,type:t,confirmedCommand:s}=e,n=r,i=t||"regular";n||(c.setInteractive(),n=await $t("Enter versions by comma (e.g. 1.2.5, 1.2.6): "));let a=n.split(",").map(l=>l.trim());c.addOption("--versions",a.join(", ")),a.length===0&&(o.error("No versions provided. Exiting..."),Rr.exit(1)),t||(c.setInteractive(),i=await Ct({message:"Select release type:",choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"})),c.addOption("--type",i),a.length===1&&o.warn('\u{1F4A1} You are creating only one release. Consider using "create-release" command for single releases.');let p=s?!0:await xt({message:`Are you sure you want to create release branches for these versions: ${a.join(", ")}?`});return s||c.setInteractive(),p||(o.info("Operation cancelled. Exiting..."),Rr.exit(0)),c.addOption("--yes",!0),{versionsList:a,type:i}},Je=async e=>{c.start("release-create-batch");let r=await K(),{versionsList:t,type:s}=await Tt(e);await ne(s);let n=[],i=[];for(let m of t)try{let d=await ie({version:m,jiraConfig:r,type:s});n.push(d),o.info(`\u2705 Successfully created release: v${m}`),o.info(`\u{1F517} GitHub PR: ${d.prUrl}`),o.info(`\u{1F517} Jira Version: ${d.jiraVersionUrl}
30
+ `)}catch(d){let u=d instanceof Error?d.message:String(d);i.push({version:m,error:u}),o.error(`\u274C Failed to create release: v${m}`),o.error(` Error: ${u}
31
+ `)}let a=n.length,p=i.length;a===t.length?o.info(`\u2705 All ${t.length} release branches were created successfully.`):a>0?(o.warn(`\u26A0\uFE0F ${a} of ${t.length} release branches were created successfully.`),o.warn(`\u274C ${p} release(s) failed.`)):o.error(`\u274C All ${t.length} release branches failed to create.`),c.print();let l={createdBranches:n.map(m=>m.branchName),successCount:a,failureCount:p,releases:n,failedReleases:i};return{content:[{type:"text",text:JSON.stringify(l,null,2)}],structuredContent:l}},St={name:"release-create-batch",description:"Create multiple release branches for specified versions with Jira version creation (batch operation)",inputSchema:{versions:k.string().describe('Comma-separated list of versions to create (e.g., "1.2.5, 1.2.6")'),type:k.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" or "hotfix" (default: "regular")')},outputSchema:{createdBranches:k.array(k.string()).describe("List of created release branches"),successCount:k.number().describe("Number of releases created successfully"),failureCount:k.number().describe("Number of releases that failed"),releases:k.array(k.object({version:k.string().describe("Version number"),type:k.enum(["regular","hotfix"]).describe("Release type"),branchName:k.string().describe("Release branch name"),prUrl:k.string().describe("GitHub PR URL"),jiraVersionUrl:k.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:k.array(k.object({version:k.string().describe("Version number that failed"),error:k.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Je};import Et from"@inquirer/checkbox";import tr from"@inquirer/confirm";import It from"node:process";import{z as V}from"zod";import{$ as Z}from"zx";var At="feature",Pt="release",Nt="release/v",Le=async e=>{let{confirmedCommand:r,all:t,versions:s,cursor:n,githubDesktop:i}=e;c.start("worktrees-add");try{let a=await D("release"),l=`${await x()}${G}`;await kr(`${l}/${Pt}`),await kr(`${l}/${At}`);let m=await w(),d=m.map($=>$.branch),u=new Map(m.map($=>[$.branch,b($.title)]));if(d.length===0)return o.info("\u2139\uFE0F No open release branches found"),c.print(),{content:[{type:"text",text:JSON.stringify({createdWorktrees:[],count:0},null,2)}],structuredContent:{createdWorktrees:[],count:0}};let f=[];if(t)f=d;else if(s)f=s.split(",").map($=>`release/v${$.trim()}`);else{c.setInteractive();let $=await R();f=await Et({required:!0,message:"\u{1F33F} Select release branches",choices:C({branches:d,descriptions:$,types:u})})}let g=f.length===d.length;g?c.addOption("--all",!0):c.addOption("--versions",f.map($=>$.replace("release/v","")));let E=r?!0:await tr({message:"Are you sure you want to proceed with these worktree changes?"});r||c.setInteractive(),E||(o.info("Operation cancelled. Exiting..."),It.exit(0)),g&&c.addOption("--yes",!0);let h=n??await tr({message:"Open created worktrees in Cursor?"});typeof n>"u"&&c.setInteractive(),h?c.addOption("--cursor",!0):c.addOption("--no-cursor",!0);let v=i??await tr({message:"Open created worktrees in GitHub Desktop?"});typeof i>"u"&&c.setInteractive(),v?c.addOption("--github-desktop",!0):c.addOption("--no-github-desktop",!0);let{branchesToCreate:nr}=Dt({selectedReleaseBranches:f,currentWorktrees:a}),J=await Ot(nr,l);if(_t(J),h)for(let $ of J)await Z`cursor ${l}/${$}`;if(v)for(let $ of J)await Z`github ${l}/${$}`,await Z`sleep 5`;c.print();let pe={createdWorktrees:J,count:J.length};return{content:[{type:"text",text:JSON.stringify(pe,null,2)}],structuredContent:pe}}catch(a){throw o.error({error:a},"\u274C Error managing worktrees"),a}},kr=async e=>{await Z`mkdir -p ${e}`},Dt=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,s=t.filter(i=>i.startsWith(Nt));return{branchesToCreate:r.filter(i=>!s.includes(i))}},Ot=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let i=`${r}/${n}`;return await Z`git worktree add ${i} ${n}`,await Z({cwd:i})`pnpm install`,n})),s=[];for(let[n,i]of t.entries())if(i.status==="fulfilled")s.push(i.value);else{let a=e[n];o.error({error:i.reason},`\u274C Failed to create worktree for ${a}`)}return s},_t=e=>{if(e.length>0){o.info("\u2705 Created git worktrees:");for(let r of e)o.info(r);o.info("")}else o.info("\u2139\uFE0F No new git worktrees to create")},Jt={name:"worktrees-add",description:"Create git worktrees for selected release branches",inputSchema:{all:V.boolean().describe("Add git worktrees for all release branches without prompting"),versions:V.string().optional().describe("Specify versions by comma, e.g. 1.2.5, 1.2.6"),cursor:V.boolean().optional().describe("Open created git worktrees in Cursor"),githubDesktop:V.boolean().optional().describe("Open created git worktrees in GitHub Desktop")},outputSchema:{createdWorktrees:V.array(V.string()).describe("List of created git worktree branches"),count:V.number().describe("Number of git worktrees created")},handler:Le};import{z as I}from"zod";import{$ as ce}from"zx";var je=async()=>{try{let[e,r]=await Promise.all([D("release"),D("feature")]),t=await x(),s=await Lt(e,r,t);Mt(s);let n={worktrees:s,totalCount:s.length,releaseCount:e.length,featureCount:r.length};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}}catch(e){throw o.error({error:e},"\u274C Error listing worktrees"),e}},Lt=async(e,r,t)=>{let s=[...e.map(i=>({branch:i,type:"release"})),...r.map(i=>({branch:i,type:"feature"}))],n=[];for(let{branch:i,type:a}of s)try{let p=`${t}/${i}`,l=await jt(i),m=await Vt(p),d=await Bt(p),u=await Wt(p),f=await Ft(p);n.push({branch:i,path:p,commit:m.substring(0,8),isCurrent:l,type:a,status:d,lastCommitMessage:u.substring(0,60)+(u.length>60?"...":""),aheadBehind:f})}catch(p){o.warn({error:p,branch:i},`\u26A0\uFE0F Could not process worktree ${i}`)}return n.sort((i,a)=>i.type!==a.type?i.type==="release"?-1:1:i.branch.localeCompare(a.branch))},jt=async e=>{try{return(await ce`git branch --show-current`).stdout.trim()===e}catch{return!1}},Vt=async e=>{try{return(await ce`cd ${e} && git rev-parse HEAD`).stdout.trim()}catch{return"unknown"}},Bt=async e=>{try{let t=(await ce`cd ${e} && git status --porcelain`).stdout.trim().split(`
32
+ `).filter(Boolean);return t.length===0?"clean":t.length<=3?"modified":"dirty"}catch{return"unknown"}},Wt=async e=>{try{return(await ce`cd ${e} && git log -1 --pretty=format:"%s"`).stdout.trim()}catch{return"No commit message available"}},Ft=async e=>{try{let t=(await ce`cd ${e} && git rev-list --count --left-right @{u}...HEAD 2>/dev/null || echo "0 0"`).stdout.trim().split(" ").map(Number),s=t[0]||0,n=t[1]||0;return n===0&&s===0?"up to date":n>0&&s===0?`\u2191${n} ahead`:s>0&&n===0?`\u2193${s} behind`:`\u2191${n} \u2193${s}`}catch{return"unknown"}},Mt=e=>{if(e.length===0){o.info(`
33
+ \u{1F33F} Git Worktrees`),o.info("\u2500".repeat(80)),o.info("\u2139\uFE0F No worktrees found"),o.info("\u2500".repeat(80));return}o.info(`
34
+ \u{1F33F} Git Worktrees`),o.info("\u2550".repeat(100));let r=e.filter(n=>n.type==="release"),t=e.filter(n=>n.type==="feature");xr("\u{1F680} Releases",r),t.length>0&&r.length>0&&o.info(""),xr("\u2728 Features",t);let s=e.find(n=>n.isCurrent);o.info(`
35
+ ${"\u2550".repeat(100)}`),o.info(`\u{1F4CA} Summary: ${e.length} total git worktrees (${r.length} releases, ${t.length} features)`),s&&o.info(`\u{1F4CD} Currently on: ${s.branch}`),o.info("")},xr=(e,r)=>{if(r.length!==0){o.info(`
36
+ ${e}`),o.info("\u2500".repeat(50));for(let[t,s]of r.entries())qt(s),t<r.length-1&&o.info("")}},qt=e=>{let r=e.isCurrent?"\u{1F4CD}":" ",t=Ut(e.status),n=`${e.type==="release"?"\u{1F680}":"\u2728"} ${e.branch}`;o.info(`${r} ${t} ${n}`);let i=e.aheadBehind!=="unknown"?` | ${e.aheadBehind}`:"";o.info(` \u{1F4DD} ${e.commit}${i}`),o.info(` \u{1F4AC} ${e.lastCommitMessage}`);let a=e.path.split("/").slice(-2).join("/");o.info(` \u{1F4C1} ${a}`)},Ut=e=>{switch(e){case"clean":return"\u2705";case"modified":return"\u26A0\uFE0F ";case"dirty":return"\u{1F534}";default:return"\u2753"}},Gt={name:"worktrees-list",description:"List all git worktrees with detailed information",inputSchema:{},outputSchema:{worktrees:I.array(I.object({branch:I.string(),path:I.string(),commit:I.string(),isCurrent:I.boolean(),type:I.enum(["release","feature"]),status:I.string(),lastCommitMessage:I.string(),aheadBehind:I.string()})).describe("List of all worktrees with details"),totalCount:I.number().describe("Total number of worktrees"),releaseCount:I.number().describe("Number of release worktrees"),featureCount:I.number().describe("Number of feature worktrees")},handler:je};import zt from"@inquirer/checkbox";import Kt from"@inquirer/confirm";import Ht from"node:process";import{z as le}from"zod";import{$ as or}from"zx";var Ve=async e=>{let{confirmedCommand:r,all:t,versions:s}=e;c.start("worktrees-remove");try{let n=await D("release");if(n.length===0)return o.info("\u2139\uFE0F No active worktrees to remove"),c.print(),{content:[{type:"text",text:JSON.stringify({removedWorktrees:[],count:0},null,2)}],structuredContent:{removedWorktrees:[],count:0}};let a=`${await x()}${G}`,p=[];if(t)p=n;else if(s)p=s.split(",").map(f=>`release/v${f.trim()}`);else{c.setInteractive();let[f,g]=await Promise.all([R(),w()]),E=new Map(g.map(h=>[h.branch,b(h.title)]));p=await zt({required:!0,message:"\u{1F33F} Select release branches",choices:C({branches:n,descriptions:f,types:E})})}let l=p.length===n.length;l?c.addOption("--all",!0):c.addOption("--versions",p);let m=r?!0:await Kt({message:"Are you sure you want to proceed with these worktree changes?"});r||c.setInteractive(),m||(o.info("Operation cancelled. Exiting..."),Ht.exit(0)),l&&c.addOption("--yes",!0);let d=await Xt(p,a);Yt(d),c.print();let u={removedWorktrees:d,count:d.length};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],structuredContent:u}}catch(n){throw o.error({error:n},"\u274C Error managing worktrees"),n}},Xt=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let i=`${r}/${n}`;return await or`git worktree remove ${i}`,n})),s=[];for(let[n,i]of t.entries())if(i.status==="fulfilled")s.push(i.value);else{let a=e[n];o.error({error:i.reason},`\u274C Failed to remove worktree for ${a}`)}return s.length===e.length&&(await or`git worktree prune`,await or`rm -rf ${r}`,o.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${r}`),o.info("")),s},Yt=e=>{if(e.length>0){o.info("\u274C Removed worktrees:");for(let r of e)o.info(r);o.info("")}else o.info("\u2139\uFE0F No unused worktrees to remove")},Zt={name:"worktrees-remove",description:"Remove selected worktrees",inputSchema:{all:le.boolean().describe("Remove all git worktrees without prompting"),versions:le.string().optional().describe("Specify versions by comma, e.g. 1.2.5, 1.2.6")},outputSchema:{removedWorktrees:le.array(le.string()).describe("List of removed git worktree branches"),count:le.number().describe("Number of git worktrees removed")},handler:Ve};import Qt from"@inquirer/confirm";import eo from"node:process";import{z as sr}from"zod";import{$ as ro}from"zx";var to="release/v",Be=async e=>{let{confirmedCommand:r}=e;c.start("worktrees-sync");try{let t=await D("release"),n=`${await x()}${G}`,i=await Se(),a=r?!0:await Qt({message:"Are you sure you want to proceed with these worktree changes?"});r||c.setInteractive(),a||(o.info("Operation cancelled. Exiting..."),eo.exit(0)),r||c.addOption("--yes",!0);let{branchesToRemove:p}=oo({releasePRsList:i,currentWorktrees:t}),l=await so(p,n);no(l),c.print();let m={removedWorktrees:l,count:l.length};return{content:[{type:"text",text:JSON.stringify(m,null,2)}],structuredContent:m}}catch(t){throw o.error({error:t},"\u274C Error managing worktrees"),t}},oo=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(i=>i.startsWith(to)).filter(i=>!r.includes(i))}},so=async(e,r)=>{let t=[];for(let s of e)try{let n=`${r}/${s}`;await ro`git worktree remove ${n}`,t.push(s)}catch(n){o.error({error:n,branch:s},`\u274C Failed to remove worktree for ${s}`)}return t},no=e=>{if(e.length>0){o.info("\u274C Removed worktrees:");for(let r of e)o.info(r);o.info("")}else o.info("\u2139\uFE0F No unused worktrees to remove")},io={name:"worktrees-sync",description:"Synchronize worktrees with active release branches",inputSchema:{},outputSchema:{removedWorktrees:sr.array(sr.string()).describe("List of removed worktree branches"),count:sr.number().describe("Number of worktrees removed during sync")},handler:Be};var y=new ao;y.command("merge-dev").description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Ee({all:e.all,confirmedCommand:e.yes})});y.command("release-list").description("List all release branches").action(async()=>{await Oe()});y.command("release-create").description("Create a single release branch").option("-v, --version <version>","Specify the version to create, e.g. 1.2.5").option("-d, --description <description>","Optional description for the Jira version").addOption(new Cr("-t, --type <type>","Release type (default: regular)").choices(["regular","hotfix"])).option("-y, --yes","Skip confirmation prompt").option("--no-checkout","Do not checkout the created branch after creation (checkout is default)").action(async e=>{await _e({version:e.version,description:e.description,type:e.type,confirmedCommand:e.yes,checkout:e.checkout})});y.command("release-create-batch").description("Create multiple release branches (batch operation)").option("-v, --versions <versions>","Specify the versions to create by comma, e.g. 1.2.5, 1.2.6").addOption(new Cr("-t, --type <type>","Release type (default: regular)").choices(["regular","hotfix"])).option("-y, --yes","Skip confirmation prompt").action(async e=>{await Je({versions:e.versions,type:e.type,confirmedCommand:e.yes})});y.command("release-deploy-all").description("Deploy any release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await Ae({version:e.version,env:e.env,skipTerraform:e.skipTerraform})});y.command("release-deploy-service").description("Deploy specific service in release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --service <service>","Specify the service to deploy, e.g. client-be").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await De({version:e.version,env:e.env,service:e.service,skipTerraform:e.skipTerraform})});y.command("release-deploy-selected").description("Deploy selected services from release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await Pe({version:e.version,env:e.env,services:e.services,skipTerraform:e.skipTerraform})});y.command("release-deliver").description("Release a new version to production").option("-v, --version <version>","Specify the version to release, e.g. 1.2.5").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Ie({version:e.version,confirmedCommand:e.yes})});y.command("worktrees-sync").description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Be({confirmedCommand:e.yes})});y.command("worktrees-add").description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-c, --cursor","Open created worktrees in Cursor").option("--no-cursor","Skip Cursor prompt").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").action(async e=>{await Le({confirmedCommand:e.yes,all:e.all,versions:e.versions,cursor:e.cursor,githubDesktop:e.githubDesktop})});y.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await je()});y.command("worktrees-remove").description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async e=>{await Ve({confirmedCommand:e.yes,all:e.all,versions:e.versions})});y.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await ue()});y.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await we()});y.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await ye()});y.command("env-init").description("Set up shell functions for env-load/env-clear in .zshrc").action(async()=>{await Me()});y.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async e=>{await be({config:e.config})});y.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await he()});y.parse();
38
37
  //# sourceMappingURL=cli.js.map