aicommit2 2.2.17 → 2.2.19

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.
Files changed (2) hide show
  1. package/dist/cli.mjs +13 -13
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import{command as Y,cli as Ho}from"cleye";import{createRequire as Uo}from"module";import{Buffer as qo}from"node:buffer";import te from"node:path";import Vt,{ChildProcess as zo}from"node:child_process";import U from"node:process";import Ko from"child_process";import P from"path";import _ from"fs";import{fileURLToPath as Xt}from"node:url";import Wo,{constants as Jt}from"node:os";import Qt from"assert";import Zt from"events";import{createWriteStream as Yo,createReadStream as Vo}from"node:fs";import Xo from"buffer";import ot from"stream";import er from"util";import{debuglog as Jo}from"node:util";import Me from"inquirer";import st from"ora";import w from"chalk";import{of as de,concatMap as M,from as $,map as A,catchError as S,mergeMap as ke,BehaviorSubject as tr,ReplaySubject as Qo,lastValueFrom as rr,filter as or,toArray as sr,Subject as nr}from"rxjs";import Zo from"@anthropic-ai/sdk";import{fromPromise as k}from"rxjs/internal/observable/innerFrom";import q from"winston";import"winston-daily-rotate-file";import x from"fs/promises";import Ie from"os";import{xxh64 as es}from"@pacote/xxhash";import ts from"axios";import{CohereClient as rs}from"cohere-ai";import ir from"openai";import{GoogleGenerativeAI as os,HarmCategory as Re,HarmBlockThreshold as Oe}from"@google/generative-ai";import ss from"groq-sdk";import{Ollama as ns}from"ollama";import{fetch as is,Agent as as}from"undici";import cs from"http";import ls from"https";import ms from"net";import us from"tls";import ps,{fileURLToPath as fs,pathToFileURL as ds}from"url";import ar from"tty";import Le from"readline";import hs from"figlet";import gs from"inquirer-reactive-list-prompt";import{rm as ys}from"node:fs/promises";import ws from"chokidar";import{takeUntil as vs}from"rxjs/operators";var bs="aicommit2",cr="2.2.17",Cs="A Reactive CLI that generates git commit messages with various AI",Ps=["cli","ai","git","commit","git-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"],$s="MIT",Es="tak-bro/aicommit2",xs="Hyungtak Jin(@tak-bro)",As="module",Ss=["dist"],Ms={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},ks={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Is={"@anthropic-ai/sdk":"^0.39.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.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^4.102.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"},Rs={"@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"},Os={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ls={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{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"]},Ts={name:bs,version:cr,description:Cs,keywords:Ps,license:$s,repository:Es,author:xs,type:As,files:Ss,bin:Ms,scripts:ks,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Is,devDependencies:Rs,eslintConfig:Os,release:Ls},Ns=Uo(import.meta.url),O=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function re(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oe={exports:{}},nt,lr;function _s(){if(lr)return nt;lr=1,nt=r,r.sync=n;var t=_;function e(s,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&s.substr(-u.length).toLowerCase()===u)return!0}return!1}function o(s,i,c){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,c)}function r(s,i,c){t.stat(s,function(l,u){c(l,l?!1:o(u,s,i))})}function n(s,i){return o(t.statSync(s),s,i)}return nt}var it,mr;function Fs(){if(mr)return it;mr=1,it=e,e.sync=o;var t=_;function e(s,i,c){t.stat(s,function(l,u){c(l,l?!1:r(u,i))})}function o(s,i){return r(t.statSync(s),i)}function r(s,i){return s.isFile()&&n(s,i)}function n(s,i){var c=s.mode,l=s.uid,u=s.gid,p=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),m=parseInt("100",8),d=parseInt("010",8),h=parseInt("001",8),g=m|d,y=c&h||c&d&&u===a||c&m&&l===p||c&g&&p===0;return y}return it}var Te;process.platform==="win32"||O.TESTING_WINDOWS?Te=_s():Te=Fs();var Ds=at;at.sync=Gs;function at(t,e,o){if(typeof e=="function"&&(o=e,e={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(r,n){at(t,e||{},function(s,i){s?n(s):r(i)})})}Te(t,e||{},function(r,n){r&&(r.code==="EACCES"||e&&e.ignoreErrors)&&(r=null,n=!1),o(r,n)})}function Gs(t,e){try{return Te.sync(t,e||{})}catch(o){if(e&&e.ignoreErrors||o.code==="EACCES")return!1;throw o}}const se=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",ur=P,js=se?";":":",pr=Ds,fr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),dr=(t,e)=>{const o=e.colon||js,r=t.match(/\//)||se&&t.match(/\\/)?[""]:[...se?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(o)],n=se?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=se?n.split(o):[""];return se&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:r,pathExt:s,pathExtExe:n}},hr=(t,e,o)=>{typeof e=="function"&&(o=e,e={}),e||(e={});const{pathEnv:r,pathExt:n,pathExtExe:s}=dr(t,e),i=[],c=u=>new Promise((p,a)=>{if(u===r.length)return e.all&&i.length?p(i):a(fr(t));const m=r[u],d=/^".*"$/.test(m)?m.slice(1,-1):m,h=ur.join(d,t),g=!d&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;p(l(g,u,0))}),l=(u,p,a)=>new Promise((m,d)=>{if(a===n.length)return m(c(p+1));const h=n[a];pr(u+h,{pathExt:s},(g,y)=>{if(!g&&y)if(e.all)i.push(u+h);else return m(u+h);return m(l(u,p,a+1))})});return o?c(0).then(u=>o(null,u),o):c(0)},Bs=(t,e)=>{e=e||{};const{pathEnv:o,pathExt:r,pathExtExe:n}=dr(t,e),s=[];for(let i=0;i<o.length;i++){const c=o[i],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=ur.join(l,t),p=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let a=0;a<r.length;a++){const m=p+r[a];try{if(pr.sync(m,{pathExt:n}))if(e.all)s.push(m);else return m}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw fr(t)};var Hs=hr;hr.sync=Bs;var ct={exports:{}};const gr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"};ct.exports=gr,ct.exports.default=gr;var Us=ct.exports;const yr=P,qs=Hs,zs=Us;function wr(t,e){const o=t.options.env||process.env,r=process.cwd(),n=t.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=qs.sync(t.command,{path:o[zs({env:o})],pathExt:e?yr.delimiter:void 0})}catch{}finally{s&&process.chdir(r)}return i&&(i=yr.resolve(n?t.options.cwd:"",i)),i}function Ks(t){return wr(t)||wr(t,!0)}var Ws=Ks,lt={};const mt=/([()\][%!^"`<>&|;, *?])/g;function Ys(t){return t=t.replace(mt,"^$1"),t}function Vs(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(mt,"^$1"),e&&(t=t.replace(mt,"^$1")),t}lt.command=Ys,lt.argument=Vs;var Xs=/^#!(.*)/;const Js=Xs;var Qs=(t="")=>{const e=t.match(Js);if(!e)return null;const[o,r]=e[0].replace(/#! ?/,"").split(" "),n=o.split("/").pop();return n==="env"?r:r?`${n} ${r}`:n};const ut=_,Zs=Qs;function en(t){const o=Buffer.alloc(150);let r;try{r=ut.openSync(t,"r"),ut.readSync(r,o,0,150,0),ut.closeSync(r)}catch{}return Zs(o.toString())}var tn=en;const rn=P,vr=Ws,br=lt,on=tn,sn=process.platform==="win32",nn=/\.(?:com|exe)$/i,an=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function cn(t){t.file=vr(t);const e=t.file&&on(t.file);return e?(t.args.unshift(t.file),t.command=e,vr(t)):t.file}function ln(t){if(!sn)return t;const e=cn(t),o=!nn.test(e);if(t.options.forceShell||o){const r=an.test(e);t.command=rn.normalize(t.command),t.command=br.command(t.command),t.args=t.args.map(s=>br.argument(s,r));const n=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${n}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function mn(t,e,o){e&&!Array.isArray(e)&&(o=e,e=null),e=e?e.slice(0):[],o=Object.assign({},o);const r={command:t,args:e,options:o,file:void 0,original:{command:t,args:e}};return o.shell?r:ln(r)}var un=mn;const pt=process.platform==="win32";function ft(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function pn(t,e){if(!pt)return;const o=t.emit;t.emit=function(r,n){if(r==="exit"){const s=Cr(n,e);if(s)return o.call(t,"error",s)}return o.apply(t,arguments)}}function Cr(t,e){return pt&&t===1&&!e.file?ft(e.original,"spawn"):null}function fn(t,e){return pt&&t===1&&!e.file?ft(e.original,"spawnSync"):null}var dn={hookChildProcess:pn,verifyENOENT:Cr,verifyENOENTSync:fn,notFoundError:ft};const Pr=Ko,dt=un,ht=dn;function $r(t,e,o){const r=dt(t,e,o),n=Pr.spawn(r.command,r.args,r.options);return ht.hookChildProcess(n,r),n}function hn(t,e,o){const r=dt(t,e,o),n=Pr.spawnSync(r.command,r.args,r.options);return n.error=n.error||ht.verifyENOENTSync(n.status,r),n}oe.exports=$r,oe.exports.spawn=$r,oe.exports.sync=hn,oe.exports._parse=dt,oe.exports._enoent=ht;var gn=oe.exports,yn=re(gn);function wn(t){const e=typeof t=="string"?`
2
+ import{command as Y,cli as Ho}from"cleye";import{createRequire as Uo}from"module";import{Buffer as qo}from"node:buffer";import te from"node:path";import Vt,{ChildProcess as zo}from"node:child_process";import U from"node:process";import Ko from"child_process";import P from"path";import _ from"fs";import{fileURLToPath as Xt}from"node:url";import Wo,{constants as Jt}from"node:os";import Qt from"assert";import Zt from"events";import{createWriteStream as Yo,createReadStream as Vo}from"node:fs";import Xo from"buffer";import ot from"stream";import er from"util";import{debuglog as Jo}from"node:util";import ke from"inquirer";import st from"ora";import w from"chalk";import{of as de,concatMap as k,from as $,map as A,catchError as S,mergeMap as Me,BehaviorSubject as tr,ReplaySubject as Qo,lastValueFrom as rr,filter as or,toArray as sr,Subject as nr}from"rxjs";import Zo from"@anthropic-ai/sdk";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import q from"winston";import"winston-daily-rotate-file";import x from"fs/promises";import Ie from"os";import{xxh64 as es}from"@pacote/xxhash";import ts from"axios";import{CohereClient as rs}from"cohere-ai";import ir from"openai";import{GoogleGenerativeAI as os,HarmCategory as Re,HarmBlockThreshold as Oe}from"@google/generative-ai";import ss from"groq-sdk";import{Ollama as ns}from"ollama";import{fetch as is,Agent as as}from"undici";import cs from"http";import ls from"https";import ms from"net";import us from"tls";import ps,{fileURLToPath as fs,pathToFileURL as ds}from"url";import ar from"tty";import Le from"readline";import hs from"figlet";import gs from"inquirer-reactive-list-prompt";import{rm as ys}from"node:fs/promises";import ws from"chokidar";import{takeUntil as vs}from"rxjs/operators";var bs="aicommit2",cr="2.2.19",Cs="A Reactive CLI that generates git commit messages with various AI",Ps=["cli","ai","git","commit","git-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"],$s="MIT",Es="tak-bro/aicommit2",xs="Hyungtak Jin(@tak-bro)",As="module",Ss=["dist"],ks={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Ms={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Is={"@anthropic-ai/sdk":"^0.39.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.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^4.102.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"},Rs={"@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"},Os={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ls={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{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"]},Ts={name:bs,version:cr,description:Cs,keywords:Ps,license:$s,repository:Es,author:xs,type:As,files:Ss,bin:ks,scripts:Ms,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Is,devDependencies:Rs,eslintConfig:Os,release:Ls},Ns=Uo(import.meta.url),O=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function re(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oe={exports:{}},nt,lr;function _s(){if(lr)return nt;lr=1,nt=r,r.sync=n;var t=_;function e(s,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&s.substr(-u.length).toLowerCase()===u)return!0}return!1}function o(s,i,c){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,c)}function r(s,i,c){t.stat(s,function(l,u){c(l,l?!1:o(u,s,i))})}function n(s,i){return o(t.statSync(s),s,i)}return nt}var it,mr;function Fs(){if(mr)return it;mr=1,it=e,e.sync=o;var t=_;function e(s,i,c){t.stat(s,function(l,u){c(l,l?!1:r(u,i))})}function o(s,i){return r(t.statSync(s),i)}function r(s,i){return s.isFile()&&n(s,i)}function n(s,i){var c=s.mode,l=s.uid,u=s.gid,p=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),m=parseInt("100",8),d=parseInt("010",8),h=parseInt("001",8),g=m|d,y=c&h||c&d&&u===a||c&m&&l===p||c&g&&p===0;return y}return it}var Te;process.platform==="win32"||O.TESTING_WINDOWS?Te=_s():Te=Fs();var Ds=at;at.sync=Gs;function at(t,e,o){if(typeof e=="function"&&(o=e,e={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(r,n){at(t,e||{},function(s,i){s?n(s):r(i)})})}Te(t,e||{},function(r,n){r&&(r.code==="EACCES"||e&&e.ignoreErrors)&&(r=null,n=!1),o(r,n)})}function Gs(t,e){try{return Te.sync(t,e||{})}catch(o){if(e&&e.ignoreErrors||o.code==="EACCES")return!1;throw o}}const se=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",ur=P,js=se?";":":",pr=Ds,fr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),dr=(t,e)=>{const o=e.colon||js,r=t.match(/\//)||se&&t.match(/\\/)?[""]:[...se?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(o)],n=se?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=se?n.split(o):[""];return se&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:r,pathExt:s,pathExtExe:n}},hr=(t,e,o)=>{typeof e=="function"&&(o=e,e={}),e||(e={});const{pathEnv:r,pathExt:n,pathExtExe:s}=dr(t,e),i=[],c=u=>new Promise((p,a)=>{if(u===r.length)return e.all&&i.length?p(i):a(fr(t));const m=r[u],d=/^".*"$/.test(m)?m.slice(1,-1):m,h=ur.join(d,t),g=!d&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;p(l(g,u,0))}),l=(u,p,a)=>new Promise((m,d)=>{if(a===n.length)return m(c(p+1));const h=n[a];pr(u+h,{pathExt:s},(g,y)=>{if(!g&&y)if(e.all)i.push(u+h);else return m(u+h);return m(l(u,p,a+1))})});return o?c(0).then(u=>o(null,u),o):c(0)},Bs=(t,e)=>{e=e||{};const{pathEnv:o,pathExt:r,pathExtExe:n}=dr(t,e),s=[];for(let i=0;i<o.length;i++){const c=o[i],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=ur.join(l,t),p=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let a=0;a<r.length;a++){const m=p+r[a];try{if(pr.sync(m,{pathExt:n}))if(e.all)s.push(m);else return m}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw fr(t)};var Hs=hr;hr.sync=Bs;var ct={exports:{}};const gr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"};ct.exports=gr,ct.exports.default=gr;var Us=ct.exports;const yr=P,qs=Hs,zs=Us;function wr(t,e){const o=t.options.env||process.env,r=process.cwd(),n=t.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=qs.sync(t.command,{path:o[zs({env:o})],pathExt:e?yr.delimiter:void 0})}catch{}finally{s&&process.chdir(r)}return i&&(i=yr.resolve(n?t.options.cwd:"",i)),i}function Ks(t){return wr(t)||wr(t,!0)}var Ws=Ks,lt={};const mt=/([()\][%!^"`<>&|;, *?])/g;function Ys(t){return t=t.replace(mt,"^$1"),t}function Vs(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(mt,"^$1"),e&&(t=t.replace(mt,"^$1")),t}lt.command=Ys,lt.argument=Vs;var Xs=/^#!(.*)/;const Js=Xs;var Qs=(t="")=>{const e=t.match(Js);if(!e)return null;const[o,r]=e[0].replace(/#! ?/,"").split(" "),n=o.split("/").pop();return n==="env"?r:r?`${n} ${r}`:n};const ut=_,Zs=Qs;function en(t){const o=Buffer.alloc(150);let r;try{r=ut.openSync(t,"r"),ut.readSync(r,o,0,150,0),ut.closeSync(r)}catch{}return Zs(o.toString())}var tn=en;const rn=P,vr=Ws,br=lt,on=tn,sn=process.platform==="win32",nn=/\.(?:com|exe)$/i,an=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function cn(t){t.file=vr(t);const e=t.file&&on(t.file);return e?(t.args.unshift(t.file),t.command=e,vr(t)):t.file}function ln(t){if(!sn)return t;const e=cn(t),o=!nn.test(e);if(t.options.forceShell||o){const r=an.test(e);t.command=rn.normalize(t.command),t.command=br.command(t.command),t.args=t.args.map(s=>br.argument(s,r));const n=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${n}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function mn(t,e,o){e&&!Array.isArray(e)&&(o=e,e=null),e=e?e.slice(0):[],o=Object.assign({},o);const r={command:t,args:e,options:o,file:void 0,original:{command:t,args:e}};return o.shell?r:ln(r)}var un=mn;const pt=process.platform==="win32";function ft(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function pn(t,e){if(!pt)return;const o=t.emit;t.emit=function(r,n){if(r==="exit"){const s=Cr(n,e);if(s)return o.call(t,"error",s)}return o.apply(t,arguments)}}function Cr(t,e){return pt&&t===1&&!e.file?ft(e.original,"spawn"):null}function fn(t,e){return pt&&t===1&&!e.file?ft(e.original,"spawnSync"):null}var dn={hookChildProcess:pn,verifyENOENT:Cr,verifyENOENTSync:fn,notFoundError:ft};const Pr=Ko,dt=un,ht=dn;function $r(t,e,o){const r=dt(t,e,o),n=Pr.spawn(r.command,r.args,r.options);return ht.hookChildProcess(n,r),n}function hn(t,e,o){const r=dt(t,e,o),n=Pr.spawnSync(r.command,r.args,r.options);return n.error=n.error||ht.verifyENOENTSync(n.status,r),n}oe.exports=$r,oe.exports.spawn=$r,oe.exports.sync=hn,oe.exports._parse=dt,oe.exports._enoent=ht;var gn=oe.exports,yn=re(gn);function wn(t){const e=typeof t=="string"?`
3
3
  `:`
4
4
  `.charCodeAt(),o=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===o&&(t=t.slice(0,-1)),t}function Er(t={}){const{env:e=process.env,platform:o=process.platform}=t;return o!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}const vn=({cwd:t=U.cwd(),path:e=U.env[Er()],preferLocal:o=!0,execPath:r=U.execPath,addExecPath:n=!0}={})=>{const s=t instanceof URL?Xt(t):t,i=te.resolve(s),c=[];return o&&bn(c,i),n&&Cn(c,r,i),[...c,e].join(te.delimiter)},bn=(t,e)=>{let o;for(;o!==e;)t.push(te.join(e,"node_modules/.bin")),o=e,e=te.resolve(e,"..")},Cn=(t,e,o)=>{const r=e instanceof URL?Xt(e):e;t.push(te.resolve(o,r,".."))},Pn=({env:t=U.env,...e}={})=>{t={...t};const o=Er({env:t});return e.path=t[o],t[o]=vn(e),t},$n=(t,e,o,r)=>{if(o==="length"||o==="prototype"||o==="arguments"||o==="caller")return;const n=Object.getOwnPropertyDescriptor(t,o),s=Object.getOwnPropertyDescriptor(e,o);!En(n,s)&&r||Object.defineProperty(t,o,s)},En=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},xn=(t,e)=>{const o=Object.getPrototypeOf(e);o!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,o)},An=(t,e)=>`/* Wrapped ${t}*/
5
- ${e}`,Sn=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Mn=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),kn=(t,e,o)=>{const r=o===""?"":`with ${o.trim()}() `,n=An.bind(null,r,e.toString());Object.defineProperty(n,"name",Mn),Object.defineProperty(t,"toString",{...Sn,value:n})};function In(t,e,{ignoreNonConfigurable:o=!1}={}){const{name:r}=t;for(const n of Reflect.ownKeys(e))$n(t,e,n,o);return xn(t,e),kn(t,e,r),t}const Ne=new WeakMap,xr=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let o,r=0;const n=t.displayName||t.name||"<anonymous>",s=function(...i){if(Ne.set(s,++r),r===1)o=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return o};return In(s,t),Ne.set(s,r),s};xr.callCount=t=>{if(!Ne.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Ne.get(t)};const Rn=()=>{const t=Sr-Ar+1;return Array.from({length:t},On)},On=(t,e)=>({name:`SIGRT${e+1}`,number:Ar+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Ar=34,Sr=64,Ln=[{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"}],Mr=()=>{const t=Rn();return[...Ln,...t].map(Tn)},Tn=({name:t,number:e,description:o,action:r,forced:n=!1,standard:s})=>{const{signals:{[t]:i}}=Jt,c=i!==void 0;return{name:t,number:c?i:e,description:o,supported:c,action:r,forced:n,standard:s}},Nn=()=>{const t=Mr();return Object.fromEntries(t.map(_n))},_n=({name:t,number:e,description:o,supported:r,action:n,forced:s,standard:i})=>[t,{name:t,number:e,description:o,supported:r,action:n,forced:s,standard:i}],Fn=Nn(),Dn=()=>{const t=Mr(),e=Sr+1,o=Array.from({length:e},(r,n)=>Gn(n,t));return Object.assign({},...o)},Gn=(t,e)=>{const o=jn(t,e);if(o===void 0)return{};const{name:r,description:n,supported:s,action:i,forced:c,standard:l}=o;return{[t]:{name:r,number:t,description:n,supported:s,action:i,forced:c,standard:l}}},jn=(t,e)=>{const o=e.find(({name:r})=>Jt.signals[r]===t);return o!==void 0?o:e.find(r=>r.number===t)};Dn();const Bn=({timedOut:t,timeout:e,errorCode:o,signal:r,signalDescription:n,exitCode:s,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":o!==void 0?`failed with ${o}`:r!==void 0?`was killed with ${r} (${n})`:s!==void 0?`failed with exit code ${s}`:"failed",kr=({stdout:t,stderr:e,all:o,error:r,signal:n,exitCode:s,command:i,escapedCommand:c,timedOut:l,isCanceled:u,killed:p,parsed:{options:{timeout:a,cwd:m=U.cwd()}}})=>{s=s===null?void 0:s,n=n===null?void 0:n;const d=n===void 0?void 0:Fn[n].description,h=r&&r.code,y=`Command ${Bn({timedOut:l,timeout:a,errorCode:h,signal:n,signalDescription:d,exitCode:s,isCanceled:u})}: ${i}`,v=Object.prototype.toString.call(r)==="[object Error]",E=v?`${y}
5
+ ${e}`,Sn=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),kn=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Mn=(t,e,o)=>{const r=o===""?"":`with ${o.trim()}() `,n=An.bind(null,r,e.toString());Object.defineProperty(n,"name",kn),Object.defineProperty(t,"toString",{...Sn,value:n})};function In(t,e,{ignoreNonConfigurable:o=!1}={}){const{name:r}=t;for(const n of Reflect.ownKeys(e))$n(t,e,n,o);return xn(t,e),Mn(t,e,r),t}const Ne=new WeakMap,xr=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let o,r=0;const n=t.displayName||t.name||"<anonymous>",s=function(...i){if(Ne.set(s,++r),r===1)o=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return o};return In(s,t),Ne.set(s,r),s};xr.callCount=t=>{if(!Ne.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Ne.get(t)};const Rn=()=>{const t=Sr-Ar+1;return Array.from({length:t},On)},On=(t,e)=>({name:`SIGRT${e+1}`,number:Ar+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Ar=34,Sr=64,Ln=[{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"}],kr=()=>{const t=Rn();return[...Ln,...t].map(Tn)},Tn=({name:t,number:e,description:o,action:r,forced:n=!1,standard:s})=>{const{signals:{[t]:i}}=Jt,c=i!==void 0;return{name:t,number:c?i:e,description:o,supported:c,action:r,forced:n,standard:s}},Nn=()=>{const t=kr();return Object.fromEntries(t.map(_n))},_n=({name:t,number:e,description:o,supported:r,action:n,forced:s,standard:i})=>[t,{name:t,number:e,description:o,supported:r,action:n,forced:s,standard:i}],Fn=Nn(),Dn=()=>{const t=kr(),e=Sr+1,o=Array.from({length:e},(r,n)=>Gn(n,t));return Object.assign({},...o)},Gn=(t,e)=>{const o=jn(t,e);if(o===void 0)return{};const{name:r,description:n,supported:s,action:i,forced:c,standard:l}=o;return{[t]:{name:r,number:t,description:n,supported:s,action:i,forced:c,standard:l}}},jn=(t,e)=>{const o=e.find(({name:r})=>Jt.signals[r]===t);return o!==void 0?o:e.find(r=>r.number===t)};Dn();const Bn=({timedOut:t,timeout:e,errorCode:o,signal:r,signalDescription:n,exitCode:s,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":o!==void 0?`failed with ${o}`:r!==void 0?`was killed with ${r} (${n})`:s!==void 0?`failed with exit code ${s}`:"failed",Mr=({stdout:t,stderr:e,all:o,error:r,signal:n,exitCode:s,command:i,escapedCommand:c,timedOut:l,isCanceled:u,killed:p,parsed:{options:{timeout:a,cwd:m=U.cwd()}}})=>{s=s===null?void 0:s,n=n===null?void 0:n;const d=n===void 0?void 0:Fn[n].description,h=r&&r.code,y=`Command ${Bn({timedOut:l,timeout:a,errorCode:h,signal:n,signalDescription:d,exitCode:s,isCanceled:u})}: ${i}`,v=Object.prototype.toString.call(r)==="[object Error]",E=v?`${y}
6
6
  ${r.message}`:y,N=[E,e,t].filter(Boolean).join(`
7
- `);return v?(r.originalMessage=r.message,r.message=N):r=new Error(N),r.shortMessage=E,r.command=i,r.escapedCommand=c,r.exitCode=s,r.signal=n,r.signalDescription=d,r.stdout=t,r.stderr=e,r.cwd=m,o!==void 0&&(r.all=o),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=u,r.killed=p&&!l,r},_e=["stdin","stdout","stderr"],Hn=t=>_e.some(e=>t[e]!==void 0),Un=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return _e.map(r=>t[r]);if(Hn(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${_e.map(r=>`\`${r}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const o=Math.max(e.length,_e.length);return Array.from({length:o},(r,n)=>e[n])};var ne={exports:{}},Fe={exports:{}};Fe.exports;var Ir;function qn(){return Ir||(Ir=1,function(t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Fe)),Fe.exports}var I=O.process;const Z=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};if(!Z(I))ne.exports=function(){return function(){}};else{var zn=Qt,he=qn(),Kn=/^win/i.test(I.platform),De=Zt;typeof De!="function"&&(De=De.EventEmitter);var L;I.__signal_exit_emitter__?L=I.__signal_exit_emitter__:(L=I.__signal_exit_emitter__=new De,L.count=0,L.emitted={}),L.infinite||(L.setMaxListeners(1/0),L.infinite=!0),ne.exports=function(t,e){if(!Z(O.process))return function(){};zn.equal(typeof t,"function","a callback must be provided for exit handler"),ge===!1&&Rr();var o="exit";e&&e.alwaysLast&&(o="afterexit");var r=function(){L.removeListener(o,t),L.listeners("exit").length===0&&L.listeners("afterexit").length===0&&gt()};return L.on(o,t),r};var gt=function(){!ge||!Z(O.process)||(ge=!1,he.forEach(function(e){try{I.removeListener(e,yt[e])}catch{}}),I.emit=wt,I.reallyExit=Or,L.count-=1)};ne.exports.unload=gt;var ie=function(e,o,r){L.emitted[e]||(L.emitted[e]=!0,L.emit(e,o,r))},yt={};he.forEach(function(t){yt[t]=function(){if(Z(O.process)){var o=I.listeners(t);o.length===L.count&&(gt(),ie("exit",null,t),ie("afterexit",null,t),Kn&&t==="SIGHUP"&&(t="SIGINT"),I.kill(I.pid,t))}}}),ne.exports.signals=function(){return he};var ge=!1,Rr=function(){ge||!Z(O.process)||(ge=!0,L.count+=1,he=he.filter(function(e){try{return I.on(e,yt[e]),!0}catch{return!1}}),I.emit=Yn,I.reallyExit=Wn)};ne.exports.load=Rr;var Or=I.reallyExit,Wn=function(e){Z(O.process)&&(I.exitCode=e||0,ie("exit",I.exitCode,null),ie("afterexit",I.exitCode,null),Or.call(I,I.exitCode))},wt=I.emit,Yn=function(e,o){if(e==="exit"&&Z(O.process)){o!==void 0&&(I.exitCode=o);var r=wt.apply(this,arguments);return ie("exit",I.exitCode,null),ie("afterexit",I.exitCode,null),r}else return wt.apply(this,arguments)}}var Vn=ne.exports,Xn=re(Vn);const Jn=1e3*5,Qn=(t,e="SIGTERM",o={})=>{const r=t(e);return Zn(t,e,o,r),r},Zn=(t,e,o,r)=>{if(!ei(e,o,r))return;const n=ri(o),s=setTimeout(()=>{t("SIGKILL")},n);s.unref&&s.unref()},ei=(t,{forceKillAfterTimeout:e},o)=>ti(t)&&e!==!1&&o,ti=t=>t===Wo.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",ri=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return Jn;if(!Number.isFinite(t)||t<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`);return t},oi=(t,e)=>{t.kill()&&(e.isCanceled=!0)},si=(t,e,o)=>{t.kill(e),o(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},ni=(t,{timeout:e,killSignal:o="SIGTERM"},r)=>{if(e===0||e===void 0)return r;let n;const s=new Promise((c,l)=>{n=setTimeout(()=>{si(t,o,l)},e)}),i=r.finally(()=>{clearTimeout(n)});return Promise.race([s,i])},ii=({timeout:t})=>{if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`)},ai=async(t,{cleanup:e,detached:o},r)=>{if(!e||o)return r;const n=Xn(()=>{t.kill()});return r.finally(()=>{n()})};function Lr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Tr(t){return Lr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const ci=t=>t instanceof zo&&typeof t.then=="function",vt=(t,e,o)=>{if(typeof o=="string")return t[e].pipe(Yo(o)),t;if(Tr(o))return t[e].pipe(o),t;if(!ci(o))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Tr(o.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(o.stdin),o},li=t=>{t.stdout!==null&&(t.pipeStdout=vt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=vt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=vt.bind(void 0,t,"all"))};var ye={exports:{}};const{PassThrough:mi}=ot;var ui=t=>{t={...t};const{array:e}=t;let{encoding:o}=t;const r=o==="buffer";let n=!1;e?n=!(o||r):o=o||"utf8",r&&(o=null);const s=new mi({objectMode:n});o&&s.setEncoding(o);let i=0;const c=[];return s.on("data",l=>{c.push(l),n?i=c.length:i+=l.length}),s.getBufferedValue=()=>e?c:r?Buffer.concat(c,i):c.join(""),s.getBufferedLength=()=>i,s};const{constants:pi}=Xo,fi=ot,{promisify:di}=er,hi=ui,gi=di(fi.pipeline);class Nr extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function bt(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:o}=e,r=hi(e);return await new Promise((n,s)=>{const i=c=>{c&&r.getBufferedLength()<=pi.MAX_LENGTH&&(c.bufferedData=r.getBufferedValue()),s(c)};(async()=>{try{await gi(t,r),n()}catch(c){i(c)}})(),r.on("data",()=>{r.getBufferedLength()>o&&i(new Nr)})}),r.getBufferedValue()}ye.exports=bt,ye.exports.buffer=(t,e)=>bt(t,{...e,encoding:"buffer"}),ye.exports.array=(t,e)=>bt(t,{...e,array:!0}),ye.exports.MaxBufferError=Nr;var yi=ye.exports,_r=re(yi);const{PassThrough:wi}=ot;var vi=function(){var t=[],e=new wi({objectMode:!0});return e.setMaxListeners(0),e.add=o,e.isEmpty=r,e.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(o),e;function o(s){return Array.isArray(s)?(s.forEach(o),this):(t.push(s),s.once("end",n.bind(null,s)),s.once("error",e.emit.bind(e,"error")),s.pipe(e,{end:!1}),this)}function r(){return t.length==0}function n(s){t=t.filter(function(i){return i!==s}),!t.length&&e.readable&&e.end()}},bi=re(vi);const Ci=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Pi=({input:t,inputFile:e})=>typeof e!="string"?t:(Ci(t),Vo(e)),$i=(t,e)=>{const o=Pi(e);o!==void 0&&(Lr(o)?o.pipe(t.stdin):t.stdin.end(o))},Ei=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const o=bi();return t.stdout&&o.add(t.stdout),t.stderr&&o.add(t.stderr),o},Ct=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(o){return o.bufferedData}}},Pt=(t,{encoding:e,buffer:o,maxBuffer:r})=>{if(!(!t||!o))return e?_r(t,{encoding:e,maxBuffer:r}):_r.buffer(t,{maxBuffer:r})},xi=async({stdout:t,stderr:e,all:o},{encoding:r,buffer:n,maxBuffer:s},i)=>{const c=Pt(t,{encoding:r,buffer:n,maxBuffer:s}),l=Pt(e,{encoding:r,buffer:n,maxBuffer:s}),u=Pt(o,{encoding:r,buffer:n,maxBuffer:s*2});try{return await Promise.all([i,c,l,u])}catch(p){return Promise.all([{error:p,signal:p.signal,timedOut:p.timedOut},Ct(t,c),Ct(e,l),Ct(o,u)])}},Ai=(async()=>{})().constructor.prototype,Si=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(Ai,t)]),Fr=(t,e)=>{for(const[o,r]of Si){const n=typeof e=="function"?(...s)=>Reflect.apply(r.value,e(),s):r.value.bind(e);Reflect.defineProperty(t,o,{...r,value:n})}},Mi=t=>new Promise((e,o)=>{t.on("exit",(r,n)=>{e({exitCode:r,signal:n})}),t.on("error",r=>{o(r)}),t.stdin&&t.stdin.on("error",r=>{o(r)})}),Dr=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],ki=/^[\w.-]+$/,Ii=/"/g,Ri=t=>typeof t!="string"||ki.test(t)?t:`"${t.replace(Ii,'\\"')}"`,Oi=(t,e)=>Dr(t,e).join(" "),Li=(t,e)=>Dr(t,e).map(o=>Ri(o)).join(" "),Ti=Jo("execa").enabled,Ge=(t,e)=>String(t).padStart(e,"0"),Ni=()=>{const t=new Date;return`${Ge(t.getHours(),2)}:${Ge(t.getMinutes(),2)}:${Ge(t.getSeconds(),2)}.${Ge(t.getMilliseconds(),3)}`},_i=(t,{verbose:e})=>{e&&U.stderr.write(`[${Ni()}] ${t}
8
- `)},Fi=1e3*1e3*100,Di=({env:t,extendEnv:e,preferLocal:o,localDir:r,execPath:n})=>{const s=e?{...U.env,...t}:t;return o?Pn({env:s,cwd:r,execPath:n}):s},Gi=(t,e,o={})=>{const r=yn._parse(t,e,o);return t=r.command,e=r.args,o=r.options,o={maxBuffer:Fi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:o.cwd||U.cwd(),execPath:U.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ti,...o},o.env=Di(o),o.stdio=Un(o),U.platform==="win32"&&te.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:o,parsed:r}},$t=(t,e,o)=>typeof e!="string"&&!qo.isBuffer(e)?o===void 0?void 0:"":t.stripFinalNewline?wn(e):e;function X(t,e,o){const r=Gi(t,e,o),n=Oi(t,e),s=Li(t,e);_i(s,r.options),ii(r.options);let i;try{i=Vt.spawn(r.file,r.args,r.options)}catch(d){const h=new Vt.ChildProcess,g=Promise.reject(kr({error:d,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Fr(h,g),h}const c=Mi(i),l=ni(i,r.options,c),u=ai(i,r.options,l),p={isCanceled:!1};i.kill=Qn.bind(null,i.kill.bind(i)),i.cancel=oi.bind(null,i,p);const m=xr(async()=>{const[{error:d,exitCode:h,signal:g,timedOut:y},v,E,N]=await xi(i,r.options,u),K=$t(r.options,v),W=$t(r.options,E),fe=$t(r.options,N);if(d||h!==0||g!==null){const V=kr({error:d,exitCode:h,signal:g,stdout:K,stderr:W,all:fe,command:n,escapedCommand:s,parsed:r,timedOut:y,isCanceled:p.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:i.killed});if(!r.options.reject)return V;throw V}return{command:n,escapedCommand:s,exitCode:0,stdout:K,stderr:W,all:fe,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return $i(i,r.options),i.all=Ei(i,r.options),li(i),Fr(i,m),i}class R{static create(e,o){return new e(o)}}const{hasOwnProperty:Et}=Object.prototype,je=typeof process<"u"&&process.platform==="win32"?`\r
7
+ `);return v?(r.originalMessage=r.message,r.message=N):r=new Error(N),r.shortMessage=E,r.command=i,r.escapedCommand=c,r.exitCode=s,r.signal=n,r.signalDescription=d,r.stdout=t,r.stderr=e,r.cwd=m,o!==void 0&&(r.all=o),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=u,r.killed=p&&!l,r},_e=["stdin","stdout","stderr"],Hn=t=>_e.some(e=>t[e]!==void 0),Un=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return _e.map(r=>t[r]);if(Hn(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${_e.map(r=>`\`${r}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const o=Math.max(e.length,_e.length);return Array.from({length:o},(r,n)=>e[n])};var ne={exports:{}},Fe={exports:{}};Fe.exports;var Ir;function qn(){return Ir||(Ir=1,function(t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Fe)),Fe.exports}var I=O.process;const Z=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};if(!Z(I))ne.exports=function(){return function(){}};else{var zn=Qt,he=qn(),Kn=/^win/i.test(I.platform),De=Zt;typeof De!="function"&&(De=De.EventEmitter);var L;I.__signal_exit_emitter__?L=I.__signal_exit_emitter__:(L=I.__signal_exit_emitter__=new De,L.count=0,L.emitted={}),L.infinite||(L.setMaxListeners(1/0),L.infinite=!0),ne.exports=function(t,e){if(!Z(O.process))return function(){};zn.equal(typeof t,"function","a callback must be provided for exit handler"),ge===!1&&Rr();var o="exit";e&&e.alwaysLast&&(o="afterexit");var r=function(){L.removeListener(o,t),L.listeners("exit").length===0&&L.listeners("afterexit").length===0&&gt()};return L.on(o,t),r};var gt=function(){!ge||!Z(O.process)||(ge=!1,he.forEach(function(e){try{I.removeListener(e,yt[e])}catch{}}),I.emit=wt,I.reallyExit=Or,L.count-=1)};ne.exports.unload=gt;var ie=function(e,o,r){L.emitted[e]||(L.emitted[e]=!0,L.emit(e,o,r))},yt={};he.forEach(function(t){yt[t]=function(){if(Z(O.process)){var o=I.listeners(t);o.length===L.count&&(gt(),ie("exit",null,t),ie("afterexit",null,t),Kn&&t==="SIGHUP"&&(t="SIGINT"),I.kill(I.pid,t))}}}),ne.exports.signals=function(){return he};var ge=!1,Rr=function(){ge||!Z(O.process)||(ge=!0,L.count+=1,he=he.filter(function(e){try{return I.on(e,yt[e]),!0}catch{return!1}}),I.emit=Yn,I.reallyExit=Wn)};ne.exports.load=Rr;var Or=I.reallyExit,Wn=function(e){Z(O.process)&&(I.exitCode=e||0,ie("exit",I.exitCode,null),ie("afterexit",I.exitCode,null),Or.call(I,I.exitCode))},wt=I.emit,Yn=function(e,o){if(e==="exit"&&Z(O.process)){o!==void 0&&(I.exitCode=o);var r=wt.apply(this,arguments);return ie("exit",I.exitCode,null),ie("afterexit",I.exitCode,null),r}else return wt.apply(this,arguments)}}var Vn=ne.exports,Xn=re(Vn);const Jn=1e3*5,Qn=(t,e="SIGTERM",o={})=>{const r=t(e);return Zn(t,e,o,r),r},Zn=(t,e,o,r)=>{if(!ei(e,o,r))return;const n=ri(o),s=setTimeout(()=>{t("SIGKILL")},n);s.unref&&s.unref()},ei=(t,{forceKillAfterTimeout:e},o)=>ti(t)&&e!==!1&&o,ti=t=>t===Wo.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",ri=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return Jn;if(!Number.isFinite(t)||t<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`);return t},oi=(t,e)=>{t.kill()&&(e.isCanceled=!0)},si=(t,e,o)=>{t.kill(e),o(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},ni=(t,{timeout:e,killSignal:o="SIGTERM"},r)=>{if(e===0||e===void 0)return r;let n;const s=new Promise((c,l)=>{n=setTimeout(()=>{si(t,o,l)},e)}),i=r.finally(()=>{clearTimeout(n)});return Promise.race([s,i])},ii=({timeout:t})=>{if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`)},ai=async(t,{cleanup:e,detached:o},r)=>{if(!e||o)return r;const n=Xn(()=>{t.kill()});return r.finally(()=>{n()})};function Lr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Tr(t){return Lr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const ci=t=>t instanceof zo&&typeof t.then=="function",vt=(t,e,o)=>{if(typeof o=="string")return t[e].pipe(Yo(o)),t;if(Tr(o))return t[e].pipe(o),t;if(!ci(o))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Tr(o.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(o.stdin),o},li=t=>{t.stdout!==null&&(t.pipeStdout=vt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=vt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=vt.bind(void 0,t,"all"))};var ye={exports:{}};const{PassThrough:mi}=ot;var ui=t=>{t={...t};const{array:e}=t;let{encoding:o}=t;const r=o==="buffer";let n=!1;e?n=!(o||r):o=o||"utf8",r&&(o=null);const s=new mi({objectMode:n});o&&s.setEncoding(o);let i=0;const c=[];return s.on("data",l=>{c.push(l),n?i=c.length:i+=l.length}),s.getBufferedValue=()=>e?c:r?Buffer.concat(c,i):c.join(""),s.getBufferedLength=()=>i,s};const{constants:pi}=Xo,fi=ot,{promisify:di}=er,hi=ui,gi=di(fi.pipeline);class Nr extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function bt(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:o}=e,r=hi(e);return await new Promise((n,s)=>{const i=c=>{c&&r.getBufferedLength()<=pi.MAX_LENGTH&&(c.bufferedData=r.getBufferedValue()),s(c)};(async()=>{try{await gi(t,r),n()}catch(c){i(c)}})(),r.on("data",()=>{r.getBufferedLength()>o&&i(new Nr)})}),r.getBufferedValue()}ye.exports=bt,ye.exports.buffer=(t,e)=>bt(t,{...e,encoding:"buffer"}),ye.exports.array=(t,e)=>bt(t,{...e,array:!0}),ye.exports.MaxBufferError=Nr;var yi=ye.exports,_r=re(yi);const{PassThrough:wi}=ot;var vi=function(){var t=[],e=new wi({objectMode:!0});return e.setMaxListeners(0),e.add=o,e.isEmpty=r,e.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(o),e;function o(s){return Array.isArray(s)?(s.forEach(o),this):(t.push(s),s.once("end",n.bind(null,s)),s.once("error",e.emit.bind(e,"error")),s.pipe(e,{end:!1}),this)}function r(){return t.length==0}function n(s){t=t.filter(function(i){return i!==s}),!t.length&&e.readable&&e.end()}},bi=re(vi);const Ci=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Pi=({input:t,inputFile:e})=>typeof e!="string"?t:(Ci(t),Vo(e)),$i=(t,e)=>{const o=Pi(e);o!==void 0&&(Lr(o)?o.pipe(t.stdin):t.stdin.end(o))},Ei=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const o=bi();return t.stdout&&o.add(t.stdout),t.stderr&&o.add(t.stderr),o},Ct=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(o){return o.bufferedData}}},Pt=(t,{encoding:e,buffer:o,maxBuffer:r})=>{if(!(!t||!o))return e?_r(t,{encoding:e,maxBuffer:r}):_r.buffer(t,{maxBuffer:r})},xi=async({stdout:t,stderr:e,all:o},{encoding:r,buffer:n,maxBuffer:s},i)=>{const c=Pt(t,{encoding:r,buffer:n,maxBuffer:s}),l=Pt(e,{encoding:r,buffer:n,maxBuffer:s}),u=Pt(o,{encoding:r,buffer:n,maxBuffer:s*2});try{return await Promise.all([i,c,l,u])}catch(p){return Promise.all([{error:p,signal:p.signal,timedOut:p.timedOut},Ct(t,c),Ct(e,l),Ct(o,u)])}},Ai=(async()=>{})().constructor.prototype,Si=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(Ai,t)]),Fr=(t,e)=>{for(const[o,r]of Si){const n=typeof e=="function"?(...s)=>Reflect.apply(r.value,e(),s):r.value.bind(e);Reflect.defineProperty(t,o,{...r,value:n})}},ki=t=>new Promise((e,o)=>{t.on("exit",(r,n)=>{e({exitCode:r,signal:n})}),t.on("error",r=>{o(r)}),t.stdin&&t.stdin.on("error",r=>{o(r)})}),Dr=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],Mi=/^[\w.-]+$/,Ii=/"/g,Ri=t=>typeof t!="string"||Mi.test(t)?t:`"${t.replace(Ii,'\\"')}"`,Oi=(t,e)=>Dr(t,e).join(" "),Li=(t,e)=>Dr(t,e).map(o=>Ri(o)).join(" "),Ti=Jo("execa").enabled,Ge=(t,e)=>String(t).padStart(e,"0"),Ni=()=>{const t=new Date;return`${Ge(t.getHours(),2)}:${Ge(t.getMinutes(),2)}:${Ge(t.getSeconds(),2)}.${Ge(t.getMilliseconds(),3)}`},_i=(t,{verbose:e})=>{e&&U.stderr.write(`[${Ni()}] ${t}
8
+ `)},Fi=1e3*1e3*100,Di=({env:t,extendEnv:e,preferLocal:o,localDir:r,execPath:n})=>{const s=e?{...U.env,...t}:t;return o?Pn({env:s,cwd:r,execPath:n}):s},Gi=(t,e,o={})=>{const r=yn._parse(t,e,o);return t=r.command,e=r.args,o=r.options,o={maxBuffer:Fi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:o.cwd||U.cwd(),execPath:U.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ti,...o},o.env=Di(o),o.stdio=Un(o),U.platform==="win32"&&te.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:o,parsed:r}},$t=(t,e,o)=>typeof e!="string"&&!qo.isBuffer(e)?o===void 0?void 0:"":t.stripFinalNewline?wn(e):e;function X(t,e,o){const r=Gi(t,e,o),n=Oi(t,e),s=Li(t,e);_i(s,r.options),ii(r.options);let i;try{i=Vt.spawn(r.file,r.args,r.options)}catch(d){const h=new Vt.ChildProcess,g=Promise.reject(Mr({error:d,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Fr(h,g),h}const c=ki(i),l=ni(i,r.options,c),u=ai(i,r.options,l),p={isCanceled:!1};i.kill=Qn.bind(null,i.kill.bind(i)),i.cancel=oi.bind(null,i,p);const m=xr(async()=>{const[{error:d,exitCode:h,signal:g,timedOut:y},v,E,N]=await xi(i,r.options,u),K=$t(r.options,v),W=$t(r.options,E),fe=$t(r.options,N);if(d||h!==0||g!==null){const V=Mr({error:d,exitCode:h,signal:g,stdout:K,stderr:W,all:fe,command:n,escapedCommand:s,parsed:r,timedOut:y,isCanceled:p.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:i.killed});if(!r.options.reject)return V;throw V}return{command:n,escapedCommand:s,exitCode:0,stdout:K,stderr:W,all:fe,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return $i(i,r.options),i.all=Ei(i,r.options),li(i),Fr(i,m),i}class R{static create(e,o){return new e(o)}}const{hasOwnProperty:Et}=Object.prototype,je=typeof process<"u"&&process.platform==="win32"?`\r
9
9
  `:`
10
10
  `,xt=(t,e)=>{const o=[];let r="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const n=e.whitespace?" = ":"=";for(const s of Object.keys(t)){const i=t[s];if(i&&Array.isArray(i))for(const c of i)r+=ae(s+"[]")+n+ae(c)+je;else i&&typeof i=="object"?o.push(s):r+=ae(s)+n+ae(i)+je}e.section&&r.length&&(r="["+ae(e.section)+"]"+je+r);for(const s of o){const i=Gr(s).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:l}=e,u=xt(t[s],{section:c,whitespace:l});r.length&&u.length&&(r+=je),r+=u}return r},Gr=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),jr=t=>{const e=Object.create(null);let o=e,r=null;const n=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,s=t.split(/[\r\n]+/g);for(const c of s){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(n);if(!l)continue;if(l[1]!==void 0){if(r=Be(l[1]),r==="__proto__"){o=Object.create(null);continue}o=e[r]=e[r]||Object.create(null);continue}const u=Be(l[2]),p=u.length>2&&u.slice(-2)==="[]",a=p?u.slice(0,-2):u;if(a==="__proto__")continue;const m=l[3]?Be(l[4]):!0,d=m==="true"||m==="false"||m==="null"?JSON.parse(m):m;p&&(Et.call(o,a)?Array.isArray(o[a])||(o[a]=[o[a]]):o[a]=[]),Array.isArray(o[a])?o[a].push(d):o[a]=d}const i=[];for(const c of Object.keys(e)){if(!Et.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const l=Gr(c);o=e;const u=l.pop(),p=u.replace(/\\\./g,".");for(const a of l)a!=="__proto__"&&((!Et.call(o,a)||typeof o[a]!="object")&&(o[a]=Object.create(null)),o=o[a]);o===e&&p===u||(o[p]=e[c],i.push(c))}for(const c of i)delete e[c];return e},Br=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),ae=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Br(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),Be=(t,e)=>{if(t=(t||"").trim(),Br(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let o=!1,r="";for(let n=0,s=t.length;n<s;n++){const i=t.charAt(n);if(o)"\\;#".indexOf(i)!==-1?r+=i:r+="\\"+i,o=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?o=!0:r+=i}}return o&&(r+="\\"),r.trim()}return t};var ji={parse:jr,decode:jr,stringify:xt,encode:xt,safe:ae,unsafe:Be},ce=re(ji);class C extends Error{}const At=" ",ee=t=>{t instanceof Error&&(t instanceof C||(t.stack&&console.error(w.dim(t.stack.split(`
11
11
  `).slice(1).join(`
12
12
  `))),console.error(`
13
13
  ${At}${w.dim(`aicommit2 v${cr}`)}`),console.error(`
14
- ${At}Please open a Bug report with the information above:`),console.error(`${At}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Hr=t=>x.lstat(t).then(()=>!0,()=>!1),Ur=async t=>{try{await x.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},He=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,Ue=(t,e)=>{const o=Math.ceil(t),r=Math.floor(e);return Math.floor(Math.random()*(r-o+1))+o},Bi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,qe=t=>t.reduce((e,o)=>Array.isArray(o)?e.concat(qe(o)):e.concat(o),[]),qr=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Hi=t=>{let e=0;for(let o=0;o<t.length;o++){const r=t.charCodeAt(o);e=(e<<5)-e+r,e=e&e}return Math.abs(e)},Ui=t=>{const e=t%360,o=65+t%15,r=45+t%10;return`hsl(${e}, ${o}%, ${r}%)`},qi=t=>{const[e,o,r]=t.match(/\d+/g).map((a,m)=>m===0?Number(a):Number(a)/100),n=(1-Math.abs(2*r-1))*o,s=n*(1-Math.abs(e/60%2-1)),i=r-n/2;let c,l,u;e<60?[c,l,u]=[n,s,0]:e<120?[c,l,u]=[s,n,0]:e<180?[c,l,u]=[0,n,s]:e<240?[c,l,u]=[0,s,n]:e<300?[c,l,u]=[s,0,n]:[c,l,u]=[n,0,s];const p=a=>{const m=Math.round((a+i)*255).toString(16);return m.length===1?"0"+m:m};return`#${p(c)}${p(l)}${p(u)}`},zi=t=>{const e=Hi(t),o=Ui(e);return{primary:qi(o),secondary:"#FFFFFF"}},ze=t=>{if(!t||typeof t!="string")return"";if(P.isAbsolute(t))return P.resolve(t);if(ve){const e=P.dirname(ve),o=P.join(e,t);return P.resolve(o)}else return""},Ki=["","conventional","gitmoji"],St="http://localhost:11434",{hasOwnProperty:Wi}=Object.prototype,Mt=(t,e)=>Wi.call(t,e),le=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK"],zr=t=>{const e=Ie.platform(),o=Ie.homedir();let r,n;switch(t){case"config":r=process.env.XDG_CONFIG_HOME;break;case"data":r=process.env.XDG_DATA_HOME;break;case"cache":r=process.env.XDG_CACHE_HOME;break;case"state":r=process.env.XDG_STATE_HOME;break;default:r=void 0}if(e==="darwin")t==="cache"?n=P.join(o,"Library","Caches"):n=P.join(o,"Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||o;else switch(t){case"config":n=P.join(o,".config");break;case"data":n=P.join(o,".local","share");break;case"cache":n=P.join(o,".cache");break;case"state":n=P.join(o,".local","state");break;default:n=o}return r||n},Yi=P.join(zr("config"),"aicommit2"),Ke=P.join(zr("state"),"aicommit2","logs"),Kr=P.join(Yi,"config.ini"),Wr=P.join(Ke,"aicommit2-%DATE%.log"),Yr=P.join(Ke,"exceptions-%DATE%.log"),Vi=t=>{const e=Object.keys(t),o=new Set([...le,...e.filter(r=>/^[A-Z][A-Z0-9_]*$/.test(r))]);return Array.from(o)},b=(t,e,o)=>{if(!e)throw new C(`Invalid config property ${t}: ${o}`)},f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;b("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;b("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return b("temperature",e>0,"Must be greater than 0"),b("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(b("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(b("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(b("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||Wr},exceptionLogFilePath(t){return t||Yr},locale(t){return t?(b("locale",t,"Cannot be empty"),b("locale",/^[a-z-]+$/i.test(t),"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"),t):"en"},generate(t){if(!t)return 1;b("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("generate",e>0,"Must be greater than 0"),b("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(b("type",Ki.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;b("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(b("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],topP:t=>{if(!t)return .9;b("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return b("topP",e>0,"Must be greater than 0"),b("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(b("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(b("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(b("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},we={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["gpt-4o-mini"],url:t=>t?(b("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>{if(!t)return["CohereForAI/c4ai-command-r-plus"];const e=typeof t=="string"?t?.split(","):t,o=["CohereForAI/c4ai-command-r-plus","meta-llama/Meta-Llama-3-70B-Instruct","HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1","mistralai/Mixtral-8x7B-Instruct-v0.1","NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO","01-ai/Yi-1.5-34B-Chat","mistralai/Mistral-7B-Instruct-v0.2","microsoft/Phi-3-mini-4k-instruct"];for(const r of e)b("HUGGINGFACE.model",o.includes(r.trim()),`Invalid model type of HuggingFace chat: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["gemini-2.0-flash"];const e=typeof t=="string"?t?.split(","):t,o=["gemini-2.5-flash-preview-04-17","gemini-2.5-flash-preview-05-20","gemini-2.5-pro-preview-05-06","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-2.0-flash-preview-image-generation","gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"];for(const r of e)b("GEMINI.model",o.includes(r.trim()),`Invalid model type of Gemini: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["claude-3-5-haiku-20241022"];const e=typeof t=="string"?t?.split(","):t,o=["claude-3-7-sonnet-20250219","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"];for(const r of e)b("ANTHROPIC.model",o.includes(r.trim()),`Invalid model type of Anthropic: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["pixtral-12b-2409"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","mistral-large-latest","pixtral-large-latest","ministral-8b-latest","mistral-small-latest","mistral-embed","mistral-moderation-latest"];for(const r of e)b("MISTRAL.model",o.includes(r.trim()),`Invalid model type of Mistral AI: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["codestral-latest"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","codestral-2501"];for(const r of e)b("CODESTRAL.model",o.includes(r.trim()),`Invalid model type of Codestral: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],host:t=>t?(b("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):St,timeout:t=>{if(!t)return 1e5;b("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;b("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["command"];const e=typeof t=="string"?t?.split(","):t,o=["command-r7b-12-2024","command-r-plus-08-2024","command-r-plus-04-2024","command-r-plus","command-r-08-2024","command-r-03-2024","command-r","command","command-nightly","command-light","command-light-nightly","c4ai-aya-expanse-8b","c4ai-aya-expanse-32b"];for(const r of e)b("COHERE.model",o.includes(r.trim()),`Invalid model type of Cohere: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["llama-3.3-70b-versatile"];const e=typeof t=="string"?t?.split(","):t,o=["allam-2-7b","compound-beta","compound-beta-mini","deepseek-r1-distill-llama-70b","distil-whisper-large-v3-en","gemma2-9b-it","llama-3.1-8b-instant","llama-3.3-70b-versatile","llama-guard-3-8b","llama3-70b-8192","llama3-8b-8192","meta-llama/llama-4-maverick-17b-128e-instruct","meta-llama/llama-4-scout-17b-16e-instruct","mistral-saba-24b","playai-tts","playai-tts-arabic","qwen-qwq-32b","whisper-large-v3","whisper-large-v3-turbo"];for(const r of e)b("GROQ.model",o.includes(r.trim()),`Invalid model type of Groq: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},PERPLEXITY:{key:t=>t||"",model:t=>{if(!t)return["sonar"];const e=typeof t=="string"?t?.split(","):t,o=["sonar-pro","sonar","llama-3.1-sonar-small-128k-online","llama-3.1-sonar-large-128k-online","llama-3.1-sonar-huge-128k-online"];for(const r of e)b("PERPLEXITY.model",o.includes(r.trim()),`Invalid model type of Perplexity: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["deepseek-chat"];const e=typeof t=="string"?t?.split(","):t,o=["deepseek-reasoner","deepseek-chat"];for(const r of e)b("DEEPSEEK.model",o.includes(r.trim()),`Invalid model type of DeepSeek: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode}};let ve;const Xi=(t=[])=>{const e={};for(const o of t)if(o.startsWith("--")){const[r,n]=o.slice(2).split("="),[s,i]=r.split(".");s&&i&&s in we?(e[s]||(e[s]={}),e[s][i]=n):e[r]=n}return e},Ji=()=>{const t=Ie.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,o=Kr,r=P.join(t,".aicommit2");return[e,o,r].filter(n=>!!n)},me=async()=>{const t=Ji();for(const e of t)if(await Hr(e))return e;return Kr},be=async()=>{const t=await me();ve=t;try{const e=await x.readFile(t,"utf8");return ce.parse(e)}catch(e){return e.code==="ENOENT"?(ve=void 0,{}):(console.error(`Error reading config file ${t}:`,e),ve=void 0,{})}},ue=async(t,e=[])=>{const o=await be(),r=Xi(e),n={...t,...r},s={},i=Vi(o),c={};for(const u of i){const a=o[u]?.envKey||`${u}_API_KEY`,m=process.env[a];m&&(c[u]={key:m})}const l=(u,p)=>{const a=n[`${u}.${p}`]??n[u]?.[p],m=c[u]?.[p],d=o[u]?.[p],h=n[p]??o[p];return a!==void 0?a:m!==void 0?m:d!==void 0?d:h};for(const[u,p]of Object.entries(f)){const a=n[u]??o[u];s[u]=p(a)}for(const u of i){s[u]={};const p=we[u]||We(u);for(const[a,m]of Object.entries(p)){const d=l(u,a);s[u][a]=m(d)}}return s},Qi=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split(".");if(!c){const p=f[n];if(!p)throw new C(`Invalid config property: ${n}`);e[n]=p(s);continue}if(e[i]||(e[i]={}),le.includes(i)){const p=we[i][c];if(!p)throw new C(`Invalid config property: ${n}`);e[i][c]=p(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new C(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const u=We(i);if(!u[c])throw new C(`Invalid config property for custom service: ${n}`);try{e[i][c]=u[c](s)}catch(p){throw p instanceof C?p:new C(`Invalid value for ${n}: ${p.message}`)}}const o=await me(),r=P.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},Zi=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split("."),l=e[i];if(c==="model"){l||(e[i]={});const p=e[i][c]||[],a=typeof s=="string"?s.split(",").map(m=>m.trim()).filter(m=>!!m):s;e[i][c]=qe([...p,...a]);continue}if(l&&l.compatible===!0){l||(e[i]={});const p=We(i);if(!p[c])throw new C(`Invalid config property: ${n}`);try{e[i][c]=p[c](s)}catch(a){throw a instanceof C?a:new C(`Invalid value for ${n}: ${a.message}`)}continue}if(i in we){l||(e[i]={});const p=we[i][c];if(!p)throw new C(`Invalid config property: ${n}`);e[i][c]=p(s)}else{const p=We(i);if(!p[c])throw new C(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][c]=p[c](s)}}const o=await me(),r=P.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},ea=async()=>{const t=await be();console.log(ce.stringify(t))},ta=async()=>{console.log(await me())},We=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(b("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(b("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(b(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode});let Ye;async function ra(t){if(Ye){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",o=t?.logFilePath||Wr,r=t?.exceptionLogFilePath||Yr,n=t?.logging??!0;await Ur(P.dirname(o)),await Ur(P.dirname(r));const s=[];n&&s.push(new q.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:q.format.combine(q.format.timestamp(),q.format.printf(({level:i,message:c,timestamp:l})=>`[${l}] ${i}: ${c}`))})),Ye=q.createLogger({level:e,format:q.format.json(),transports:s,exceptionHandlers:n?[new q.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:q.format.combine(q.format.timestamp(),q.format.json())})]:[],exitOnError:!1})}const Vr=new Proxy({},{get:(t,e,o)=>{if(!Ye)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(Ye,e,o)}});class G{constructor(e){this.handleError$=o=>{let r=o.name??"Unknown Error";return Vr.error(`${this.errorPrefix} ${o.toString()}`),o.status?r=`${o.status} ${r}`:o.code&&(r=`${o.code} ${r}`),de({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""}}parseMessage(e,o,r){const n=a=>a.replace(/[\u0000-\u001F\u007F-\u009F]/g,"").replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),s=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=e.match(s);if(!i){const a=new Error("AI response did not contain a valid JSON object or array.");throw a.name="InvalidJsonResponse",a}const c=n(i[0]),l=JSON.parse(c),u=Array.isArray(l)?l:[l];if(!u.length||!u.every(a=>typeof a.subject=="string")){const a=new Error("AI response contained malformed commit message data.");throw a.name="MalformedCommitMessage",a}return u.map(a=>this.extractMessageAsType(a,o)).map(a=>({title:`${a.subject}`,value:`${a.subject}${a.body?`
14
+ ${At}Please open a Bug report with the information above:`),console.error(`${At}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Hr=t=>x.lstat(t).then(()=>!0,()=>!1),Ur=async t=>{try{await x.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},He=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,Ue=(t,e)=>{const o=Math.ceil(t),r=Math.floor(e);return Math.floor(Math.random()*(r-o+1))+o},Bi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,qe=t=>t.reduce((e,o)=>Array.isArray(o)?e.concat(qe(o)):e.concat(o),[]),qr=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Hi=t=>{let e=0;for(let o=0;o<t.length;o++){const r=t.charCodeAt(o);e=(e<<5)-e+r,e=e&e}return Math.abs(e)},Ui=t=>{const e=t%360,o=65+t%15,r=45+t%10;return`hsl(${e}, ${o}%, ${r}%)`},qi=t=>{const[e,o,r]=t.match(/\d+/g).map((a,m)=>m===0?Number(a):Number(a)/100),n=(1-Math.abs(2*r-1))*o,s=n*(1-Math.abs(e/60%2-1)),i=r-n/2;let c,l,u;e<60?[c,l,u]=[n,s,0]:e<120?[c,l,u]=[s,n,0]:e<180?[c,l,u]=[0,n,s]:e<240?[c,l,u]=[0,s,n]:e<300?[c,l,u]=[s,0,n]:[c,l,u]=[n,0,s];const p=a=>{const m=Math.round((a+i)*255).toString(16);return m.length===1?"0"+m:m};return`#${p(c)}${p(l)}${p(u)}`},zi=t=>{const e=Hi(t),o=Ui(e);return{primary:qi(o),secondary:"#FFFFFF"}},ze=t=>{if(!t||typeof t!="string")return"";if(P.isAbsolute(t))return P.resolve(t);if(ve){const e=P.dirname(ve),o=P.join(e,t);return P.resolve(o)}else return""},Ki=["","conventional","gitmoji"],St="http://localhost:11434",{hasOwnProperty:Wi}=Object.prototype,kt=(t,e)=>Wi.call(t,e),le=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK"],zr=t=>{const e=Ie.platform(),o=Ie.homedir();let r,n;switch(t){case"config":r=process.env.XDG_CONFIG_HOME;break;case"data":r=process.env.XDG_DATA_HOME;break;case"cache":r=process.env.XDG_CACHE_HOME;break;case"state":r=process.env.XDG_STATE_HOME;break;default:r=void 0}if(e==="darwin")t==="cache"?n=P.join(o,"Library","Caches"):n=P.join(o,"Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||o;else switch(t){case"config":n=P.join(o,".config");break;case"data":n=P.join(o,".local","share");break;case"cache":n=P.join(o,".cache");break;case"state":n=P.join(o,".local","state");break;default:n=o}return r||n},Yi=P.join(zr("config"),"aicommit2"),Ke=P.join(zr("state"),"aicommit2","logs"),Kr=P.join(Yi,"config.ini"),Wr=P.join(Ke,"aicommit2-%DATE%.log"),Yr=P.join(Ke,"exceptions-%DATE%.log"),Vi=t=>{const e=Object.keys(t),o=new Set([...le,...e.filter(r=>/^[A-Z][A-Z0-9_]*$/.test(r))]);return Array.from(o)},b=(t,e,o)=>{if(!e)throw new C(`Invalid config property ${t}: ${o}`)},f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;b("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;b("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return b("temperature",e>0,"Must be greater than 0"),b("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(b("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(b("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(b("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||Wr},exceptionLogFilePath(t){return t||Yr},locale(t){return t?(b("locale",t,"Cannot be empty"),b("locale",/^[a-z-]+$/i.test(t),"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"),t):"en"},generate(t){if(!t)return 1;b("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("generate",e>0,"Must be greater than 0"),b("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(b("type",Ki.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;b("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(b("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],topP:t=>{if(!t)return .9;b("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return b("topP",e>0,"Must be greater than 0"),b("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(b("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(b("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(b("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},we={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):["gpt-4o-mini"],url:t=>t?(b("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>{if(!t)return["CohereForAI/c4ai-command-r-plus"];const e=typeof t=="string"?t?.split(","):t,o=["CohereForAI/c4ai-command-r-plus","meta-llama/Meta-Llama-3-70B-Instruct","HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1","mistralai/Mixtral-8x7B-Instruct-v0.1","NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO","01-ai/Yi-1.5-34B-Chat","mistralai/Mistral-7B-Instruct-v0.2","microsoft/Phi-3-mini-4k-instruct"];for(const r of e)b("HUGGINGFACE.model",o.includes(r.trim()),`Invalid model type of HuggingFace chat: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["gemini-2.0-flash"];const e=typeof t=="string"?t?.split(","):t,o=["gemini-2.5-flash-preview-04-17","gemini-2.5-flash-preview-05-20","gemini-2.5-pro-preview-05-06","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-2.0-flash-preview-image-generation","gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"];for(const r of e)b("GEMINI.model",o.includes(r.trim()),`Invalid model type of Gemini: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["claude-3-5-haiku-20241022"];const e=typeof t=="string"?t?.split(","):t,o=["claude-opus-4-20250514","claude-sonnet-4-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"];for(const r of e)b("ANTHROPIC.model",o.includes(r.trim()),`Invalid model type of Anthropic: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["pixtral-12b-2409"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","mistral-large-latest","pixtral-large-latest","ministral-8b-latest","mistral-small-latest","mistral-embed","mistral-moderation-latest"];for(const r of e)b("MISTRAL.model",o.includes(r.trim()),`Invalid model type of Mistral AI: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["codestral-latest"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","codestral-2501"];for(const r of e)b("CODESTRAL.model",o.includes(r.trim()),`Invalid model type of Codestral: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],host:t=>t?(b("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):St,timeout:t=>{if(!t)return 1e5;b("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;b("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["command"];const e=typeof t=="string"?t?.split(","):t,o=["command-r7b-12-2024","command-r-plus-08-2024","command-r-plus-04-2024","command-r-plus","command-r-08-2024","command-r-03-2024","command-r","command","command-nightly","command-light","command-light-nightly","c4ai-aya-expanse-8b","c4ai-aya-expanse-32b"];for(const r of e)b("COHERE.model",o.includes(r.trim()),`Invalid model type of Cohere: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["llama-3.3-70b-versatile"];const e=typeof t=="string"?t?.split(","):t,o=["allam-2-7b","compound-beta","compound-beta-mini","deepseek-r1-distill-llama-70b","distil-whisper-large-v3-en","gemma2-9b-it","llama-3.1-8b-instant","llama-3.3-70b-versatile","llama-guard-3-8b","llama3-70b-8192","llama3-8b-8192","meta-llama/llama-4-maverick-17b-128e-instruct","meta-llama/llama-4-scout-17b-16e-instruct","mistral-saba-24b","playai-tts","playai-tts-arabic","qwen-qwq-32b","whisper-large-v3","whisper-large-v3-turbo"];for(const r of e)b("GROQ.model",o.includes(r.trim()),`Invalid model type of Groq: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},PERPLEXITY:{key:t=>t||"",model:t=>{if(!t)return["sonar"];const e=typeof t=="string"?t?.split(","):t,o=["sonar-pro","sonar","llama-3.1-sonar-small-128k-online","llama-3.1-sonar-large-128k-online","llama-3.1-sonar-huge-128k-online"];for(const r of e)b("PERPLEXITY.model",o.includes(r.trim()),`Invalid model type of Perplexity: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["deepseek-chat"];const e=typeof t=="string"?t?.split(","):t,o=["deepseek-reasoner","deepseek-chat"];for(const r of e)b("DEEPSEEK.model",o.includes(r.trim()),`Invalid model type of DeepSeek: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode}};let ve;const Xi=(t=[])=>{const e={};for(const o of t)if(o.startsWith("--")){const[r,n]=o.slice(2).split("="),[s,i]=r.split(".");s&&i&&s in we?(e[s]||(e[s]={}),e[s][i]=n):e[r]=n}return e},Ji=()=>{const t=Ie.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,o=Kr,r=P.join(t,".aicommit2");return[e,o,r].filter(n=>!!n)},me=async()=>{const t=Ji();for(const e of t)if(await Hr(e))return e;return Kr},be=async()=>{const t=await me();ve=t;try{const e=await x.readFile(t,"utf8");return ce.parse(e)}catch(e){return e.code==="ENOENT"?(ve=void 0,{}):(console.error(`Error reading config file ${t}:`,e),ve=void 0,{})}},ue=async(t,e=[])=>{const o=await be(),r=Xi(e),n={...t,...r},s={},i=Vi(o),c={};for(const u of i){const a=o[u]?.envKey||`${u}_API_KEY`,m=process.env[a];m&&(c[u]={key:m})}const l=(u,p)=>{const a=n[`${u}.${p}`]??n[u]?.[p],m=c[u]?.[p],d=o[u]?.[p],h=n[p]??o[p];return a!==void 0?a:m!==void 0?m:d!==void 0?d:h};for(const[u,p]of Object.entries(f)){const a=n[u]??o[u];s[u]=p(a)}for(const u of i){s[u]={};const p=we[u]||We(u);for(const[a,m]of Object.entries(p)){const d=l(u,a);s[u][a]=m(d)}}return s},Qi=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split(".");if(!c){const p=f[n];if(!p)throw new C(`Invalid config property: ${n}`);e[n]=p(s);continue}if(e[i]||(e[i]={}),le.includes(i)){const p=we[i][c];if(!p)throw new C(`Invalid config property: ${n}`);e[i][c]=p(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new C(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const u=We(i);if(!u[c])throw new C(`Invalid config property for custom service: ${n}`);try{e[i][c]=u[c](s)}catch(p){throw p instanceof C?p:new C(`Invalid value for ${n}: ${p.message}`)}}const o=await me(),r=P.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},Zi=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split("."),l=e[i];if(c==="model"){l||(e[i]={});const p=e[i][c]||[],a=typeof s=="string"?s.split(",").map(m=>m.trim()).filter(m=>!!m):s;e[i][c]=qe([...p,...a]);continue}if(l&&l.compatible===!0){l||(e[i]={});const p=We(i);if(!p[c])throw new C(`Invalid config property: ${n}`);try{e[i][c]=p[c](s)}catch(a){throw a instanceof C?a:new C(`Invalid value for ${n}: ${a.message}`)}continue}if(i in we){l||(e[i]={});const p=we[i][c];if(!p)throw new C(`Invalid config property: ${n}`);e[i][c]=p(s)}else{const p=We(i);if(!p[c])throw new C(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][c]=p[c](s)}}const o=await me(),r=P.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},ea=async()=>{const t=await be();console.log(ce.stringify(t))},ta=async()=>{console.log(await me())},We=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(b("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(b("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(b(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode});let Ye;async function ra(t){if(Ye){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",o=t?.logFilePath||Wr,r=t?.exceptionLogFilePath||Yr,n=t?.logging??!0;await Ur(P.dirname(o)),await Ur(P.dirname(r));const s=[];n&&s.push(new q.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:q.format.combine(q.format.timestamp(),q.format.printf(({level:i,message:c,timestamp:l})=>`[${l}] ${i}: ${c}`))})),Ye=q.createLogger({level:e,format:q.format.json(),transports:s,exceptionHandlers:n?[new q.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:q.format.combine(q.format.timestamp(),q.format.json())})]:[],exitOnError:!1})}const Vr=new Proxy({},{get:(t,e,o)=>{if(!Ye)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(Ye,e,o)}});class G{constructor(e){this.handleError$=o=>{let r=o.name??"Unknown Error";return Vr.error(`${this.errorPrefix} ${o.toString()}`),o.status?r=`${o.status} ${r}`:o.code&&(r=`${o.code} ${r}`),de({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""}}parseMessage(e,o,r){const n=a=>a.replace(/[\u0000-\u001F\u007F-\u009F]/g,"").replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),s=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=e.match(s);if(!i){const a=new Error("AI response did not contain a valid JSON object or array.");throw a.name="InvalidJsonResponse",a}const c=n(i[0]),l=JSON.parse(c),u=Array.isArray(l)?l:[l];if(!u.length||!u.every(a=>typeof a.subject=="string")){const a=new Error("AI response contained malformed commit message data.");throw a.name="MalformedCommitMessage",a}return u.map(a=>this.extractMessageAsType(a,o)).map(a=>({title:`${a.subject}`,value:`${a.subject}${a.body?`
15
15
 
16
16
  ${a.body}`:""}${a.footer?`
17
17
 
@@ -67,8 +67,8 @@ ${Ve(r,n)}`}},H=t=>{const{codeReviewPromptPath:e,locale:o}=t,r=`I'll give you th
67
67
  4. Performance improvements
68
68
  5. Readability and maintainability
69
69
 
70
- Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return r;try{const n=_.readFileSync(ze(e),"utf-8");return`${Jr(n,t)}`}catch{return r}},Zr=async t=>{if(t.systemPromptPath)try{_.readFileSync(ze(t.systemPromptPath),"utf-8")}catch(e){throw new C(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{_.readFileSync(ze(t.codeReviewPromptPath),"utf-8")}catch(e){throw new C(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},ca=10*60*1e3;class eo extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=w.red.bold("[Anthropic]"),this.anthropic=new Zo({apiKey:this.params.config.key,...this.params.config.timeout>ca&&{timeout:this.params.config.timeout}})}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:l,generate:u,type:p,maxLength:a,maxTokens:m,topP:d,model:h}=this.params.config,g={...D,locale:l,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?H(g):B(g),v={max_tokens:m,temperature:c,system:y,messages:[{role:"user",content:`Here is the diff: ${o}`}],top_p:d,model:h},N=(await this.anthropic.messages.create(v)).content.map(({text:K})=>K).join("");return i&&j("Anthropic",o,y,N,e),e==="review"?this.sanitizeResponse(N):this.parseMessage(N,p,u)}}class Ce{constructor(e={}){if(!e.method)throw new Error("method should be defined!");if(!e.baseURL)throw new Error("baseURL should be defined!");this.config={...e},this.axiosInstance=ts.create(this.config)}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}addBody(e){return this.config.data={...this.config.data,...e},this}setMethod(e){return this.config.method=e,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(e){throw e}}}class to extends G{constructor(e){super(e),this.params=e,this.host="https://codestral.mistral.ai",this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=w.red.bold("[Codestral]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a);this.checkAvailableModels();const d=await this.createChatCompletions(m,e);return i&&j("Codestral",o,m,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,u,l)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,o){const r=new Ce({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ue(10,1e3)});o==="commit"&&r.addBody({response_format:{type:"json_object"}});const s=(await r.execute()).data;if(!s.choices||s.choices.length===0||!s.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return s.choices[0].message.content}}const la=2*60*1e3;class ro extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=w.red.bold("[Cohere]"),this.cohere=new rs({token:this.params.config.key})}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:l,generate:u,type:p,maxLength:a,maxTokens:m}=this.params.config,d={...D,locale:l,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?H(d):B(d),g=await this.cohere.chat({chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:`Here is the diff: ${o}`,connectors:[{id:"web-search"}],maxTokens:m,temperature:c,model:this.params.config.model,seed:Ue(10,1e3),p:this.params.config.topP},{...this.params.config.timeout>la&&{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}});return i&&j("Cohere",o,h,g.text,e),e==="review"?this.sanitizeResponse(g.text):this.parseMessage(g.text,p,u)}}class oo extends G{constructor(e){super(e),this.params=e,this.host="https://api.deepseek.com",this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=w.red.bold("[DeepSeek]"),this.deepSeek=new ir({baseURL:this.host,apiKey:this.params.config.key})}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a);this.checkAvailableModels();const d=await this.createChatCompletions(m);return i&&j("DeepSeek",o,m,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,u,l)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e){return(await this.deepSeek.chat.completions.create({messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature},{timeout:this.params.config.timeout})).choices[0].message.content||""}}class so extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=w.red.bold("[Gemini]"),this.genAI=new os(this.params.config.key)}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,logging:s,locale:i,codeReviewPromptPath:c,generate:l,type:u,maxLength:p}=this.params.config,a=this.params.config.maxTokens,m={...D,locale:i,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:c},d=e==="review"?H(m):B(m),h={maxOutputTokens:a,temperature:this.params.config.temperature,topP:this.params.config.topP},E=(await this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:d,generationConfig:h,safetySettings:[{category:Re.HARM_CATEGORY_HATE_SPEECH,threshold:Oe.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Oe.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_HARASSMENT,threshold:Oe.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Oe.BLOCK_LOW_AND_ABOVE}]}).generateContent(`Here is the diff: ${o}`)).response.text();return s&&j("Gemini",o,d,E,e),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,u,l)}}class no extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=w.red.bold("[Groq]"),this.groq=new ss({apiKey:this.params.config.key})}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:l,generate:u,type:p,maxLength:a}=this.params.config,m=this.params.config.maxTokens,d={...D,locale:c,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?H(d):B(d),y=(await this.groq.chat.completions.create({messages:[{role:"system",content:h},{role:"user",content:`Here is the diff: ${o}`}],model:this.params.config.model,max_tokens:m,top_p:this.params.config.topP,temperature:l},{timeout:this.params.config.timeout})).choices[0].message.content||"";return i&&j("Groq",o,h,y,e),e==="review"?this.sanitizeResponse(y):this.parseMessage(y,p,u)}}class io extends G{constructor(e){super(e),this.params=e,this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:"https://huggingface.co","Referrer-Policy":"strict-origin-when-cross-origin"},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=w.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){await this.initialize();const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a),d=await this.getNewChat(m),g=await(await this.sendMessage(`Here is the diff: ${o}`,d.id)).completeResponsePromise();return await this.deleteConversation(d.id),i&&j("HuggingFace",o,m,g,e),e==="review"?this.sanitizeResponse(g):this.parseMessage(g,u,l)}async initialize(){const e=await this.getRemoteLlms(),o=e.find(r=>r.name?.toLowerCase()===this.params.config.model.toLowerCase());if(o){this.currentModel=o,this.currentModelId=o.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=await fetch("https://huggingface.co/chat/__data.json",{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(e.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${e.status}`);const r=(await e.json()).nodes[0].data,n=r[r[0].models],s=[],i=c=>c===-1?null:r[c];for(const c of n){const l=r[c];if(r[l.unlisted])continue;const u={id:i(l.id),name:i(l.name),displayName:i(l.displayName),preprompt:i(l.preprompt),promptExamples:[],websiteUrl:i(l.websiteUrl),description:i(l.description),datasetName:i(l.datasetName),datasetUrl:i(l.datasetUrl),modelUrl:i(l.modelUrl),parameters:{}},p=i(l.promptExamples);if(p!==null){const d=p.map(h=>i(h));u.promptExamples=d.map(h=>({title:r[h.title],prompt:r[h.prompt]}))}const a=i(l.parameters),m={};for(const[d,h]of Object.entries(a)){if(h===-1){m[d]=null;continue}if(Array.isArray(r[h])){m[d]=r[h].map(g=>r[g]);continue}m[d]=r[h]}u.parameters=m,s.push(u)}return this.models=s,s}async getNewChat(e){const o={model:this.currentModelId,preprompt:e};let r=0;for(;r<5;){const n=await fetch("https://huggingface.co/chat/conversation",{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:JSON.stringify(o),method:"POST"}),{conversationId:s}=await n.json();if(s){this.currentConversionID=s;break}else r++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const o=await fetch("https://huggingface.co/chat/conversation/"+e+"/__data.json",{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const r=await o.json();return this.metadataParser(r,e)}}metadataParser(e,o){const r={id:"",model:"",systemPrompt:"",title:"",history:[]},n=e.nodes[1].data,s=n[n[0].model],i=n[n[0].preprompt],c=n[n[0].title],l=n[n[0].messages],u=[];for(const p of l){const a=n[p],m=new Date(n[a.createdAt][1]).getTime()/1e3,d=new Date(n[a.updatedAt][1]).getTime()/1e3;u.push({id:n[a.id],role:n[a.from],content:n[a.content],createdAt:m,updatedAt:d})}return r.id=o,r.model=s,r.systemPrompt=i,r.title=c,r.history=u,this.currentConversation=r,r}async sendMessage(e,o){if(e==="")throw new Error("the prompt can not be empty.");if(!o&&!this.currentConversionID?await this.getNewChat():o?(this.currentConversionID=o,await this.getConversationHistory(o)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const r={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},n=new FormData;n.append("data",JSON.stringify(r));const s=await fetch("https://huggingface.co/chat/conversation/"+this.currentConversionID,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/conversation/"+this.currentConversionID},body:n,method:"POST"});function i(m){try{const d=m.split(`
71
- `),h=[];for(const g of d)g.trim()&&h.push(JSON.parse(g));return h}catch{return[{}]}}const c=new TextDecoder;let l="";const u=new TransformStream({async transform(m,d){const h=c.decode(m);try{const g=i(h);for(const y of g)y.type==="finalAnswer"?(l=y?.text||"",d.terminate()):y.type==="stream"&&d.enqueue(y?.token||"")}catch{throw new Error("Error during parsing response")}}}),p=s.body?.pipeThrough(u);async function a(){return new Promise(async(m,d)=>{try{if(!p)d("ModifiedStream undefined");else{const h=p.getReader();for(;;){const{done:g,value:y}=await h.read();if(g){m(l);break}}}}catch(h){d(h)}})}return{id:this.currentConversionID,stream:p,completeResponsePromise:a}}async deleteConversation(e){return(await fetch(`https://huggingface.co/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"DELETE"})).json()}}class ao extends G{constructor(e){super(e),this.params=e,this.host="https://api.mistral.ai",this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=w.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a);await this.checkAvailableModels();const d=await this.createChatCompletions(m,`Here is the diff: ${o}`);return i&&j("MistralAI",o,m,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,u,l)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){return(await new Ce({method:"GET",baseURL:`${this.host}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,o){const n=(await new Ce({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:o}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ue(10,1e3)}).execute()).data;if(!n.choices||n.choices.length===0||!n.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return n.choices[0].message.content}}class co extends G{constructor(e){super(e),this.params=e,this.host=St,this.model="",this.key="",this.auth="",this.setupFetch=(o,r={})=>is(o,{...r,dispatcher:new as({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${He(this.model)}]`),this.errorPrefix=w.red.bold(`[${He(this.model)}]`),this.host=this.params.config.host||St,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new ns({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a);await this.checkIsAvailableOllama();const d=await this.createChatCompletions(m,`Here is the diff: ${o}`);return i&&j(`Ollama_${this.model}`,o,m,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,u,l)}async checkIsAvailableOllama(){const e=new Ce({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,o){const r=this.params.config.stream||!1,n=await this.ollama.chat({model:this.model,messages:[{role:"system",content:e},{role:"user",content:o}],stream:r,keep_alive:this.params.config.timeout,options:{num_ctx:this.params.config.numCtx,temperature:this.params.config.temperature,top_p:this.params.config.topP,seed:Ue(10,1e3)}});if(r){let s="";if(n)for await(const i of n)s+=i.message.content;return s}return n.message.content}}class lo extends G{constructor(e){super(e),this.params=e;const o=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=zi(o),this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${He(o)}]`),this.errorPrefix=w.red.bold(`[${He(o)}]`),this.openAI=new ir({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:l,generate:u,type:p,maxLength:a,timeout:m,stream:d=!1}=this.params.config,h=this.params.config.maxTokens,g={...D,locale:c,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?H(g):B(g),v=await this.openAI.chat.completions.create({messages:[{role:"system",content:y},{role:"user",content:`Here is the diff: ${o}`}],model:this.params.config.model,stream:d,max_tokens:h,top_p:this.params.config.topP,temperature:l},{timeout:m});let E="";if(d&&v){const N=v;for await(const K of N){const W=K.choices?.[0]?.delta?.content||"",fe=K.choices?.[0]?.delta?.reasoning_content||"",V=`${W}${fe}`;E+=V}}else E=v.choices?.[0]?.message.content||"";return i&&j(this.params.keyName,o,y,E,e),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,p,u)}}var kt={},It={exports:{}},Pe={exports:{}},Rt,mo;function ma(){if(mo)return Rt;mo=1;var t=1e3,e=t*60,o=e*60,r=o*24,n=r*7,s=r*365.25;Rt=function(p,a){a=a||{};var m=typeof p;if(m==="string"&&p.length>0)return i(p);if(m==="number"&&isFinite(p))return a.long?l(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function i(p){if(p=String(p),!(p.length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(a){var m=parseFloat(a[1]),d=(a[2]||"ms").toLowerCase();switch(d){case"years":case"year":case"yrs":case"yr":case"y":return m*s;case"weeks":case"week":case"w":return m*n;case"days":case"day":case"d":return m*r;case"hours":case"hour":case"hrs":case"hr":case"h":return m*o;case"minutes":case"minute":case"mins":case"min":case"m":return m*e;case"seconds":case"second":case"secs":case"sec":case"s":return m*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return m;default:return}}}}function c(p){var a=Math.abs(p);return a>=r?Math.round(p/r)+"d":a>=o?Math.round(p/o)+"h":a>=e?Math.round(p/e)+"m":a>=t?Math.round(p/t)+"s":p+"ms"}function l(p){var a=Math.abs(p);return a>=r?u(p,a,r,"day"):a>=o?u(p,a,o,"hour"):a>=e?u(p,a,e,"minute"):a>=t?u(p,a,t,"second"):p+" ms"}function u(p,a,m,d){var h=a>=m*1.5;return Math.round(p/m)+" "+d+(h?"s":"")}return Rt}var Ot,uo;function po(){if(uo)return Ot;uo=1;function t(e){r.debug=r,r.default=r,r.coerce=u,r.disable=c,r.enable=s,r.enabled=l,r.humanize=ma(),r.destroy=p,Object.keys(e).forEach(a=>{r[a]=e[a]}),r.names=[],r.skips=[],r.formatters={};function o(a){let m=0;for(let d=0;d<a.length;d++)m=(m<<5)-m+a.charCodeAt(d),m|=0;return r.colors[Math.abs(m)%r.colors.length]}r.selectColor=o;function r(a){let m,d=null,h,g;function y(...v){if(!y.enabled)return;const E=y,N=Number(new Date),K=N-(m||N);E.diff=K,E.prev=m,E.curr=N,m=N,v[0]=r.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let W=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(V,jo)=>{if(V==="%%")return"%";W++;const Yt=r.formatters[jo];if(typeof Yt=="function"){const Bo=v[W];V=Yt.call(E,Bo),v.splice(W,1),W--}return V}),r.formatArgs.call(E,v),(E.log||r.log).apply(E,v)}return y.namespace=a,y.useColors=r.useColors(),y.color=r.selectColor(a),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==r.namespaces&&(h=r.namespaces,g=r.enabled(a)),g),set:v=>{d=v}}),typeof r.init=="function"&&r.init(y),y}function n(a,m){const d=r(this.namespace+(typeof m>"u"?":":m)+a);return d.log=this.log,d}function s(a){r.save(a),r.namespaces=a,r.names=[],r.skips=[];const m=(typeof a=="string"?a:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const d of m)d[0]==="-"?r.skips.push(d.slice(1)):r.names.push(d)}function i(a,m){let d=0,h=0,g=-1,y=0;for(;d<a.length;)if(h<m.length&&(m[h]===a[d]||m[h]==="*"))m[h]==="*"?(g=h,y=d,h++):(d++,h++);else if(g!==-1)h=g+1,y++,d=y;else return!1;for(;h<m.length&&m[h]==="*";)h++;return h===m.length}function c(){const a=[...r.names,...r.skips.map(m=>"-"+m)].join(",");return r.enable(""),a}function l(a){for(const m of r.skips)if(i(a,m))return!1;for(const m of r.names)if(i(a,m))return!0;return!1}function u(a){return a instanceof Error?a.stack||a.message:a}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}return Ot=t,Ot}Pe.exports;var fo;function ua(){return fo||(fo=1,function(t,e){e.formatArgs=r,e.save=n,e.load=s,e.useColors=o,e.storage=i(),e.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function o(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const u="color: "+this.color;l.splice(1,0,u,"color: inherit");let p=0,a=0;l[0].replace(/%[a-zA-Z%]/g,m=>{m!=="%%"&&(p++,m==="%c"&&(a=p))}),l.splice(a,0,u)}e.log=console.debug||console.log||(()=>{});function n(l){try{l?e.storage.setItem("debug",l):e.storage.removeItem("debug")}catch{}}function s(){let l;try{l=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l=process.env.DEBUG),l}function i(){try{return localStorage}catch{}}t.exports=po()(e);const{formatters:c}=t.exports;c.j=function(l){try{return JSON.stringify(l)}catch(u){return"[UnexpectedJSONParseError]: "+u.message}}}(Pe,Pe.exports)),Pe.exports}var $e={exports:{}},Lt,ho;function pa(){return ho||(ho=1,Lt=(t,e=process.argv)=>{const o=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(o+t),n=e.indexOf("--");return r!==-1&&(n===-1||r<n)}),Lt}var Tt,go;function fa(){if(go)return Tt;go=1;const t=Ie,e=ar,o=pa(),{env:r}=process;let n;o("no-color")||o("no-colors")||o("color=false")||o("color=never")?n=0:(o("color")||o("colors")||o("color=true")||o("color=always"))&&(n=1),"FORCE_COLOR"in r&&(r.FORCE_COLOR==="true"?n=1:r.FORCE_COLOR==="false"?n=0:n=r.FORCE_COLOR.length===0?1:Math.min(parseInt(r.FORCE_COLOR,10),3));function s(l){return l===0?!1:{level:l,hasBasic:!0,has256:l>=2,has16m:l>=3}}function i(l,u){if(n===0)return 0;if(o("color=16m")||o("color=full")||o("color=truecolor"))return 3;if(o("color=256"))return 2;if(l&&!u&&n===void 0)return 0;const p=n||0;if(r.TERM==="dumb")return p;if(process.platform==="win32"){const a=t.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(a=>a in r)||r.CI_NAME==="codeship"?1:p;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if(r.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in r){const a=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:p}function c(l){const u=i(l,l&&l.isTTY);return s(u)}return Tt={supportsColor:c,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},Tt}$e.exports;var yo;function da(){return yo||(yo=1,function(t,e){const o=ar,r=er;e.init=p,e.log=c,e.formatArgs=s,e.save=l,e.load=u,e.useColors=n,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const m=fa();m&&(m.stderr||m).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(m=>/^debug_/i.test(m)).reduce((m,d)=>{const h=d.substring(6).toLowerCase().replace(/_([a-z])/g,(y,v)=>v.toUpperCase());let g=process.env[d];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),m[h]=g,m},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:o.isatty(process.stderr.fd)}function s(m){const{namespace:d,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),v=` ${y};1m${d} \x1B[0m`;m[0]=v+m[0].split(`
70
+ Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return r;try{const n=_.readFileSync(ze(e),"utf-8");return`${Jr(n,t)}`}catch{return r}},Zr=async t=>{if(t.systemPromptPath)try{_.readFileSync(ze(t.systemPromptPath),"utf-8")}catch(e){throw new C(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{_.readFileSync(ze(t.codeReviewPromptPath),"utf-8")}catch(e){throw new C(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},ca=10*60*1e3;class eo extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=w.red.bold("[Anthropic]"),this.anthropic=new Zo({apiKey:this.params.config.key,...this.params.config.timeout>ca&&{timeout:this.params.config.timeout}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:l,generate:u,type:p,maxLength:a,maxTokens:m,topP:d,model:h}=this.params.config,g={...D,locale:l,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?H(g):B(g),v={max_tokens:m,temperature:c,system:y,messages:[{role:"user",content:`Here is the diff: ${o}`}],top_p:d,model:h},N=(await this.anthropic.messages.create(v)).content.map(({text:K})=>K).join("");return i&&j("Anthropic",o,y,N,e),e==="review"?this.sanitizeResponse(N):this.parseMessage(N,p,u)}}class Ce{constructor(e={}){if(!e.method)throw new Error("method should be defined!");if(!e.baseURL)throw new Error("baseURL should be defined!");this.config={...e},this.axiosInstance=ts.create(this.config)}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}addBody(e){return this.config.data={...this.config.data,...e},this}setMethod(e){return this.config.method=e,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(e){throw e}}}class to extends G{constructor(e){super(e),this.params=e,this.host="https://codestral.mistral.ai",this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=w.red.bold("[Codestral]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a);this.checkAvailableModels();const d=await this.createChatCompletions(m,e);return i&&j("Codestral",o,m,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,u,l)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,o){const r=new Ce({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ue(10,1e3)});o==="commit"&&r.addBody({response_format:{type:"json_object"}});const s=(await r.execute()).data;if(!s.choices||s.choices.length===0||!s.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return s.choices[0].message.content}}const la=2*60*1e3;class ro extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=w.red.bold("[Cohere]"),this.cohere=new rs({token:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:l,generate:u,type:p,maxLength:a,maxTokens:m}=this.params.config,d={...D,locale:l,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?H(d):B(d),g=await this.cohere.chat({chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:`Here is the diff: ${o}`,connectors:[{id:"web-search"}],maxTokens:m,temperature:c,model:this.params.config.model,seed:Ue(10,1e3),p:this.params.config.topP},{...this.params.config.timeout>la&&{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}});return i&&j("Cohere",o,h,g.text,e),e==="review"?this.sanitizeResponse(g.text):this.parseMessage(g.text,p,u)}}class oo extends G{constructor(e){super(e),this.params=e,this.host="https://api.deepseek.com",this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=w.red.bold("[DeepSeek]"),this.deepSeek=new ir({baseURL:this.host,apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a);this.checkAvailableModels();const d=await this.createChatCompletions(m);return i&&j("DeepSeek",o,m,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,u,l)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e){return(await this.deepSeek.chat.completions.create({messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature},{timeout:this.params.config.timeout})).choices[0].message.content||""}}class so extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=w.red.bold("[Gemini]"),this.genAI=new os(this.params.config.key)}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,logging:s,locale:i,codeReviewPromptPath:c,generate:l,type:u,maxLength:p}=this.params.config,a=this.params.config.maxTokens,m={...D,locale:i,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:c},d=e==="review"?H(m):B(m),h={maxOutputTokens:a,temperature:this.params.config.temperature,topP:this.params.config.topP},E=(await this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:d,generationConfig:h,safetySettings:[{category:Re.HARM_CATEGORY_HATE_SPEECH,threshold:Oe.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Oe.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_HARASSMENT,threshold:Oe.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Oe.BLOCK_LOW_AND_ABOVE}]}).generateContent(`Here is the diff: ${o}`)).response.text();return s&&j("Gemini",o,d,E,e),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,u,l)}}class no extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=w.red.bold("[Groq]"),this.groq=new ss({apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:l,generate:u,type:p,maxLength:a}=this.params.config,m=this.params.config.maxTokens,d={...D,locale:c,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?H(d):B(d),y=(await this.groq.chat.completions.create({messages:[{role:"system",content:h},{role:"user",content:`Here is the diff: ${o}`}],model:this.params.config.model,max_tokens:m,top_p:this.params.config.topP,temperature:l},{timeout:this.params.config.timeout})).choices[0].message.content||"";return i&&j("Groq",o,h,y,e),e==="review"?this.sanitizeResponse(y):this.parseMessage(y,p,u)}}class io extends G{constructor(e){super(e),this.params=e,this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:"https://huggingface.co","Referrer-Policy":"strict-origin-when-cross-origin"},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=w.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){await this.initialize();const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a),d=await this.getNewChat(m),g=await(await this.sendMessage(`Here is the diff: ${o}`,d.id)).completeResponsePromise();return await this.deleteConversation(d.id),i&&j("HuggingFace",o,m,g,e),e==="review"?this.sanitizeResponse(g):this.parseMessage(g,u,l)}async initialize(){const e=await this.getRemoteLlms(),o=e.find(r=>r.name?.toLowerCase()===this.params.config.model.toLowerCase());if(o){this.currentModel=o,this.currentModelId=o.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=await fetch("https://huggingface.co/chat/__data.json",{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(e.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${e.status}`);const r=(await e.json()).nodes[0].data,n=r[r[0].models],s=[],i=c=>c===-1?null:r[c];for(const c of n){const l=r[c];if(r[l.unlisted])continue;const u={id:i(l.id),name:i(l.name),displayName:i(l.displayName),preprompt:i(l.preprompt),promptExamples:[],websiteUrl:i(l.websiteUrl),description:i(l.description),datasetName:i(l.datasetName),datasetUrl:i(l.datasetUrl),modelUrl:i(l.modelUrl),parameters:{}},p=i(l.promptExamples);if(p!==null){const d=p.map(h=>i(h));u.promptExamples=d.map(h=>({title:r[h.title],prompt:r[h.prompt]}))}const a=i(l.parameters),m={};for(const[d,h]of Object.entries(a)){if(h===-1){m[d]=null;continue}if(Array.isArray(r[h])){m[d]=r[h].map(g=>r[g]);continue}m[d]=r[h]}u.parameters=m,s.push(u)}return this.models=s,s}async getNewChat(e){const o={model:this.currentModelId,preprompt:e};let r=0;for(;r<5;){const n=await fetch("https://huggingface.co/chat/conversation",{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:JSON.stringify(o),method:"POST"}),{conversationId:s}=await n.json();if(s){this.currentConversionID=s;break}else r++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const o=await fetch("https://huggingface.co/chat/conversation/"+e+"/__data.json",{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const r=await o.json();return this.metadataParser(r,e)}}metadataParser(e,o){const r={id:"",model:"",systemPrompt:"",title:"",history:[]},n=e.nodes[1].data,s=n[n[0].model],i=n[n[0].preprompt],c=n[n[0].title],l=n[n[0].messages],u=[];for(const p of l){const a=n[p],m=new Date(n[a.createdAt][1]).getTime()/1e3,d=new Date(n[a.updatedAt][1]).getTime()/1e3;u.push({id:n[a.id],role:n[a.from],content:n[a.content],createdAt:m,updatedAt:d})}return r.id=o,r.model=s,r.systemPrompt=i,r.title=c,r.history=u,this.currentConversation=r,r}async sendMessage(e,o){if(e==="")throw new Error("the prompt can not be empty.");if(!o&&!this.currentConversionID?await this.getNewChat():o?(this.currentConversionID=o,await this.getConversationHistory(o)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const r={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},n=new FormData;n.append("data",JSON.stringify(r));const s=await fetch("https://huggingface.co/chat/conversation/"+this.currentConversionID,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/conversation/"+this.currentConversionID},body:n,method:"POST"});function i(m){try{const d=m.split(`
71
+ `),h=[];for(const g of d)g.trim()&&h.push(JSON.parse(g));return h}catch{return[{}]}}const c=new TextDecoder;let l="";const u=new TransformStream({async transform(m,d){const h=c.decode(m);try{const g=i(h);for(const y of g)y.type==="finalAnswer"?(l=y?.text||"",d.terminate()):y.type==="stream"&&d.enqueue(y?.token||"")}catch{throw new Error("Error during parsing response")}}}),p=s.body?.pipeThrough(u);async function a(){return new Promise(async(m,d)=>{try{if(!p)d("ModifiedStream undefined");else{const h=p.getReader();for(;;){const{done:g,value:y}=await h.read();if(g){m(l);break}}}}catch(h){d(h)}})}return{id:this.currentConversionID,stream:p,completeResponsePromise:a}}async deleteConversation(e){return(await fetch(`https://huggingface.co/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"DELETE"})).json()}}class ao extends G{constructor(e){super(e),this.params=e,this.host="https://api.mistral.ai",this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=w.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a);await this.checkAvailableModels();const d=await this.createChatCompletions(m,`Here is the diff: ${o}`);return i&&j("MistralAI",o,m,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,u,l)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){return(await new Ce({method:"GET",baseURL:`${this.host}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,o){const n=(await new Ce({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:o}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ue(10,1e3)}).execute()).data;if(!n.choices||n.choices.length===0||!n.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return n.choices[0].message.content}}class co extends G{constructor(e){super(e),this.params=e,this.host=St,this.model="",this.key="",this.auth="",this.setupFetch=(o,r={})=>is(o,{...r,dispatcher:new as({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${He(this.model)}]`),this.errorPrefix=w.red.bold(`[${He(this.model)}]`),this.host=this.params.config.host||St,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new ns({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a);await this.checkIsAvailableOllama();const d=await this.createChatCompletions(m,`Here is the diff: ${o}`);return i&&j(`Ollama_${this.model}`,o,m,d,e),e==="review"?this.sanitizeResponse(d):this.parseMessage(d,u,l)}async checkIsAvailableOllama(){const e=new Ce({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,o){const{stream:r,numCtx:n,temperature:s,topP:i,timeout:c,maxTokens:l}=this.params.config,u=r||!1,p=await this.ollama.chat({model:this.model,messages:[{role:"system",content:e},{role:"user",content:o}],stream:u,keep_alive:c,options:{num_ctx:n,temperature:s,top_p:i,seed:Ue(10,1e3),num_predict:l??-1}});if(u){let a="";if(p)for await(const m of p)a+=m.message.content;return a}return p.message.content}}class lo extends G{constructor(e){super(e),this.params=e;const o=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=zi(o),this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${He(o)}]`),this.errorPrefix=w.red.bold(`[${He(o)}]`),this.openAI=new ir({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:l,generate:u,type:p,maxLength:a,timeout:m,stream:d=!1}=this.params.config,h=this.params.config.maxTokens,g={...D,locale:c,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?H(g):B(g),v=await this.openAI.chat.completions.create({messages:[{role:"system",content:y},{role:"user",content:`Here is the diff: ${o}`}],model:this.params.config.model,stream:d,max_tokens:h,top_p:this.params.config.topP,temperature:l},{timeout:m});let E="";if(d&&v){const N=v;for await(const K of N){const W=K.choices?.[0]?.delta?.content||"",fe=K.choices?.[0]?.delta?.reasoning_content||"",V=`${W}${fe}`;E+=V}}else E=v.choices?.[0]?.message.content||"";return i&&j(this.params.keyName,o,y,E,e),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,p,u)}}var Mt={},It={exports:{}},Pe={exports:{}},Rt,mo;function ma(){if(mo)return Rt;mo=1;var t=1e3,e=t*60,o=e*60,r=o*24,n=r*7,s=r*365.25;Rt=function(p,a){a=a||{};var m=typeof p;if(m==="string"&&p.length>0)return i(p);if(m==="number"&&isFinite(p))return a.long?l(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function i(p){if(p=String(p),!(p.length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(a){var m=parseFloat(a[1]),d=(a[2]||"ms").toLowerCase();switch(d){case"years":case"year":case"yrs":case"yr":case"y":return m*s;case"weeks":case"week":case"w":return m*n;case"days":case"day":case"d":return m*r;case"hours":case"hour":case"hrs":case"hr":case"h":return m*o;case"minutes":case"minute":case"mins":case"min":case"m":return m*e;case"seconds":case"second":case"secs":case"sec":case"s":return m*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return m;default:return}}}}function c(p){var a=Math.abs(p);return a>=r?Math.round(p/r)+"d":a>=o?Math.round(p/o)+"h":a>=e?Math.round(p/e)+"m":a>=t?Math.round(p/t)+"s":p+"ms"}function l(p){var a=Math.abs(p);return a>=r?u(p,a,r,"day"):a>=o?u(p,a,o,"hour"):a>=e?u(p,a,e,"minute"):a>=t?u(p,a,t,"second"):p+" ms"}function u(p,a,m,d){var h=a>=m*1.5;return Math.round(p/m)+" "+d+(h?"s":"")}return Rt}var Ot,uo;function po(){if(uo)return Ot;uo=1;function t(e){r.debug=r,r.default=r,r.coerce=u,r.disable=c,r.enable=s,r.enabled=l,r.humanize=ma(),r.destroy=p,Object.keys(e).forEach(a=>{r[a]=e[a]}),r.names=[],r.skips=[],r.formatters={};function o(a){let m=0;for(let d=0;d<a.length;d++)m=(m<<5)-m+a.charCodeAt(d),m|=0;return r.colors[Math.abs(m)%r.colors.length]}r.selectColor=o;function r(a){let m,d=null,h,g;function y(...v){if(!y.enabled)return;const E=y,N=Number(new Date),K=N-(m||N);E.diff=K,E.prev=m,E.curr=N,m=N,v[0]=r.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let W=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(V,jo)=>{if(V==="%%")return"%";W++;const Yt=r.formatters[jo];if(typeof Yt=="function"){const Bo=v[W];V=Yt.call(E,Bo),v.splice(W,1),W--}return V}),r.formatArgs.call(E,v),(E.log||r.log).apply(E,v)}return y.namespace=a,y.useColors=r.useColors(),y.color=r.selectColor(a),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==r.namespaces&&(h=r.namespaces,g=r.enabled(a)),g),set:v=>{d=v}}),typeof r.init=="function"&&r.init(y),y}function n(a,m){const d=r(this.namespace+(typeof m>"u"?":":m)+a);return d.log=this.log,d}function s(a){r.save(a),r.namespaces=a,r.names=[],r.skips=[];const m=(typeof a=="string"?a:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const d of m)d[0]==="-"?r.skips.push(d.slice(1)):r.names.push(d)}function i(a,m){let d=0,h=0,g=-1,y=0;for(;d<a.length;)if(h<m.length&&(m[h]===a[d]||m[h]==="*"))m[h]==="*"?(g=h,y=d,h++):(d++,h++);else if(g!==-1)h=g+1,y++,d=y;else return!1;for(;h<m.length&&m[h]==="*";)h++;return h===m.length}function c(){const a=[...r.names,...r.skips.map(m=>"-"+m)].join(",");return r.enable(""),a}function l(a){for(const m of r.skips)if(i(a,m))return!1;for(const m of r.names)if(i(a,m))return!0;return!1}function u(a){return a instanceof Error?a.stack||a.message:a}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}return Ot=t,Ot}Pe.exports;var fo;function ua(){return fo||(fo=1,function(t,e){e.formatArgs=r,e.save=n,e.load=s,e.useColors=o,e.storage=i(),e.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function o(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const u="color: "+this.color;l.splice(1,0,u,"color: inherit");let p=0,a=0;l[0].replace(/%[a-zA-Z%]/g,m=>{m!=="%%"&&(p++,m==="%c"&&(a=p))}),l.splice(a,0,u)}e.log=console.debug||console.log||(()=>{});function n(l){try{l?e.storage.setItem("debug",l):e.storage.removeItem("debug")}catch{}}function s(){let l;try{l=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l=process.env.DEBUG),l}function i(){try{return localStorage}catch{}}t.exports=po()(e);const{formatters:c}=t.exports;c.j=function(l){try{return JSON.stringify(l)}catch(u){return"[UnexpectedJSONParseError]: "+u.message}}}(Pe,Pe.exports)),Pe.exports}var $e={exports:{}},Lt,ho;function pa(){return ho||(ho=1,Lt=(t,e=process.argv)=>{const o=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(o+t),n=e.indexOf("--");return r!==-1&&(n===-1||r<n)}),Lt}var Tt,go;function fa(){if(go)return Tt;go=1;const t=Ie,e=ar,o=pa(),{env:r}=process;let n;o("no-color")||o("no-colors")||o("color=false")||o("color=never")?n=0:(o("color")||o("colors")||o("color=true")||o("color=always"))&&(n=1),"FORCE_COLOR"in r&&(r.FORCE_COLOR==="true"?n=1:r.FORCE_COLOR==="false"?n=0:n=r.FORCE_COLOR.length===0?1:Math.min(parseInt(r.FORCE_COLOR,10),3));function s(l){return l===0?!1:{level:l,hasBasic:!0,has256:l>=2,has16m:l>=3}}function i(l,u){if(n===0)return 0;if(o("color=16m")||o("color=full")||o("color=truecolor"))return 3;if(o("color=256"))return 2;if(l&&!u&&n===void 0)return 0;const p=n||0;if(r.TERM==="dumb")return p;if(process.platform==="win32"){const a=t.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(a=>a in r)||r.CI_NAME==="codeship"?1:p;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if(r.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in r){const a=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:p}function c(l){const u=i(l,l&&l.isTTY);return s(u)}return Tt={supportsColor:c,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},Tt}$e.exports;var yo;function da(){return yo||(yo=1,function(t,e){const o=ar,r=er;e.init=p,e.log=c,e.formatArgs=s,e.save=l,e.load=u,e.useColors=n,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const m=fa();m&&(m.stderr||m).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(m=>/^debug_/i.test(m)).reduce((m,d)=>{const h=d.substring(6).toLowerCase().replace(/_([a-z])/g,(y,v)=>v.toUpperCase());let g=process.env[d];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),m[h]=g,m},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:o.isatty(process.stderr.fd)}function s(m){const{namespace:d,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),v=` ${y};1m${d} \x1B[0m`;m[0]=v+m[0].split(`
72
72
  `).join(`
73
73
  `+v),m.push(y+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else m[0]=i()+d+" "+m[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function c(...m){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...m)+`
74
74
  `)}function l(m){m?process.env.DEBUG=m:delete process.env.DEBUG}function u(){return process.env.DEBUG}function p(m){m.inspectOpts={};const d=Object.keys(e.inspectOpts);for(let h=0;h<d.length;h++)m.inspectOpts[d[h]]=e.inspectOpts[d[h]]}t.exports=po()(e);const{formatters:a}=t.exports;a.o=function(m){return this.inspectOpts.colors=this.useColors,r.inspect(m,this.inspectOpts).split(`
@@ -76,14 +76,14 @@ Please structure your response with appropriate Markdown headings, code blocks,
76
76
  `).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function Xe(t,e){return new Xe.Agent(t,e)}(function(t){class e extends ga.EventEmitter{constructor(r,n){super();let s=n;typeof r=="function"?this.callback=r:r&&(s=r),this.timeout=null,s&&typeof s.timeout=="number"&&(this.timeout=s.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:Ft()?443:80}set defaultPort(r){this.explicitDefaultPort=r}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:Ft()?"https:":"http:"}set protocol(r){this.explicitProtocol=r}callback(r,n,s){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(r,n){const s=Object.assign({},n);typeof s.secureEndpoint!="boolean"&&(s.secureEndpoint=Ft()),s.host==null&&(s.host="localhost"),s.port==null&&(s.port=s.secureEndpoint?443:80),s.protocol==null&&(s.protocol=s.secureEndpoint?"https:":"http:"),s.host&&s.path&&delete s.path,delete s.agent,delete s.hostname,delete s._defaultAgent,delete s.defaultPort,delete s.createConnection,r._last=!0,r.shouldKeepAlive=!1;let i=!1,c=null;const l=s.timeout||this.timeout,u=d=>{r._hadError||(r.emit("error",d),r._hadError=!0)},p=()=>{c=null,i=!0;const d=new Error(`A "socket" was not created for HTTP request before ${l}ms`);d.code="ETIMEOUT",u(d)},a=d=>{i||(c!==null&&(clearTimeout(c),c=null),u(d))},m=d=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),va(d)){Ee("Callback returned another Agent instance %o",d.constructor.name),d.addRequest(r,s);return}if(d){d.once("free",()=>{this.freeSocket(d,s)}),r.onSocket(d);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${r.method} ${r.path}\``);u(h)};if(typeof this.callback!="function"){u(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(Ee("Converting legacy callback function to promise"),this.promisifiedCallback=wa.default(this.callback)):this.promisifiedCallback=this.callback),typeof l=="number"&&l>0&&(c=setTimeout(p,l)),"port"in s&&typeof s.port!="number"&&(s.port=Number(s.port));try{Ee("Resolving socket for %o request: %o",s.protocol,`${r.method} ${r.path}`),Promise.resolve(this.promisifiedCallback(r,s)).then(m,a)}catch(d){Promise.reject(d).catch(a)}}freeSocket(r,n){Ee("Freeing socket %o %o",r.constructor.name,n),r.destroy()}destroy(){Ee("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(Xe||(Xe={}));var ba=Xe,Dt={},Ca=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Dt,"__esModule",{value:!0});const Pa=Ca(Nt),xe=Pa.default("https-proxy-agent:parse-proxy-response");function $a(t){return new Promise((e,o)=>{let r=0;const n=[];function s(){const a=t.read();a?p(a):t.once("readable",s)}function i(){t.removeListener("end",l),t.removeListener("error",u),t.removeListener("close",c),t.removeListener("readable",s)}function c(a){xe("onclose had error %o",a)}function l(){xe("onend")}function u(a){i(),xe("onerror %o",a),o(a)}function p(a){n.push(a),r+=a.length;const m=Buffer.concat(n,r);if(m.indexOf(`\r
77
77
  \r
78
78
  `)===-1){xe("have not received end of HTTP headers yet..."),s();return}const h=m.toString("ascii",0,m.indexOf(`\r
79
- `)),g=+h.split(" ")[1];xe("got proxy server response: %o",h),e({statusCode:g,buffered:m})}t.on("error",u),t.on("close",c),t.on("end",l),s()})}Dt.default=$a;var Ea=O&&O.__awaiter||function(t,e,o,r){function n(s){return s instanceof o?s:new o(function(i){i(s)})}return new(o||(o=Promise))(function(s,i){function c(p){try{u(r.next(p))}catch(a){i(a)}}function l(p){try{u(r.throw(p))}catch(a){i(a)}}function u(p){p.done?s(p.value):n(p.value).then(c,l)}u((r=r.apply(t,e||[])).next())})},pe=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(kt,"__esModule",{value:!0});const vo=pe(ms),bo=pe(us),xa=pe(ps),Aa=pe(Qt),Sa=pe(Nt),Ma=ba,ka=pe(Dt),Ae=Sa.default("https-proxy-agent:agent");class Ia extends Ma.Agent{constructor(e){let o;if(typeof e=="string"?o=xa.default.parse(e):o=e,!o)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ae("creating new HttpsProxyAgent instance: %o",o),super(o);const r=Object.assign({},o);this.secureProxy=o.secureProxy||La(r.protocol),r.host=r.hostname||r.host,typeof r.port=="string"&&(r.port=parseInt(r.port,10)),!r.port&&r.host&&(r.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in r)&&(r.ALPNProtocols=["http 1.1"]),r.host&&r.path&&(delete r.path,delete r.pathname),this.proxy=r}callback(e,o){return Ea(this,void 0,void 0,function*(){const{proxy:r,secureProxy:n}=this;let s;n?(Ae("Creating `tls.Socket`: %o",r),s=bo.default.connect(r)):(Ae("Creating `net.Socket`: %o",r),s=vo.default.connect(r));const i=Object.assign({},r.headers);let l=`CONNECT ${`${o.host}:${o.port}`} HTTP/1.1\r
79
+ `)),g=+h.split(" ")[1];xe("got proxy server response: %o",h),e({statusCode:g,buffered:m})}t.on("error",u),t.on("close",c),t.on("end",l),s()})}Dt.default=$a;var Ea=O&&O.__awaiter||function(t,e,o,r){function n(s){return s instanceof o?s:new o(function(i){i(s)})}return new(o||(o=Promise))(function(s,i){function c(p){try{u(r.next(p))}catch(a){i(a)}}function l(p){try{u(r.throw(p))}catch(a){i(a)}}function u(p){p.done?s(p.value):n(p.value).then(c,l)}u((r=r.apply(t,e||[])).next())})},pe=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Mt,"__esModule",{value:!0});const vo=pe(ms),bo=pe(us),xa=pe(ps),Aa=pe(Qt),Sa=pe(Nt),ka=ba,Ma=pe(Dt),Ae=Sa.default("https-proxy-agent:agent");class Ia extends ka.Agent{constructor(e){let o;if(typeof e=="string"?o=xa.default.parse(e):o=e,!o)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ae("creating new HttpsProxyAgent instance: %o",o),super(o);const r=Object.assign({},o);this.secureProxy=o.secureProxy||La(r.protocol),r.host=r.hostname||r.host,typeof r.port=="string"&&(r.port=parseInt(r.port,10)),!r.port&&r.host&&(r.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in r)&&(r.ALPNProtocols=["http 1.1"]),r.host&&r.path&&(delete r.path,delete r.pathname),this.proxy=r}callback(e,o){return Ea(this,void 0,void 0,function*(){const{proxy:r,secureProxy:n}=this;let s;n?(Ae("Creating `tls.Socket`: %o",r),s=bo.default.connect(r)):(Ae("Creating `net.Socket`: %o",r),s=vo.default.connect(r));const i=Object.assign({},r.headers);let l=`CONNECT ${`${o.host}:${o.port}`} HTTP/1.1\r
80
80
  `;r.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(r.auth).toString("base64")}`);let{host:u,port:p,secureEndpoint:a}=o;Oa(p,a)||(u+=`:${p}`),i.Host=u,i.Connection="close";for(const y of Object.keys(i))l+=`${y}: ${i[y]}\r
81
- `;const m=ka.default(s);s.write(`${l}\r
82
- `);const{statusCode:d,buffered:h}=yield m;if(d===200){if(e.once("socket",Ra),o.secureEndpoint){Ae("Upgrading socket connection to TLS");const y=o.servername||o.host;return bo.default.connect(Object.assign(Object.assign({},Ta(o,"host","hostname","path","port")),{socket:s,servername:y}))}return s}s.destroy();const g=new vo.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Ae("replaying proxy buffer for failed request"),Aa.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}kt.default=Ia;function Ra(t){t.resume()}function Oa(t,e){return!!(!e&&t===80||e&&t===443)}function La(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function Ta(t,...e){const o={};let r;for(r in t)e.includes(r)||(o[r]=t[r]);return o}var Na=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Gt=Na(kt);function jt(t){return new Gt.default(t)}(function(t){t.HttpsProxyAgent=Gt.default,t.prototype=Gt.default.prototype})(jt||(jt={}));var _a=jt,Fa=re(_a);const Da=async(t,e,o,r,n,s,i)=>new Promise((c,l)=>{const u=JSON.stringify(r),a=(t.protocol.includes("https")?ls:cs).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(u),...o},timeout:n,agent:s?Fa(s):void 0},m=>{const d=[];m.on("data",h=>d.push(h)),m.on("end",()=>{c({request:a,response:m,data:Buffer.concat(d).toString()})})});a.on("error",l),a.on("timeout",()=>{a.destroy(),l(new C(`Time out error: request took over ${n}ms. Try increasing the \`timeout\` config`))}),a.write(u),a.end()}),Ga=async(t,e,o,r,n,s)=>{const i=new URL(t),{response:c,data:l}=await Da(i,e,{Authorization:`Bearer ${o}`},r,n,s);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let u=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw l&&(u+=`
81
+ `;const m=Ma.default(s);s.write(`${l}\r
82
+ `);const{statusCode:d,buffered:h}=yield m;if(d===200){if(e.once("socket",Ra),o.secureEndpoint){Ae("Upgrading socket connection to TLS");const y=o.servername||o.host;return bo.default.connect(Object.assign(Object.assign({},Ta(o,"host","hostname","path","port")),{socket:s,servername:y}))}return s}s.destroy();const g=new vo.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Ae("replaying proxy buffer for failed request"),Aa.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}Mt.default=Ia;function Ra(t){t.resume()}function Oa(t,e){return!!(!e&&t===80||e&&t===443)}function La(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function Ta(t,...e){const o={};let r;for(r in t)e.includes(r)||(o[r]=t[r]);return o}var Na=O&&O.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Gt=Na(Mt);function jt(t){return new Gt.default(t)}(function(t){t.HttpsProxyAgent=Gt.default,t.prototype=Gt.default.prototype})(jt||(jt={}));var _a=jt,Fa=re(_a);const Da=async(t,e,o,r,n,s,i)=>new Promise((c,l)=>{const u=JSON.stringify(r),a=(t.protocol.includes("https")?ls:cs).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(u),...o},timeout:n,agent:s?Fa(s):void 0},m=>{const d=[];m.on("data",h=>d.push(h)),m.on("end",()=>{c({request:a,response:m,data:Buffer.concat(d).toString()})})});a.on("error",l),a.on("timeout",()=>{a.destroy(),l(new C(`Time out error: request took over ${n}ms. Try increasing the \`timeout\` config`))}),a.write(u),a.end()}),Ga=async(t,e,o,r,n,s)=>{const i=new URL(t),{response:c,data:l}=await Da(i,e,{Authorization:`Bearer ${o}`},r,n,s);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let u=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw l&&(u+=`
83
83
 
84
84
  ${l}`),c.statusCode===500&&(u+=`
85
85
 
86
- Check the API status: ${t}`),new C(u)}return JSON.parse(l)},Co=t=>t.trim(),ja=async(t,e,o,r,n,s,i,c,l,u,p,a,m,d)=>{try{const h={model:n,messages:[{role:"system",content:p},{role:"user",content:`Here is the diff: ${s}`}],temperature:l,max_tokens:c,stream:!1,n:1,top_p:u,frequency_penalty:0,presence_penalty:0},g=await Ga(e,o,r,h,i,d),y=g.choices.filter(v=>v.message?.content).map(v=>Co(v.message.content)).join();return a&&j(t,s,p,y,m),g.choices.filter(v=>v.message?.content).map(v=>Co(v.message.content))}catch(h){const g=h;throw g.code==="ENOTFOUND"?new C(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class Po extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=w.red.bold("[ChatGPT]")}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}extractJSONFromError(e){const o=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(o);return r?Object.assign({},...r.map(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,temperature:i,logging:c,locale:l,generate:u,type:p,maxLength:a,proxy:m,maxTokens:d,timeout:h}=this.params.config,g={...D,locale:l,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?H(g):B(g),v=await ja("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,o,h,d,i,this.params.config.topP,y,c,e,m);return qe(e==="review"?v.map(E=>this.sanitizeResponse(E)):v.map(E=>this.parseMessage(E,p,u)))}}class $o extends G{constructor(e){super(e),this.params=e,this.host="https://api.perplexity.ai",this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=w.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return k(this.generateMessage("commit")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(M(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}extractJSONFromError(e){const o=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(o);return r?Object.assign({},...r.map(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a),d=await this.createChatCompletions(m,o);return i&&j("Perplexity",o,m,d,e),this.parseMessage(d,u,l)}async createChatCompletions(e,o){const n=(await new Ce({method:"POST",baseURL:`${this.host}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:`${e}`},{role:"user",content:`Here is the diff: ${o}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1}).execute()).data;if(!n.choices||n.choices.length===0||!n.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return n.choices[0].message.content}}class Je{constructor(e,o){this.config=e,this.stagedDiff=o}createCommitMsgRequests$(e){return $(e).pipe(ke(o=>{const r=this.config[o],n=Array.isArray(r.model)?r.model:[r.model];return $(n).pipe(ke(s=>{if(r.compatible)return R.create(lo,{config:{...r,url:r.url||"",path:r.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();switch(o){case"OPENAI":return R.create(Po,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GEMINI":return R.create(so,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"ANTHROPIC":return R.create(eo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"HUGGINGFACE":return R.create(io,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"MISTRAL":return R.create(ao,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"CODESTRAL":return R.create(to,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"OLLAMA":return R.create(co,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCommitMessage$();case"COHERE":return R.create(ro,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GROQ":return R.create(no,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"PERPLEXITY":return R.create($o,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"DEEPSEEK":return R.create(oo,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();default:const i=w.red.bold(`[${o}]`);return de({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),S(o=>{const r=w.red.bold("[UNKNOWN]");return de({name:r+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return $(e).pipe(ke(o=>{const r=this.config[o],n=Array.isArray(r.model)?r.model:[r.model];return $(n).pipe(ke(s=>{if(r.compatible)return R.create(lo,{config:{...r,url:r.url||"",path:r.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();switch(o){case"OPENAI":return R.create(Po,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GEMINI":return R.create(so,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"ANTHROPIC":return R.create(eo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"HUGGINGFACE":return R.create(io,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"MISTRAL":return R.create(ao,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"CODESTRAL":return R.create(to,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"OLLAMA":return R.create(co,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCodeReview$();case"COHERE":return R.create(ro,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GROQ":return R.create(no,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"PERPLEXITY":return R.create($o,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"DEEPSEEK":return R.create(oo,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();default:const i=w.red.bold(`[${o}]`);return de({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),S(o=>{const r=w.red.bold("[UNKNOWN]");return de({name:r+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}const Bt=async()=>{const{stdout:t,failed:e}=await X("git",["rev-parse","--show-toplevel"],{reject:!1});if(e)throw new C("The current directory must be a Git repository!");return t},J=t=>`:(exclude)${t}`,Qe=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb","*.gif","*.png"].map(J),Ht=async(t,e)=>{const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:r}=await X("git",[...o,"--name-only",...Qe,...t?t.map(J):[],...e?e.map(J):[]]);if(!r)return null;const{stdout:n}=await X("git",[...o,...Qe,...t?t.map(J):[]]);return{files:r.split(`
86
+ Check the API status: ${t}`),new C(u)}return JSON.parse(l)},Co=t=>t.trim(),ja=async(t,e,o,r,n,s,i,c,l,u,p,a,m,d)=>{try{const h={model:n,messages:[{role:"system",content:p},{role:"user",content:`Here is the diff: ${s}`}],temperature:l,max_tokens:c,stream:!1,n:1,top_p:u,frequency_penalty:0,presence_penalty:0},g=await Ga(e,o,r,h,i,d),y=g.choices.filter(v=>v.message?.content).map(v=>Co(v.message.content)).join();return a&&j(t,s,p,y,m),g.choices.filter(v=>v.message?.content).map(v=>Co(v.message.content))}catch(h){const g=h;throw g.code==="ENOTFOUND"?new C(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class Po extends G{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=w.red.bold("[ChatGPT]")}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}extractJSONFromError(e){const o=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(o);return r?Object.assign({},...r.map(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,temperature:i,logging:c,locale:l,generate:u,type:p,maxLength:a,proxy:m,maxTokens:d,timeout:h}=this.params.config,g={...D,locale:l,maxLength:a,type:p,generate:u,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?H(g):B(g),v=await ja("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,o,h,d,i,this.params.config.topP,y,c,e,m);return qe(e==="review"?v.map(E=>this.sanitizeResponse(E)):v.map(E=>this.parseMessage(E,p,u)))}}class $o extends G{constructor(e){super(e),this.params=e,this.host="https://api.perplexity.ai",this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=w.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),S(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(k(e=>$(e)),A(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),S(this.handleError$))}extractJSONFromError(e){const o=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(o);return r?Object.assign({},...r.map(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const o=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:l,type:u,maxLength:p}=this.params.config,a={...D,locale:c,maxLength:p,type:u,generate:l,systemPrompt:r,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?H(a):B(a),d=await this.createChatCompletions(m,o);return i&&j("Perplexity",o,m,d,e),this.parseMessage(d,u,l)}async createChatCompletions(e,o){const n=(await new Ce({method:"POST",baseURL:`${this.host}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:`${e}`},{role:"user",content:`Here is the diff: ${o}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1}).execute()).data;if(!n.choices||n.choices.length===0||!n.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return n.choices[0].message.content}}class Je{constructor(e,o){this.config=e,this.stagedDiff=o}createCommitMsgRequests$(e){return $(e).pipe(Me(o=>{const r=this.config[o],n=Array.isArray(r.model)?r.model:[r.model];return $(n).pipe(Me(s=>{if(r.compatible)return R.create(lo,{config:{...r,url:r.url||"",path:r.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();switch(o){case"OPENAI":return R.create(Po,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GEMINI":return R.create(so,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"ANTHROPIC":return R.create(eo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"HUGGINGFACE":return R.create(io,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"MISTRAL":return R.create(ao,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"CODESTRAL":return R.create(to,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"OLLAMA":return R.create(co,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCommitMessage$();case"COHERE":return R.create(ro,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GROQ":return R.create(no,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"PERPLEXITY":return R.create($o,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"DEEPSEEK":return R.create(oo,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();default:const i=w.red.bold(`[${o}]`);return de({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),S(o=>{const r=w.red.bold("[UNKNOWN]");return de({name:r+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return $(e).pipe(Me(o=>{const r=this.config[o],n=Array.isArray(r.model)?r.model:[r.model];return $(n).pipe(Me(s=>{if(r.compatible)return R.create(lo,{config:{...r,url:r.url||"",path:r.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();switch(o){case"OPENAI":return R.create(Po,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GEMINI":return R.create(so,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"ANTHROPIC":return R.create(eo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"HUGGINGFACE":return R.create(io,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"MISTRAL":return R.create(ao,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"CODESTRAL":return R.create(to,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"OLLAMA":return R.create(co,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCodeReview$();case"COHERE":return R.create(ro,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GROQ":return R.create(no,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"PERPLEXITY":return R.create($o,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"DEEPSEEK":return R.create(oo,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();default:const i=w.red.bold(`[${o}]`);return de({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),S(o=>{const r=w.red.bold("[UNKNOWN]");return de({name:r+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}const Bt=async()=>{const{stdout:t,failed:e}=await X("git",["rev-parse","--show-toplevel"],{reject:!1});if(e)throw new C("The current directory must be a Git repository!");return t},J=t=>`:(exclude)${t}`,Qe=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb","*.gif","*.png"].map(J),Ht=async(t,e)=>{const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:r}=await X("git",[...o,"--name-only",...Qe,...t?t.map(J):[],...e?e.map(J):[]]);if(!r)return null;const{stdout:n}=await X("git",[...o,...Qe,...t?t.map(J):[]]);return{files:r.split(`
87
87
  `),diff:n}},Ba=t=>`Detected ${t.files.length.toLocaleString()} staged file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`,Ha=async(t,e,o)=>{const r=["diff-tree","-r","--no-commit-id","--name-only",t],{stdout:n}=await X("git",[...r,...Qe,...e?e.map(J):[],...o?o.map(J):[]]);if(!n)return null;const{stdout:s}=await X("git",["show",t,"--",...Qe,...e?e.map(J):[],...o?o.map(J):[]]);return{files:n.split(`
88
88
  `).filter(Boolean),diff:s}},Ua=async()=>{try{const{stdout:t}=await X("git",["config","--get","core.commentChar"]);return t}catch{return"#"}};class Q{constructor(){this.title="aicommit2"}printTitle(){console.log(hs.textSync(this.title,{font:"Small"}))}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=st(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return st(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(w.bold.green("\u2714 ")+w.bold(`${Ba(e)}:`)),console.log(`${e.files.map(o=>` ${o}`).join(`
89
89
  `)}
@@ -95,10 +95,10 @@ ${w.bold.green("\u2714")} ${w.bold("Saved commit message")}`)}printCancelledComm
95
95
  ${w.bold.yellow("\u26A0")} ${w.yellow("Commit cancelled")}`)}printError(e){console.log(`
96
96
  ${w.bold.red("\u2716")} ${w.red(`${e}`)}`)}printWarning(e){console.log(`
97
97
  ${w.bold.yellow("\u26A0")} ${w.red(`${e}`)}`)}printSetupGitEvent(e){console.log(`
98
- ${w.bold.green("\u2714")} ${w.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Le.createInterface({input:process.stdin,output:process.stdout});Le.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Le.createInterface({input:process.stdin,output:process.stdout});Le.moveCursor(process.stdout,0,2),e.close()}}const qa={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Eo={isLoading:!1,startOption:{text:"AI is performing a code review"}},Ut="No commit messages were generated",xo="No code reviews were generated",qt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Ut}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class zt{constructor(e){this.choices$=new tr([]),this.destroyed$=new Qo(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new tr(e)}initPrompt(e=qt){return this.stopMessage=e.stopMessage,Me.registerPrompt("reactiveListPrompt",gs),this.inquirerInstance=Me.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){const{value:o,isError:r}=e;!e||!o||this.choices$.next([...this.currentChoices,e].sort(Bi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(r=>r).every(r=>r?.isError||r?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){this.choices$.complete(),this.loader$.complete(),this.destroyed$.next(!0),this.destroyed$.complete()}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Ut,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${w.bold.yellow("\u26A0")} ${w.yellow(`${Ut}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const z=new Q;var za=async(t,e,o,r,n,s,i,c,l)=>(async()=>{z.printTitle(),await Bt(),r&&await X("git",["add","--update"]);const u=await ue({locale:t?.toString(),generate:e?.toString(),commitType:n?.toString(),systemPrompt:c?.toString()},l);await Zr(u);const p=z.displaySpinner("Detecting staged files"),a=await Ht(o,u.exclude);if(p.stop(),!a)throw new C("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");z.printStagedFiles(a);const m=Ao(u,"commit");if(m.length===0)throw new C("Please set at least one API key via the `aicommit2 config set` command");const d=new Je(u,a),h=Ao(u,"review");h.length>0&&await Ka(d,h);const g=await Wa(d,m);i&&(Ns("copy-paste").copy(g),z.printCopied(),process.exit()),s&&(await So(g,l),process.exit());const{confirmationPrompt:y}=await Me.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);y?await So(g,l):z.printCancelledCommit(),process.exit()})().catch(u=>{z.printError(u.message),ee(u),process.exit(1)});function Ao(t,e){return Object.entries(t).map(([o,r])=>[o,r]).filter(([o,r])=>!r.disabled).filter(([o,r])=>le.includes(o)||r.compatible===!0).filter(([o,r])=>{switch(e){case"commit":return o==="OLLAMA"?!!r&&!!r.model&&r.model.length>0:o==="HUGGINGFACE"?!!r&&!!r.cookie:!!r.key&&r.key.length>0;case"review":const n=t.codeReview||r.codeReview;return o==="OLLAMA"?!!r&&!!r.model&&r.model.length>0&&n:o==="HUGGINGFACE"?!!r&&!!r.cookie&&n:!!r.key&&r.key.length>0&&n}}).map(([o])=>o)}async function Ka(t,e){const o=new zt(Eo),r=o.initPrompt({...qt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${xo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});o.startLoader();const n=t.createCodeReviewRequests$(e).subscribe(l=>o.refreshChoices(l),()=>{},()=>o.checkErrorOnChoices());if(!(await r).codeReviewPrompt?.value)throw new C("An error occurred! No selected code review");n.unsubscribe(),o.completeSubject(),z.moveCursorUp();const{continuePrompt:c}=await Me.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(z.printCancelledCommit(),process.exit())}async function Wa(t,e){const o=new zt(qa),r=o.initPrompt();o.startLoader();const n=t.createCommitMsgRequests$(e).subscribe(c=>o.refreshChoices(c),()=>{},()=>o.checkErrorOnChoices()),s=await r;n.unsubscribe(),o.completeSubject(),z.moveCursorUp();const i=s.aicommit2Prompt?.value;if(!i)throw new C("An error occurred! No selected message");return i}async function So(t,e){const o=st("Committing with the generated message").start();await X("git",["commit","-m",t,...e]),o.stop(),o.clear(),z.printCommitted()}var Ya=Y({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:[Y({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"]}}),Y({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),Y({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"']}}),Y({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),Y({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"]}}),Y({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},t=>{(async()=>{const{mode:e,keyValue:o}=t._,r=t._[1];if(e==="get"){const n=await ue({},[]);if(o.length===0){console.log(n);return}for(const s of o){const i=s.split(".");let c=n,l=!0;for(const u of i)if(Mt(c,u))c=c[u];else{l=!1;break}l?console.log(s,c):console.log(`${s} not found`)}return}if(e==="set"){await Qi(o.map(n=>{const s=n.indexOf("=");if(s===-1)throw new C("Invalid format. Use: key=value");const i=n.slice(0,s),c=n.slice(s+1);return[i,c]}));return}if(e==="add"){await Zi(o.map(n=>{const s=n.indexOf("=");if(s===-1)throw new C("Invalid format. Use: key=value");const i=n.slice(0,s),c=n.slice(s+1);return[i,c]}));return}if(e==="list"){await ea();return}if(e==="del"){if(!r)throw new C("Please provide the config name to delete.");const n=await be(),s=r.split(".");if(s.length===2){const[i,c]=s;if(n[i]&&typeof n[i]=="object"&&Mt(n[i],c)){delete n[i][c],Object.keys(n[i]).length===0&&delete n[i];const l=await me();await x.writeFile(l,ce.stringify(n),"utf8"),console.log(`Successfully deleted config: ${r}`);const u=await x.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(u),console.log("----------------------------")}else throw new C(`Config not found: ${r}`)}else if(s.length===1){const i=s[0];if(Mt(n,i)){delete n[i];const c=await me();await x.writeFile(c,ce.stringify(n),"utf8"),console.log(`Successfully deleted config: ${r}`);const l=await x.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new C(`Config not found: ${r}`)}else throw new C(`Invalid config name format: ${r}`);return}if(e==="path"){await ta();return}throw new C(`Invalid mode: ${e}`)})().catch(e=>{new Q().printError(e.message),ee(e),process.exit(1)})});const Mo="prepare-commit-msg",ko=`.git/hooks/${Mo}`,Ze=fs(new URL("cli.mjs",import.meta.url)),Va=process.argv[1].replace(/\\/g,"/").endsWith(`/${ko}`),Io=process.platform==="win32",Ro=`
98
+ ${w.bold.green("\u2714")} ${w.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Le.createInterface({input:process.stdin,output:process.stdout});Le.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Le.createInterface({input:process.stdin,output:process.stdout});Le.moveCursor(process.stdout,0,2),e.close()}}const qa={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Eo={isLoading:!1,startOption:{text:"AI is performing a code review"}},Ut="No commit messages were generated",xo="No code reviews were generated",qt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Ut}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class zt{constructor(e){this.choices$=new tr([]),this.destroyed$=new Qo(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new tr(e)}initPrompt(e=qt){return this.stopMessage=e.stopMessage,ke.registerPrompt("reactiveListPrompt",gs),this.inquirerInstance=ke.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){const{value:o,isError:r}=e;!e||!o||this.choices$.next([...this.currentChoices,e].sort(Bi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(r=>r).every(r=>r?.isError||r?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){this.choices$.complete(),this.loader$.complete(),this.destroyed$.next(!0),this.destroyed$.complete()}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Ut,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${w.bold.yellow("\u26A0")} ${w.yellow(`${Ut}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const z=new Q;var za=async(t,e,o,r,n,s,i,c,l)=>(async()=>{z.printTitle(),await Bt(),r&&await X("git",["add","--update"]);const u=await ue({locale:t?.toString(),generate:e?.toString(),commitType:n?.toString(),systemPrompt:c?.toString()},l);await Zr(u);const p=z.displaySpinner("Detecting staged files"),a=await Ht(o,u.exclude);if(p.stop(),!a)throw new C("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");z.printStagedFiles(a);const m=Ao(u,"commit");if(m.length===0)throw new C("Please set at least one API key via the `aicommit2 config set` command");const d=new Je(u,a),h=Ao(u,"review");h.length>0&&await Ka(d,h);const g=await Wa(d,m);i&&(Ns("copy-paste").copy(g),z.printCopied(),process.exit()),s&&(await So(g,l),process.exit());const{confirmationPrompt:y}=await ke.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);y?await So(g,l):z.printCancelledCommit(),process.exit()})().catch(u=>{z.printError(u.message),ee(u),process.exit(1)});function Ao(t,e){return Object.entries(t).map(([o,r])=>[o,r]).filter(([o,r])=>!r.disabled).filter(([o,r])=>le.includes(o)||r.compatible===!0).filter(([o,r])=>{switch(e){case"commit":return o==="OLLAMA"?!!r&&!!r.model&&r.model.length>0:o==="HUGGINGFACE"?!!r&&!!r.cookie:!!r.key&&r.key.length>0;case"review":const n=t.codeReview||r.codeReview;return o==="OLLAMA"?!!r&&!!r.model&&r.model.length>0&&n:o==="HUGGINGFACE"?!!r&&!!r.cookie&&n:!!r.key&&r.key.length>0&&n}}).map(([o])=>o)}async function Ka(t,e){const o=new zt(Eo),r=o.initPrompt({...qt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${xo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});o.startLoader();const n=t.createCodeReviewRequests$(e).subscribe(l=>o.refreshChoices(l),()=>{},()=>o.checkErrorOnChoices());if(!(await r).codeReviewPrompt?.value)throw new C("An error occurred! No selected code review");n.unsubscribe(),o.completeSubject(),z.moveCursorUp();const{continuePrompt:c}=await ke.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(z.printCancelledCommit(),process.exit())}async function Wa(t,e){const o=new zt(qa),r=o.initPrompt();o.startLoader();const n=t.createCommitMsgRequests$(e).subscribe(c=>o.refreshChoices(c),()=>{},()=>o.checkErrorOnChoices()),s=await r;n.unsubscribe(),o.completeSubject(),z.moveCursorUp();const i=s.aicommit2Prompt?.value;if(!i)throw new C("An error occurred! No selected message");return i}async function So(t,e){const o=st("Committing with the generated message").start();await X("git",["commit","-m",t,...e]),o.stop(),o.clear(),z.printCommitted()}var Ya=Y({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:[Y({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"]}}),Y({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),Y({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"']}}),Y({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),Y({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"]}}),Y({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},t=>{(async()=>{const{mode:e,keyValue:o}=t._,r=t._[1];if(e==="get"){const n=await ue({},[]);if(o.length===0){console.log(n);return}for(const s of o){const i=s.split(".");let c=n,l=!0;for(const u of i)if(kt(c,u))c=c[u];else{l=!1;break}l?console.log(s,c):console.log(`${s} not found`)}return}if(e==="set"){await Qi(o.map(n=>{const s=n.indexOf("=");if(s===-1)throw new C("Invalid format. Use: key=value");const i=n.slice(0,s),c=n.slice(s+1);return[i,c]}));return}if(e==="add"){await Zi(o.map(n=>{const s=n.indexOf("=");if(s===-1)throw new C("Invalid format. Use: key=value");const i=n.slice(0,s),c=n.slice(s+1);return[i,c]}));return}if(e==="list"){await ea();return}if(e==="del"){if(!r)throw new C("Please provide the config name to delete.");const n=await be(),s=r.split(".");if(s.length===2){const[i,c]=s;if(n[i]&&typeof n[i]=="object"&&kt(n[i],c)){delete n[i][c],Object.keys(n[i]).length===0&&delete n[i];const l=await me();await x.writeFile(l,ce.stringify(n),"utf8"),console.log(`Successfully deleted config: ${r}`);const u=await x.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(u),console.log("----------------------------")}else throw new C(`Config not found: ${r}`)}else if(s.length===1){const i=s[0];if(kt(n,i)){delete n[i];const c=await me();await x.writeFile(c,ce.stringify(n),"utf8"),console.log(`Successfully deleted config: ${r}`);const l=await x.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new C(`Config not found: ${r}`)}else throw new C(`Invalid config name format: ${r}`);return}if(e==="path"){await ta();return}throw new C(`Invalid mode: ${e}`)})().catch(e=>{new Q().printError(e.message),ee(e),process.exit(1)})});const ko="prepare-commit-msg",Mo=`.git/hooks/${ko}`,Ze=fs(new URL("cli.mjs",import.meta.url)),Va=process.argv[1].replace(/\\/g,"/").endsWith(`/${Mo}`),Io=process.platform==="win32",Ro=`
99
99
  #!/usr/bin/env node
100
100
  import(${JSON.stringify(ds(Ze))})
101
- `.trim();var Xa=Y({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},t=>{(async()=>{const e=await Bt(),{installUninstall:o}=t._,r=P.join(e,ko),n=await Hr(r);if(o==="install"){if(n){if(await x.realpath(r).catch(()=>{})===Ze){console.warn("The hook is already installed");return}throw new C(`A different ${Mo} hook seems to be installed. Please remove it before installing aicommit2.`)}await x.mkdir(P.dirname(r),{recursive:!0}),Io?await x.writeFile(r,Ro):(await x.symlink(Ze,r,"file"),await x.chmod(r,493)),console.log(`${w.green("\u2714")} Hook installed`);return}if(o==="uninstall"){if(!n){console.warn("Hook is not installed");return}if(Io){if(await x.readFile(r,"utf8")!==Ro){console.warn("Hook is not installed");return}}else if(await x.realpath(r)!==Ze){console.warn("Hook is not installed");return}await x.rm(r),console.log(`${w.green("\u2714")} Hook uninstalled`);return}throw new C(`Invalid mode: ${o}`)})().catch(e=>{console.error(`${w.red("\u2716")} ${e.message}`),ee(e),process.exit(1)})}),Ja=Y({name:"log",parameters:["<removeAll>"],help:{description:"Manage log files generated by the application",examples:["aic2 log removeAll"]}},t=>{(async()=>{const{removeAll:e}=t._;if(e==="removeAll"){await ys(Ke,{recursive:!0,force:!0}),console.log(`${w.green("\u2714")} All Log files are removed!`);return}throw new C(`Invalid mode: ${e}`)})().catch(e=>{new Q().printError(e.message),ee(e),process.exit(1)})});const Qa=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[et,Oo]=Qa;var Za=()=>(async()=>{if(!et)throw new C('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Oo){console.log(`Skipping aicommit2 message generation for ${Oo} commit`);return}const t=await Ht();if(!t)return;const e=new Q;e.printTitle();const o=await ue({});if(o.systemPromptPath)try{await x.readFile(P.resolve(o.systemPromptPath),"utf-8")}catch{throw new C(`Error reading system prompt file: ${o.systemPromptPath}`)}const r=Object.entries(o).filter(([d])=>le.includes(d)).map(([d,h])=>[d,h]).filter(([d,h])=>!h.disabled).filter(([d,h])=>d==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:d==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([d])=>d);if(r.length===0)throw new C("Please set at least one API key via the `aicommit2 config set` command");const s=new Je(o,t);let i;try{i=await rr(s.createCommitMsgRequests$(r).pipe(or(d=>!d.isError),A(d=>d.value),sr()))}finally{e.printAnalyzed()}const l=await x.readFile(et,"utf8")!=="",u=i.length>1;let p="";l&&(p=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
101
+ `.trim();var Xa=Y({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},t=>{(async()=>{const e=await Bt(),{installUninstall:o}=t._,r=P.join(e,Mo),n=await Hr(r);if(o==="install"){if(n){if(await x.realpath(r).catch(()=>{})===Ze){console.warn("The hook is already installed");return}throw new C(`A different ${ko} hook seems to be installed. Please remove it before installing aicommit2.`)}await x.mkdir(P.dirname(r),{recursive:!0}),Io?await x.writeFile(r,Ro):(await x.symlink(Ze,r,"file"),await x.chmod(r,493)),console.log(`${w.green("\u2714")} Hook installed`);return}if(o==="uninstall"){if(!n){console.warn("Hook is not installed");return}if(Io){if(await x.readFile(r,"utf8")!==Ro){console.warn("Hook is not installed");return}}else if(await x.realpath(r)!==Ze){console.warn("Hook is not installed");return}await x.rm(r),console.log(`${w.green("\u2714")} Hook uninstalled`);return}throw new C(`Invalid mode: ${o}`)})().catch(e=>{console.error(`${w.red("\u2716")} ${e.message}`),ee(e),process.exit(1)})}),Ja=Y({name:"log",parameters:["<removeAll>"],help:{description:"Manage log files generated by the application",examples:["aic2 log removeAll"]}},t=>{(async()=>{const{removeAll:e}=t._;if(e==="removeAll"){await ys(Ke,{recursive:!0,force:!0}),console.log(`${w.green("\u2714")} All Log files are removed!`);return}throw new C(`Invalid mode: ${e}`)})().catch(e=>{new Q().printError(e.message),ee(e),process.exit(1)})});const Qa=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[et,Oo]=Qa;var Za=()=>(async()=>{if(!et)throw new C('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Oo){console.log(`Skipping aicommit2 message generation for ${Oo} commit`);return}const t=await Ht();if(!t)return;const e=new Q;e.printTitle();const o=await ue({});if(o.systemPromptPath)try{await x.readFile(P.resolve(o.systemPromptPath),"utf-8")}catch{throw new C(`Error reading system prompt file: ${o.systemPromptPath}`)}const r=Object.entries(o).filter(([d])=>le.includes(d)).map(([d,h])=>[d,h]).filter(([d,h])=>!h.disabled).filter(([d,h])=>d==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:d==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([d])=>d);if(r.length===0)throw new C("Please set at least one API key via the `aicommit2 config set` command");const s=new Je(o,t);let i;try{i=await rr(s.createCommitMsgRequests$(r).pipe(or(d=>!d.isError),A(d=>d.value),sr()))}finally{e.printAnalyzed()}const l=await x.readFile(et,"utf8")!=="",u=i.length>1;let p="";l&&(p=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
102
102
  `,p+=`# ----------------------------------------
103
103
  `,p+=`# How to use:
104
104
  `,u?(p+=`# 1. Remove the "#" from your chosen message
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aicommit2",
3
- "version": "2.2.17",
3
+ "version": "2.2.19",
4
4
  "description": "A Reactive CLI that generates git commit messages with various AI",
5
5
  "keywords": [
6
6
  "cli",