aicommit2 2.5.4 → 2.5.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -18
- package/dist/ai.service-9119469d.mjs +17 -0
- package/dist/anthropic.service-68956862.mjs +1 -0
- package/dist/bedrock.service-9933a587.mjs +1 -0
- package/dist/cli-c30dd603.mjs +273 -0
- package/dist/cli.mjs +1 -1
- package/dist/codestral.service-0390f41e.mjs +1 -0
- package/dist/cohere.service-7282793a.mjs +1 -0
- package/dist/deep-seek.service-689940ee.mjs +1 -0
- package/dist/gemini.service-595d667c.mjs +1 -0
- package/dist/github-models.service-a89f5f34.mjs +5 -0
- package/dist/groq.service-41276877.mjs +1 -0
- package/dist/hugging-face.service-50193927.mjs +2 -0
- package/dist/mistral.service-14601dd7.mjs +1 -0
- package/dist/ollama.service-f01b8d7a.mjs +1 -0
- package/dist/{openai-a5caac9c.mjs → openai-aca766eb.mjs} +1 -1
- package/dist/openai-compatible.service-d8949180.mjs +1 -0
- package/dist/openai.service-f4ea1dc7.mjs +1 -0
- package/dist/perplexity.service-c2894100.mjs +1 -0
- package/package.json +1 -1
- package/dist/ai.service-e4638af5.mjs +0 -5
- package/dist/anthropic.service-d6f32293.mjs +0 -1
- package/dist/bedrock.service-8f357ef0.mjs +0 -1
- package/dist/cli-6797d3ee.mjs +0 -294
- package/dist/codestral.service-52aea4ab.mjs +0 -1
- package/dist/cohere.service-1de1f236.mjs +0 -1
- package/dist/deep-seek.service-e7d260aa.mjs +0 -1
- package/dist/gemini.service-9ea5644a.mjs +0 -1
- package/dist/github-models.service-0ec74310.mjs +0 -5
- package/dist/groq.service-dc7f5129.mjs +0 -1
- package/dist/hugging-face.service-0ca40e02.mjs +0 -2
- package/dist/mistral.service-e1ed37fd.mjs +0 -1
- package/dist/ollama.service-2905a90b.mjs +0 -1
- package/dist/openai-compatible.service-833e4451.mjs +0 -1
- package/dist/openai.service-e2d5fc19.mjs +0 -1
- package/dist/perplexity.service-90e30b99.mjs +0 -1
package/dist/cli-6797d3ee.mjs
DELETED
|
@@ -1,294 +0,0 @@
|
|
|
1
|
-
import{command as j,cli as Fn}from"cleye";import{createRequire as Gn}from"module";import Bn from"crypto";import N from"fs";import $e from"os";import E from"path";import{Buffer as Jt}from"node:buffer";import Q from"node:path";import nt,{ChildProcess as Xt,exec as Hn}from"node:child_process";import _ from"node:process";import Un,{execSync as Se,exec as Kn}from"child_process";import{fileURLToPath as Qt}from"node:url";import qn,{constants as Zt}from"node:os";import Wn from"assert";import Yn from"events";import{createWriteStream as zn,createReadStream as Vn,readFileSync as Jn}from"node:fs";import Xn from"buffer";import st from"stream";import Qn,{promisify as Zn}from"util";import{debuglog as es,promisify as ts}from"node:util";import T from"inquirer";import{from as Ie,switchMap as eo,of as os,tap as ns,mergeMap as to,catchError as ss,BehaviorSubject as oo,ReplaySubject as rs,Subscription as rt,lastValueFrom as it,toArray as at,filter as no,map as so,Subject as ct}from"rxjs";import R from"fs/promises";import h from"chalk";import Re from"readline";import ro from"figlet";import is from"gradient-string";import io from"ora";import as from"inquirer-reactive-list-prompt";import F from"winston";import"winston-daily-rotate-file";import cs from"axios";import{fileURLToPath as ls,pathToFileURL as us}from"url";import{readdir as ao,stat as ds,rm as ms}from"node:fs/promises";import ps from"chokidar";import{takeUntil as co,finalize as lo}from"rxjs/operators";var fs="aicommit2",uo="2.5.4",hs="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",gs=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],ys="MIT",ws="tak-bro/aicommit2",bs="Hyungtak Jin(@tak-bro)",Es="module",vs=["dist"],Cs={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},As={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Ps={"@anthropic-ai/sdk":"^0.39.0","@aws-sdk/client-bedrock-runtime":"^3.678.0","@aws-sdk/credential-providers":"^3.678.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.19.0","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.16",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},$s={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Ss={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Is={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"docs",release:!1},{type:"style",release:!1},{type:"test",release:!1},{type:"ci",release:!1},{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},Rs={name:fs,version:uo,description:hs,keywords:gs,license:ys,repository:ws,author:bs,type:Es,files:vs,bin:Cs,scripts:As,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Ps,devDependencies:$s,eslintConfig:Ss,release:Is},xs=Gn(import.meta.url),Y=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ne(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var se={exports:{}},lt,mo;function ks(){if(mo)return lt;mo=1,lt=n,n.sync=s;var e=N;function t(r,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var u=0;u<c.length;u++){var l=c[u].toLowerCase();if(l&&r.substr(-l.length).toLowerCase()===l)return!0}return!1}function o(r,i,c){return!r.isSymbolicLink()&&!r.isFile()?!1:t(i,c)}function n(r,i,c){e.stat(r,function(u,l){c(u,u?!1:o(l,r,i))})}function s(r,i){return o(e.statSync(r),r,i)}return lt}var ut,po;function Ms(){if(po)return ut;po=1,ut=t,t.sync=o;var e=N;function t(r,i,c){e.stat(r,function(u,l){c(u,u?!1:n(l,i))})}function o(r,i){return n(e.statSync(r),i)}function n(r,i){return r.isFile()&&s(r,i)}function s(r,i){var c=r.mode,u=r.uid,l=r.gid,d=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),f=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),y=parseInt("100",8),g=parseInt("010",8),m=parseInt("001",8),A=y|g,v=c&m||c&g&&l===f||c&y&&u===d||c&A&&d===0;return v}return ut}var xe;process.platform==="win32"||Y.TESTING_WINDOWS?xe=ks():xe=Ms();var Ts=dt;dt.sync=Os;function dt(e,t,o){if(typeof t=="function"&&(o=t,t={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,s){dt(e,t||{},function(r,i){r?s(r):n(i)})})}xe(e,t||{},function(n,s){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,s=!1),o(n,s)})}function Os(e,t){try{return xe.sync(e,t||{})}catch(o){if(t&&t.ignoreErrors||o.code==="EACCES")return!1;throw o}}const re=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",fo=E,Ds=re?";":":",ho=Ts,go=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),yo=(e,t)=>{const o=t.colon||Ds,n=e.match(/\//)||re&&e.match(/\\/)?[""]:[...re?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(o)],s=re?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=re?s.split(o):[""];return re&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:n,pathExt:r,pathExtExe:s}},wo=(e,t,o)=>{typeof t=="function"&&(o=t,t={}),t||(t={});const{pathEnv:n,pathExt:s,pathExtExe:r}=yo(e,t),i=[],c=l=>new Promise((d,f)=>{if(l===n.length)return t.all&&i.length?d(i):f(go(e));const y=n[l],g=/^".*"$/.test(y)?y.slice(1,-1):y,m=fo.join(g,e),A=!g&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;d(u(A,l,0))}),u=(l,d,f)=>new Promise((y,g)=>{if(f===s.length)return y(c(d+1));const m=s[f];ho(l+m,{pathExt:r},(A,v)=>{if(!A&&v)if(t.all)i.push(l+m);else return y(l+m);return y(u(l,d,f+1))})});return o?c(0).then(l=>o(null,l),o):c(0)},Ls=(e,t)=>{t=t||{};const{pathEnv:o,pathExt:n,pathExtExe:s}=yo(e,t),r=[];for(let i=0;i<o.length;i++){const c=o[i],u=/^".*"$/.test(c)?c.slice(1,-1):c,l=fo.join(u,e),d=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let f=0;f<n.length;f++){const y=d+n[f];try{if(ho.sync(y,{pathExt:s}))if(t.all)r.push(y);else return y}catch{}}}if(t.all&&r.length)return r;if(t.nothrow)return null;throw go(e)};var Ns=wo;wo.sync=Ls;var mt={exports:{}};const bo=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};mt.exports=bo,mt.exports.default=bo;var js=mt.exports;const Eo=E,_s=Ns,Fs=js;function vo(e,t){const o=e.options.env||process.env,n=process.cwd(),s=e.options.cwd!=null,r=s&&process.chdir!==void 0&&!process.chdir.disabled;if(r)try{process.chdir(e.options.cwd)}catch{}let i;try{i=_s.sync(e.command,{path:o[Fs({env:o})],pathExt:t?Eo.delimiter:void 0})}catch{}finally{r&&process.chdir(n)}return i&&(i=Eo.resolve(s?e.options.cwd:"",i)),i}function Gs(e){return vo(e)||vo(e,!0)}var Bs=Gs,pt={};const ft=/([()\][%!^"`<>&|;, *?])/g;function Hs(e){return e=e.replace(ft,"^$1"),e}function Us(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(ft,"^$1"),t&&(e=e.replace(ft,"^$1")),e}pt.command=Hs,pt.argument=Us;var Ks=/^#!(.*)/;const qs=Ks;var Ws=(e="")=>{const t=e.match(qs);if(!t)return null;const[o,n]=t[0].replace(/#! ?/,"").split(" "),s=o.split("/").pop();return s==="env"?n:n?`${s} ${n}`:s};const ht=N,Ys=Ws;function zs(e){const o=Buffer.alloc(150);let n;try{n=ht.openSync(e,"r"),ht.readSync(n,o,0,150,0),ht.closeSync(n)}catch{}return Ys(o.toString())}var Vs=zs;const Js=E,Co=Bs,Ao=pt,Xs=Vs,Qs=process.platform==="win32",Zs=/\.(?:com|exe)$/i,er=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function tr(e){e.file=Co(e);const t=e.file&&Xs(e.file);return t?(e.args.unshift(e.file),e.command=t,Co(e)):e.file}function or(e){if(!Qs)return e;const t=tr(e),o=!Zs.test(t);if(e.options.forceShell||o){const n=er.test(t);e.command=Js.normalize(e.command),e.command=Ao.command(e.command),e.args=e.args.map(r=>Ao.argument(r,n));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function nr(e,t,o){t&&!Array.isArray(t)&&(o=t,t=null),t=t?t.slice(0):[],o=Object.assign({},o);const n={command:e,args:t,options:o,file:void 0,original:{command:e,args:t}};return o.shell?n:or(n)}var sr=nr;const gt=process.platform==="win32";function yt(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function rr(e,t){if(!gt)return;const o=e.emit;e.emit=function(n,s){if(n==="exit"){const r=Po(s,t);if(r)return o.call(e,"error",r)}return o.apply(e,arguments)}}function Po(e,t){return gt&&e===1&&!t.file?yt(t.original,"spawn"):null}function ir(e,t){return gt&&e===1&&!t.file?yt(t.original,"spawnSync"):null}var ar={hookChildProcess:rr,verifyENOENT:Po,verifyENOENTSync:ir,notFoundError:yt};const $o=Un,wt=sr,bt=ar;function So(e,t,o){const n=wt(e,t,o),s=$o.spawn(n.command,n.args,n.options);return bt.hookChildProcess(s,n),s}function cr(e,t,o){const n=wt(e,t,o),s=$o.spawnSync(n.command,n.args,n.options);return s.error=s.error||bt.verifyENOENTSync(s.status,n),s}se.exports=So,se.exports.spawn=So,se.exports.sync=cr,se.exports._parse=wt,se.exports._enoent=bt;var lr=se.exports,ur=ne(lr);function dr(e){const t=typeof e=="string"?`
|
|
2
|
-
`:`
|
|
3
|
-
`.charCodeAt(),o=typeof e=="string"?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===o&&(e=e.slice(0,-1)),e}function Io(e={}){const{env:t=process.env,platform:o=process.platform}=e;return o!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"}const mr=({cwd:e=_.cwd(),path:t=_.env[Io()],preferLocal:o=!0,execPath:n=_.execPath,addExecPath:s=!0}={})=>{const r=e instanceof URL?Qt(e):e,i=Q.resolve(r),c=[];return o&&pr(c,i),s&&fr(c,n,i),[...c,t].join(Q.delimiter)},pr=(e,t)=>{let o;for(;o!==t;)e.push(Q.join(t,"node_modules/.bin")),o=t,t=Q.resolve(t,"..")},fr=(e,t,o)=>{const n=t instanceof URL?Qt(t):t;e.push(Q.resolve(o,n,".."))},hr=({env:e=_.env,...t}={})=>{e={...e};const o=Io({env:e});return t.path=e[o],e[o]=mr(t),e},gr=(e,t,o,n)=>{if(o==="length"||o==="prototype"||o==="arguments"||o==="caller")return;const s=Object.getOwnPropertyDescriptor(e,o),r=Object.getOwnPropertyDescriptor(t,o);!yr(s,r)&&n||Object.defineProperty(e,o,r)},yr=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},wr=(e,t)=>{const o=Object.getPrototypeOf(t);o!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,o)},br=(e,t)=>`/* Wrapped ${e}*/
|
|
4
|
-
${t}`,Er=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),vr=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Cr=(e,t,o)=>{const n=o===""?"":`with ${o.trim()}() `,s=br.bind(null,n,t.toString());Object.defineProperty(s,"name",vr),Object.defineProperty(e,"toString",{...Er,value:s})};function Ar(e,t,{ignoreNonConfigurable:o=!1}={}){const{name:n}=e;for(const s of Reflect.ownKeys(t))gr(e,t,s,o);return wr(e,t),Cr(e,t,n),e}const ke=new WeakMap,Ro=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let o,n=0;const s=e.displayName||e.name||"<anonymous>",r=function(...i){if(ke.set(r,++n),n===1)o=e.apply(this,i),e=null;else if(t.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return o};return Ar(r,e),ke.set(r,n),r};Ro.callCount=e=>{if(!ke.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return ke.get(e)};const Pr=()=>{const e=ko-xo+1;return Array.from({length:e},$r)},$r=(e,t)=>({name:`SIGRT${t+1}`,number:xo+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),xo=34,ko=64,Sr=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Mo=()=>{const e=Pr();return[...Sr,...e].map(Ir)},Ir=({name:e,number:t,description:o,action:n,forced:s=!1,standard:r})=>{const{signals:{[e]:i}}=Zt,c=i!==void 0;return{name:e,number:c?i:t,description:o,supported:c,action:n,forced:s,standard:r}},Rr=()=>{const e=Mo();return Object.fromEntries(e.map(xr))},xr=({name:e,number:t,description:o,supported:n,action:s,forced:r,standard:i})=>[e,{name:e,number:t,description:o,supported:n,action:s,forced:r,standard:i}],kr=Rr(),Mr=()=>{const e=Mo(),t=ko+1,o=Array.from({length:t},(n,s)=>Tr(s,e));return Object.assign({},...o)},Tr=(e,t)=>{const o=Or(e,t);if(o===void 0)return{};const{name:n,description:s,supported:r,action:i,forced:c,standard:u}=o;return{[e]:{name:n,number:e,description:s,supported:r,action:i,forced:c,standard:u}}},Or=(e,t)=>{const o=t.find(({name:n})=>Zt.signals[n]===e);return o!==void 0?o:t.find(n=>n.number===e)};Mr();const Dr=({timedOut:e,timeout:t,errorCode:o,signal:n,signalDescription:s,exitCode:r,isCanceled:i})=>e?`timed out after ${t} milliseconds`:i?"was canceled":o!==void 0?`failed with ${o}`:n!==void 0?`was killed with ${n} (${s})`:r!==void 0?`failed with exit code ${r}`:"failed",Me=({stdout:e,stderr:t,all:o,error:n,signal:s,exitCode:r,command:i,escapedCommand:c,timedOut:u,isCanceled:l,killed:d,parsed:{options:{timeout:f,cwd:y=_.cwd()}}})=>{r=r===null?void 0:r,s=s===null?void 0:s;const g=s===void 0?void 0:kr[s].description,m=n&&n.code,v=`Command ${Dr({timedOut:u,timeout:f,errorCode:m,signal:s,signalDescription:g,exitCode:r,isCanceled:l})}: ${i}`,P=Object.prototype.toString.call(n)==="[object Error]",C=P?`${v}
|
|
5
|
-
${n.message}`:v,k=[C,t,e].filter(Boolean).join(`
|
|
6
|
-
`);return P?(n.originalMessage=n.message,n.message=k):n=new Error(k),n.shortMessage=C,n.command=i,n.escapedCommand=c,n.exitCode=r,n.signal=s,n.signalDescription=g,n.stdout=e,n.stderr=t,n.cwd=y,o!==void 0&&(n.all=o),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=!!u,n.isCanceled=l,n.killed=d&&!u,n},Te=["stdin","stdout","stderr"],Lr=e=>Te.some(t=>e[t]!==void 0),To=e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Te.map(n=>e[n]);if(Lr(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Te.map(n=>`\`${n}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const o=Math.max(t.length,Te.length);return Array.from({length:o},(n,s)=>t[s])},Nr=e=>{const t=To(e);return t==="ipc"?"ipc":t===void 0||typeof t=="string"?[t,t,t,"ipc"]:t.includes("ipc")?t:[...t,"ipc"]};var ie={exports:{}},Oe={exports:{}};Oe.exports;var Oo;function jr(){return Oo||(Oo=1,function(e){e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Oe)),Oe.exports}var x=Y.process;const Z=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};if(!Z(x))ie.exports=function(){return function(){}};else{var _r=Wn,fe=jr(),Fr=/^win/i.test(x.platform),De=Yn;typeof De!="function"&&(De=De.EventEmitter);var O;x.__signal_exit_emitter__?O=x.__signal_exit_emitter__:(O=x.__signal_exit_emitter__=new De,O.count=0,O.emitted={}),O.infinite||(O.setMaxListeners(1/0),O.infinite=!0),ie.exports=function(e,t){if(!Z(Y.process))return function(){};_r.equal(typeof e,"function","a callback must be provided for exit handler"),he===!1&&Do();var o="exit";t&&t.alwaysLast&&(o="afterexit");var n=function(){O.removeListener(o,e),O.listeners("exit").length===0&&O.listeners("afterexit").length===0&&Et()};return O.on(o,e),n};var Et=function(){!he||!Z(Y.process)||(he=!1,fe.forEach(function(t){try{x.removeListener(t,vt[t])}catch{}}),x.emit=Ct,x.reallyExit=Lo,O.count-=1)};ie.exports.unload=Et;var ae=function(t,o,n){O.emitted[t]||(O.emitted[t]=!0,O.emit(t,o,n))},vt={};fe.forEach(function(e){vt[e]=function(){if(Z(Y.process)){var o=x.listeners(e);o.length===O.count&&(Et(),ae("exit",null,e),ae("afterexit",null,e),Fr&&e==="SIGHUP"&&(e="SIGINT"),x.kill(x.pid,e))}}}),ie.exports.signals=function(){return fe};var he=!1,Do=function(){he||!Z(Y.process)||(he=!0,O.count+=1,fe=fe.filter(function(t){try{return x.on(t,vt[t]),!0}catch{return!1}}),x.emit=Br,x.reallyExit=Gr)};ie.exports.load=Do;var Lo=x.reallyExit,Gr=function(t){Z(Y.process)&&(x.exitCode=t||0,ae("exit",x.exitCode,null),ae("afterexit",x.exitCode,null),Lo.call(x,x.exitCode))},Ct=x.emit,Br=function(t,o){if(t==="exit"&&Z(Y.process)){o!==void 0&&(x.exitCode=o);var n=Ct.apply(this,arguments);return ae("exit",x.exitCode,null),ae("afterexit",x.exitCode,null),n}else return Ct.apply(this,arguments)}}var Hr=ie.exports,Ur=ne(Hr);const Kr=1e3*5,qr=(e,t="SIGTERM",o={})=>{const n=e(t);return Wr(e,t,o,n),n},Wr=(e,t,o,n)=>{if(!Yr(t,o,n))return;const s=Vr(o),r=setTimeout(()=>{e("SIGKILL")},s);r.unref&&r.unref()},Yr=(e,{forceKillAfterTimeout:t},o)=>zr(e)&&t!==!1&&o,zr=e=>e===qn.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",Vr=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return Kr;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},Jr=(e,t)=>{e.kill()&&(t.isCanceled=!0)},Xr=(e,t,o)=>{e.kill(t),o(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},Qr=(e,{timeout:t,killSignal:o="SIGTERM"},n)=>{if(t===0||t===void 0)return n;let s;const r=new Promise((c,u)=>{s=setTimeout(()=>{Xr(e,o,u)},t)}),i=n.finally(()=>{clearTimeout(s)});return Promise.race([r,i])},Zr=({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},ei=async(e,{cleanup:t,detached:o},n)=>{if(!t||o)return n;const s=Ur(()=>{e.kill()});return n.finally(()=>{s()})};function At(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}function No(e){return At(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}const ti=e=>e instanceof Xt&&typeof e.then=="function",Pt=(e,t,o)=>{if(typeof o=="string")return e[t].pipe(zn(o)),e;if(No(o))return e[t].pipe(o),e;if(!ti(o))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!No(o.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(o.stdin),o},oi=e=>{e.stdout!==null&&(e.pipeStdout=Pt.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=Pt.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=Pt.bind(void 0,e,"all"))};var ge={exports:{}};const{PassThrough:ni}=st;var si=e=>{e={...e};const{array:t}=e;let{encoding:o}=e;const n=o==="buffer";let s=!1;t?s=!(o||n):o=o||"utf8",n&&(o=null);const r=new ni({objectMode:s});o&&r.setEncoding(o);let i=0;const c=[];return r.on("data",u=>{c.push(u),s?i=c.length:i+=u.length}),r.getBufferedValue=()=>t?c:n?Buffer.concat(c,i):c.join(""),r.getBufferedLength=()=>i,r};const{constants:ri}=Xn,ii=st,{promisify:ai}=Qn,ci=si,li=ai(ii.pipeline);class jo extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function $t(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};const{maxBuffer:o}=t,n=ci(t);return await new Promise((s,r)=>{const i=c=>{c&&n.getBufferedLength()<=ri.MAX_LENGTH&&(c.bufferedData=n.getBufferedValue()),r(c)};(async()=>{try{await li(e,n),s()}catch(c){i(c)}})(),n.on("data",()=>{n.getBufferedLength()>o&&i(new jo)})}),n.getBufferedValue()}ge.exports=$t,ge.exports.buffer=(e,t)=>$t(e,{...t,encoding:"buffer"}),ge.exports.array=(e,t)=>$t(e,{...t,array:!0}),ge.exports.MaxBufferError=jo;var ui=ge.exports,_o=ne(ui);const{PassThrough:di}=st;var mi=function(){var e=[],t=new di({objectMode:!0});return t.setMaxListeners(0),t.add=o,t.isEmpty=n,t.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(o),t;function o(r){return Array.isArray(r)?(r.forEach(o),this):(e.push(r),r.once("end",s.bind(null,r)),r.once("error",t.emit.bind(t,"error")),r.pipe(t,{end:!1}),this)}function n(){return e.length==0}function s(r){e=e.filter(function(i){return i!==r}),!e.length&&t.readable&&t.end()}},pi=ne(mi);const Fo=e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},fi=({input:e,inputFile:t})=>typeof t!="string"?e:(Fo(e),Jn(t)),hi=e=>{const t=fi(e);if(At(t))throw new TypeError("The `input` option cannot be a stream in sync mode");return t},gi=({input:e,inputFile:t})=>typeof t!="string"?e:(Fo(e),Vn(t)),yi=(e,t)=>{const o=gi(t);o!==void 0&&(At(o)?o.pipe(e.stdin):e.stdin.end(o))},wi=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const o=pi();return e.stdout&&o.add(e.stdout),e.stderr&&o.add(e.stderr),o},St=async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(o){return o.bufferedData}}},It=(e,{encoding:t,buffer:o,maxBuffer:n})=>{if(!(!e||!o))return t?_o(e,{encoding:t,maxBuffer:n}):_o.buffer(e,{maxBuffer:n})},bi=async({stdout:e,stderr:t,all:o},{encoding:n,buffer:s,maxBuffer:r},i)=>{const c=It(e,{encoding:n,buffer:s,maxBuffer:r}),u=It(t,{encoding:n,buffer:s,maxBuffer:r}),l=It(o,{encoding:n,buffer:s,maxBuffer:r*2});try{return await Promise.all([i,c,u,l])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},St(e,c),St(t,u),St(o,l)])}},Ei=(async()=>{})().constructor.prototype,vi=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Ei,e)]),Go=(e,t)=>{for(const[o,n]of vi){const s=typeof t=="function"?(...r)=>Reflect.apply(n.value,t(),r):n.value.bind(t);Reflect.defineProperty(e,o,{...n,value:s})}},Ci=e=>new Promise((t,o)=>{e.on("exit",(n,s)=>{t({exitCode:n,signal:s})}),e.on("error",n=>{o(n)}),e.stdin&&e.stdin.on("error",n=>{o(n)})}),Bo=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Ai=/^[\w.-]+$/,Pi=/"/g,$i=e=>typeof e!="string"||Ai.test(e)?e:`"${e.replace(Pi,'\\"')}"`,Ho=(e,t)=>Bo(e,t).join(" "),Uo=(e,t)=>Bo(e,t).map(o=>$i(o)).join(" "),Ko=/ +/g,qo=e=>{const t=[];for(const o of e.trim().split(Ko)){const n=t[t.length-1];n&&n.endsWith("\\")?t[t.length-1]=`${n.slice(0,-1)} ${o}`:t.push(o)}return t},Wo=e=>{const t=typeof e;if(t==="string")return e;if(t==="number")return String(e);if(t==="object"&&e!==null&&!(e instanceof Xt)&&"stdout"in e){const o=typeof e.stdout;if(o==="string")return e.stdout;if(Jt.isBuffer(e.stdout))return e.stdout.toString();throw new TypeError(`Unexpected "${o}" stdout in template expression`)}throw new TypeError(`Unexpected "${t}" in template expression`)},Yo=(e,t,o)=>o||e.length===0||t.length===0?[...e,...t]:[...e.slice(0,-1),`${e[e.length-1]}${t[0]}`,...t.slice(1)],Si=({templates:e,expressions:t,tokens:o,index:n,template:s})=>{const r=s??e.raw[n],i=r.split(Ko).filter(Boolean),c=Yo(o,i,r.startsWith(" "));if(n===t.length)return c;const u=t[n],l=Array.isArray(u)?u.map(d=>Wo(d)):[Wo(u)];return Yo(c,l,r.endsWith(" "))},zo=(e,t)=>{let o=[];for(const[n,s]of e.entries())o=Si({templates:e,expressions:t,tokens:o,index:n,template:s});return o},Ii=es("execa").enabled,Le=(e,t)=>String(e).padStart(t,"0"),Ri=()=>{const e=new Date;return`${Le(e.getHours(),2)}:${Le(e.getMinutes(),2)}:${Le(e.getSeconds(),2)}.${Le(e.getMilliseconds(),3)}`},Vo=(e,{verbose:t})=>{t&&_.stderr.write(`[${Ri()}] ${e}
|
|
7
|
-
`)},xi=1e3*1e3*100,ki=({env:e,extendEnv:t,preferLocal:o,localDir:n,execPath:s})=>{const r=t?{..._.env,...e}:e;return o?hr({env:r,cwd:n,execPath:s}):r},Jo=(e,t,o={})=>{const n=ur._parse(e,t,o);return e=n.command,t=n.args,o=n.options,o={maxBuffer:xi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:o.cwd||_.cwd(),execPath:_.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ii,...o},o.env=ki(o),o.stdio=To(o),_.platform==="win32"&&Q.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:o,parsed:n}},ye=(e,t,o)=>typeof t!="string"&&!Jt.isBuffer(t)?o===void 0?void 0:"":e.stripFinalNewline?dr(t):t;function b(e,t,o){const n=Jo(e,t,o),s=Ho(e,t),r=Uo(e,t);Vo(r,n.options),Zr(n.options);let i;try{i=nt.spawn(n.file,n.args,n.options)}catch(g){const m=new nt.ChildProcess,A=Promise.reject(Me({error:g,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:n,timedOut:!1,isCanceled:!1,killed:!1}));return Go(m,A),m}const c=Ci(i),u=Qr(i,n.options,c),l=ei(i,n.options,u),d={isCanceled:!1};i.kill=qr.bind(null,i.kill.bind(i)),i.cancel=Jr.bind(null,i,d);const y=Ro(async()=>{const[{error:g,exitCode:m,signal:A,timedOut:v},P,C,k]=await bi(i,n.options,l),I=ye(n.options,P),M=ye(n.options,C),X=ye(n.options,k);if(g||m!==0||A!==null){const z=Me({error:g,exitCode:m,signal:A,stdout:I,stderr:M,all:X,command:s,escapedCommand:r,parsed:n,timedOut:v,isCanceled:d.isCanceled||(n.options.signal?n.options.signal.aborted:!1),killed:i.killed});if(!n.options.reject)return z;throw z}return{command:s,escapedCommand:r,exitCode:0,stdout:I,stderr:M,all:X,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return yi(i,n.options),i.all=wi(i,n.options),oi(i),Go(i,y),i}function Rt(e,t,o){const n=Jo(e,t,o),s=Ho(e,t),r=Uo(e,t);Vo(r,n.options);const i=hi(n.options);let c;try{c=nt.spawnSync(n.file,n.args,{...n.options,input:i})}catch(d){throw Me({error:d,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const u=ye(n.options,c.stdout,c.error),l=ye(n.options,c.stderr,c.error);if(c.error||c.status!==0||c.signal!==null){const d=Me({stdout:u,stderr:l,error:c.error,signal:c.signal,exitCode:c.status,command:s,escapedCommand:r,parsed:n,timedOut:c.error&&c.error.code==="ETIMEDOUT",isCanceled:!1,killed:c.signal!==null});if(!n.options.reject)return d;throw d}return{command:s,escapedCommand:r,exitCode:0,stdout:u,stderr:l,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}const Mi=({input:e,inputFile:t,stdio:o})=>e===void 0&&t===void 0&&o===void 0?{stdin:"inherit"}:{},Xo=(e={})=>({preferLocal:!0,...Mi(e),...e});function Qo(e){function t(o,...n){if(!Array.isArray(o))return Qo({...e,...o});const[s,...r]=zo(o,n);return b(s,r,Xo(e))}return t.sync=(o,...n)=>{if(!Array.isArray(o))throw new TypeError("Please use $(options).sync`command` instead of $.sync(options)`command`.");const[s,...r]=zo(o,n);return Rt(s,r,Xo(e))},t}const Ti=Qo();function Oi(e,t){const[o,...n]=qo(e);return b(o,n,t)}function Di(e,t){const[o,...n]=qo(e);return Rt(o,n,t)}function Li(e,t,o={}){t&&!Array.isArray(t)&&typeof t=="object"&&(o=t,t=[]);const n=Nr(o),s=_.execArgv.filter(c=>!c.startsWith("--inspect")),{nodePath:r=_.execPath,nodeOptions:i=s}=o;return b(r,[...i,e,...Array.isArray(t)?t:[]],{...o,stdin:void 0,stdout:void 0,stderr:void 0,stdio:n,shell:!1})}var Ni=Object.freeze({__proto__:null,execa:b,execaSync:Rt,$:Ti,execaCommand:Oi,execaCommandSync:Di,execaNode:Li});const{hasOwnProperty:xt}=Object.prototype,Ne=typeof process<"u"&&process.platform==="win32"?`\r
|
|
8
|
-
`:`
|
|
9
|
-
`,kt=(e,t)=>{const o=[];let n="";typeof t=="string"?t={section:t,whitespace:!1}:(t=t||Object.create(null),t.whitespace=t.whitespace===!0);const s=t.whitespace?" = ":"=";for(const r of Object.keys(e)){const i=e[r];if(i&&Array.isArray(i))for(const c of i)n+=ce(r+"[]")+s+ce(c)+Ne;else i&&typeof i=="object"?o.push(r):n+=ce(r)+s+ce(i)+Ne}t.section&&n.length&&(n="["+ce(t.section)+"]"+Ne+n);for(const r of o){const i=Zo(r).join("\\."),c=(t.section?t.section+".":"")+i,{whitespace:u}=t,l=kt(e[r],{section:c,whitespace:u});n.length&&l.length&&(n+=Ne),n+=l}return n},Zo=e=>e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(t=>t.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),en=e=>{const t=Object.create(null);let o=t,n=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,r=e.split(/[\r\n]+/g);for(const c of r){if(!c||c.match(/^\s*[;#]/))continue;const u=c.match(s);if(!u)continue;if(u[1]!==void 0){if(n=je(u[1]),n==="__proto__"){o=Object.create(null);continue}o=t[n]=t[n]||Object.create(null);continue}const l=je(u[2]),d=l.length>2&&l.slice(-2)==="[]",f=d?l.slice(0,-2):l;if(f==="__proto__")continue;const y=u[3]?je(u[4]):!0,g=y==="true"||y==="false"||y==="null"?JSON.parse(y):y;d&&(xt.call(o,f)?Array.isArray(o[f])||(o[f]=[o[f]]):o[f]=[]),Array.isArray(o[f])?o[f].push(g):o[f]=g}const i=[];for(const c of Object.keys(t)){if(!xt.call(t,c)||typeof t[c]!="object"||Array.isArray(t[c]))continue;const u=Zo(c);o=t;const l=u.pop(),d=l.replace(/\\\./g,".");for(const f of u)f!=="__proto__"&&((!xt.call(o,f)||typeof o[f]!="object")&&(o[f]=Object.create(null)),o=o[f]);o===t&&d===l||(o[d]=t[c],i.push(c))}for(const c of i)delete t[c];return t},tn=e=>e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"),ce=e=>typeof e!="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&tn(e)||e!==e.trim()?JSON.stringify(e):e.split(";").join("\\;").split("#").join("\\#"),je=(e,t)=>{if(e=(e||"").trim(),tn(e)){e.charAt(0)==="'"&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let o=!1,n="";for(let s=0,r=e.length;s<r;s++){const i=e.charAt(s);if(o)"\\;#".indexOf(i)!==-1?n+=i:n+="\\"+i,o=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?o=!0:n+=i}}return o&&(n+="\\"),n.trim()}return e};var ji={parse:en,decode:en,stringify:kt,encode:kt,safe:ce,unsafe:je},le=ne(ji);class p extends Error{constructor(t,o={}){super(t,{cause:o.cause}),this.name="KnownError",this.code=o.code,this.suggestions=o.suggestions||[]}}const we=" ",q=e=>{if(e instanceof Error){if(e instanceof p){e.suggestions.length>0&&(console.error(""),console.error(`${we}${h.yellow("Suggestions:")}`),e.suggestions.forEach(t=>{console.error(`${we} ${h.dim("\u2022")} ${t}`)}));return}e.stack&&console.error(h.dim(e.stack.split(`
|
|
10
|
-
`).slice(1).join(`
|
|
11
|
-
`))),console.error(`
|
|
12
|
-
${we}${h.dim(`aicommit2 v${uo}`)}`),console.error(`
|
|
13
|
-
${we}Please open a Bug report with the information above:`),console.error(`${we}https://github.com/tak-bro/aicommit2/issues/new/choose`)}},_e=e=>R.lstat(e).then(()=>!0,()=>!1),on=async e=>{try{await R.mkdir(e,{recursive:!0})}catch(t){if(t.code!=="EEXIST")throw t}},_i=e=>e&&`${e[0].toUpperCase()}${e.slice(1)}`,Fi=(e,t)=>{const o=Math.ceil(e),n=Math.floor(t);return Math.floor(Math.random()*(n-o+1))+o},Gi=(e,t)=>e.disabled&&!t.disabled?1:!e.disabled&&t.disabled?-1:0,Mt=e=>e.reduce((t,o)=>Array.isArray(o)?t.concat(Mt(o)):t.concat(o),[]),Bi=(e,t=5)=>e.replace(/[\n\r]/g,"").split(" ").slice(0,t).join(" "),Hi=e=>{let t=0;for(let o=0;o<e.length;o++){const n=e.charCodeAt(o);t=(t<<5)-t+n,t=t&t}return Math.abs(t)},Ui=e=>{const t=e%360,o=65+e%15,n=45+e%10;return`hsl(${t}, ${o}%, ${n}%)`},Ki=e=>{const[t,o,n]=e.match(/\d+/g).map((f,y)=>y===0?Number(f):Number(f)/100),s=(1-Math.abs(2*n-1))*o,r=s*(1-Math.abs(t/60%2-1)),i=n-s/2;let c,u,l;t<60?[c,u,l]=[s,r,0]:t<120?[c,u,l]=[r,s,0]:t<180?[c,u,l]=[0,s,r]:t<240?[c,u,l]=[0,r,s]:t<300?[c,u,l]=[r,0,s]:[c,u,l]=[s,0,r];const d=f=>{const y=Math.round((f+i)*255).toString(16);return y.length===1?"0"+y:y};return`#${d(c)}${d(u)}${d(l)}`},qi=e=>{const t=Hi(e),o=Ui(t);return{primary:Ki(o),secondary:"#FFFFFF"}},Wi=e=>{try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,error:t}}},Fe=e=>{if(!e||typeof e!="string")return"";if(E.isAbsolute(e))return E.resolve(e);if(ve){const t=E.dirname(ve),o=E.join(t,e);return E.resolve(o)}else return""},Yi=["","conventional","gitmoji"],be="http://localhost:11434",{hasOwnProperty:zi}=Object.prototype,Tt=(e,t)=>zi.call(e,t),ue=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],nn=e=>{const t=$e.platform(),o=$e.homedir();let n,s;switch(e){case"config":n=process.env.XDG_CONFIG_HOME;break;case"data":n=process.env.XDG_DATA_HOME;break;case"cache":n=process.env.XDG_CACHE_HOME;break;case"state":n=process.env.XDG_STATE_HOME;break;default:n=void 0}if(t==="darwin")e==="cache"?s=E.join(o,"Library","Caches"):s=E.join(o,"Library","Application Support");else if(t==="win32")s=process.env.LOCALAPPDATA||o;else switch(e){case"config":s=E.join(o,".config");break;case"data":s=E.join(o,".local","share");break;case"cache":s=E.join(o,".cache");break;case"state":s=E.join(o,".local","state");break;default:s=o}return n||s},sn=E.join(nn("config"),"aicommit2"),G=E.join(nn("state"),"aicommit2","logs"),rn=E.join(sn,"config.ini"),an=E.join(G,"aicommit2-%DATE%.log"),cn=E.join(G,"exceptions-%DATE%.log"),Vi=e=>{const t=Object.keys(e),o=new Set([...ue,...t.filter(n=>/^[A-Z][A-Z0-9_]*$/.test(n))]);return Array.from(o)},$=(e,t,o)=>{if(!t)throw new p(`Invalid config property ${e}: ${o}`)},B=(e,t=!1)=>o=>typeof o=="boolean"?o:o==null?t:($(e,/^(?:true|false)$/.test(o),"Must be a boolean(true or false)"),o==="true"),a={systemPrompt(e){return e||""},systemPromptPath(e){return e||""},codeReviewPromptPath(e){return e||""},timeout(e){if(!e)return 6e4;$("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return $("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .7;$("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return $("temperature",t>0,"Must be greater than 0"),$("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens(e){return e?($("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)):8192},logLevel(e){return e?($("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(e),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),e):"info"},logFilePath(e){return e||an},exceptionLogFilePath(e){return e||cn},locale(e){return e?($("locale",e,"Cannot be empty"),$("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),e):"en"},generate(e){if(!e)return 1;$("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return $("generate",t>0,"Must be greater than 0"),$("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?($("type",Yi.includes(e),"Invalid commit type"),e):"conventional"},maxLength(e){if(!e)return 50;$("maxLength",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return $("maxLength",t>=20,"Must be greater than 20 characters"),t},exclude:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],topP:e=>{if(!e)return .9;$("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return $("topP",t>0,"Must be greater than 0"),$("topP",t<=1,"Must be less than or equal to 1"),t},logging:B("logging",!0),includeBody:B("includeBody"),codeReview:B("codeReview"),disabled:B("disabled"),watchMode:B("watchMode"),forceGit:B("forceGit"),disableLowerCase:B("disableLowerCase"),jjAutoNew:B("jjAutoNew"),autoCopy:B("autoCopy"),useStats:B("useStats",!0),statsDays:e=>{if(!e)return 30;$("statsDays",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return $("statsDays",t>0,"Must be greater than 0"),t}},Ee={OPENAI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["gpt-4o-mini"],url:e=>e?($("OPENAI.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.openai.com",path:e=>e||"/v1/chat/completions",proxy:e=>e||"",topP:a.topP,systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},HUGGINGFACE:{cookie:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,topP:a.topP,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},GEMINI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["gemini-3-flash-preview"],systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:a.topP,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},ANTHROPIC:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["claude-sonnet-4-20250514"],systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:a.topP,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},MISTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["mistral-small-latest"],systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:a.topP,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},CODESTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["codestral-latest"],topP:a.topP,systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},OLLAMA:{model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],host:e=>e?($("OLLAMA.host",/^https?:\/\//.test(e),"Must be a valid URL"),e):be,timeout:e=>{if(!e)return 1e5;$("OLLAMA.timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return $("OLLAMA.timeout",t>=500,"Must be greater than 500ms"),t},auth:e=>e||"",key:e=>e||"",envKey:e=>e||"",numCtx:e=>{if(!e)return 2048;$("OLLAMA.numCtx",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return $("OLLAMA.numCtx",t>=2048,"Must be greater than 2048"),t},systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:a.topP,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},COHERE:{key:e=>e||"",envKey:e=>e||"",url:e=>e?($("COHERE.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.cohere.ai",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["command-a-03-2025"],systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,timeout:a.timeout,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:a.topP,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},GROQ:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["llama-3.3-70b-versatile"],systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:a.topP,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},PERPLEXITY:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["sonar"],topP:a.topP,systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},DEEPSEEK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["deepseek-chat"],topP:a.topP,systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},GITHUB_MODELS:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["gpt-4o-mini"],systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:a.topP,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase},BEDROCK:{key:e=>e||"",envKey:e=>e&&e.length>0?e:"BEDROCK_API_KEY",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>{const n=o.trim();return n&&!n.includes(".")&&!n.includes(":")&&console.warn(`[Bedrock] Model ID "${n}" may be invalid.
|
|
14
|
-
Expected formats:
|
|
15
|
-
- Foundation model: "provider.model-name-version" (e.g., "anthropic.claude-haiku-4-5-20251001-v1:0")
|
|
16
|
-
- Inference profile: "prefix.provider.model-name-version" (e.g., "us.anthropic.claude-haiku-4-5-20251001-v1:0")
|
|
17
|
-
- ARN: Full Amazon Resource Name
|
|
18
|
-
See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html`),n}).filter(o=>!!o&&o.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:e=>{e&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:e=>e||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:e=>e||process.env.AWS_PROFILE||"",accessKeyId:e=>e||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:e=>e||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:e=>e||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:e=>e||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:e=>e||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:e=>e||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:e=>{if(!e)return;$("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return $("temperature",t>0,"Must be greater than 0"),$("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return $("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)},logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:e=>{if(!e)return;$("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return $("topP",t>0,"Must be greater than 0"),$("topP",t<=1,"Must be less than or equal to 1"),t},codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase,inferenceParameters:e=>{if(!e)return{};if(typeof e=="object")return e;try{const t=JSON.parse(e);return $("BEDROCK.inferenceParameters",typeof t=="object"&&t!==null&&!Array.isArray(t),"Must be a valid JSON object"),t}catch(t){throw new p(`Invalid BEDROCK.inferenceParameters: Must be valid JSON. Error: ${t.message}`)}}}},Ji=e=>typeof e=="object"&&e!==null,ln=(e,t)=>{Object.keys(e).forEach(o=>{const n=e[o];Ji(n)&&t in n&&(n[t]=!0)})},Xi=e=>{ln(e,"includeBody")},Qi=e=>{ln(e,"disableLowerCase")};let ve,Ce=null,Ot=null;const Zi=(e=[])=>{const t={};for(const o of e)if(o.startsWith("--")){const[n,s]=o.slice(2).split("="),[r,i]=n.split(".");r&&i&&r in Ee?(t[r]||(t[r]={}),t[r][i]=s):t[n]=s}return t},ea=()=>{const e=$e.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,o=rn,n=E.join(e,".aicommit2");return[t,o,n].filter(s=>!!s)},de=async()=>{const e=ea();for(const t of e)if(await _e(t))return t;return rn},ta=e=>e.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}|\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,o,n)=>{const s=o||n;return process.env[s]??""}),Ae=async()=>{const e=await de();if(Ce&&Ot===e)return Ce;ve=e;try{const t=await R.readFile(e,"utf8"),o=ta(t);return Ce=le.parse(o),Ot=e,Ce}catch(t){return t.code==="ENOENT"?(ve=void 0,{}):(console.error(`Error reading config file ${e}:`,t),ve=void 0,{})}},un=()=>{Ce=null,Ot=null},J=async(e,t=[])=>{const o=await Ae(),n=Zi(t),s={...e,...n},r={},i=Vi(o),c={};for(const l of i){const d=o[l]?.envKey;let f;d?(f=[d],l==="BEDROCK"&&d!=="BEDROCK_APPLICATION_API_KEY"&&f.push("BEDROCK_APPLICATION_API_KEY")):l==="BEDROCK"?f=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:f=[`${l}_API_KEY`];const y=f.map(g=>g?process.env[g]:void 0).find(g=>typeof g=="string"&&g.length>0);y&&(c[l]={key:y})}const u=(l,d)=>{const f=s[`${l}.${d}`]??s[l]?.[d],y=c[l]?.[d],g=o[l]?.[d],m=s[d]??o[d];return f!==void 0?f:y!==void 0?y:g!==void 0?g:m};for(const[l,d]of Object.entries(a)){const f=s[l]??o[l];r[l]=d(f)}for(const l of i){r[l]={};const d=Ee[l]||Be(l);for(const[f,y]of Object.entries(d)){const g=u(l,f);r[l][f]=y(g)}}return r},Ge=async e=>{const t=await Ae();for(const[s,r]of e){const[i,c]=s.split(".");if(!c){const d=a[s];if(!d)throw new p(`Invalid config property: ${s}`);t[s]=d(r);continue}if(t[i]||(t[i]={}),ue.includes(i)){const d=Ee[i][c];if(!d)throw new p(`Invalid config property: ${s}`);t[i][c]=d(r);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new p(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const l=Be(i);if(!l[c])throw new p(`Invalid config property for custom service: ${s}`);try{t[i][c]=l[c](r)}catch(d){throw d instanceof p?d:new p(`Invalid value for ${s}: ${d.message}`)}}const o=await de(),n=E.dirname(o);await R.mkdir(n,{recursive:!0}),await R.writeFile(o,le.stringify(t),"utf8"),un()},oa=async e=>{const t=await Ae();for(const[s,r]of e){const[i,c]=s.split("."),u=t[i];if(c==="model"){u||(t[i]={});const d=t[i][c]||[],f=typeof r=="string"?r.split(",").map(y=>y.trim()).filter(y=>!!y):r;t[i][c]=Mt([...d,...f]);continue}if(u&&u.compatible===!0){u||(t[i]={});const d=Be(i);if(!d[c])throw new p(`Invalid config property: ${s}`);try{t[i][c]=d[c](r)}catch(f){throw f instanceof p?f:new p(`Invalid value for ${s}: ${f.message}`)}continue}if(i in Ee){u||(t[i]={});const d=Ee[i][c];if(!d)throw new p(`Invalid config property: ${s}`);t[i][c]=d(r)}else{const d=Be(i);if(!d[c])throw new p(`Invalid config property: ${s}`);t[i]||(t[i]={}),t[i][c]=d[c](r)}}const o=await de(),n=E.dirname(o);await R.mkdir(n,{recursive:!0}),await R.writeFile(o,le.stringify(t),"utf8"),un()},na=async()=>{const e=await Ae();console.log(le.stringify(e))},sa=async()=>{console.log(await de())},Be=e=>({compatible:B("compatible"),stream:B("stream"),url:t=>t?($(`${e}.url`,/^https?:\/\//.test(t),"Must be a valid URL"),t):"",path:t=>t||"",key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],systemPrompt:a.systemPrompt,systemPromptPath:a.systemPromptPath,codeReviewPromptPath:a.codeReviewPromptPath,timeout:a.timeout,temperature:a.temperature,maxTokens:a.maxTokens,logging:a.logging,locale:a.locale,generate:a.generate,type:a.type,maxLength:a.maxLength,includeBody:a.includeBody,topP:a.topP,codeReview:a.codeReview,disabled:a.disabled,watchMode:a.watchMode,disableLowerCase:a.disableLowerCase,autoCopy:a.autoCopy}),D=e=>typeof e=="string"&&e.trim().length>0,ee=e=>(Array.isArray(e.model)?e.model:D(e.model)?[e.model.trim()]:[]).length>0,He=e=>{const t=D(e.key),o=D(e.region)||D(process.env.AWS_REGION)||D(process.env.AWS_DEFAULT_REGION),n=D(e.profile)||D(process.env.AWS_PROFILE),s=D(e.accessKeyId)&&D(e.secretAccessKey)||D(process.env.AWS_ACCESS_KEY_ID)&&D(process.env.AWS_SECRET_ACCESS_KEY),r=D(e.applicationBaseUrl)||D(process.env.BEDROCK_APPLICATION_BASE_URL),i=D(e.applicationEndpointId)||D(process.env.BEDROCK_APPLICATION_ENDPOINT_ID),c=D(process.env.BEDROCK_APPLICATION_API_KEY);return o&&(t||n||s)||(r&&t||i&&c)},me=(e,t)=>Object.entries(e).map(([o,n])=>[o,n]).filter(([o,n])=>!n.disabled).filter(([o,n])=>ue.includes(o)||n.compatible===!0).filter(([o,n])=>{switch(t){case"commit":return o==="OLLAMA"?!!n&&ee(n):o==="HUGGINGFACE"?!!n&&!!n.cookie:o==="BEDROCK"?ee(n)&&He(n):!!n.key&&n.key.length>0;case"review":const s=e.codeReview||n.codeReview;return o==="OLLAMA"?!!n&&ee(n)&&s:o==="HUGGINGFACE"?!!n&&!!n.cookie&&s:o==="BEDROCK"?ee(n)&&He(n)&&s:!!n.key&&n.key.length>0&&s;case"watch":const r=e.watchMode||n.watchMode;return o==="OLLAMA"?!!n&&ee(n)&&r:o==="HUGGINGFACE"?!!n&&!!n.cookie&&r:o==="BEDROCK"?ee(n)&&He(n)&&r:n.compatible?!!n.url&&!!n.key&&r:!!n.key&&n.key.length>0&&r}}).map(([o])=>o);class ra{static create(t,o){return new t(o)}}const ia="stats.json",Ue=2,aa=30,Dt=()=>E.join(sn,ia),Ke=async()=>{const e=Dt();if(!await _e(e))return{version:Ue,metrics:[],selections:[]};try{const t=await R.readFile(e,"utf-8"),o=JSON.parse(t);return!o.version||o.version<Ue?{version:Ue,metrics:o.metrics||[],selections:o.selections||[]}:o}catch{return{version:Ue,metrics:[],selections:[]}}},ca=(e,t)=>{const o=Date.now()-t*24*60*60*1e3;return{version:e.version,metrics:e.metrics.filter(n=>n.timestamp>=o),selections:e.selections.filter(n=>n.timestamp>=o)}},dn=async(e,t)=>{const o=Dt(),n=E.dirname(o),s=t?ca(e,t):e;await R.mkdir(n,{recursive:!0}),await R.writeFile(o,JSON.stringify(s,null,2),"utf-8")},la=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model,responseTimeMs:e.responseTimeMs,success:e.success,errorCode:e.errorCode,tokensUsed:e.tokensUsed},o=await Ke();o.metrics.push(t),await dn(o,e.statsDays)},ua=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},o=await Ke();o.selections.push(t),await dn(o,e.statsDays)},da=(e,t,o)=>{const n=t.filter(l=>l.provider===e),s=o.filter(l=>l.provider===e);if(n.length===0)return{provider:e,totalRequests:0,successCount:0,failureCount:0,selectedCount:s.length,selectionRate:0,avgResponseTimeMs:0,minResponseTimeMs:0,maxResponseTimeMs:0};const r=n.filter(l=>l.success),i=n.map(l=>l.responseTimeMs),c=s.length,u=r.length>0?Math.min(100,Math.round(c/r.length*1e3)/10):0;return{provider:e,totalRequests:n.length,successCount:r.length,failureCount:n.length-r.length,selectedCount:c,selectionRate:u,avgResponseTimeMs:Math.round(i.reduce((l,d)=>l+d,0)/i.length),minResponseTimeMs:Math.min(...i),maxResponseTimeMs:Math.max(...i)}},ma=async(e=aa)=>{const t=await Ke(),o=Date.now()-e*24*60*60*1e3,n=t.metrics.filter(l=>l.timestamp>=o),s=t.selections.filter(l=>l.timestamp>=o);if(n.length===0)return{totalRequests:0,successRate:0,avgResponseTimeMs:0,providerStats:[],periodStart:o,periodEnd:Date.now()};const i=[...new Set(n.map(l=>l.provider))].map(l=>da(l,n,s)).sort((l,d)=>d.totalRequests-l.totalRequests),c=n.filter(l=>l.success).length,u=n.reduce((l,d)=>l+d.responseTimeMs,0);return{totalRequests:n.length,successRate:Math.round(c/n.length*1e3)/10,avgResponseTimeMs:Math.round(u/n.length),providerStats:i,periodStart:Math.min(...n.map(l=>l.timestamp)),periodEnd:Math.max(...n.map(l=>l.timestamp))}},pa=async()=>{const e=Dt();await _e(e)&&await R.unlink(e)},fa=async()=>(await Ke()).metrics.length>0,mn=(e,t)=>{const o=h.red.bold(`[${e}]`);return os({name:`${o} ${t}`,value:t,isError:!0,disabled:!0})},pn=e=>{let t=!1;return ns({next:o=>{if(Object.assign(o,{provider:e.provider,model:e.model}),e.statsEnabled===!1||t)return;t=!0;const n=o.isError===!0,s={provider:e.provider,model:e.model,responseTimeMs:Date.now()-e.startTime,success:!n,errorCode:n?"REQUEST_ERROR":void 0,statsDays:e.statsDays};la(s).catch(()=>{})}})};class ha{constructor(){this.loaders=new Map,this.cache=new Map,this.loadService=async t=>{const o=this.cache.get(t);if(o)return o;const n=this.loaders.get(t);if(!n)return null;const s=await n();return this.cache.set(t,s),s},this.createService=async(t,o)=>{const n=await this.loadService(t);return n?new n(o):null},this.createRequest$=(t,o,n)=>{const s=Date.now(),r=Array.isArray(o.config.model)?o.config.model[0]:o.config.model;return Ie(this.createService(t,o)).pipe(eo(i=>i?(n==="commit"?i.generateCommitMessage$():i.generateCodeReview$()).pipe(pn({provider:t,model:r||"unknown",startTime:s,statsEnabled:o.statsEnabled,statsDays:o.statsDays})):mn(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-e2d5fc19.mjs").then(t=>t.OpenAIService)),this.loaders.set("GEMINI",()=>import("./gemini.service-9ea5644a.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-d6f32293.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-0ca40e02.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-e1ed37fd.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-52aea4ab.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-2905a90b.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-1de1f236.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-dc7f5129.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-90e30b99.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-8f357ef0.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-0ec74310.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-e7d260aa.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const ga=new ha;class qe{constructor(t,o,n=""){this.config=t,this.stagedDiff=o,this.branchName=n,this.extractProviderName=s=>{if(!s)return"compatible";try{return new URL(s).hostname}catch{return"compatible"}},this.createCommitMsgRequests$=s=>this.createServiceRequests$(s,"commit"),this.createCodeReviewRequests$=s=>this.createServiceRequests$(s,"review"),this.createServiceRequests$=(s,r)=>Ie(s).pipe(to(i=>this.createProviderRequests$(i,r)),ss(i=>mn("UNKNOWN",i.message||"Unknown error"))),this.createProviderRequests$=(s,r)=>{const i=this.config[s],c=Array.isArray(i.model)?i.model:[i.model];return Ie(c).pipe(to(u=>this.createModelRequest$(s,u,r)))},this.createModelRequest$=(s,r,i)=>{const c=this.config[s];return c.compatible?this.createCompatibleServiceRequest$(c,r,i):ga.createRequest$(s,{config:{...c,model:r},stagedDiff:this.stagedDiff,keyName:r,branchName:this.branchName,statsEnabled:this.config.useStats,statsDays:this.config.statsDays},i)},this.createCompatibleServiceRequest$=(s,r,i)=>{const c=Date.now(),u=this.extractProviderName(s.url);return Ie(import("./openai-compatible.service-833e4451.mjs")).pipe(eo(({OpenAICompatibleService:l})=>{const d=ra.create(l,{config:{...s,url:s.url||"",path:s.path||"",model:r},stagedDiff:this.stagedDiff,keyName:r,branchName:this.branchName});return(i==="commit"?d.generateCommitMessage$():d.generateCodeReview$()).pipe(pn({provider:u,model:r,startTime:c,statsEnabled:this.config.useStats,statsDays:this.config.statsDays}))}))}}}class Lt{getDetectedMessage(t){return`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`}getDetectedFiles(t){return`Detected ${t.length.toLocaleString()} changed file${t.length>1?"s":""}`}}class We extends Lt{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=t=>`:(exclude)${t}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:t}=await b("git",["rev-parse","--show-toplevel"],{reject:!0});return t.trim()}catch(t){const o=t;if(o.code==="ENOENT")throw new p(`Git command not found!
|
|
19
|
-
|
|
20
|
-
Please install Git first: https://git-scm.com/downloads`);if(o.stderr){if(o.stderr.includes("not a git repository"))throw new p(`Not in a Git repository!
|
|
21
|
-
|
|
22
|
-
Initialize with: git init
|
|
23
|
-
Or navigate to an existing Git repository.`);if(o.stderr.includes("permission denied"))throw new p(`Git permission denied: ${o.stderr.trim()}
|
|
24
|
-
|
|
25
|
-
Check file permissions and repository access.`)}throw new p(`Failed to verify Git repository: ${o.message||"Unknown error"}`)}}async getStagedDiff(t,o){const n=["diff","--cached","--diff-algorithm=minimal"],s=[...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],r=[...this.filesToExclude,...s],[i,c,u]=await Promise.all([b("git",[...n,"--name-only",...r]),b("git",[...n,...r]),b("git",[...n,"--numstat",...s])]),l=i.stdout;if(!l)return null;const d=c.stdout,f=l.split(`
|
|
26
|
-
`).filter(Boolean),y=u.stdout,g=[],m=y.split(`
|
|
27
|
-
`).filter(Boolean);for(const P of m){const C=P.split(" ");C[0]==="-"&&C[1]==="-"&&C[2]&&g.push(C[2])}let A=d;if(g.length>0){d.trim()||(A=""),A+=`
|
|
28
|
-
|
|
29
|
-
--- Binary Files Changed ---
|
|
30
|
-
`;for(const P of g){const{stdout:C}=await b("git",["status","--porcelain",P]),k=C.substring(0,2).trim();A+=`Binary file ${P} ${k==="A"?"added":k==="M"?"modified":k==="D"?"deleted":"changed"}
|
|
31
|
-
`}}const v=[...new Set([...f,...g])];return{files:v,diff:A||`Files changed: ${v.join(", ")}`}}async getCommitDiff(t,o,n){const s=[...o?o.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],r=[...this.filesToExclude,...s],[i,c,u]=await Promise.all([b("git",["diff-tree","-r","--no-commit-id","--name-only",t,...r]),b("git",["show",t,"--",...r]),b("git",["diff-tree","-r","--numstat",t,...s])]),l=i.stdout;if(!l)return null;const d=c.stdout,f=u.stdout,y=[],g=f.split(`
|
|
32
|
-
`).filter(Boolean);for(const v of g){const P=v.split(" ");P[0]==="-"&&P[1]==="-"&&P[2]&&y.push(P[2])}let m=d;if(y.length>0){d.trim()||(m=""),m+=`
|
|
33
|
-
|
|
34
|
-
--- Binary Files Changed ---
|
|
35
|
-
`;for(const v of y)m+=`Binary file ${v} changed
|
|
36
|
-
`}const A=[...new Set([...l.split(`
|
|
37
|
-
`).filter(Boolean),...y])];return{files:A,diff:m||`Files changed: ${A.join(", ")}`}}async commit(t,o=[],n={}){try{await b("git",["commit","-m",t,...o],{stdio:"inherit"})}catch(s){const r=s;throw r.stderr?r.stderr.includes("nothing to commit")?new p(`Nothing to commit.
|
|
38
|
-
|
|
39
|
-
Stage your changes with: git add <files>
|
|
40
|
-
Or use the --all flag to stage all changes.`):r.stderr.includes("Please enter the commit message")?new p(`Commit message cannot be empty.
|
|
41
|
-
|
|
42
|
-
Provide a meaningful commit message.`):r.stderr.includes("Author identity unknown")?new p(`Git author identity not configured.
|
|
43
|
-
|
|
44
|
-
Configure with:
|
|
45
|
-
git config --global user.name "Your Name"
|
|
46
|
-
git config --global user.email "your.email@example.com"`):r.stderr.includes("Permission denied")?new p(`Git permission error: ${r.stderr.trim()}
|
|
47
|
-
|
|
48
|
-
Check repository permissions and file access.`):new p(`Git commit failed: ${r.stderr.trim()}`):r.exitCode===1?new p("Git commit failed. Check your staged changes and try again."):new p(`Failed to commit with Git: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await b("git",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getBranchName(){try{const{stdout:t}=await b("git",["branch","--show-current"]),o=t.trim();if(!o){const{stdout:n}=await b("git",["rev-parse","--short","HEAD"]);return`HEAD@${n.trim()}`}return o}catch{return"HEAD"}}}class Nt extends Lt{constructor(){super(...arguments),this.name="jujutsu",this.excludeFromDiff=t=>t.includes("*")||t.includes("?")||t.includes("[")?`~glob:"${t}"`:`~"${t}"`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"]}async assertRepo(){try{const{stdout:t}=await b("jj",["--version"],{reject:!0});process.env.DEBUG&&console.log(`Jujutsu version: ${t}`)}catch(t){const o=t;throw o.code==="ENOENT"?new p(`Jujutsu (jj) command not found!
|
|
49
|
-
|
|
50
|
-
Please install Jujutsu:
|
|
51
|
-
- macOS: brew install jj
|
|
52
|
-
- Linux: cargo install jj-cli
|
|
53
|
-
- Windows: cargo install jj-cli
|
|
54
|
-
- See: https://github.com/jj-vcs/jj#installation`):new p(`Failed to execute jj command: ${o.message}`)}try{const{stdout:t,stderr:o}=await b("jj",["workspace","root"],{reject:!0}),n=t.trim();if(!n)throw new p("jj workspace root returned empty path");const s=E.join(n,".jj");if(!N.existsSync(s))throw new p(`Jujutsu repository directory not found at ${s}
|
|
55
|
-
|
|
56
|
-
Initialize a jj repository with: jj init`);return n}catch(t){if(t instanceof p)throw t;const o=t;throw o.stderr?o.stderr.includes("not in a jj repo")?new p(`Not in a Jujutsu repository!
|
|
57
|
-
|
|
58
|
-
Initialize with: jj init
|
|
59
|
-
Or navigate to an existing jj repository.`):o.stderr.includes("No workspace found")?new p(`No Jujutsu workspace found!
|
|
60
|
-
|
|
61
|
-
This may be a bare repository. Navigate to a workspace directory.`):new p(`Jujutsu error: ${o.stderr.trim()}`):new p(`Failed to verify Jujutsu repository: ${o.message||"Unknown error"}`)}}async getStagedDiff(t,o){try{const{stdout:n}=await b("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(n)),console.log("excludeFiles:",t),console.log("exclude:",o)),n.includes("No changes.")||n.includes("The working copy is clean"))return null;const s=this.filesToExclude.map(this.excludeFromDiff),r=[...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],i=[...s,...r];let c="all()";i.length>0&&(c=`all() & ${i.join(" & ")}`);const u=["diff","--name-only"],l=["diff","--git"];i.length>0&&(u.push(c),l.push(c)),process.env.DEBUG&&(console.log("jj diff command with fileset:",u),console.log("fileset expression:",c));const{stdout:d}=await b("jj",u);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(d)),!d.trim())return null;const{stdout:f}=await b("jj",l),{stdout:y}=await b("jj",["status","--no-pager"]),g=d.split(`
|
|
62
|
-
`).filter(Boolean),m=[],A=y.split(`
|
|
63
|
-
`);for(const C of A)if(C.includes("(binary)")||C.includes("Binary file")){const k=C.match(/([^\s]+)\s*\(binary\)/);k&&k[1]&&m.push(k[1])}let v=f;if(m.length>0){v+=`
|
|
64
|
-
|
|
65
|
-
--- Binary Files Changed ---
|
|
66
|
-
`;for(const C of m)v+=`Binary file ${C} changed
|
|
67
|
-
`}const P=[...new Set([...g,...m])];return{files:P,diff:v||`Files changed: ${P.join(", ")}`}}catch(n){const s=n;if(s.stderr){if(s.stderr.includes("No changes to show"))return null;if(s.stderr.includes("Operation not allowed"))throw new p(`Jujutsu diff failed: ${s.stderr.trim()}
|
|
68
|
-
|
|
69
|
-
Try: jj status --no-pager`);if(s.stderr.includes("Invalid revision"))throw new p(`Jujutsu revision error: ${s.stderr.trim()}
|
|
70
|
-
|
|
71
|
-
Check if you're in a valid workspace.`)}if(s.exitCode===1&&!s.stderr)return null;if(process.env.DEBUG)throw new p(`Jujutsu diff failed: ${s.message}
|
|
72
|
-
stderr: ${s.stderr}
|
|
73
|
-
exitCode: ${s.exitCode}`);return null}}async getCommitDiff(t,o,n){const s=[...o?o.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]];try{const r=["diff","--name-only","--revision",t],i=["diff","--git","--revision",t];if(s.length>0){const d=`all() & ${s.join(" & ")}`;r.push(d),i.push(d),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",d)}const{stdout:c}=await b("jj",r);if(!c.trim())return null;const{stdout:u}=await b("jj",i),l=c.split(`
|
|
74
|
-
`).filter(Boolean);return{files:l,diff:u||`Files changed: ${l.join(", ")}`}}catch(r){if(process.env.DEBUG){const i=r;console.log("jj getCommitDiff error:",i.message,i.stderr)}return null}}async commit(t,o=[],n={}){try{await b("jj",["describe","-m",t,...o],{stdio:"inherit"}),n.autoNew&&await b("jj",["new"],{stdio:"inherit"})}catch(s){const r=s;throw r.stderr?r.stderr.includes("Empty commit message")?new p(`Commit message cannot be empty.
|
|
75
|
-
|
|
76
|
-
Provide a meaningful commit message.`):r.stderr.includes("No changes to commit")?new p(`No changes to commit.
|
|
77
|
-
|
|
78
|
-
Make some changes first, then try again.`):r.stderr.includes("Invalid revision")?new p(`Jujutsu commit error: ${r.stderr.trim()}
|
|
79
|
-
|
|
80
|
-
Ensure you're in a valid workspace with changes.`):r.stderr.includes("Operation not allowed")?new p(`Jujutsu operation not allowed: ${r.stderr.trim()}
|
|
81
|
-
|
|
82
|
-
Check repository state with: jj status`):new p(`Jujutsu describe failed: ${r.stderr.trim()}`):r.exitCode===1?new p("Jujutsu commit failed. Check your changes and repository state."):new p(`Failed to commit with Jujutsu: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await b("jj",["config","get","ui.comment-char"]);return t.trim()||"#"}catch{return"#"}}async getBranchName(){try{const{stdout:t}=await b("jj",["bookmark","list","--revisions","@"]);if(t.trim()){const s=t.split(`
|
|
83
|
-
`)[0].split(":")[0].trim();if(s)return s}const{stdout:o}=await b("jj",["log","-r","@","--no-graph","-T","change_id.short()"]);return o.trim()||"HEAD"}catch{return"HEAD"}}}class jt extends Lt{constructor(){super(...arguments),this.name="yadm",this.excludeFromDiff=t=>`:(exclude)${t}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:t}=await b("yadm",["rev-parse","--show-toplevel"],{reject:!0}),o=t.trim(),n=process.env.HOME||process.env.USERPROFILE;if(!n)throw new p("HOME environment variable not set. Cannot determine YADM repository.");const s=await import("path"),r=s.resolve(o),i=s.resolve(n);if(r!==i)throw new p(`Not a YADM repository (work tree is not $HOME).
|
|
84
|
-
|
|
85
|
-
YADM work tree: ${r}
|
|
86
|
-
Expected: ${i}
|
|
87
|
-
|
|
88
|
-
This appears to be a regular Git repository.`);const{stdout:c}=await b("yadm",["rev-parse","--git-dir"],{reject:!0}),u=c.trim();if(!u.includes("yadm"))throw new p(`Not a YADM repository (git-dir does not contain "yadm").
|
|
89
|
-
|
|
90
|
-
Git directory: ${u}
|
|
91
|
-
|
|
92
|
-
This appears to be a regular Git repository.`);return o}catch(t){if(t instanceof p)throw t;const o=t;if(o.code==="ENOENT")throw new p(`YADM command not found!
|
|
93
|
-
|
|
94
|
-
Please install YADM first: https://yadm.io/`);if(o.stderr){if(o.stderr.includes("not a git repository"))throw new p(`Not in a YADM repository!
|
|
95
|
-
|
|
96
|
-
Initialize with: yadm init
|
|
97
|
-
Or clone your dotfiles: yadm clone <url>`);if(o.stderr.includes("permission denied"))throw new p(`YADM permission denied: ${o.stderr.trim()}
|
|
98
|
-
|
|
99
|
-
Check file permissions and repository access.`)}throw new p(`Failed to verify YADM repository: ${o.message||"Unknown error"}`)}}async getStagedDiff(t,o){const n=["diff","--cached","--diff-algorithm=minimal"],s=[...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],r=[...this.filesToExclude,...s],[i,c,u]=await Promise.all([b("yadm",[...n,"--name-only",...r]),b("yadm",[...n,...r]),b("yadm",[...n,"--numstat",...s])]),l=i.stdout;if(!l)return null;const d=c.stdout,f=l.split(`
|
|
100
|
-
`).filter(Boolean),y=u.stdout,g=[],m=y.split(`
|
|
101
|
-
`).filter(Boolean);for(const P of m){const C=P.split(" ");C[0]==="-"&&C[1]==="-"&&C[2]&&g.push(C[2])}let A=d;if(g.length>0){d.trim()||(A=""),A+=`
|
|
102
|
-
|
|
103
|
-
--- Binary Files Changed ---
|
|
104
|
-
`;for(const P of g){const{stdout:C}=await b("yadm",["status","--porcelain",P]),k=C.substring(0,2).trim();A+=`Binary file ${P} ${k==="A"?"added":k==="M"?"modified":k==="D"?"deleted":"changed"}
|
|
105
|
-
`}}const v=[...new Set([...f,...g])];return{files:v,diff:A||`Files changed: ${v.join(", ")}`}}async getCommitDiff(t,o,n){const s=[...o?o.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],r=[...this.filesToExclude,...s],[i,c,u]=await Promise.all([b("yadm",["diff-tree","-r","--no-commit-id","--name-only",t,...r]),b("yadm",["show",t,"--",...r]),b("yadm",["diff-tree","-r","--numstat",t,...s])]),l=i.stdout;if(!l)return null;const d=c.stdout,f=u.stdout,y=[],g=f.split(`
|
|
106
|
-
`).filter(Boolean);for(const v of g){const P=v.split(" ");P[0]==="-"&&P[1]==="-"&&P[2]&&y.push(P[2])}let m=d;if(y.length>0){d.trim()||(m=""),m+=`
|
|
107
|
-
|
|
108
|
-
--- Binary Files Changed ---
|
|
109
|
-
`;for(const v of y)m+=`Binary file ${v} changed
|
|
110
|
-
`}const A=[...new Set([...l.split(`
|
|
111
|
-
`).filter(Boolean),...y])];return{files:A,diff:m||`Files changed: ${A.join(", ")}`}}async commit(t,o=[],n={}){try{await b("yadm",["commit","-m",t,...o],{stdio:"inherit"})}catch(s){const r=s;throw r.stderr?r.stderr.includes("nothing to commit")?new p(`Nothing to commit.
|
|
112
|
-
|
|
113
|
-
Stage your changes with: yadm add <file>
|
|
114
|
-
Or stage tracked file modifications: aicommit2 --all
|
|
115
|
-
|
|
116
|
-
Note: The --all flag only stages already-tracked files (YADM best practice).`):r.stderr.includes("Please enter the commit message")?new p(`Commit message cannot be empty.
|
|
117
|
-
|
|
118
|
-
Provide a meaningful commit message.`):r.stderr.includes("Author identity unknown")?new p(`YADM author identity not configured.
|
|
119
|
-
|
|
120
|
-
Configure with:
|
|
121
|
-
yadm config --global user.name "Your Name"
|
|
122
|
-
yadm config --global user.email "your.email@example.com"`):r.stderr.includes("Permission denied")?new p(`YADM permission error: ${r.stderr.trim()}
|
|
123
|
-
|
|
124
|
-
Check repository permissions and file access.`):new p(`YADM commit failed: ${r.stderr.trim()}`):r.exitCode===1?new p("YADM commit failed. Check your staged changes and try again."):new p(`Failed to commit with YADM: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await b("yadm",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getBranchName(){try{const{stdout:t}=await b("yadm",["branch","--show-current"]),o=t.trim();if(!o){const{stdout:n}=await b("yadm",["rev-parse","--short","HEAD"]);return`HEAD@${n.trim()}`}return o}catch{return"HEAD"}}}let _t=null;async function ya(){const e=process.argv.includes("--git"),t=process.argv.includes("--yadm"),o=process.argv.includes("--jj");if(e)try{const m=new We;return await m.assertRepo(),m}catch(m){throw new p(`--git flag is set, but Git is not available or not in a git repository.
|
|
125
|
-
${m instanceof Error?m.message:String(m)}`)}if(t)try{const m=new jt;return await m.assertRepo(),m}catch(m){throw new p(`--yadm flag is set, but YADM is not available or not in a YADM repository.
|
|
126
|
-
${m instanceof Error?m.message:String(m)}`)}if(o)try{const m=new Nt;return await m.assertRepo(),m}catch(m){throw new p(`--jj flag is set, but Jujutsu is not available or not in a jj repository.
|
|
127
|
-
${m instanceof Error?m.message:String(m)}`)}const n=process.env.FORCE_GIT==="true",s=process.env.FORCE_YADM==="true",r=process.env.FORCE_JJ==="true";if(n)try{const m=new We;return await m.assertRepo(),m}catch(m){throw new p(`FORCE_GIT="true" environment variable is set, but Git is not available or not in a git repository.
|
|
128
|
-
${m instanceof Error?m.message:String(m)}`)}if(s)try{const m=new jt;return await m.assertRepo(),m}catch(m){throw new p(`FORCE_YADM="true" environment variable is set, but YADM is not available or not in a YADM repository.
|
|
129
|
-
${m instanceof Error?m.message:String(m)}`)}if(r)try{const m=new Nt;return await m.assertRepo(),m}catch(m){throw new p(`FORCE_JJ="true" environment variable is set, but Jujutsu is not available or not in a jj repository.
|
|
130
|
-
${m instanceof Error?m.message:String(m)}`)}let i=!1;try{i=(await J({})).forceGit===!0}catch{i=!1}if(i)try{const m=new We;return await m.assertRepo(),m}catch(m){throw new p(`forceGit=true is set in config, but Git is not available or not in a git repository.
|
|
131
|
-
${m instanceof Error?m.message:String(m)}`)}const[c,u,l]=await Promise.allSettled([(async()=>{const m=new Nt;return await m.assertRepo(),m})(),(async()=>{const m=new We;return await m.assertRepo(),m})(),(async()=>{const m=new jt;return await m.assertRepo(),m})()]);if(c.status==="fulfilled")return c.value;if(u.status==="fulfilled")return u.value;if(l.status==="fulfilled")return l.value;const d=m=>m.status==="fulfilled"?"unexpected success":String(m.reason?.message??m.reason).replace("KnownError: ","").trim(),f=d(c),y=d(u),g=d(l);throw new p(`No supported VCS repository found.
|
|
132
|
-
|
|
133
|
-
Jujutsu Error:
|
|
134
|
-
${f}
|
|
135
|
-
|
|
136
|
-
Git Error:
|
|
137
|
-
${y}
|
|
138
|
-
|
|
139
|
-
YADM Error:
|
|
140
|
-
${g}
|
|
141
|
-
|
|
142
|
-
Solutions:
|
|
143
|
-
\u2022 Initialize a Jujutsu repository: jj init
|
|
144
|
-
\u2022 Initialize a Git repository: git init
|
|
145
|
-
\u2022 Initialize a YADM repository: yadm init (or yadm clone <url>)
|
|
146
|
-
\u2022 Navigate to an existing Jujutsu, Git, or YADM repository
|
|
147
|
-
\u2022 Set FORCE_GIT="true" environment variable to force Git detection
|
|
148
|
-
\u2022 Set forceGit=true in config file to prefer Git detection`)}async function te(){return _t||(_t=await ya()),_t}const Ft=async()=>(await te()).assertRepo(),Gt=async(e,t)=>(await te()).getStagedDiff(e,t),wa=async(e,t,o)=>{const n=await te();if(!n.getCommitDiff)throw new p(`Commit diff not supported for ${n.name}`);return n.getCommitDiff(e,t,o)},ba=async()=>(await te()).getCommentChar(),Ea=e=>`Detected ${e.files.length.toLocaleString()} changed file${e.files.length>1?"s":""} (${e.diff.length.toLocaleString()} characters)`,Ye=async()=>(await te()).name,va=async(e,t,o)=>{await(await te()).commit(e,t||[],o)},ze=async()=>(await te()).getBranchName(),Ca=1e5;class H{constructor(){this.title="aicommit2",this.formatBytes=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}printTitle(){try{const t=ro.textSync(this.title,{font:"Small Slant"}),o=is(["#8B5CF6","#A020F0","#D946EF"]);console.log(h.bold(o.multiline(t)))}catch{console.log(h.bold(ro.textSync(this.title,{font:"Small Slant"})))}}showLoader(t){if(this.loader){this.loader.text=t;return}this.loader=io(t).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(t){return io(t).start()}stopSpinner(t){t.stop(),t.clear()}printStagedFiles(t){const o=Buffer.byteLength(t.diff,"utf8"),n=this.formatBytes(o);console.log(h.bold.green("\u2714 ")+h.bold(`${Ea(t)}`)+h.dim(` (${n})`)+h.bold(":")),console.log(`${t.files.map(r=>` ${r}`).join(`
|
|
149
|
-
`)}
|
|
150
|
-
`),o>Ca&&(console.log(h.yellow(`\u26A0 Large diff detected (${n}). This may increase processing time and costs.`)),console.log(h.dim(` Consider using --exclude to filter large files.
|
|
151
|
-
`)))}printAnalyzed(){console.log(`
|
|
152
|
-
${h.bold.green("\u2714")} ${h.bold("Changes analyzed")}`)}printCommitted(){console.log(`
|
|
153
|
-
${h.bold.green("\u2714")} ${h.bold("Successfully committed!")}`)}printCopied(){console.log(`
|
|
154
|
-
${h.bold.green("\u2714")} ${h.bold("Successfully copied! Press 'Ctrl + V' to paste")}`)}printSavedCommitMessage(){console.log(`
|
|
155
|
-
${h.bold.green("\u2714")} ${h.bold("Saved commit message")}`)}printCancelledCommit(){console.log(`
|
|
156
|
-
${h.bold.yellow("\u26A0")} ${h.yellow("Commit cancelled")}`)}printError(t){console.log(`
|
|
157
|
-
${h.bold.red("\u2716")} ${h.red(`${t}`)}`)}printWarning(t){console.log(`
|
|
158
|
-
${h.bold.yellow("\u26A0")} ${h.red(`${t}`)}`)}printSuccess(t){console.log(`
|
|
159
|
-
${h.bold.green("\u2714")} ${h.green(`${t}`)}`)}printInfo(t){console.log(`
|
|
160
|
-
${h.bold.blue("\u2139")} ${h.blue(`${t}`)}`)}printSetupGitEvent(t){console.log(`
|
|
161
|
-
${h.bold.green("\u2714")} ${h.bold(`Git ${t} hook has been set up`)}`)}moveCursorUp(){const t=Re.createInterface({input:process.stdin,output:process.stdout});Re.moveCursor(process.stdout,0,-1),t.close()}moveCursorDown(){const t=Re.createInterface({input:process.stdin,output:process.stdout});Re.moveCursor(process.stdout,0,2),t.close()}print(t){console.log(t)}}let Ve,fn="info";async function Aa(e){if(Ve){console.warn("Logger already initialized. Skipping re-initialization.");return}const t=e?.logLevel||"info";fn=t;const o=e?.logFilePath||an,n=e?.exceptionLogFilePath||cn,s=e?.logging??!0;await on(E.dirname(o)),await on(E.dirname(n));const r=[];s?r.push(new F.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:t,format:F.format.combine(F.format.timestamp(),F.format.printf(({level:i,message:c,timestamp:u})=>`[${u}] ${i}: ${c}`))})):r.push(new F.transports.Console({silent:!0})),Ve=F.createLogger({level:t,format:F.format.json(),transports:r,exceptionHandlers:s?[new F.transports.DailyRotateFile({filename:n,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:F.format.combine(F.format.timestamp(),F.format.json())})]:[],exitOnError:!1,silent:!s})}const hn=new Proxy({},{get:(e,t,o)=>{if(!Ve)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(Ve,t,o)}});function gn(){const e=F.config.npm.levels;return(e[fn]??e.info)>=e.verbose}const Pa={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},yn={isLoading:!1,startOption:{text:"AI is performing a code review"}},Bt="No commit messages were generated",wn="No code reviews were generated",Ht={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Bt}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Ut{constructor(t){this.choices$=new oo([]),this.destroyed$=new rs(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new rt,this.inquirerInstance=null,this.loader$=new oo(t)}addSubscription(t){if(this.isDestroyed){t.unsubscribe();return}this.subscriptions.add(t)}initPrompt(t=Ht){return this.stopMessage=t.stopMessage,T.registerPrompt("reactiveListPrompt",as),this.inquirerInstance=T.prompt({choices$:this.choices$,loader$:this.loader$,...t}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}updateLoaderText(t){this.isDestroyed||this.loader$.next({isLoading:!0,startOption:{text:t}})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(t){this.isDestroyed||!t||!t.value||this.choices$.next([...this.currentChoices,t].sort(Gi))}checkErrorOnChoices(t=!0){if(this.choices$.getValue().map(n=>n).every(n=>n?.isError||n?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),t&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){try{this.destroyed$.next(!0),this.destroyed$.complete(),this.choices$.closed||this.choices$.complete(),this.loader$.closed||this.loader$.complete()}catch(t){console.warn("Error completing subjects:",t)}}closeInquirerInstance(){if(!this.inquirerInstance)return;const t=this.inquirerInstance.ui;t?.rl&&!t.rl.closed&&t.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.cancel(),this.closeInquirerInstance(),this.subscriptions.unsubscribe(),this.completeSubject()}catch(t){gn()&&console.warn("Error during ReactivePromptManager destruction:",t)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Bt,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
|
|
162
|
-
${h.bold.yellow("\u26A0")} ${h.yellow(`${Bt}`)}`)}get currentChoices(){return this.choices$.getValue().map(t=>t)}}const w={label:h.bold.green,command:h.bold.white,hint:h.gray,highlight:h.bold.magenta,dim:h.dim},S={MISSING_API_KEY:"MISSING_API_KEY",INVALID_API_KEY:"INVALID_API_KEY",AUTH_FAILED:"AUTH_FAILED",RATE_LIMITED:"RATE_LIMITED",QUOTA_EXCEEDED:"QUOTA_EXCEEDED",MODEL_NOT_FOUND:"MODEL_NOT_FOUND",MODEL_ACCESS_DENIED:"MODEL_ACCESS_DENIED",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",SERVICE_UNAVAILABLE:"SERVICE_UNAVAILABLE",NO_STAGED_CHANGES:"NO_STAGED_CHANGES",EMPTY_COMMIT_MESSAGE:"EMPTY_COMMIT_MESSAGE",VCS_NOT_FOUND:"VCS_NOT_FOUND",INVALID_CONFIG:"INVALID_CONFIG",CONFIG_NOT_FOUND:"CONFIG_NOT_FOUND",SERVER_ERROR:"SERVER_ERROR",UNKNOWN:"UNKNOWN"},Kt={missingApiKey:e=>{const t=e.toUpperCase();return[`Missing API key for ${w.highlight(t)}.`,"",`${w.label("\u2192")} Run: ${w.command(`aicommit2 config set ${t}.key=YOUR_API_KEY`)}`].join(`
|
|
163
|
-
`)},invalidApiKey:e=>{const t=e.toUpperCase();return[`Invalid or expired API key for ${w.highlight(t)}.`,"",`${w.label("\u2192")} Update: ${w.command(`aicommit2 config set ${t}.key=YOUR_NEW_KEY`)}`].join(`
|
|
164
|
-
`)},noApiKeysConfigured:()=>["No AI provider API keys configured.","",`${w.label("\u2192")} Please set at least one API key:`,` ${w.command("aicommit2 config set OPENAI.key=sk-...")}`,` ${w.command("aicommit2 config set ANTHROPIC.key=sk-ant-...")}`,` ${w.command("aicommit2 config set OLLAMA.model=llama3.2")} ${w.dim("(no key needed)")}`,"",`${w.hint("Tip:")} ${w.command("aicommit2 config get")} ${w.hint("to see current config")}`].join(`
|
|
165
|
-
`),rateLimited:e=>[`Rate limit exceeded${e?` for ${w.highlight(e)}`:""}.`,"",`${w.label("\u2192")} Wait a moment and try again`,`${w.label("\u2192")} Or use a different AI provider`].join(`
|
|
166
|
-
`),quotaExceeded:e=>[`API quota exceeded${e?` for ${w.highlight(e)}`:""}.`,"",`${w.label("\u2192")} Upgrade your API plan or wait for reset`].join(`
|
|
167
|
-
`),modelNotFound:(e,t)=>{const o=t.toUpperCase();return[`Model ${w.highlight(`"${e}"`)} not found for ${w.highlight(o)}.`,"",`${w.label("\u2192")} Update: ${w.command(`aicommit2 config set ${o}.model=VALID_MODEL`)}`].join(`
|
|
168
|
-
`)},modelAccessDenied:(e,t)=>[`Access denied to model ${w.highlight(`"${e}"`)} on ${w.highlight(t)}.`,"",`${w.label("\u2192")} Check API access or upgrade your plan`].join(`
|
|
169
|
-
`),networkError:e=>[`Network connection failed${e?` to ${w.highlight(e)}`:""}.`,"",`${w.label("\u2192")} Check internet connectivity and try again`].join(`
|
|
170
|
-
`),timeout:(e,t)=>{const o=t?` from ${w.highlight(t)}`:"",n=Math.round(e*1.5);return[`Request timed out${o} after ${e}ms.`,"",`${w.label("\u2192")} Increase: ${w.command(`aicommit2 config set timeout=${n}`)}`].join(`
|
|
171
|
-
`)},serviceUnavailable:e=>[`${w.highlight(e)} service is temporarily unavailable.`,"",`${w.label("\u2192")} Try again in a few minutes`].join(`
|
|
172
|
-
`),noStagedChanges:e=>{const t=e.toLowerCase()==="jujutsu"?"jj":e.toLowerCase()==="yadm"?"yadm add":"git add";return[`No staged changes found in ${w.highlight(e)} repository.`,"",`${w.label("\u2192")} Stage: ${w.command(`${t} <files>`)}`,`${w.label("\u2192")} Or use: ${w.command("aicommit2 --all")}`].join(`
|
|
173
|
-
`)},emptyCommitMessage:()=>"Commit message cannot be empty.",vcsNotFound:e=>{const o={git:"https://git-scm.com/downloads",yadm:"https://yadm.io/docs/install",jujutsu:"https://github.com/jj-vcs/jj#installation"}[e.toLowerCase()]||"";return[`${w.highlight(e)} is not installed or not found in PATH.`,"",o?`${w.label("\u2192")} Install: ${w.command(o)}`:""].filter(Boolean).join(`
|
|
174
|
-
`)},notInRepository:e=>[`Not in a ${w.highlight(e)} repository.`,"",`${w.label("\u2192")} Init: ${w.command(`${e.toLowerCase()} init`)}`].join(`
|
|
175
|
-
`),invalidConfigFormat:e=>[`Invalid configuration format for ${w.highlight(`"${e}"`)}`,"",`${w.label("\u2192")} Use: ${w.command("aicommit2 config set PROVIDER.key=value")}`].join(`
|
|
176
|
-
`),invalidConfigValue:(e,t)=>[`Invalid value for ${w.highlight(`"${e}"`)}`,"",`${w.label("\u2192")} Expected: ${w.dim(t)}`].join(`
|
|
177
|
-
`),serverError:(e,t)=>{const o=t?` ${w.dim(`(HTTP ${t})`)}`:"";return`${w.highlight(e)} server error${o}. Try again later.`},ollamaNotRunning:()=>[`${w.highlight("Ollama")} is not running or not accessible.`,"",`${w.label("\u2192")} Start: ${w.command("ollama serve")}`].join(`
|
|
178
|
-
`),ollamaModelNotPulled:e=>[`Ollama model ${w.highlight(`"${e}"`)} is not available locally.`,"",`${w.label("\u2192")} Pull: ${w.command(`ollama pull ${e}`)}`].join(`
|
|
179
|
-
`)},$a=e=>({401:S.INVALID_API_KEY,403:S.MODEL_ACCESS_DENIED,404:S.MODEL_NOT_FOUND,429:S.RATE_LIMITED,500:S.SERVER_ERROR,502:S.SERVICE_UNAVAILABLE,503:S.SERVICE_UNAVAILABLE,504:S.TIMEOUT})[e]||S.UNKNOWN,Sa=e=>{const t=e.toLowerCase();return t.includes("api key")||t.includes("api_key")||t.includes("apikey")?t.includes("missing")?S.MISSING_API_KEY:S.INVALID_API_KEY:t.includes("401")||t.includes("unauthorized")||t.includes("authentication")?S.AUTH_FAILED:t.includes("rate")||t.includes("429")||t.includes("too many")?S.RATE_LIMITED:t.includes("quota")||t.includes("usage")||t.includes("limit exceeded")?S.QUOTA_EXCEEDED:t.includes("model")&&(t.includes("not found")||t.includes("404"))?S.MODEL_NOT_FOUND:t.includes("403")||t.includes("forbidden")||t.includes("access denied")?S.MODEL_ACCESS_DENIED:t.includes("econnrefused")||t.includes("network")||t.includes("connection")?S.NETWORK_ERROR:t.includes("timeout")||t.includes("timed out")||t.includes("504")?S.TIMEOUT:t.includes("unavailable")||t.includes("overloaded")||t.includes("503")||t.includes("502")?S.SERVICE_UNAVAILABLE:t.includes("500")||t.includes("internal server error")?S.SERVER_ERROR:S.UNKNOWN},U={missingApiKey:e=>`Missing API key for ${e.toUpperCase()}`,invalidApiKey:e=>`Invalid API key for ${e.toUpperCase()}`,rateLimited:e=>`Rate limit exceeded${e?` for ${e}`:""}`,quotaExceeded:e=>`API quota exceeded${e?` for ${e}`:""}`,modelNotFound:(e,t)=>`Model "${e}" not found for ${t.toUpperCase()}`,modelAccessDenied:(e,t)=>`Access denied to model "${e}" on ${t}`,networkError:e=>`Network connection failed${e?` to ${e}`:""}`,timeout:(e,t)=>`Request timed out${t?` from ${t}`:""} after ${e}ms`,serviceUnavailable:e=>`${e} service is temporarily unavailable`,serverError:(e,t)=>`${e} server error${t?` (HTTP ${t})`:""}`,unknown:e=>`An error occurred with ${e}. Please try again.`,ollamaNotRunning:()=>"Ollama is not running. Start with: ollama serve",ollamaModelNotPulled:e=>`Ollama model "${e}" not found. Pull with: ollama pull ${e}`},Ia=(e,t={})=>{const{provider:o="AI",model:n,timeout:s}=t;switch(e){case S.MISSING_API_KEY:return U.missingApiKey(o);case S.INVALID_API_KEY:case S.AUTH_FAILED:return U.invalidApiKey(o);case S.RATE_LIMITED:return U.rateLimited(o);case S.QUOTA_EXCEEDED:return U.quotaExceeded(o);case S.MODEL_NOT_FOUND:return U.modelNotFound(n||"unknown",o);case S.MODEL_ACCESS_DENIED:return U.modelAccessDenied(n||"unknown",o);case S.NETWORK_ERROR:return U.networkError(o);case S.TIMEOUT:return U.timeout(s||1e4,o);case S.SERVICE_UNAVAILABLE:return U.serviceUnavailable(o);case S.SERVER_ERROR:return U.serverError(o);default:return U.unknown(o)}},bn={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:"",vcs_branch:""},Ra={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
|
|
180
|
-
|
|
181
|
-
[optional body]
|
|
182
|
-
|
|
183
|
-
[optional footer(s)]`,gitmoji:`:<emoji>:(<optional scope>): <description>
|
|
184
|
-
|
|
185
|
-
[optional body]
|
|
186
|
-
|
|
187
|
-
[optional footer(s)]`},xa={"":"",gitmoji:`
|
|
188
|
-
${Object.entries({":sparkles:":"Introduce new features.",":bug:":"Fix a bug.",":memo:":"Add or update documentation.",":art:":"Improve structure / format of the code.",":zap:":"Improve performance.",":fire:":"Remove code or files.",":ambulance:":"Critical hotfix.",":white_check_mark:":"Add, update, or pass tests.",":lock:":"Fix security or privacy issues.",":rocket:":"Deploy stuff.",":lipstick:":"Add or update the UI and style files.",":tada:":"Begin a project.",":recycle:":"Refactor code.",":wrench:":"Add or update configuration files.",":bulb:":"Add or update comments in source code.",":twisted_rightwards_arrows:":"Merge branches."}).map(([e,t])=>` - ${e}: ${t}`).join(`
|
|
189
|
-
`)}`,conventional:`
|
|
190
|
-
${Object.entries({docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that neither fixes a bug nor adds a feature",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to CI configuration files, scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit",feat:"A new feature",fix:"A bug fix"}).map(([e,t])=>` - ${e}: ${t}`).join(`
|
|
191
|
-
`)}`},qt=(e,t)=>e.replace(/{(\w+)}/g,(o,n)=>t[n]?.toString()||bn[n]?.toString()),ka=(e,t)=>{const o=t.split("-")[0].toLowerCase(),n={conventional:{en:{subject:"fix(auth): fix bug in user authentication process",body:"- Update login function to handle edge cases\\n- Add additional error logging for debugging"},zh:{subject:"fix(auth): \u4FEE\u590D\u7528\u6237\u8BA4\u8BC1\u8FC7\u7A0B\u4E2D\u7684\u9519\u8BEF",body:"- \u66F4\u65B0\u767B\u5F55\u51FD\u6570\u4EE5\u5904\u7406\u8FB9\u7F18\u60C5\u51B5\\n- \u6DFB\u52A0\u989D\u5916\u7684\u9519\u8BEF\u65E5\u5FD7\u7528\u4E8E\u8C03\u8BD5"},ja:{subject:"fix(auth): \u30E6\u30FC\u30B6\u30FC\u8A8D\u8A3C\u30D7\u30ED\u30BB\u30B9\u306E\u30D0\u30B0\u3092\u4FEE\u6B63",body:"- \u30A8\u30C3\u30B8\u30B1\u30FC\u30B9\u3092\u51E6\u7406\u3059\u308B\u305F\u3081\u306B\u30ED\u30B0\u30A4\u30F3\u6A5F\u80FD\u3092\u66F4\u65B0\\n- \u30C7\u30D0\u30C3\u30B0\u7528\u306E\u8FFD\u52A0\u30A8\u30E9\u30FC\u30ED\u30B0\u3092\u8FFD\u52A0"},ko:{subject:"fix(auth): \uC0AC\uC6A9\uC790 \uC778\uC99D \uD504\uB85C\uC138\uC2A4\uC758 \uBC84\uADF8 \uC218\uC815",body:"- \uC5E3\uC9C0 \uCF00\uC774\uC2A4\uB97C \uCC98\uB9AC\uD558\uB3C4\uB85D \uB85C\uADF8\uC778 \uD568\uC218 \uC5C5\uB370\uC774\uD2B8\\n- \uB514\uBC84\uAE45\uC744 \uC704\uD55C \uCD94\uAC00 \uC624\uB958 \uB85C\uAE45 \uCD94\uAC00"},es:{subject:"fix(auth): corregir error en el proceso de autenticaci\xF3n",body:"- Actualizar funci\xF3n de inicio de sesi\xF3n para manejar casos extremos\\n- Agregar registro de errores adicional para depuraci\xF3n"},fr:{subject:"fix(auth): corriger un bug dans le processus d'authentification",body:"- Mettre \xE0 jour la fonction de connexion pour g\xE9rer les cas limites\\n- Ajouter une journalisation d'erreurs suppl\xE9mentaire pour le d\xE9bogage"},de:{subject:"fix(auth): Fehler im Benutzerauthentifizierungsprozess beheben",body:"- Login-Funktion aktualisiert, um Randf\xE4lle zu behandeln\\n- Zus\xE4tzliche Fehlerprotokollierung f\xFCr Debugging hinzugef\xFCgt"}},gitmoji:{en:{subject:":sparkles: Add real-time chat feature",body:"- Implement WebSocket connection\\n- Add message encryption\\n- Include typing indicators"},zh:{subject:":sparkles: \u6DFB\u52A0\u5B9E\u65F6\u804A\u5929\u529F\u80FD",body:"- \u5B9E\u73B0WebSocket\u8FDE\u63A5\\n- \u6DFB\u52A0\u6D88\u606F\u52A0\u5BC6\\n- \u5305\u542B\u8F93\u5165\u6307\u793A\u5668"},ja:{subject:":sparkles: \u30EA\u30A2\u30EB\u30BF\u30A4\u30E0\u30C1\u30E3\u30C3\u30C8\u6A5F\u80FD\u3092\u8FFD\u52A0",body:"- WebSocket\u63A5\u7D9A\u3092\u5B9F\u88C5\\n- \u30E1\u30C3\u30BB\u30FC\u30B8\u6697\u53F7\u5316\u3092\u8FFD\u52A0\\n- \u5165\u529B\u30A4\u30F3\u30B8\u30B1\u30FC\u30BF\u30FC\u3092\u542B\u3080"},ko:{subject:":sparkles: \uC2E4\uC2DC\uAC04 \uCC44\uD305 \uAE30\uB2A5 \uCD94\uAC00",body:"- WebSocket \uC5F0\uACB0 \uAD6C\uD604\\n- \uBA54\uC2DC\uC9C0 \uC554\uD638\uD654 \uCD94\uAC00\\n- \uC785\uB825 \uD45C\uC2DC\uAE30 \uD3EC\uD568"},es:{subject:":sparkles: Agregar funci\xF3n de chat en tiempo real",body:"- Implementar conexi\xF3n WebSocket\\n- Agregar cifrado de mensajes\\n- Incluir indicadores de escritura"},fr:{subject:":sparkles: Ajouter une fonctionnalit\xE9 de chat en temps r\xE9el",body:"- Impl\xE9menter une connexion WebSocket\\n- Ajouter le chiffrement des messages\\n- Inclure des indicateurs de saisie"},de:{subject:":sparkles: Echtzeit-Chat-Funktion hinzuf\xFCgen",body:"- WebSocket-Verbindung implementieren\\n- Nachrichtenverschl\xFCsselung hinzuf\xFCgen\\n- Tippindikatoren einschlie\xDFen"}},"":{en:{subject:"",body:""}}},s=n[e]||n[""];return s[o]||s.en},En=e=>{const{type:t,maxLength:o,generate:n,locale:s}=e,r="You are an expert Git commit message writer specializing in analyzing code changes and creating precise, meaningful commit messages.",i=`Your task is to generate exactly ${n} ${t} style commit message${n!==1?"s":""} based on the provided git diff.`;return[r,i,"",["## Requirements:",`1. Language: Write all messages in ${s}`,`2. Format: Strictly follow the ${t} commit format:`,`${Ra[t]}`,`3. Allowed Types:${xa[t]}`,"","## Guidelines:",`- Subject line: Max ${o} characters, imperative mood, no period`,"- Analyze the diff to understand:"," * What files were changed"," * What functionality was added, modified, or removed"," * The scope and impact of changes","- For the commit type, choose based on:"," * feat: New functionality or feature"," * fix: Bug fixes or error corrections"," * refactor: Code restructuring without changing functionality"," * docs: Documentation changes only"," * style: Formatting, missing semi-colons, etc"," * test: Adding or modifying tests"," * chore: Maintenance tasks, dependency updates"," * perf: Performance improvements"," * build: Build system or external dependency changes"," * ci: CI configuration changes","- Scope: Extract from file paths or logical grouping (e.g., auth, api, ui)","- Body (when needed):"," * Explain the motivation for the change"," * Compare previous behavior with new behavior"," * Note any breaking changes or important details","- Footer: Include references to issues, breaking changes if applicable","","## Analysis Approach:","1. Identify the primary purpose of the changes","2. Group related changes together","3. Determine the most appropriate type and scope","4. Write a clear, concise subject line","5. Add body details for complex changes","","Remember: The commit message should help future developers understand WHY this change was made, not just WHAT was changed."].join(`
|
|
192
|
-
`)].filter(Boolean).join(`
|
|
193
|
-
`)},Je=(e,t,o)=>{const n=s=>{const r=ka(s,o);return s==="conventional"||s==="gitmoji"?`${Array(t).fill(null).map((i,c)=>`
|
|
194
|
-
{
|
|
195
|
-
"subject": "${r.subject}",
|
|
196
|
-
"body": "${r.body}",
|
|
197
|
-
"footer": ""
|
|
198
|
-
}`).join(",")}`:""};return[`
|
|
199
|
-
Lastly, Provide your response as a JSON array containing exactly ${t} object${t!==1?"s":""}, each with the following keys:`,`- "subject": The main commit message using the ${e} style. It should be a concise summary of the changes.`,'- "body": An optional detailed explanation of the changes. If not needed, use an empty string.','- "footer": An optional footer for metadata like BREAKING CHANGES. If not needed, use an empty string.',`The array must always contain ${t} element${t!==1?"s":""}, no more and no less.`,`Example response format:
|
|
200
|
-
[${n(e)}
|
|
201
|
-
]`,`Ensure you generate exactly ${t} commit message${t!==1?"s":""}, even if it requires creating slightly varied versions for similar changes.`,"The response should be valid JSON that can be parsed without errors."].filter(Boolean).join(`
|
|
202
|
-
`)},Ma=e=>{const{systemPrompt:t,systemPromptPath:o,type:n,generate:s,locale:r}=e;if(t)return`${qt(t,e)}
|
|
203
|
-
${Je(n,s,r)}`;if(!o)return`${En(e)}
|
|
204
|
-
${Je(n,s,r)}`;try{const i=N.readFileSync(Fe(o),"utf-8");return`${qt(i,e)}
|
|
205
|
-
${Je(n,s,r)}`}catch{return`${En(e)}
|
|
206
|
-
${Je(n,s,r)}`}},Ta=e=>{const{codeReviewPromptPath:t,locale:o}=e,n=`I'll give you the output of the "git diff" command as an input. Please review the following code and provide your feedback in Markdown format. Focus on:
|
|
207
|
-
|
|
208
|
-
1. Language: ${o}
|
|
209
|
-
2. Code quality and best practices
|
|
210
|
-
3. Potential bugs or errors
|
|
211
|
-
4. Performance improvements
|
|
212
|
-
5. Readability and maintainability
|
|
213
|
-
|
|
214
|
-
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!t)return n;try{const s=N.readFileSync(Fe(t),"utf-8");return`${qt(s,e)}`}catch{return n}},vn=async e=>{if(e.systemPromptPath)try{N.readFileSync(Fe(e.systemPromptPath),"utf-8")}catch(t){throw new p(`Error reading system prompt file: ${e.systemPromptPath}, ${t}`)}if(e.codeReview&&e.codeReviewPromptPath)try{N.readFileSync(Fe(e.codeReviewPromptPath),"utf-8")}catch(t){throw new p(`Error reading code review prompt file: ${e.codeReviewPromptPath}, ${t}`)}},Oa=(e,t="commit")=>t==="review"?`Please analyze the following diff and provide a comprehensive code review:
|
|
215
|
-
|
|
216
|
-
\`\`\`diff
|
|
217
|
-
${e}
|
|
218
|
-
\`\`\`
|
|
219
|
-
|
|
220
|
-
Focus on code quality, potential issues, and improvement suggestions.`:`Please analyze the following diff and generate commit message(s) based on the changes:
|
|
221
|
-
|
|
222
|
-
\`\`\`diff
|
|
223
|
-
${e}
|
|
224
|
-
\`\`\`
|
|
225
|
-
|
|
226
|
-
Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,L=new H;var Da=async(e,t,o,n,s,r,i,c,u,l,d,f,y,g,m,A,v)=>(async()=>{const P=A==="json";P||L.printTitle();const C=P?null:L.displaySpinner("Detecting repository...");if(await Ft(),n){C&&(C.text="Staging changes...");const oe=await Ye();oe==="git"?await b("git",["add","."]):oe==="yadm"&&await b("yadm",["add","--update"])}C&&(C.text="Loading configuration...");const k={locale:e?.toString(),generate:t?.toString(),type:s?.toString(),systemPrompt:c?.toString(),...u===!0&&{includeBody:"true"},...f===!0&&{disableLowerCase:"true"}};y&&(k.logLevel="verbose");const I=await J(k,v);(u===!0||I.includeBody===!0)&&Xi(I),f&&Qi(I),await vn(I);const X={autoNew:m||I.jjAutoNew};C&&(C.text="Detecting staged files...");const z=await Gt(o,I.exclude);if(C?.stop(),!z){const oe=await Ye();throw new p(Kt.noStagedChanges(oe),{code:S.NO_STAGED_CHANGES})}P||L.printStagedFiles(z);const K=me(I,"commit");if(K.length===0)throw new p(Kt.noApiKeysConfigured(),{code:S.MISSING_API_KEY});const Nn=await ze(),tt=new qe(I,z,Nn);P&&((await _a(tt,K)).forEach(_n=>{process.stdout.write(JSON.stringify(_n)+`
|
|
227
|
-
`)}),process.exit(0));const Vt=me(I,"review");Vt.length>0&&await La(tt,Vt);const ot=await Na(tt,K,l);I.useStats!==!1&&ua({provider:ot.provider,model:ot.model,statsDays:I.statsDays}).catch(()=>{});let V=ot.value;if(d){if(L.printInfo("Opening editor to modify commit message..."),V=await ja(V),!V.trim())throw new p(Kt.emptyCommitMessage(),{code:S.EMPTY_COMMIT_MESSAGE});L.printSuccess("Commit message edited successfully!"),L.print(`
|
|
228
|
-
${V}
|
|
229
|
-
`)}(i||I.autoCopy)&&(xs("copy-paste").copy(V),i&&L.printCopied()),i&&!g&&process.exit(),g&&(process.stdout.write(V+`
|
|
230
|
-
`),process.exit()),(r||l&&K.length===1)&&(await Cn(V,v,X),process.exit());const{confirmationPrompt:jn}=await T.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);jn?await Cn(V,v,X):L.printCancelledCommit(),process.exit()})().catch(P=>{if(A==="json"){const C={error:P.message||"Unknown error occurred"};process.stderr.write(JSON.stringify(C)+`
|
|
231
|
-
`),process.exit(1)}L.printError(P.message),q(P),process.exit(1)});async function La(e,t){const o=new Ut(yn);let n=null;try{const s=o.initPrompt({...Ht,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${wn}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});if(o.startLoader(),n=e.createCodeReviewRequests$(t).subscribe({next:u=>o.refreshChoices(u),error:u=>{console.error("Code review request error:",u),o.checkErrorOnChoices()},complete:()=>o.checkErrorOnChoices()}),!(await s).codeReviewPrompt?.value)throw new p("An error occurred! No selected code review");L.moveCursorUp();const{continuePrompt:c}=await T.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(L.printCancelledCommit(),process.exit())}finally{n&&n.unsubscribe(),o.destroy()}}const Na=async(e,t,o)=>{const n=new Ut(Pa);let s=null;try{if(o&&t.length===1){const f=[];n.startLoader(),s=e.createCommitMsgRequests$(t).subscribe({next:g=>{f.push(g),n.refreshChoices(g)},error:g=>{console.error("Commit message generation error:",g),n.checkErrorOnChoices(!1)},complete:()=>n.checkErrorOnChoices(!1)}),await new Promise(g=>{s?.add(()=>g())}),n.clearLoader(),L.moveCursorUp();const y=f.find(g=>g.value&&!g.isError&&!g.disabled);if(!y||!y.value)throw new p("No valid commit message was generated");return L.print(`
|
|
232
|
-
${y.name}
|
|
233
|
-
`),{value:y.value,provider:y.provider||"unknown",model:y.model||"unknown"}}const r=new Map,i=n.initPrompt();n.startLoader();let c=0;s=e.createCommitMsgRequests$(t).subscribe({next:f=>{const y=f;y.value&&r.set(y.value,y),f.value&&!f.isError&&!f.disabled&&(c++,n.updateLoaderText(`AI is analyzing your changes (${c} message${c>1?"s":""} generated)`)),n.refreshChoices(f)},error:f=>{console.error("Commit message generation error:",f),n.checkErrorOnChoices()},complete:()=>n.checkErrorOnChoices()});const u=await i;L.moveCursorUp();const l=u.aicommit2Prompt?.value;if(!l)throw new p("An error occurred! No selected message");const d=r.get(l);return{value:l,provider:d?.provider||"unknown",model:d?.model||"unknown"}}finally{s&&s.unsubscribe(),n.destroy()}};async function ja(e){const t=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),o=E.join($e.tmpdir(),`aicommit2-${Date.now()}-${Bn.randomBytes(4).toString("hex")}.txt`);try{N.writeFileSync(o,e,"utf8");const n=t.split(" "),[s,...r]=n;await b(s,[...r,o],{stdio:"inherit"});const i=N.readFileSync(o,"utf8").trim();if(N.unlinkSync(o),!i)throw new p("Commit cancelled - empty message");return i}catch(n){throw N.existsSync(o)&&N.unlinkSync(o),n instanceof p?n:n&&typeof n=="object"&&"exitCode"in n&&n.exitCode!==0?new p("Commit cancelled"):process.env.VISUAL||process.env.EDITOR?new p(`Failed to open editor "${t}". Please check:
|
|
234
|
-
- Editor binary exists in PATH
|
|
235
|
-
- Editor flags are correct
|
|
236
|
-
- EDITOR/VISUAL is set correctly`):new p(`Failed to open editor "${t}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}const Cn=async(e,t,o)=>{await va(e,t,o),L.printCommitted()},_a=async(e,t)=>{const n=(await it(e.createCommitMsgRequests$(t).pipe(at()),{defaultValue:[]})).filter(s=>s.value&&!s.isError&&!s.disabled);if(n.length===0)throw new p("No valid commit messages were generated");return n.map(({value:s=""})=>{const[r="",...i]=s.split(`
|
|
237
|
-
`);return{subject:r,body:i.join(`
|
|
238
|
-
`).trim()}})};var Fa=j({name:"config",parameters:["<mode>","[key=value...]"],help:{description:"Manage configuration settings",examples:["aic2 config set <key>=<value> [<key>=<value> ...]","aic2 config get [<key> [<key> ...]]","aic2 config add <key>=<value> [<key>=<value> ...]","aic2 config del <key>","aic2 config list"]},commands:[j({name:"set",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Set configuration values. Multiple key-value pairs can be set at once.",examples:["aic2 config set OPENAI.key=<your key>","aic2 config set ANTHROPIC.topP=0.8 ANTHROPIC.generate=2"]}}),j({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),j({name:"add",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Add new model to existing configuration. Only Ollama.model can be added.",examples:['aic2 config add OLLAMA.model="gemma2"']}}),j({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),j({name:"del",parameters:["<config-name>"],help:{description:"Delete a configuration setting or section.",examples:["aic2 config del <config-name>","aic2 config del OPENAI.key","aic2 config del OPENAI"]}}),j({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},e=>{(async()=>{const{mode:t,keyValue:o}=e._,n=e._[1];if(t==="get"){const s=await J({},[]);if(o.length===0){console.log(s);return}for(const r of o){const i=r.split(".");let c=s,u=!0;for(const l of i)if(Tt(c,l))c=c[l];else{u=!1;break}u?console.log(r,c):console.log(`${r} not found`)}return}if(t==="set"){await Ge(o.map(s=>{const r=s.indexOf("=");if(r===-1)throw new p("Invalid format. Use: key=value");const i=s.slice(0,r),c=s.slice(r+1);return[i,c]}));return}if(t==="add"){await oa(o.map(s=>{const r=s.indexOf("=");if(r===-1)throw new p("Invalid format. Use: key=value");const i=s.slice(0,r),c=s.slice(r+1);return[i,c]}));return}if(t==="list"){await na();return}if(t==="del"){if(!n)throw new p("Please provide the config name to delete.");const s=await Ae(),r=n.split(".");if(r.length===2){const[i,c]=r;if(s[i]&&typeof s[i]=="object"&&Tt(s[i],c)){delete s[i][c],Object.keys(s[i]).length===0&&delete s[i];const u=await de();await R.writeFile(u,le.stringify(s),"utf8"),console.log(`Successfully deleted config: ${n}`);const l=await R.readFile(u,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new p(`Config not found: ${n}`)}else if(r.length===1){const i=r[0];if(Tt(s,i)){delete s[i];const c=await de();await R.writeFile(c,le.stringify(s),"utf8"),console.log(`Successfully deleted config: ${n}`);const u=await R.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(u),console.log("----------------------------")}else throw new p(`Config not found: ${n}`)}else throw new p(`Invalid config name format: ${n}`);return}if(t==="path"){await sa();return}throw new p(`Invalid mode: ${t}`)})().catch(t=>{new H().printError(t.message),q(t),process.exit(1)})});class An{constructor(t={}){if(!t.method)throw new Error("method should be defined!");if(!t.baseURL)throw new Error("baseURL should be defined!");this.config={...t},this.axiosInstance=cs.create(this.config)}setHeaders(t){return this.config.headers=t,this}setParams(t){return this.config.params=t,this}setBody(t){return this.config.data=t,this}addBody(t){return this.config.data={...this.config.data,...t},this}setMethod(t){return this.config.method=t,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(t){throw t}}}const Ga={healthy:h.green("\u2705"),error:h.red("\u274C"),warning:h.yellow("\u26A0\uFE0F"),skipped:h.gray("\u23ED\uFE0F")},Ba={healthy:h.green,error:h.red,warning:h.yellow,skipped:h.gray},Ha=e=>typeof e.key=="string"&&e.key.trim().length>0,Ua=async(e,t)=>{try{return await new An({method:"GET",baseURL:e,timeout:t}).execute(),{ok:!0}}catch(o){const n=o instanceof Error?o.message:String(o);return n.includes("ECONNREFUSED")?{ok:!1,error:"Not running"}:{ok:!1,error:n}}},Ka=async(e,t,o)=>{if(e==="OLLAMA"){if(!ee(t))return{provider:e,status:"skipped",message:"No models configured"};const n=typeof t.host=="string"&&t.host.trim()?t.host:be,s=await Ua(n,o);return s.ok?{provider:e,status:"healthy",message:"Running",details:`Host: ${n}`}:{provider:e,status:"warning",message:s.error||"Connection failed",details:`Host: ${n}`}}return e==="HUGGINGFACE"?t.cookie?{provider:e,status:"healthy",message:"Cookie configured"}:{provider:e,status:"skipped",message:"No cookie configured"}:e==="BEDROCK"?He(t)?{provider:e,status:"healthy",message:"Credentials configured"}:{provider:e,status:"skipped",message:"Not configured"}:Ha(t)?{provider:e,status:"healthy",message:"API key configured"}:{provider:e,status:"skipped",message:"Not configured"}},qa=async e=>{const t=[],o=e.timeout||1e4;for(const n of ue){const s=e[n];if(!s||typeof s!="object"){t.push({provider:n,status:"skipped",message:"Not configured"});continue}if(s.disabled){t.push({provider:n,status:"skipped",message:"Disabled"});continue}const r=await Ka(n,s,o);t.push(r)}return t},Wa=Math.max(...ue.map(e=>e.length)),Ya=e=>e.padEnd(Wa),za=e=>{console.log(""),console.log(h.bold("\u{1FA7A} aicommit2 Health Check")),console.log(""),console.log(h.bold("Providers:"));for(const o of e){const n=Ga[o.status],s=Ya(o.provider),r=Ba[o.status](o.message),i=o.details?h.gray(` (${o.details})`):"";console.log(` ${n} ${s} ${r}${i}`)}const t={healthy:e.filter(o=>o.status==="healthy").length,error:e.filter(o=>o.status==="error").length,warning:e.filter(o=>o.status==="warning").length,skipped:e.filter(o=>o.status==="skipped").length};console.log(""),console.log(h.bold("Summary: ")+h.green(`${t.healthy} healthy`)+", "+h.red(`${t.error} error`)+", "+h.yellow(`${t.warning} warning`)+", "+h.gray(`${t.skipped} skipped`)),console.log(""),t.error>0&&(process.exitCode=1)},Va=j({name:"doctor",parameters:[],help:{description:"Check health status of configured AI providers",examples:["aicommit2 doctor"]}},()=>{(async()=>{const e=await J({},[]),t=await qa(e);za(t)})().catch(e=>{console.error(h.red(e.message)),q(e),process.exit(1)})});var Ja=j({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token ghp_xxxxxxxxxxxxxxxxxxxx"]}},e=>{(async()=>{const t=new H;if(e.flags.token){try{await Xa(e.flags.token,t)}catch(o){throw new p(`Token authentication failed: ${o.message}`)}return}try{await Qa(t)}catch(o){throw new p(`Browser authentication failed: ${o.message}`)}})().catch(t=>{new H().printError(t.message),q(t),process.exit(1)})});async function Xa(e,t){if(t.printWarning("Authenticating with provided token..."),!e.startsWith("ghp_")&&!e.startsWith("gho_")&&!e.startsWith("ghu_"))throw new Error("Invalid token format. GitHub tokens should start with ghp_, gho_, or ghu_");try{const o=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!o.ok)throw new Error(`GitHub API request failed: ${o.status} ${o.statusText}`);const n=await o.json();try{(await fetch("https://models.github.ai/inference/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:"gpt-4o-mini",max_tokens:1})})).ok?t.printSuccess("GitHub Models access verified!"):t.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}catch{t.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}await Ge([["GITHUB_MODELS.key",e]]),t.printSuccess(`Successfully authenticated as ${n.login}`)}catch(o){throw new Error(`Token validation failed: ${o.message}`)}}async function Qa(e){e.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{Se("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{Se("gh auth status",{encoding:"utf8",stdio:"pipe"}).includes("Logged in to github.com")&&e.printInfo("Already authenticated with GitHub CLI")}catch{e.printInfo("Authenticating with GitHub CLI..."),e.printInfo("Please follow the instructions in your browser to complete authentication.");try{Se("gh auth login --web -h github.com",{stdio:"inherit"})}catch{throw new Error("GitHub CLI authentication failed")}}e.printInfo("Verifying GitHub Models access...");try{const t=Se("gh auth token",{encoding:"utf8"}).trim();t&&(await Ge([["GITHUB_MODELS.key",t]]),e.printSuccess("GitHub token stored for GitHub Models access"))}catch{e.printWarning("Could not extract token from GitHub CLI, but authentication completed")}e.printSuccess("GitHub authentication completed and GitHub Models access verified!"),e.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),e.printInfo("Available models: gpt-4o-mini, gpt-4o, meta-llama-3.1-405b-instruct, etc."),e.printInfo("Using GitHub Models API: https://models.github.ai")}catch(t){throw t}}const pe="prepare-commit-msg",Za=async()=>{const e=await Ye();if(e==="git")return`.git/hooks/${pe}`;if(e==="yadm"){const t=process.env.HOME||process.env.USERPROFILE;if(!t)throw new p("HOME environment variable not set. Cannot determine YADM hook path.");try{const{execa:s}=await Promise.resolve().then(function(){return Ni}),{stdout:r}=await s("yadm",["introspect","repo"]),i=r.trim();if(i)return E.join(i,"hooks",pe)}catch{}const o=E.join(t,".config/yadm/hooks"),n=E.join(t,".yadm/hooks");try{return await R.access(o),E.join(o,pe)}catch{return E.join(n,pe)}}throw e==="jujutsu"?new p("Hooks are not supported for Jujutsu repositories."):new p(`Hooks are not supported for ${e} repositories.`)},Xe=ls(new URL("cli.mjs",import.meta.url)),ec=process.argv[1].replace(/\\/g,"/").includes(`/hooks/${pe}`),Pn=process.platform==="win32",$n=`
|
|
239
|
-
#!/usr/bin/env node
|
|
240
|
-
import(${JSON.stringify(us(Xe))})
|
|
241
|
-
`.trim();var tc=j({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},e=>{(async()=>{const t=await Ft(),{installUninstall:o}=e._,n=await Za(),s=E.isAbsolute(n)?n:E.join(t,n),r=await _e(s);if(o==="install"){if(r){if(await R.realpath(s).catch(()=>{})===Xe){console.warn("The hook is already installed");return}throw new p(`A different ${pe} hook seems to be installed. Please remove it before installing aicommit2.`)}await R.mkdir(E.dirname(s),{recursive:!0}),Pn?await R.writeFile(s,$n):(await R.symlink(Xe,s,"file"),await R.chmod(s,493)),console.log(`${h.green("\u2714")} Hook installed`);return}if(o==="uninstall"){if(!r){console.warn("Hook is not installed");return}if(Pn){if(await R.readFile(s,"utf8")!==$n){console.warn("Hook is not installed");return}}else if(await R.realpath(s)!==Xe){console.warn("Hook is not installed");return}await R.rm(s),console.log(`${h.green("\u2714")} Hook uninstalled`);return}throw new p(`Invalid mode: ${o}`)})().catch(t=>{console.error(`${h.red("\u2716")} ${t.message}`),q(t),process.exit(1)})});const oc=ts(Hn),nc=e=>{const t=["B","KB","MB","GB"];if(e===0)return"0 B";const o=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,o)*100)/100+" "+t[o]},sc=e=>e.toLocaleDateString()+" "+e.toLocaleTimeString(),rc=async e=>{try{const t=await ao(G);if(t.length===0){console.log(`${h.yellow("No log files found.")}`);return}console.log(`${h.blue("Log files in")} ${G}:
|
|
242
|
-
`);const o=await Promise.all(t.map(async n=>{const s=Q.join(G,n),r=await ds(s);return{name:n,size:nc(r.size),modified:sc(r.mtime)}}));o.sort((n,s)=>new Date(s.modified).getTime()-new Date(n.modified).getTime()),o.forEach((n,s)=>{console.log(`${s===0?"\u{1F4C4}":" "} ${h.cyan(n.name)} ${h.gray(`(${n.size}, ${n.modified})`)}`)}),console.log(`
|
|
243
|
-
${h.green("Total:")} ${t.length} file${t.length!==1?"s":""}`)}catch(t){if(t.code==="ENOENT")console.log(`${h.yellow("Logs directory does not exist yet.")}`);else throw t}},ic=async e=>{try{await ao(G);const t=process.platform;let o;switch(t){case"darwin":o=`open "${G}"`;break;case"win32":o=`start "" "${G}"`;break;default:o=`xdg-open "${G}"`;break}await oc(o),console.log(`${h.green("\u2714")} Opened logs directory in file manager`)}catch(t){t.code==="ENOENT"?console.log(`${h.yellow("Logs directory does not exist yet.")}`):e.printError(`Failed to open logs directory: ${t.message}`)}},ac=async e=>{try{await ms(G,{recursive:!0,force:!0}),console.log(`${h.green("\u2714")} All log files removed!`)}catch(t){e.printError(`Failed to remove log files: ${t.message}`)}};var cc=j({name:"log",parameters:["<action>"],help:{description:"Manage log files generated by the application",examples:["aic2 log list # List all log files","aic2 log path # Show logs directory path","aic2 log open # Open logs directory","aic2 log removeAll # Remove all log files"]}},e=>{(async()=>{const{action:t}=e._,o=new H;switch(t){case"list":await rc();break;case"path":console.log(`${h.blue("Logs directory:")} ${G}`);break;case"open":await ic(o);break;case"removeAll":await ac(o);break;default:throw new p(`Invalid action: ${t}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(t=>{new H().printError(t.message),q(t),process.exit(1)})});const lc=process.argv.slice(2).filter(e=>!e.startsWith("--pre-commit")),[Qe,Sn]=lc;var uc=(e=!1)=>(async()=>{if(!Qe)throw new p('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Sn){console.log(`Skipping aicommit2 message generation for ${Sn} commit`);return}const t=await Gt();if(!t)return;const o=new H;o.printTitle();const n={};e&&(n.logLevel="verbose");const s=await J(n);if(s.systemPromptPath)try{await R.readFile(E.resolve(s.systemPromptPath),"utf-8")}catch{throw new p(`Error reading system prompt file: ${s.systemPromptPath}`)}const r=me(s,"commit");if(r.length===0)throw new p("Please set at least one API key via the `aicommit2 config set` command");const c=await ze(),u=new qe(s,t,c);let l;try{l=await it(u.createCommitMsgRequests$(r).pipe(no(v=>!v.isError),so(v=>v.value),at()))}finally{o.printAnalyzed()}const f=await R.readFile(Qe,"utf8")!=="",y=l.length>1;let g="";f&&(g=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
244
|
-
`,g+=`# ----------------------------------------
|
|
245
|
-
`,g+=`# How to use:
|
|
246
|
-
`,y?(g+=`# 1. Remove the "#" from your chosen message
|
|
247
|
-
`,g+=`# 2. Edit the message if needed
|
|
248
|
-
`,g+=`# 3. Save and close the editor
|
|
249
|
-
`):(g+=`# 1. The message below will be used
|
|
250
|
-
`,g+=`# 2. Edit the message if needed
|
|
251
|
-
`,g+=`# 3. Save and close the editor
|
|
252
|
-
`),g+=`# ----------------------------------------
|
|
253
|
-
`),y?(f&&(g+=`
|
|
254
|
-
# \u{1F4DD} Choose one of these messages:
|
|
255
|
-
`),g+=`
|
|
256
|
-
${l.map(v=>`# ${v}`).join(`
|
|
257
|
-
`)}`):(f&&(g+=`
|
|
258
|
-
# \u{1F4DD} Generated commit message:
|
|
259
|
-
`),g+=`
|
|
260
|
-
${l[0]}
|
|
261
|
-
`);const m=await R.readFile(Qe,"utf8"),A=g+`
|
|
262
|
-
`+m;await R.writeFile(Qe,A),o.printSavedCommitMessage()})().catch(t=>{new H().printError(t.message),q(t),process.exit(1)});const Wt=process.argv.slice(2),In=[];let Yt=!1;for(let e=0;e<Wt.length;e++){const t=Wt[e];if(Yt){Yt=!1;continue}if(t!=="--hook-mode"){if(t.startsWith("-")){const o=Wt[e+1];o&&!o.startsWith("-")&&(Yt=!0);continue}In.push(t)}}const[Ze,Rn]=In;var dc=(e,t,o,n,s,r,i)=>(async()=>{if(!Ze)throw new p('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Rn){console.log(`Skipping aicommit2 message generation for ${Rn} commit`);return}const c=await Gt();if(!c)return;const u=new H;u.printTitle();const l={locale:e?.toString(),generate:t?.toString(),type:n?.toString(),systemPrompt:s?.toString(),...r===!0&&{includeBody:"true"}};i&&(l.logLevel="verbose");const d=await J(l,o);if(d.systemPromptPath)try{await R.readFile(E.resolve(d.systemPromptPath),"utf-8")}catch{throw new p(`Error reading system prompt file: ${d.systemPromptPath}`)}const f=me(d,"commit");if(f.length===0)throw new p("Please set at least one API key via the `aicommit2 config set` command");const g=await ze(),m=new qe(d,c,g),A=u.displaySpinner("The AI is analyzing your changes");let v;try{v=await it(m.createCommitMsgRequests$(f).pipe(no(K=>!K.isError),so(K=>K.value),at()))}finally{A.stop(),A.clear(),u.printAnalyzed()}const C=await R.readFile(Ze,"utf8")!=="",k=v.length>1,I=await ba();let M="";C&&(M=`${I} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
263
|
-
`,M+=`${I} ----------------------------------------
|
|
264
|
-
`,M+=`${I} How to use:
|
|
265
|
-
`,k?(M+=`${I} 1. Remove the "${I}" from your chosen message
|
|
266
|
-
`,M+=`${I} 2. Edit the message if needed
|
|
267
|
-
`,M+=`${I} 3. Save and close the editor
|
|
268
|
-
`):(M+=`${I} 1. The message below will be used
|
|
269
|
-
`,M+=`${I} 2. Edit the message if needed
|
|
270
|
-
`,M+=`${I} 3. Save and close the editor
|
|
271
|
-
`),M+=`${I} ----------------------------------------
|
|
272
|
-
`),k?(C&&(M+=`
|
|
273
|
-
${I} \u{1F4DD} Choose one of these messages:
|
|
274
|
-
`),M+=`
|
|
275
|
-
${v.map(K=>`${I} ${K}`).join(`
|
|
276
|
-
`)}`):(C&&(M+=`
|
|
277
|
-
${I} \u{1F4DD} Generated commit message:
|
|
278
|
-
`),M+=`
|
|
279
|
-
${v[0]}
|
|
280
|
-
`);const X=await R.readFile(Ze,"utf8"),z=M+`
|
|
281
|
-
`+X;await R.writeFile(Ze,z),u.printSavedCommitMessage()})().catch(c=>{new H().printError(c.message),q(c),process.exit(1)});const W=new H,zt={OPENAI:{displayName:"OpenAI (ChatGPT)",authType:"api-key",envKeyHint:"OPENAI_API_KEY",defaultModel:"gpt-4o-mini"},ANTHROPIC:{displayName:"Anthropic (Claude)",authType:"api-key",envKeyHint:"ANTHROPIC_API_KEY",defaultModel:"claude-sonnet-4-20250514"},GEMINI:{displayName:"Google Gemini",authType:"api-key",envKeyHint:"GEMINI_API_KEY",defaultModel:"gemini-1.5-flash"},OLLAMA:{displayName:"Ollama (Local)",authType:"none",defaultModel:"llama3.2",setupNotes:"Ollama runs locally \u2014 no API key needed. Make sure Ollama is running."},GROQ:{displayName:"Groq",authType:"api-key",envKeyHint:"GROQ_API_KEY",defaultModel:"llama-3.3-70b-versatile"},DEEPSEEK:{displayName:"DeepSeek",authType:"api-key",envKeyHint:"DEEPSEEK_API_KEY",defaultModel:"deepseek-chat"},MISTRAL:{displayName:"Mistral AI",authType:"api-key",envKeyHint:"MISTRAL_API_KEY",defaultModel:"mistral-small-latest"},CODESTRAL:{displayName:"Codestral",authType:"api-key",envKeyHint:"CODESTRAL_API_KEY",defaultModel:"codestral-latest"},COHERE:{displayName:"Cohere",authType:"api-key",envKeyHint:"COHERE_API_KEY",defaultModel:"command-r-plus"},PERPLEXITY:{displayName:"Perplexity",authType:"api-key",envKeyHint:"PERPLEXITY_API_KEY",defaultModel:"sonar"},GITHUB_MODELS:{displayName:"GitHub Models",authType:"api-key",envKeyHint:"GITHUB_MODELS_API_KEY",defaultModel:"gpt-4o-mini",setupNotes:"Use a GitHub personal access token. Run `aic2 github-login` for browser-based auth."},HUGGINGFACE:{displayName:"Hugging Face",authType:"cookie",defaultModel:"CohereForAI/c4ai-command-r-plus",setupNotes:"Requires a Hugging Face cookie for authentication."},BEDROCK:{displayName:"AWS Bedrock",authType:"complex",setupNotes:"Requires AWS credentials. Configure via AWS CLI or set region + access keys."}},xn=["OPENAI","ANTHROPIC","GEMINI","OLLAMA","GROQ","DEEPSEEK"];var mc=j({name:"setup",parameters:[],help:{description:"Interactive setup wizard for configuring AI providers",examples:["aic2 setup"]}},e=>{(async()=>{for(W.printTitle(),console.log(),W.printInfo(`Welcome to aicommit2 setup! Let's configure your AI providers.
|
|
282
|
-
`);;){const t=await pc();if(!t)break;await fc(t.key,t.info);const{addMore:o}=await T.prompt([{type:"confirm",name:"addMore",message:"Would you like to configure another provider?",default:!1}]);if(!o)break;console.log()}W.printSuccess("Setup complete! Run `aic2` to generate commit messages.")})().catch(t=>{W.printError(t.message),q(t),process.exit(1)})});const pc=async()=>{const e=xn.map(r=>({name:zt[r].displayName,value:r})),o=ue.filter(r=>!xn.includes(r)).map(r=>({name:zt[r]?.displayName||r,value:r})),{provider:n}=await T.prompt([{type:"list",name:"provider",message:"Select an AI provider to configure:",choices:[new T.Separator("\u2500\u2500 Popular \u2500\u2500"),...e,new T.Separator("\u2500\u2500 Other \u2500\u2500"),...o,new T.Separator,{name:"Done (exit setup)",value:null}]}]);if(!n)return null;const s=zt[n]||{displayName:n,authType:"api-key"};return{key:n,info:s}},fc=async(e,t)=>{console.log(),t.setupNotes&&(W.printInfo(t.setupNotes),console.log());const o=[];switch(t.authType){case"api-key":{const{apiKey:r}=await T.prompt([{type:"password",name:"apiKey",message:`Enter your ${t.displayName} API key:`,mask:"*",validate:i=>i.trim()?!0:"API key is required"}]);o.push([`${e}.key`,r.trim()]);break}case"cookie":{const{cookie:r}=await T.prompt([{type:"password",name:"cookie",message:`Enter your ${t.displayName} cookie:`,mask:"*",validate:i=>i.trim()?!0:"Cookie is required"}]);o.push([`${e}.cookie`,r.trim()]);break}case"none":{const{host:r}=await T.prompt([{type:"input",name:"host",message:"Ollama host URL:",default:be}]);r&&r!==be&&o.push([`${e}.host`,r.trim()]);break}case"complex":{W.printInfo("AWS Bedrock requires region and credentials."),console.log();const{region:r}=await T.prompt([{type:"input",name:"region",message:"AWS Region (e.g., us-east-1):",validate:c=>c.trim()?!0:"Region is required"}]);o.push([`${e}.region`,r.trim()]);const{authMethod:i}=await T.prompt([{type:"list",name:"authMethod",message:"Authentication method:",choices:[{name:"AWS Profile (from ~/.aws/credentials)",value:"profile"},{name:"Access Key + Secret Key",value:"keys"},{name:"Environment variables (already set)",value:"env"}]}]);if(i==="profile"){const{profile:c}=await T.prompt([{type:"input",name:"profile",message:"AWS Profile name:",default:"default"}]);o.push([`${e}.profile`,c.trim()])}else if(i==="keys"){const{accessKeyId:c,secretAccessKey:u}=await T.prompt([{type:"password",name:"accessKeyId",message:"AWS Access Key ID:",mask:"*"},{type:"password",name:"secretAccessKey",message:"AWS Secret Access Key:",mask:"*"}]);o.push([`${e}.accessKeyId`,c.trim()]),o.push([`${e}.secretAccessKey`,u.trim()])}break}}const{model:n}=await T.prompt([{type:"input",name:"model",message:"Model to use (comma-separated for multiple):",default:t.defaultModel||"",validate:r=>r.trim()?!0:"At least one model is required"}]);o.push([`${e}.model`,n.trim()]);const s=W.displaySpinner("Saving configuration...");try{await Ge(o),W.stopSpinner(s),W.printSuccess(`${t.displayName} configured successfully!`),t.envKeyHint&&console.log(` Tip: You can also set the ${t.envKeyHint} environment variable instead.`)}catch(r){W.stopSpinner(s),W.printError(`Failed to save configuration: ${r.message}`)}},kn=20,Mn=e=>e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,Tn=e=>new Date(e).toLocaleDateString(),hc=e=>{const t=Math.round(e/100*kn),o=kn-t;return(e>=80?h.green:e>=50?h.yellow:h.red)("\u2588".repeat(t))+h.gray("\u2591".repeat(o))},gc=e=>{const t=e.totalRequests>0?Math.round(e.successCount/e.totalRequests*100):0,o=hc(t),n=e.provider.padEnd(14),s=`${t}%`.padStart(4),r=`${e.totalRequests}`.padStart(4),i=`${e.selectedCount}`.padStart(4),c=e.selectionRate>0?`(${e.selectionRate}%)`.padStart(7):"".padStart(7),u=Mn(e.avgResponseTimeMs).padStart(6);console.log(` ${h.bold(n)} ${s} ${o} ${r} ${h.cyan(i)} ${h.gray(c)} ${u}`)},yc=async e=>{if(!await fa()){console.log(h.yellow(`
|
|
283
|
-
No statistics recorded yet.`)),console.log(h.gray(`Statistics will be collected as you generate commit messages.
|
|
284
|
-
`));return}const o=await ma(e);if(o.totalRequests===0){console.log(h.yellow(`
|
|
285
|
-
No statistics in the last ${e} days.
|
|
286
|
-
`));return}if(console.log(""),console.log(h.bold("\u{1F4CA} aicommit2 Statistics")),console.log(h.gray(` Period: ${Tn(o.periodStart)} - ${Tn(o.periodEnd)}`)),console.log(""),console.log(h.bold("Overview:")),console.log(` Total requests: ${h.cyan(o.totalRequests)}`),console.log(` Success rate: ${h.green(o.successRate+"%")}`),console.log(` Avg response time: ${h.yellow(Mn(o.avgResponseTimeMs))}`),console.log(""),o.providerStats.length>0){console.log(h.bold("Provider Usage:")),console.log(h.gray(" Provider Rate Bar Cnt Selected Time"));for(const n of o.providerStats)gc(n);console.log("")}},wc=async()=>{await pa(),console.log(h.green(`
|
|
287
|
-
Statistics cleared successfully.
|
|
288
|
-
`))},bc=j({name:"stats",parameters:["[action]"],flags:{days:{type:Number,description:"Number of days to include in statistics (default: 30)",alias:"d",default:30}},help:{description:"View AI request statistics and performance metrics",examples:["aicommit2 stats Show statistics for last 30 days","aicommit2 stats -d 7 Show statistics for last 7 days","aicommit2 stats clear Clear all statistics"]}},e=>{(async()=>{const t=e._[0],{days:o}=e.flags;switch(t){case"clear":await wc();break;default:await yc(o);break}})().catch(t=>{console.error(h.red(t.message)),q(t),process.exit(1)})});class On{constructor(t="SubscriptionManager"){this.destroyed$=new ct,this.subscriptions=new rt,this.isDestroyed=!1,this.name=t}add(t,o){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`);const s=new rt;return s.unsubscribe(),s}const n=t.pipe(co(this.destroyed$),lo(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Observable finalized`)})).subscribe({next:o?.next,error:s=>{console.error(`${this.name}: Observable error:`,s),o?.error?.(s)},complete:o?.complete});return this.subscriptions.add(n),n}pipe(t){return this.isDestroyed?(console.warn(`${this.name}: Cannot pipe - manager is destroyed`),t):t.pipe(co(this.destroyed$),lo(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Piped observable finalized`)}))}addSubscription(t){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`),t.unsubscribe();return}this.subscriptions.add(t)}get destroySignal$(){return this.destroyed$.asObservable()}get isActive(){return!this.isDestroyed}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.subscriptions.unsubscribe(),this.destroyed$.next(),this.destroyed$.complete(),process.env.NODE_ENV==="development"&&console.log(`${this.name}: Destroyed successfully`))}}const Ec=new On("Global"),Pe=()=>{Ec.destroy()};process.on("exit",Pe),process.on("SIGINT",Pe),process.on("SIGTERM",Pe),process.on("uncaughtException",e=>{console.error("Uncaught exception:",e),Pe(),process.exit(1)}),process.on("unhandledRejection",(e,t)=>{console.error("Unhandled rejection at:",t,"reason:",e),Pe(),process.exit(1)});class vc{constructor(){this.destroyed$=new ct,this.consoleManager=new H,this.subscriptionManager=new On,this.currentCodeReviewSubscription=null,this.currentCodeReviewPromptManager=null,this.watcher=null,this.lastCommitHash=null,this.isProcessingCommit=!1,this.REPO_PATH=process.cwd(),this.GIT_PATH=E.join(this.REPO_PATH,".git"),this.HEAD_PATH=E.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=E.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=E.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers()}setupProcessHandlers(){const t=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t),process.on("SIGQUIT",t)}async watch(t,o,n,s,r,i){this.consoleManager.printTitle(),await Ft();const c=await Ye();if(c!=="git")throw new p(`Watch mode is only supported for Git repositories. Current VCS: ${c}`);const u=await this.initializeConfig(t,o,s,r,i);await this.initializeCurrentCommit();try{await this.watchGitEvents(u)}catch(l){return await this.handleWatchGitError(l),this.watch(t,o,n,s,r,i)}}async initializeConfig(t,o,n,s,r){const i={locale:t?.toString(),generate:o?.toString(),systemPrompt:n?.toString()};s&&(i.logLevel="verbose");const c=await J(i,r);return await vn(c),me(c,"watch").length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
289
|
-
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
290
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),c}async handleWatchGitError(t){this.consoleManager.printError(`An error occurred: ${t.message}`),q(t),await new Promise(o=>setTimeout(o,3e3)),this.consoleManager.printWarning("Restarting the commit monitoring process...")}async initializeCurrentCommit(){try{const t=await this.executeGitCommand("git rev-parse HEAD");this.lastCommitHash=t.trim(),this.consoleManager.printInfo(`Starting watch from commit: ${this.lastCommitHash.substring(0,8)}`)}catch{this.consoleManager.printWarning("No commits found in repository"),this.lastCommitHash=null}}async executeGitCommand(t){const o=Zn(Kn),{stdout:n}=await o(t,{cwd:this.REPO_PATH});return n}clearTerminal(){process.stdout.write("\x1Bc")}async handleCommitEvent(t,o){try{const n=await wa(o);if(!n){this.consoleManager.printWarning("No changes found in this commit");return}this.consoleManager.stopLoader(),this.consoleManager.printStagedFiles(n);const s=me(t,"watch");if(s.length===0){this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
291
|
-
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
292
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await this.performCodeReview(t,n,s)}catch(n){this.consoleManager.printError(`Error processing commit ${o}: ${n.message}`)}}async performCodeReview(t,o,n){this.cleanupPreviousCodeReview();const s=await ze(),r=new qe(t,o,s);this.currentCodeReviewPromptManager=new Ut(yn);try{const i=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader(),this.currentCodeReviewSubscription=this.subscribeToCodeReviewRequests(r,n),await i}finally{this.cleanupCodeReview()}}cleanupPreviousCodeReview(){this.cleanupCurrentReviewResources(),this.destroyed$.closed||(this.destroyed$.next(),this.destroyed$.complete()),this.destroyed$=new ct}initializeCodeReviewInquirer(){return this.currentCodeReviewPromptManager.initPrompt({...Ht,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${wn}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20})}subscribeToCodeReviewRequests(t,o){return this.subscriptionManager.add(t.createCodeReviewRequests$(o),{next:n=>{this.currentCodeReviewPromptManager?.refreshChoices(n)},error:n=>{console.error("Code review request error:",n),this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}})}cleanupCurrentReviewResources(){this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}cleanupCodeReview(){this.cleanupCurrentReviewResources(),this.clearTerminal(),this.consoleManager.showLoader("Watching for new Git commits...")}async isGitReset(t){if(!this.lastCommitHash)return!1;try{const o=await this.executeGitCommand(`git merge-base --is-ancestor ${t} ${this.lastCommitHash}`);return!0}catch{return!1}}cancelCurrentReview(){this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources(),this.destroyed$.next()}async watchGitEvents(t){this.consoleManager.showLoader("Watching for new Git commits...");const n=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,E.join(this.GIT_PATH,"logs","HEAD")].filter(s=>{try{return N.accessSync(s),!0}catch{return!1}});this.watcher=ps.watch(n,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}}),this.watcher.on("change",async s=>{await this.handleGitChange(t,s)}),this.watcher.on("add",async s=>{await this.handleGitChange(t,s)}),this.watcher.on("error",s=>{this.consoleManager.printError(`Watcher error: ${s.message}`),setTimeout(()=>this.watchGitEvents(t),1e3)})}async handleGitChange(t,o){try{const s=(await this.executeGitCommand("git rev-parse HEAD")).trim();if(s!==this.lastCommitHash){if(await this.isGitReset(s)){this.clearTerminal(),this.consoleManager.printInfo(`\u21A9\uFE0F Git reset detected: ${s.substring(0,8)}`),this.lastCommitHash=s,this.isProcessingCommit&&(this.cancelCurrentReview(),this.isProcessingCommit=!1);return}if(this.isProcessingCommit){this.consoleManager.printInfo(`
|
|
293
|
-
\u{1F504} New commit detected, cancelling current review...`);try{this.cancelCurrentReview(),await new Promise(i=>setTimeout(i,200))}catch(i){console.warn("Error during review cancellation:",i)}}this.isProcessingCommit=!0;try{this.consoleManager.stopLoader(),this.consoleManager.printInfo(`
|
|
294
|
-
\u{1F50D} New commit detected: ${s.substring(0,8)}`);const i=this.lastCommitHash;this.lastCommitHash=s,this.clearTerminal(),await this.handleCommitEvent(t,s)}catch(i){this.consoleManager.printError(`Error processing commit ${s.substring(0,8)}: ${i.message}`)}finally{this.isProcessingCommit=!1}}}catch(n){this.isProcessingCommit=!1,n.message?.includes("fatal: not a git repository")||this.consoleManager.printError(`Error checking for new commits: ${n.message}`)}}destroy(){this.isProcessingCommit=!1,this.lastCommitHash=null;try{this.subscriptionManager.destroy(),this.cleanupCurrentReviewResources(),this.watcher&&(this.watcher.close(),this.watcher=null),this.consoleManager.stopLoader(),this.destroyed$.next(),this.destroyed$.complete()}catch(t){console.warn("Error during WatchGitManager destruction:",t)}}}const Cc=new vc,Ac=async(e,t,o,n,s,r)=>Cc.watch(e,t,o,n,s,r),Dn={"Message Options":["locale","generate","type","prompt","include-body"],Behavior:["all","confirm","auto-select","edit","clipboard","dry-run","output"],"VCS Selection":["git","yadm","jj","jj-auto-new"],"Hook Integration":["hook-mode","pre-commit","watch-commit"],Formatting:["disable-lowercase","exclude"],Debug:["verbose"]},Pc=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.data?.name!==void 0&&typeof t.data.name=="string"},$c=e=>Pc(e)?e.data.name:null,Sc=e=>{for(const[t,o]of Object.entries(Dn))if(o.includes(e))return t;return null},Ic=e=>e.type==="section"&&e.data?.title==="Flags:",Rc=e=>e.data?.body?.data?.tableData!==void 0,xc=e=>{const t=new Map;for(const o of Object.keys(Dn))t.set(o,[]);if(t.set("Other",[]),!Array.isArray(e))return t;for(const o of e){if(!Array.isArray(o))continue;const n=$c(o[0]),s=n&&Sc(n)||"Other";t.get(s)?.push(o)}return t},kc=(e,t,o,n,s)=>({type:"section",data:{title:s?`Flags - ${e}:`:` ${e}:`,body:{type:"table",data:{tableData:t,tableOptions:o,tableBreakpoints:n}}}}),Mc=(e,t)=>{const o=[];for(const n of e){if(!Ic(n)||!Rc(n)){o.push(n);continue}const{tableData:s,tableOptions:r,tableBreakpoints:i}=n.data.body.data;[...xc(s).entries()].filter(([,l])=>l.length>0).forEach(([l,d],f)=>{o.push(kc(l,d,r,i,f===0))})}return t.render(o)},et=process.argv.slice(2),{version:Ln,description:Tc}=Rs;Fn({name:"aicommit2",version:Ln,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1},"disable-lowercase":{type:Boolean,description:"Disable automatic lowercase conversion of commit messages",default:!1},verbose:{type:Boolean,description:"Enable verbose logging for this run",alias:"v",default:!1},git:{type:Boolean,description:"Force use Git (overrides auto-detection)",default:!1},yadm:{type:Boolean,description:"Force use YADM (overrides auto-detection)",default:!1},jj:{type:Boolean,description:"Force use Jujutsu (overrides auto-detection)",default:!1},"jj-auto-new":{type:Boolean,description:"Run jj new after jj describe (default: false, only describe)",default:!1},"dry-run":{type:Boolean,description:"Generate commit message without committing (output only)",alias:"d",default:!1},output:{type:String,description:"Output format for non-interactive mode (json). For LazyGit integration",alias:"o"}},commands:[Fa,Va,Ja,tc,cc,mc,bc],help:{description:Tc,render:Mc},ignoreArgv:e=>e==="unknown-flag"||e==="argument"},async e=>{const t={};e.flags.verbose&&(t.logLevel="verbose");const o=await J(t,et);if(await Aa(o),hn.info(`aicommit2 version: ${Ln}`),e.flags["pre-commit"]){uc(e.flags.verbose);return}if(e.flags["hook-mode"]||ec){dc(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.type,e.flags.prompt,e.flags["include-body"],e.flags.verbose);return}if(e.flags["watch-commit"]){Ac(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.prompt,e.flags.verbose,et);return}Da(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.confirm,e.flags.clipboard,e.flags.prompt,e.flags["include-body"],e.flags["auto-select"],e.flags.edit,e.flags["disable-lowercase"],e.flags.verbose,e.flags["dry-run"],e.flags["jj-auto-new"],e.flags.output,et)},et);export{G as A,bn as D,S as E,An as H,p as K,U as P,Ta as a,Ma as b,_i as c,Sa as d,Ia as e,Bi as f,qi as g,$a as h,Y as i,ne as j,Oa as k,hn as l,Mt as m,Fi as n,be as o,gn as p,Wi as s};
|