@stagewise/agent-runtime-node 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +661 -0
  2. package/dist/__tests__/file-operations.test.d.ts +2 -0
  3. package/dist/__tests__/fixtures/sample-project/src/components/Button.d.ts +10 -0
  4. package/dist/__tests__/fixtures/sample-project/src/components/Input.d.ts +9 -0
  5. package/dist/__tests__/fixtures/sample-project/src/index.d.ts +5 -0
  6. package/dist/__tests__/fixtures/sample-project/src/lib/helpers.d.ts +13 -0
  7. package/dist/__tests__/fixtures/sample-project/src/lib/utils.d.ts +13 -0
  8. package/dist/__tests__/fixtures/sample-project/src/types.d.ts +20 -0
  9. package/dist/__tests__/fixtures/sample-project/tests/utils.test.d.ts +2 -0
  10. package/dist/__tests__/glob-node-fallback.test.d.ts +2 -0
  11. package/dist/__tests__/glob-ripgrep.test.d.ts +2 -0
  12. package/dist/__tests__/glob-searchreplace.test.d.ts +2 -0
  13. package/dist/__tests__/grep-fallback.test.d.ts +2 -0
  14. package/dist/__tests__/grep-node-fallback.test.d.ts +2 -0
  15. package/dist/__tests__/grep-ripgrep.test.d.ts +2 -0
  16. package/dist/__tests__/grep.test.d.ts +2 -0
  17. package/dist/__tests__/search-replace.test.d.ts +2 -0
  18. package/dist/__tests__/shared/glob-test-suite.d.ts +10 -0
  19. package/dist/__tests__/shared/grep-test-suite.d.ts +10 -0
  20. package/dist/__tests__/utils/assertions.d.ts +50 -0
  21. package/dist/__tests__/utils/cleanup.d.ts +12 -0
  22. package/dist/__tests__/utils/test-fixtures.d.ts +47 -0
  23. package/dist/glob/glob-node-fallback.d.ts +3 -0
  24. package/dist/glob/glob-ripgrep.d.ts +17 -0
  25. package/dist/glob/index.d.ts +3 -0
  26. package/dist/glob/utils.d.ts +6 -0
  27. package/dist/glob.d.ts +26 -0
  28. package/dist/grep/grep-node-fallback.d.ts +3 -0
  29. package/dist/grep/grep-ripgrep.d.ts +32 -0
  30. package/dist/grep/index.d.ts +3 -0
  31. package/dist/grep.d.ts +12 -0
  32. package/dist/index.d.ts +155 -0
  33. package/dist/index.js +11 -0
  34. package/dist/ripgrep/binary-resolver.d.ts +10 -0
  35. package/dist/ripgrep/executor.d.ts +33 -0
  36. package/dist/ripgrep/index.d.ts +25 -0
  37. package/dist/ripgrep/output-parser.d.ts +17 -0
  38. package/dist/ripgrep/platform.d.ts +21 -0
  39. package/dist/shared.d.ts +11 -0
  40. package/dist/types.d.ts +128 -0
  41. package/dist/vscode-ripgrep/download.d.ts +10 -0
  42. package/dist/vscode-ripgrep/ensure-ripgrep.d.ts +21 -0
  43. package/dist/vscode-ripgrep/get-path.d.ts +22 -0
  44. package/package.json +52 -0
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ var kt=Object.create;var Oe=Object.defineProperty;var Ot=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var ae=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Mt=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Gt(e))!Ct.call(i,s)&&s!==t&&Oe(i,s,{get:()=>e[s],enumerable:!(r=Ot(e,s))||r.enumerable});return i};var Ge=(i,e,t)=>(t=i!=null?kt(At(i)):{},Mt(e||!i||!i.__esModule?Oe(t,"default",{value:i,enumerable:!0}):t,i));var Ne=ae((Cs,De)=>{"use strict";De.exports=Ce;function Ce(i,e,t){i instanceof RegExp&&(i=Ae(i,t)),e instanceof RegExp&&(e=Ae(e,t));var r=Me(i,e,t);return r&&{start:r[0],end:r[1],pre:t.slice(0,r[0]),body:t.slice(r[0]+i.length,r[1]),post:t.slice(r[1]+e.length)}}function Ae(i,e){var t=e.match(i);return t?t[0]:null}Ce.range=Me;function Me(i,e,t){var r,s,n,a,o,l=t.indexOf(i),c=t.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(i===e)return[l,c];for(r=[],n=t.length;u>=0&&!o;)u==l?(r.push(u),l=t.indexOf(i,u+1)):r.length==1?o=[r.pop(),c]:(s=r.pop(),s<n&&(n=s,a=c),c=t.indexOf(e,u+1)),u=l<c&&l>=0?l:c;r.length&&(o=[n,a])}return o}});var ze=ae((Ms,Ue)=>{var Te=Ne();Ue.exports=Tt;var Fe="\0SLASH"+Math.random()+"\0",Ie="\0OPEN"+Math.random()+"\0",ce="\0CLOSE"+Math.random()+"\0",je="\0COMMA"+Math.random()+"\0",We="\0PERIOD"+Math.random()+"\0";function oe(i){return parseInt(i,10)==i?parseInt(i,10):i.charCodeAt(0)}function Dt(i){return i.split("\\\\").join(Fe).split("\\{").join(Ie).split("\\}").join(ce).split("\\,").join(je).split("\\.").join(We)}function Nt(i){return i.split(Fe).join("\\").split(Ie).join("{").split(ce).join("}").split(je).join(",").split(We).join(".")}function Be(i){if(!i)return[""];var e=[],t=Te("{","}",i);if(!t)return i.split(",");var r=t.pre,s=t.body,n=t.post,a=r.split(",");a[a.length-1]+="{"+s+"}";var o=Be(n);return n.length&&(a[a.length-1]+=o.shift(),a.push.apply(a,o)),e.push.apply(e,a),e}function Tt(i,e){if(!i)return[];e=e||{};var t=e.max==null?1/0:e.max;return i.substr(0,2)==="{}"&&(i="\\{\\}"+i.substr(2)),B(Dt(i),t,!0).map(Nt)}function Ft(i){return"{"+i+"}"}function It(i){return/^-?0\d/.test(i)}function jt(i,e){return i<=e}function Wt(i,e){return i>=e}function B(i,e,t){var r=[],s=Te("{","}",i);if(!s)return[i];var n=s.pre,a=s.post.length?B(s.post,e,!1):[""];if(/\$$/.test(s.pre))for(var o=0;o<a.length&&o<e;o++){var l=n+"{"+s.body+"}"+a[o];r.push(l)}else{var c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),h=c||u,g=s.body.indexOf(",")>=0;if(!h&&!g)return s.post.match(/,(?!,).*\}/)?(i=s.pre+"{"+s.body+ce+s.post,B(i,e,!0)):[i];var f;if(h)f=s.body.split(/\.\./);else if(f=Be(s.body),f.length===1&&(f=B(f[0],e,!1).map(Ft),f.length===1))return a.map(function(ne){return s.pre+f[0]+ne});var d;if(h){var p=oe(f[0]),y=oe(f[1]),x=Math.max(f[0].length,f[1].length),m=f.length==3?Math.max(Math.abs(oe(f[2])),1):1,w=jt,R=y<p;R&&(m*=-1,w=Wt);var O=f.some(It);d=[];for(var M=p;w(M,y);M+=m){var S;if(u)S=String.fromCharCode(M),S==="\\"&&(S="");else if(S=String(M),O){var X=x-S.length;if(X>0){var V=new Array(X+1).join("0");M<0?S="-"+V+S.slice(1):S=V+S}}d.push(S)}}else{d=[];for(var G=0;G<f.length;G++)d.push.apply(d,B(f[G],e,!1))}for(var G=0;G<d.length;G++)for(var o=0;o<a.length&&r.length<e;o++){var l=n+d[G]+a[o];(!t||h||l)&&r.push(l)}}return r}});var yt=ae((Gi,Q)=>{function ht(i){return Array.isArray(i)?i:[i]}var zr=void 0,ye="",lt=" ",me="\\",Lr=/^\s+$/,Hr=/(?:[^\\]|^)\\$/,Xr=/^\\!/,Vr=/^\\#/,Zr=/\r?\n/g,Jr=/^\.{0,2}\/|^\.{1,2}$/,Kr=/\/$/,j="/",ft="node-ignore";typeof Symbol<"u"&&(ft=Symbol.for("node-ignore"));var gt=ft,W=(i,e,t)=>(Object.defineProperty(i,e,{value:t}),t),qr=/([0-z])-([0-z])/g,pt=()=>!1,Yr=i=>i.replace(qr,(e,t,r)=>t.charCodeAt(0)<=r.charCodeAt(0)?e:ye),Qr=i=>{let{length:e}=i;return i.slice(0,e-e%2)},es=[[/^\uFEFF/,()=>ye],[/((?:\\\\)*?)(\\?\s+)$/,(i,e,t)=>e+(t.indexOf("\\")===0?lt:ye)],[/(\\+?)\s/g,(i,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+lt}],[/[\\$.|*+(){^]/g,i=>`\\${i}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(i,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(i,e,t)=>{let r=t.replace(/\\\*/g,"[^\\/]*");return e+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>me],[/\\\\/g,()=>me],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(i,e,t,r,s)=>e===me?`\\[${t}${Qr(r)}${s}`:s==="]"&&r.length%2===0?`[${Yr(t)}${r}]`:"[]"],[/(?:[^*])$/,i=>/\/$/.test(i)?`${i}$`:`${i}(?=$|\\/$)`]],ts=/(^|\\\/)?\\\*$/,L="regex",q="checkRegex",ut="_",rs={[L](i,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[q](i,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ss=i=>es.reduce((e,[t,r])=>e.replace(t,r.bind(i)),i),Y=i=>typeof i=="string",is=i=>i&&Y(i)&&!Lr.test(i)&&!Hr.test(i)&&i.indexOf("#")!==0,ns=i=>i.split(Zr).filter(Boolean),we=class{constructor(e,t,r,s,n,a){this.pattern=e,this.mark=t,this.negative=n,W(this,"body",r),W(this,"ignoreCase",s),W(this,"regexPrefix",a)}get regex(){let e=ut+L;return this[e]?this[e]:this._make(L,e)}get checkRegex(){let e=ut+q;return this[e]?this[e]:this._make(q,e)}_make(e,t){let r=this.regexPrefix.replace(ts,rs[e]),s=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return W(this,t,s)}},as=({pattern:i,mark:e},t)=>{let r=!1,s=i;s.indexOf("!")===0&&(r=!0,s=s.substr(1)),s=s.replace(Xr,"!").replace(Vr,"#");let n=ss(s);return new we(i,e,s,t,r,n)},xe=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[gt]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Y(e)&&(e={pattern:e}),is(e.pattern)){let t=as(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,ht(Y(e)?ns(e):e).forEach(this._add,this),this._added}test(e,t,r){let s=!1,n=!1,a;this._rules.forEach(l=>{let{negative:c}=l;n===c&&s!==n||c&&!s&&!n&&!t||!l[r].test(e)||(s=!c,n=c,a=c?zr:l)});let o={ignored:s,unignored:n};return a&&(o.rule=a),o}},os=(i,e)=>{throw new e(i)},$=(i,e,t)=>Y(i)?i?$.isNotRelative(i)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),dt=i=>Jr.test(i);$.isNotRelative=dt;$.convert=i=>i;var be=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:r=!1}={}){W(this,gt,!0),this._rules=new xe(t),this._strictPathCheck=!r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,r,s){let n=e&&$.convert(e);return $(n,e,this._strictPathCheck?os:pt),this._t(n,t,r,s)}checkIgnore(e){if(!Kr.test(e))return this.test(e);let t=e.split(j).filter(Boolean);if(t.pop(),t.length){let r=this._t(t.join(j)+j,this._testCache,!0,t);if(r.ignored)return r}return this._rules.test(e,!1,q)}_t(e,t,r,s){if(e in t)return t[e];if(s||(s=e.split(j).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,r,L);let n=this._t(s.join(j)+j,t,r,s);return t[e]=n.ignored?n:this._rules.test(e,r,L)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return ht(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Re=i=>new be(i),cs=i=>$(i&&$.convert(i),i,pt),mt=()=>{let i=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");$.convert=i;let e=/^[a-z]:\//i;$.isNotRelative=t=>e.test(t)||dt(t)};typeof process<"u"&&process.platform==="win32"&&mt();Q.exports=Re;Re.default=Re;Q.exports.isPathValid=cs;W(Q.exports,Symbol.for("setupWindows"),mt)});import{dirname as se,resolve as _t,join as ie,relative as k,extname as ks}from"node:path";var Z={CHECK_BUFFER_SIZE:8192};import{promises as K}from"node:fs";import ge from"node:path";var Ye=Ge(ze(),1);var U=i=>{if(typeof i!="string")throw new TypeError("invalid pattern");if(i.length>65536)throw new TypeError("pattern is too long")};var Bt={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},z=i=>i.replace(/[[\]\\-]/g,"\\$&"),Ut=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Le=i=>i.join(""),He=(i,e)=>{let t=e;if(i.charAt(t)!=="[")throw new Error("not in a brace expression");let r=[],s=[],n=t+1,a=!1,o=!1,l=!1,c=!1,u=t,h="";e:for(;n<i.length;){let p=i.charAt(n);if((p==="!"||p==="^")&&n===t+1){c=!0,n++;continue}if(p==="]"&&a&&!l){u=n+1;break}if(a=!0,p==="\\"&&!l){l=!0,n++;continue}if(p==="["&&!l){for(let[y,[x,m,w]]of Object.entries(Bt))if(i.startsWith(y,n)){if(h)return["$.",!1,i.length-t,!0];n+=y.length,w?s.push(x):r.push(x),o=o||m;continue e}}if(l=!1,h){p>h?r.push(z(h)+"-"+z(p)):p===h&&r.push(z(p)),h="",n++;continue}if(i.startsWith("-]",n+1)){r.push(z(p+"-")),n+=2;continue}if(i.startsWith("-",n+1)){h=p,n+=2;continue}r.push(z(p)),n++}if(u<n)return["",!1,0,!1];if(!r.length&&!s.length)return["$.",!1,i.length-t,!0];if(s.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!c){let p=r[0].length===2?r[0].slice(-1):r[0];return[Ut(p),!1,u-t,!1]}let g="["+(c?"^":"")+Le(r)+"]",f="["+(c?"":"^")+Le(s)+"]";return[r.length&&s.length?"("+g+"|"+f+")":r.length?g:f,o,u-t,!0]};var A=(i,{windowsPathsNoEscape:e=!1}={})=>e?i.replace(/\[([^\/\\])\]/g,"$1"):i.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var v,zt=new Set(["!","?","+","*","@"]),le=i=>zt.has(i),Xe=i=>le(i.type),Lt=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Ht=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),Xt=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),Ve=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Vt="(?!(?:^|/)\\.\\.?(?:$|/))",J="(?!\\.)",Zt=new Set(["[","."]),Jt=new Set(["..","."]),Kt=new Set("().*{}+?[]^$\\!"),qt=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ue="[^/]",Ze=ue+"*?",Je=ue+"+?",D=class{type;#r;#s;#i=!1;#e=[];#t;#o;#l;#c=!1;#n;#a;#u=!1;constructor(e,t,r={}){this.type=e,e&&(this.#s=!0),this.#t=t,this.#r=this.#t?this.#t.#r:this,this.#n=this.#r===this?r:this.#r.#n,this.#l=this.#r===this?[]:this.#r.#l,e==="!"&&!this.#r.#c&&this.#l.push(this),this.#o=this.#t?this.#t.#e.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let e of this.#e)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#a!==void 0?this.#a:this.type?this.#a=this.type+"("+this.#e.map(e=>String(e)).join("|")+")":this.#a=this.#e.map(e=>String(e)).join("")}#y(){if(this!==this.#r)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let e;for(;e=this.#l.pop();){if(e.type!=="!")continue;let t=e,r=t.#t;for(;r;){for(let s=t.#o+1;!r.type&&s<r.#e.length;s++)for(let n of e.#e){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(r.#e[s])}t=r,r=t.#t}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof v&&t.#t===this))throw new Error("invalid part: "+t);this.#e.push(t)}}toJSON(){var t;let e=this.type===null?this.#e.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#e.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#r||this.#r.#c&&((t=this.#t)==null?void 0:t.type)==="!")&&e.push({}),e}isStart(){var t;if(this.#r===this)return!0;if(!((t=this.#t)!=null&&t.isStart()))return!1;if(this.#o===0)return!0;let e=this.#t;for(let r=0;r<this.#o;r++){let s=e.#e[r];if(!(s instanceof v&&s.type==="!"))return!1}return!0}isEnd(){var t,r,s;if(this.#r===this||((t=this.#t)==null?void 0:t.type)==="!")return!0;if(!((r=this.#t)!=null&&r.isEnd()))return!1;if(!this.type)return(s=this.#t)==null?void 0:s.isEnd();let e=this.#t?this.#t.#e.length:0;return this.#o===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new v(this.type,e);for(let r of this.#e)t.copyIn(r);return t}static#h(e,t,r,s,n){let a=s.maxExtglobRecursion??2,o=!1,l=!1,c=-1,u=!1;if(t.type===null){let p=r,y="";for(;p<e.length;){let x=e.charAt(p++);if(o||x==="\\"){o=!o,y+=x;continue}if(l){p===c+1?(x==="^"||x==="!")&&(u=!0):x==="]"&&!(p===c+2&&u)&&(l=!1),y+=x;continue}else if(x==="["){l=!0,c=p,u=!1,y+=x;continue}if(!s.noext&&le(x)&&e.charAt(p)==="("&&n<=a){t.push(y),y="";let w=new v(x,t);p=v.#h(e,w,p,s,n+1),t.push(w);continue}y+=x}return t.push(y),p}let h=r+1,g=new v(null,t),f=[],d="";for(;h<e.length;){let p=e.charAt(h++);if(o||p==="\\"){o=!o,d+=p;continue}if(l){h===c+1?(p==="^"||p==="!")&&(u=!0):p==="]"&&!(h===c+2&&u)&&(l=!1),d+=p;continue}else if(p==="["){l=!0,c=h,u=!1,d+=p;continue}if(le(p)&&e.charAt(h)==="("&&(n<=a||t&&t.#f(p))){let x=t&&t.#f(p)?0:1;g.push(d),d="";let m=new v(p,g);g.push(m),h=v.#h(e,m,h,s,n+x);continue}if(p==="|"){g.push(d),d="",f.push(g),g=new v(null,t);continue}if(p===")")return d===""&&t.#e.length===0&&(t.#u=!0),g.push(d),d="",t.push(...f,g),h;d+=p}return t.type=null,t.#s=void 0,t.#e=[e.substring(r-1)],h}#w(e){return this.#p(e,Ht)}#p(e,t=Lt){if(!e||typeof e!="object"||e.type!==null||e.#e.length!==1||this.type===null)return!1;let r=e.#e[0];return!r||typeof r!="object"||r.type===null?!1:this.#f(r.type,t)}#f(e,t=Xt){var r;return!!((r=t.get(this.type))!=null&&r.includes(e))}#x(e,t){let r=e.#e[0],s=new v(null,r,this.options);s.#e.push(""),r.push(s),this.#d(e,t)}#d(e,t){let r=e.#e[0];this.#e.splice(t,1,...r.#e);for(let s of r.#e)typeof s=="object"&&(s.#t=this);this.#a=void 0}#b(e){let t=Ve.get(this.type);return!!(t!=null&&t.has(e))}#R(e){if(!e||typeof e!="object"||e.type!==null||e.#e.length!==1||this.type===null||this.#e.length!==1)return!1;let t=e.#e[0];return!t||typeof t!="object"||t.type===null?!1:this.#b(t.type)}#E(e){let t=Ve.get(this.type),r=e.#e[0],s=t==null?void 0:t.get(r.type);if(!s)return!1;this.#e=r.#e;for(let n of this.#e)typeof n=="object"&&(n.#t=this);this.type=s,this.#a=void 0,this.#u=!1}#g(){if(Xe(this)){let e=0,t=!1;do{t=!0;for(let r=0;r<this.#e.length;r++){let s=this.#e[r];typeof s=="object"&&(s.#g(),this.#p(s)?(t=!1,this.#d(s,r)):this.#w(s)?(t=!1,this.#x(s,r)):this.#R(s)&&(t=!1,this.#E(s)))}}while(!t&&++e<10)}else for(let e of this.#e)typeof e=="object"&&e.#g();this.#a=void 0}static fromGlob(e,t={}){let r=new v(null,void 0,t);return v.#h(e,r,0,t,0),r}toMMPattern(){if(this!==this.#r)return this.#r.toMMPattern();let e=this.toString(),[t,r,s,n]=this.toRegExpSource();if(!(s||this.#s||this.#n.nocase&&!this.#n.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let o=(this.#n.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return this.#n}toRegExpSource(e){var l;let t=e??!!this.#n.dot;if(this.#r===this&&(this.#g(),this.#y()),!Xe(this)){let c=this.isStart()&&this.isEnd(),u=this.#e.map(d=>{let[p,y,x,m]=typeof d=="string"?v.#P(d,this.#s,c):d.toRegExpSource(e);return this.#s=this.#s||x,this.#i=this.#i||m,p}).join(""),h="";if(this.isStart()&&typeof this.#e[0]=="string"&&!(this.#e.length===1&&Jt.has(this.#e[0]))){let p=Zt,y=t&&p.has(u.charAt(0))||u.startsWith("\\.")&&p.has(u.charAt(2))||u.startsWith("\\.\\.")&&p.has(u.charAt(4)),x=!t&&!e&&p.has(u.charAt(0));h=y?Vt:x?J:""}let g="";return this.isEnd()&&this.#r.#c&&((l=this.#t)==null?void 0:l.type)==="!"&&(g="(?:$|\\/)"),[h+u+g,A(u),this.#s=!!this.#s,this.#i]}let r=this.type==="*"||this.type==="+",s=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#m(t);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let c=this.toString(),u=this;return u.#e=[c],u.type=null,u.#s=void 0,[c,A(this.toString()),!1,!1]}let a=!r||e||t||!J?"":this.#m(!0);a===n&&(a=""),a&&(n=`(?:${n})(?:${a})*?`);let o="";if(this.type==="!"&&this.#u)o=(this.isStart()&&!t?J:"")+Je;else{let c=this.type==="!"?"))"+(this.isStart()&&!t&&!e?J:"")+Ze+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;o=s+n+c}return[o,A(n),this.#s=!!this.#s,this.#i]}#m(e){return this.#e.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[r,s,n,a]=t.toRegExpSource(e);return this.#i=this.#i||a,r}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#P(e,t,r=!1){let s=!1,n="",a=!1,o=!1;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(s){s=!1,n+=(Kt.has(c)?"\\":"")+c,o=!1;continue}if(c==="\\"){l===e.length-1?n+="\\\\":s=!0;continue}if(c==="["){let[u,h,g,f]=He(e,l);if(g){n+=u,a=a||h,l+=g-1,t=t||f,o=!1;continue}}if(c==="*"){if(o)continue;o=!0,n+=r&&/^[*]+$/.test(e)?Je:Ze,t=!0;continue}else o=!1;if(c==="?"){n+=ue,t=!0;continue}n+=qt(c)}return[n,A(e),!!t,a]}};v=D;var he=(i,{windowsPathsNoEscape:e=!1}={})=>e?i.replace(/[?*()[\]]/g,"[$&]"):i.replace(/[?*()[\]\\]/g,"\\$&");var b=(i,e,t={})=>(U(e),!t.nocomment&&e.charAt(0)==="#"?!1:new F(e,t).match(i)),Yt=/^\*+([^+@!?\*\[\(]*)$/,Qt=i=>e=>!e.startsWith(".")&&e.endsWith(i),er=i=>e=>e.endsWith(i),tr=i=>(i=i.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(i)),rr=i=>(i=i.toLowerCase(),e=>e.toLowerCase().endsWith(i)),sr=/^\*+\.\*+$/,ir=i=>!i.startsWith(".")&&i.includes("."),nr=i=>i!=="."&&i!==".."&&i.includes("."),ar=/^\.\*+$/,or=i=>i!=="."&&i!==".."&&i.startsWith("."),cr=/^\*+$/,lr=i=>i.length!==0&&!i.startsWith("."),ur=i=>i.length!==0&&i!=="."&&i!=="..",hr=/^\?+([^+@!?\*\[\(]*)?$/,fr=([i,e=""])=>{let t=Qe([i]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},gr=([i,e=""])=>{let t=et([i]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},pr=([i,e=""])=>{let t=et([i]);return e?r=>t(r)&&r.endsWith(e):t},dr=([i,e=""])=>{let t=Qe([i]);return e?r=>t(r)&&r.endsWith(e):t},Qe=([i])=>{let e=i.length;return t=>t.length===e&&!t.startsWith(".")},et=([i])=>{let e=i.length;return t=>t.length===e&&t!=="."&&t!==".."},tt=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ke={win32:{sep:"\\"},posix:{sep:"/"}},mr=tt==="win32"?Ke.win32.sep:Ke.posix.sep;b.sep=mr;var P=Symbol("globstar **");b.GLOBSTAR=P;var yr="[^/]",wr=yr+"*?",xr="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",br="(?:(?!(?:\\/|^)\\.).)*?",Rr=(i,e={})=>t=>b(t,i,e);b.filter=Rr;var _=(i,e={})=>Object.assign({},i,e),Er=i=>{if(!i||typeof i!="object"||!Object.keys(i).length)return b;let e=b;return Object.assign((r,s,n={})=>e(r,s,_(i,n)),{Minimatch:class extends e.Minimatch{constructor(s,n={}){super(s,_(i,n))}static defaults(s){return e.defaults(_(i,s)).Minimatch}},AST:class extends e.AST{constructor(s,n,a={}){super(s,n,_(i,a))}static fromGlob(s,n={}){return e.AST.fromGlob(s,_(i,n))}},unescape:(r,s={})=>e.unescape(r,_(i,s)),escape:(r,s={})=>e.escape(r,_(i,s)),filter:(r,s={})=>e.filter(r,_(i,s)),defaults:r=>e.defaults(_(i,r)),makeRe:(r,s={})=>e.makeRe(r,_(i,s)),braceExpand:(r,s={})=>e.braceExpand(r,_(i,s)),match:(r,s,n={})=>e.match(r,s,_(i,n)),sep:e.sep,GLOBSTAR:P})};b.defaults=Er;var rt=(i,e={})=>(U(i),e.nobrace||!/\{(?:(?!\{).)*\}/.test(i)?[i]:(0,Ye.default)(i));b.braceExpand=rt;var fe=(i,e={})=>new F(i,e).makeRe();b.makeRe=fe;var Pr=(i,e,t={})=>{let r=new F(e,t);return i=i.filter(s=>r.match(s)),r.options.nonull&&!i.length&&i.push(e),i};b.match=Pr;var qe=/[?*]|[+@!]\(.*?\)|\[|\]/,vr=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),F=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){U(e),t=t||{},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||tt,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...n)=>console.error(...n)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(n=>this.slashSplit(n));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((n,a,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=n[0]===""&&n[1]===""&&(n[2]==="?"||!qe.test(n[2]))&&!qe.test(n[3]),c=/^[a-z]:/i.test(n[0]);if(l)return[...n.slice(0,4),...n.slice(4).map(u=>this.parse(u))];if(c)return[n[0],...n.slice(1).map(u=>this.parse(u))]}return n.map(l=>this.parse(l))});if(this.debug(this.pattern,s),this.set=s.filter(n=>n.indexOf(!1)===-1),this.isWindows)for(let n=0;n<this.set.length;n++){let a=this.set[n];a[0]===""&&a[1]===""&&this.globParts[n][2]==="?"&&typeof a[3]=="string"&&/^[a-z]:$/i.test(a[3])&&(a[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let s=0;s<e[r].length;s++)e[r][s]==="**"&&(e[r][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let r=-1;for(;(r=t.indexOf("**",r+1))!==-1;){let s=r;for(;t[s+1]==="**";)s++;s!==r&&t.splice(r,s-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((r,s)=>{let n=r[r.length-1];return s==="**"&&n==="**"?r:s===".."&&n&&n!==".."&&n!=="."&&n!=="**"?(r.pop(),r):(r.push(s),r)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let n=e[s];s===1&&n===""&&e[0]===""||(n==="."||n==="")&&(t=!0,e.splice(s,1),s--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let s=e[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=!0,e.splice(r-1,2),r-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let r of e){let s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let a=s;for(;r[a+1]==="**";)a++;a>s&&r.splice(s+1,a-s);let o=r[s+1],l=r[s+2],c=r[s+3];if(o!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=!0,r.splice(s,1);let u=r.slice(0);u[s]="**",e.push(u),s--}if(!this.preserveMultipleSlashes){for(let a=1;a<r.length-1;a++){let o=r[a];a===1&&o===""&&r[0]===""||(o==="."||o==="")&&(t=!0,r.splice(a,1),a--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let n=0;for(;(n=r.indexOf("..",n+1))!==-1;){let a=r[n-1];if(a&&a!=="."&&a!==".."&&a!=="**"){t=!0;let l=n===1&&r[n+1]==="**"?["."]:[];r.splice(n-1,2,...l),r.length===0&&r.push(""),n-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let r=t+1;r<e.length;r++){let s=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(s){e[t]=[],e[r]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let s=0,n=0,a=[],o="";for(;s<e.length&&n<t.length;)if(e[s]===t[n])a.push(o==="b"?t[n]:e[s]),s++,n++;else if(r&&e[s]==="**"&&t[n]===e[s+1])a.push(e[s]),s++;else if(r&&t[n]==="**"&&e[s]===t[n+1])a.push(t[n]),n++;else if(e[s]==="*"&&t[n]&&(this.options.dot||!t[n].startsWith("."))&&t[n]!=="**"){if(o==="b")return!1;o="a",a.push(e[s]),s++,n++}else if(t[n]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return!1;o="b",a.push(t[n]),s++,n++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let s=0,n=0;if(this.isWindows){let o=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),l=!o&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),c=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),u=!c&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),h=l?3:o?0:void 0,g=u?3:c?0:void 0;if(typeof h=="number"&&typeof g=="number"){let[f,d]=[e[h],t[g]];f.toLowerCase()===d.toLowerCase()&&(t[g]=f,n=g,s=h)}}let{optimizationLevel:a=1}=this.options;return a>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(P)?this.#r(e,t,r,s,n):this.#i(e,t,r,s,n)}#r(e,t,r,s,n){let a=t.indexOf(P,n),o=t.lastIndexOf(P),[l,c,u]=r?[t.slice(n,a),t.slice(a+1),[]]:[t.slice(n,a),t.slice(a+1,o),t.slice(o+1)];if(l.length){let m=e.slice(s,s+l.length);if(!this.#i(m,l,r,0,0))return!1;s+=l.length}let h=0;if(u.length){if(u.length+s>e.length)return!1;let m=e.length-u.length;if(this.#i(e,u,r,m,0))h=u.length;else{if(e[e.length-1]!==""||s+u.length===e.length||(m--,!this.#i(e,u,r,m,0)))return!1;h=u.length+1}}if(!c.length){let m=!!h;for(let w=s;w<e.length-h;w++){let R=String(e[w]);if(m=!0,R==="."||R===".."||!this.options.dot&&R.startsWith("."))return!1}return r||m}let g=[[[],0]],f=g[0],d=0,p=[0];for(let m of c)m===P?(p.push(d),f=[[],0],g.push(f)):(f[0].push(m),d++);let y=g.length-1,x=e.length-h;for(let m of g)m[1]=x-(p[y--]+m[0].length);return!!this.#s(e,g,s,0,r,0,!!h)}#s(e,t,r,s,n,a,o){let l=t[s];if(!l){for(let h=r;h<e.length;h++){o=!0;let g=e[h];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1}return o}let[c,u]=l;for(;r<=u;){if(this.#i(e.slice(0,r+c.length),c,n,r,0)&&a<this.maxGlobstarRecursion){let f=this.#s(e,t,r+c.length,s+1,n,a+1,o);if(f!==!1)return f}let g=e[r];if(g==="."||g===".."||!this.options.dot&&g.startsWith("."))return!1;r++}return n||null}#i(e,t,r,s,n){let a,o,l,c;for(a=s,o=n,c=e.length,l=t.length;a<c&&o<l;a++,o++){this.debug("matchOne loop");let u=t[o],h=e[a];if(this.debug(t,u,h),u===!1||u===P)return!1;let g;if(typeof u=="string"?(g=h===u,this.debug("string match",u,h,g)):(g=u.test(h),this.debug("pattern match",u,h,g)),!g)return!1}if(a===c&&o===l)return!0;if(a===c)return r;if(o===l)return a===c-1&&e[a]==="";throw new Error("wtf?")}braceExpand(){return rt(this.pattern,this.options)}parse(e){U(e);let t=this.options;if(e==="**")return P;if(e==="")return"";let r,s=null;(r=e.match(cr))?s=t.dot?ur:lr:(r=e.match(Yt))?s=(t.nocase?t.dot?rr:tr:t.dot?er:Qt)(r[1]):(r=e.match(hr))?s=(t.nocase?t.dot?gr:fr:t.dot?pr:dr)(r):(r=e.match(sr))?s=t.dot?nr:ir:(r=e.match(ar))&&(s=or);let n=D.fromGlob(e,this.options).toMMPattern();return s&&typeof n=="object"&&Reflect.defineProperty(n,"test",{value:s}),n}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?wr:t.dot?xr:br,s=new Set(t.nocase?["i"]:[]),n=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let h of u.flags.split(""))s.add(h);return typeof u=="string"?vr(u):u===P?P:u._src});return c.forEach((u,h)=>{let g=c[h+1],f=c[h-1];u!==P||f===P||(f===void 0?g!==void 0&&g!==P?c[h+1]="(?:\\/|"+r+"\\/)?"+g:c[h]=r:g===void 0?c[h-1]=f+"(?:\\/|"+r+")?":g!==P&&(c[h-1]=f+"(?:\\/|\\/"+r+"\\/)"+g,c[h+1]=P))}),c.filter(u=>u!==P).join("/")}).join("|"),[a,o]=e.length>1?["(?:",")"]:["",""];n="^"+a+n+o+"$",this.negate&&(n="^(?!"+n+").+$");try{this.regexp=new RegExp(n,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let n=this.set;this.debug(this.pattern,"set",n);let a=s[s.length-1];if(!a)for(let o=s.length-2;!a&&o>=0;o--)a=s[o];for(let o=0;o<n.length;o++){let l=n[o],c=s;if(r.matchBase&&l.length===1&&(c=[a]),this.matchOne(c,l,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return b.defaults(e).Minimatch}};b.AST=D;b.Minimatch=F;b.escape=he;b.unescape=A;async function st(i,e,t){try{let r=new RegExp(e,t!=null&&t.caseSensitive?"g":"gi"),s=[],n=0,a=0,o=1*1024*1024,l=(t==null?void 0:t.absoluteSearchPath)??i.getCurrentWorkingDirectory(),c=async d=>{if(!(t!=null&&t.maxMatches&&s.length>=t.maxMatches)&&!(a>=o))try{let p=await K.stat(d),y=Math.min(p.size,Z.CHECK_BUFFER_SIZE);if(y>0){let w=await K.open(d,"r");try{let R=Buffer.alloc(y);if(await w.read(R,0,y,0),R.includes(0))return}finally{await w.close()}}let m=(await K.readFile(d,"utf-8")).split(`
2
+ `);n++;for(let w=0;w<m.length;w++){let R=m[w];if(!R)continue;let O=null;for(r.lastIndex=0;O=r.exec(R),!!O;){if(t!=null&&t.maxMatches&&s.length>=t.maxMatches)return;let M=5,S=5,X=Math.max(0,w-M),V=Math.min(m.length-1,w+S),ne=m.slice(X,V+1).join(`
3
+ `),$e={relativePath:ge.relative(l,d),absolutePath:d,line:w+1,column:O.index+1,match:O[0],preview:ne},ke=JSON.stringify($e).length;if(a+ke>o)return;s.push($e),a+=ke}}}catch{}},u=async(d,p)=>{var x;if((t==null?void 0:t.maxDepth)!==void 0&&p>t.maxDepth)return;let y=await K.readdir(d,{withFileTypes:!0});for(let m of y){let w=ge.join(d,m.name),R=ge.relative(l,w);if(!((x=t==null?void 0:t.excludePatterns)!=null&&x.some(O=>b(R,O)))&&!((t==null?void 0:t.respectGitignore)!==!1&&await i.isIgnored(w)))if(m.isFile()){if(t!=null&&t.filePattern&&!b(m.name,t.filePattern))continue;await c(w)}else m.isDirectory()&&(t!=null&&t.recursive)&&await u(w,p+1)}};await i.isDirectory(l)?await u(l,0):await c(l);let h=a>=o,g=(t==null?void 0:t.maxMatches)&&s.length>=t.maxMatches,f=`Found ${s.length} matches in ${n} files`;return h?f+=" (truncated due to output size limit)":g&&(f+=" (truncated due to match limit)"),{success:!0,message:f,matches:s,totalMatches:s.length,filesSearched:n}}catch(r){return{success:!1,message:`Failed to search: ${r instanceof Error?r.message:"Unknown error"}`,error:r instanceof Error?r.message:"Unknown error"}}}import{spawn as _r}from"node:child_process";import{existsSync as $r}from"node:fs";import{createInterface as kr}from"node:readline";import Or,{relative as Gr}from"node:path";import Sr from"node:os";import pe from"node:path";function N(i){let e=pe.join(i,"bin","ripgrep"),t=Sr.platform()==="win32"?"rg.exe":"rg";return pe.join(e,t)}function de(i){return pe.join(i,"bin","ripgrep")}function Ar(i,e,t){let r=[];if(r.push("--json"),r.push("--no-config"),r.push("--no-ignore-global"),t!=null&&t.caseSensitive?r.push("--case-sensitive"):r.push("-i"),(t==null?void 0:t.maxMatches)!==void 0&&r.push("--max-count",String(t.maxMatches)),(t==null?void 0:t.maxDepth)!==void 0&&r.push("--max-depth",String(t.maxDepth)),t!=null&&t.filePattern&&r.push("-g",t.filePattern),t!=null&&t.excludePatterns&&t.excludePatterns.length>0)for(let s of t.excludePatterns)r.push("--glob",`!${s}`);return(t==null?void 0:t.respectGitignore)===!1&&r.push("--no-ignore"),t!=null&&t.searchBinaryFiles&&r.push("--text"),r.push("-e",i),r.push(e),r}var Cr=10*1024*1024;async function Mr(i,e,t,r){let s=[],n=new Set,a=!1,o=new Map;return new Promise(l=>{let c=kr({input:i,crlfDelay:Number.POSITIVE_INFINITY});c.on("line",u=>{var h,g;if(!a){if(u.length>Cr){t==null||t(new Error(`Skipping overly large ripgrep output line (${u.length} bytes)`));return}try{let f=JSON.parse(u);if(f.type==="context"){let d=f.data,p=d.path.text;o.has(p)||o.set(p,[]),(h=o.get(p))==null||h.push({lineNum:d.line_number,text:d.lines.text})}else if(f.type==="match"){let d=f.data;n.add(d.path.text);let p=d.lines.text;for(let y of d.submatches)s.push({relativePath:Gr(e,d.path.text),absolutePath:Or.join(e,d.path.text),line:d.line_number,column:y.start+1,match:y.match.text,preview:p});if(r!=null&&r.maxMatches&&s.length>=r.maxMatches){a=!0,c.close(),(g=r.childProcess)==null||g.kill();return}}else f.type==="begin"&&(n.add(f.data.path.text),o.set(f.data.path.text,[]))}catch(f){t==null||t(new Error(`Failed to parse ripgrep JSON output: ${f}`))}}}),c.on("close",()=>{let u=`Found ${s.length} matches in ${n.size} files`;l({success:!0,message:u,matches:s,totalMatches:s.length,filesSearched:n.size})}),c.on("error",u=>{t==null||t(new Error(`Error reading ripgrep output: ${u}`)),l({success:!1,message:`Failed to parse ripgrep output: ${u instanceof Error?u.message:"Unknown error"}`,error:u instanceof Error?u.message:"Unknown error"})})})}async function it(i,e,t,r,s){try{let n=N(t);if(!n||!$r(n))return null;let a=(r==null?void 0:r.absoluteSearchPath)??i.getCurrentWorkingDirectory(),o=Ar(e,a,r),l=_r(n,o,{stdio:["ignore","pipe","pipe"],windowsHide:!0,cwd:i.getCurrentWorkingDirectory()});return l.stdout?(l.on("error",u=>{s==null||s(new Error(`Ripgrep process error: ${u}`))}),await Mr(l.stdout,a,s,{maxMatches:r==null?void 0:r.maxMatches,childProcess:l})):null}catch(n){return s==null||s(new Error(`Ripgrep execution failed, falling back to Node.js implementation: ${n}`)),null}}async function nt(i,e,t,r){let s=await it(i,e,t,r);return s!==null?s:st(i,e,r)}import{existsSync as Dr}from"node:fs";import{spawn as Nr}from"node:child_process";import{createInterface as Tr}from"node:readline";import Fr from"node:path";function I(i){return i.replace(/\\/g,"/")}function Ir(i,e){let t=[];if(t.push("--files"),t.push("--no-config"),t.push("--hidden"),t.push("-g","!.git"),i!=="**"&&t.push("-g",i),e!=null&&e.excludePatterns&&e.excludePatterns.length>0)for(let r of e.excludePatterns)t.push("-g",`!${r}`);return(e==null?void 0:e.respectGitignore)===!1&&t.push("--no-ignore"),t}async function jr(i,e,t,r){let s=[],n=!1;return new Promise(a=>{let o=Tr({input:i,crlfDelay:Number.POSITIVE_INFINITY});o.on("line",l=>{var c;if(!(n||!l.trim()))try{if(s.push(I(l)),r!=null&&r.maxResults&&s.length>=r.maxResults){n=!0,o.close(),(c=r.childProcess)==null||c.kill();return}}catch(u){t==null||t(new Error(`Failed to process ripgrep output line: ${u}`))}}),o.on("close",()=>{a({success:!0,message:`Found ${s.length} matching paths`,relativePaths:s,absolutePaths:s.map(l=>Fr.join(e,l)),totalMatches:s.length})}),o.on("error",l=>{t==null||t(new Error(`Error reading ripgrep output: ${l}`)),a({success:!1,message:`Failed to parse ripgrep output: ${l instanceof Error?l.message:"Unknown error"}`,error:l instanceof Error?l.message:"Unknown error",relativePaths:[],absolutePaths:[]})})})}async function at(i,e,t,r,s){try{let n=N(t);if(!n||!Dr(n))return null;let a=r!=null&&r.absoluteSearchPath?r.absoluteSearchPath:i.getCurrentWorkingDirectory(),o=Ir(e,r),l=Nr(n,o,{stdio:["ignore","pipe","pipe"],windowsHide:!0,cwd:a});return l.stdout?(l.on("error",u=>{s==null||s(new Error(`Ripgrep process error: ${u}`))}),await jr(l.stdout,i.getCurrentWorkingDirectory(),s,{maxResults:r==null?void 0:r.maxResults,childProcess:l})):null}catch(n){return s==null||s(new Error(`Ripgrep execution failed, falling back to Node.js implementation: ${n}`)),null}}import{promises as Wr}from"node:fs";import Br,{join as Ur}from"node:path";async function ot(i,e,t){try{let r=[],s=t!=null&&t.absoluteSearchPath?t.absoluteSearchPath:e.getCurrentWorkingDirectory(),n=((t==null?void 0:t.excludePatterns)??[]).map(c=>fe(c)),a=c=>n.some(u=>u!==!1&&u.test(c)),o=[s],l=t==null?void 0:t.maxResults;for(;o.length&&!(l&&r.length>=l);){let c=o.pop();try{let u=await Wr.opendir(c),h=[];for await(let g of u){let f=Ur(c,g.name),d=I(Br.relative(e.getCurrentWorkingDirectory(),f));h.push({dirent:g,full:f,rel:d})}for(let{dirent:g,full:f,rel:d}of h){if(l&&r.length>=l)break;if((t==null?void 0:t.respectGitignore)!==!1&&await e.isIgnored(f)||a(d))continue;if(b(d,i)&&g.isFile()){let y=t!=null&&t.absoluteSearchPath?f:d;r.push(y)}g.isDirectory()&&i.includes("**")&&o.push(f)}}catch{continue}}return{success:!0,message:`Found ${r.length} matching paths`,relativePaths:r,absolutePaths:r.map(c=>e.resolvePath(c)),totalMatches:r.length}}catch(r){return{success:!1,message:`Failed to glob: ${r instanceof Error?r.message:"Unknown error"}`,error:r instanceof Error?r.message:"Unknown error",relativePaths:[],absolutePaths:[]}}}async function ct(i,e,t,r){let s=await at(i,e,t,r);return s!==null?s:ot(e,i,r)}import{promises as E}from"node:fs";var Se=Ge(yt(),1);import Os from"chokidar";import ve from"node:os";import vt from"node:fs";import St from"node:util";import T from"node:path";import C from"node:fs";import wt from"node:os";import xt from"node:https";import re from"node:util";import H from"node:url";import ls from"node:child_process";import bt from"proxy-from-env";import{HttpsProxyAgent as Rt}from"https-proxy-agent";import us from"yauzl";var ee=T.join(wt.tmpdir(),"vscode-ripgrep-cache-1.0.0"),Ee=re.promisify(C.unlink),te=re.promisify(C.exists),hs=re.promisify(C.mkdir),Pe=wt.platform()==="win32",fs="microsoft/ripgrep-prebuilt";function gs(i){return H.parse(i).hostname==="api.github.com"}function Et(i,e,t,r){var a;let s=bt.getProxyForUrl(H.parse(i)),n;return s!==""?n={...t,agent:new Rt(s),proxy:s}:n=t,(a=n.headers)!=null&&a.authorization&&!gs(i)&&delete n.headers.authorization,new Promise((o,l)=>{r==null||r(`Download options: ${JSON.stringify(n)}`);let c=C.createWriteStream(e),u={...H.parse(i),...n};xt.get(u,h=>{if(r==null||r(`statusCode: ${h.statusCode}`),h.statusCode===302)return h.resume(),r==null||r(`Following redirect to: ${h.headers.location}`),Et(h.headers.location,e,n,r).then(o,l);if(h.statusCode!==200){l(new Error(`Download failed with ${h.statusCode}`));return}h.pipe(c),c.on("finish",()=>{o(void 0)})}).on("error",async h=>{await Ee(e),l(h)})})}function ps(i,e,t){t==null||t(`GET ${i}`);let r=bt.getProxyForUrl(H.parse(i)),s;return r!==""?s={...e,agent:new Rt(r)}:s=e,new Promise((n,a)=>{let o="";s={...H.parse(i),...s},xt.get(s,l=>{l.statusCode!==200&&a(new Error(`Request failed: ${l.statusCode}`)),l.on("data",c=>{o+=c.toString()}),l.on("end",()=>{n(o)}),l.on("error",c=>{a(c)})}).on("error",l=>a(l))})}function ds(i,e){return`https://api.github.com/repos/${i}/releases/tags/${e}`}async function ms(i,e,t,r){let s=T.join(t,e);if(!i.force&&await te(s))return r==null||r(`Using cached download: ${s}`),s;let n={headers:{"user-agent":"vscode-ripgrep"}};i.token&&(n.headers.authorization=`token ${i.token}`),r==null||r(`Finding release for ${i.version}`);let a=await ps(ds(fs,i.version),n,r),o;try{o=JSON.parse(a)}catch(c){throw new Error(`Malformed API response: ${c.stack}`)}if(!o.assets)throw new Error(`Bad API response: ${JSON.stringify(a)}`);let l=o.assets.find(c=>c.name===e);if(!l)throw new Error(`Asset not found with name: ${e}`);r==null||r(`Downloading from ${l.url}`),r==null||r(`Downloading to ${s}`),n.headers.accept="application/octet-stream",await Et(l.url,s,n,r)}function ys(i,e,t){return t==null||t(`Unzipping Windows zip to ${e}`),new Promise((r,s)=>{try{C.promises.mkdir(T.dirname(e),{recursive:!0}),us.open(i,{lazyEntries:!0},(n,a)=>{if(n){a==null||a.close(),s(n);return}a.readEntry(),a.on("entry",o=>{try{/\/$/.test(o.fileName)?(C.promises.mkdir(T.join(e,o.fileName),{recursive:!0}),a.readEntry()):a.openReadStream(o,(l,c)=>{if(l){a.close(),s(l);return}let u=C.createWriteStream(T.join(e,o.fileName));c.pipe(u),u.on("finish",()=>{u.close(()=>{a.readEntry()}),u.on("error",h=>{a.close(),s(h)})})})}catch(l){a.close(),s(l)}}),a.on("end",o=>{r(void 0)}),a.on("error",o=>{a.close(),s(o)})})}catch(n){s(n)}})}function ws(i,e,t){return new Promise((r,s)=>{let n=ls.spawn("tar",["xvf",i,"-C",e],{stdio:"inherit"});n.on("error",a=>{s(a)}),n.on("close",a=>{if(t==null||t(`tar xvf exited with ${a}`),a!==0){s(new Error(`tar xvf exited with ${a}`));return}r(void 0)})})}async function xs(i,e,t){Pe?await ys(i,e,t):await ws(i,e,t);let r=T.join(e,"rg");if(await te(r))return r;if(await te(`${r}.exe`))return`${r}.exe`;throw new Error(`Expecting rg or rg.exe unzipped into ${e}, didn't find one.`)}async function Pt(i){var s,n,a,o,l;let e=Pe?".zip":".tar.gz",t=["ripgrep",i.version,i.target].join("-")+e;await te(ee)||await hs(ee);let r=T.join(ee,t);try{await ms(i,t,ee,i.onLog)}catch(c){(s=i.onLog)==null||s.call(i,"Deleting invalid download cache");try{await Ee(r)}catch{(n=i.onLog)==null||n.call(i,"Failed to delete invalid download cache")}throw c}(a=i.onLog)==null||a.call(i,`Unzipping to ${i.destDir}`);try{let c=await xs(r,i.destDir,i.onLog);Pe||await re.promisify(C.chmod)(c,"755")}catch(c){(o=i.onLog)==null||o.call(i,"Deleting invalid download");try{await Ee(r)}catch{(l=i.onLog)==null||l.call(i,"Failed to delete invalid download")}throw c}}var bs=St.promisify(vt.exists),Rs=St.promisify(vt.mkdir),Es="v15.0.0",Ps="v13.0.0-4";async function vs(){let i=process.env.npm_config_arch||ve.arch();switch(ve.platform()){case"darwin":return i==="arm64"?"aarch64-apple-darwin":"x86_64-apple-darwin";case"win32":return i==="x64"?"x86_64-pc-windows-msvc":i==="arm64"?"aarch64-pc-windows-msvc":"i686-pc-windows-msvc";case"linux":return i==="x64"?"x86_64-unknown-linux-musl":i==="arm"||i==="armv7l"?"arm-unknown-linux-gnueabihf":i==="arm64"?"aarch64-unknown-linux-musl":i==="ppc64"?"powerpc64le-unknown-linux-gnu":i==="riscv64"?"riscv64gc-unknown-linux-gnu":i==="s390x"?"s390x-unknown-linux-gnu":"i686-unknown-linux-musl";default:throw new Error(`Unknown platform: ${ve.platform()}`)}}function Ss(i){return new Promise(e=>setTimeout(e,i))}async function _s(i,e=5,t){let r=0,s;for(;r<e;)try{return await i()}catch(n){if(s=n,r++,r>=e)break;let a=Math.pow(2,r)*1e3;t==null||t(`Download attempt ${r} failed, retrying in ${a/1e3} seconds...`),await Ss(a)}throw s}async function $s(i){let{rgBinaryBasePath:e,force:t=!1,onLog:r=()=>{}}=i;try{let s=de(e),n=N(e),a=await bs(s);if(!t&&a)return r("Ripgrep binary already exists"),{success:!0,rgPath:n};a||await Rs(s,{recursive:!0});let o=await vs(),l={version:o==="arm-unknown-linux-gnueabihf"||o==="powerpc64le-unknown-linux-gnu"||o==="s390x-unknown-linux-gnu"?Ps:Es,token:process.env.GITHUB_TOKEN,target:o,destDir:s,force:t,onLog:r};return await _s(()=>Pt(l)),r("Ripgrep installed successfully"),{success:!0,rgPath:n}}catch(s){let n=`Failed to install ripgrep: ${s instanceof Error?s.message:String(s)}`;return r(n),{success:!1,rgPath:null,error:n}}}var _e=class{config;gitignoreMap=new Map;gitignoreInitialized=!1;sortedGitignoreEntries=[];constructor(e){this.config=e}getCurrentWorkingDirectory(){return this.config.workingDirectory}setCurrentWorkingDirectory(e){this.config.workingDirectory=e,this.gitignoreInitialized=!1,this.gitignoreMap.clear(),this.sortedGitignoreEntries=[]}async readFile(e,t){try{let r=this.resolvePath(e),s=await E.readFile(r,"utf-8"),n=s.split(`
4
+ `),a=n.length;if((t==null?void 0:t.startLine)!==void 0){if(t.startLine>a)return{success:!1,message:`startLine ${t.startLine} exceeds file length (${a} lines)`,error:"LINE_OUT_OF_RANGE"};let o=t.endLine??a,l=Math.min(o,a);return{success:!0,content:n.slice(t.startLine-1,l).join(`
5
+ `),totalLines:a}}return{success:!0,content:s,totalLines:a}}catch(r){return{success:!1,message:`Failed to read file: ${e}`,error:r instanceof Error?r.message:"Unknown error"}}}async writeFile(e,t){try{let r=this.resolvePath(e);return await this.createDirectory(se(r)),await E.writeFile(r,t,"utf-8"),{success:!0,message:`Successfully wrote file: ${e}`}}catch(r){return{success:!1,message:`Failed to write file: ${e}`,error:r instanceof Error?r.message:"Unknown error"}}}async editFile(e,t,r,s){try{let n=this.resolvePath(e),o=(await E.readFile(n,"utf-8")).split(`
6
+ `);if(r>o.length||s>o.length)return{success:!1,message:`Line range ${r}-${s} exceeds file length (${o.length} lines)`,error:"LINE_OUT_OF_RANGE"};if(r<1||s<r)return{success:!1,message:`Invalid line range ${r}-${s}`,error:"INVALID_RANGE"};let l=o.slice(0,r-1),c=o.slice(s),u=t.split(`
7
+ `);return await E.writeFile(n,[...l,...u,...c].join(`
8
+ `),"utf-8"),{success:!0,message:`Successfully edited lines ${r}-${s}`}}catch(n){return{success:!1,message:`Failed to edit file: ${e}`,error:n instanceof Error?n.message:"Unknown error"}}}async createDirectory(e){try{let t=this.resolvePath(e);return await E.mkdir(t,{recursive:!0}),{success:!0,message:`Successfully created directory: ${e}`}}catch(t){return{success:!1,message:`Failed to create directory: ${e}`,error:t instanceof Error?t.message:"Unknown error"}}}async listDirectory(e,t){try{let r=this.resolvePath(e),s=[],n=0,a=0,o=async(l,c)=>{if((t==null?void 0:t.maxDepth)!==void 0&&c>t.maxDepth)return;let u=await E.readdir(l,{withFileTypes:!0});for(let h of u){let g=ie(l,h.name),f=k(r,g);if(!(t!=null&&t.pattern&&!b(f,t.pattern))&&!((t==null?void 0:t.respectGitignore)!==!1&&this.isIgnoredSync(g))){if(h.isDirectory())a++,(t==null?void 0:t.includeDirectories)!==!1&&s.push({relativePath:k(this.config.workingDirectory,g),name:h.name,type:"directory",depth:c}),t!=null&&t.recursive&&await o(g,c+1);else if(h.isFile()&&(n++,(t==null?void 0:t.includeFiles)!==!1)){let d=await E.stat(g);s.push({relativePath:k(this.config.workingDirectory,g),name:h.name,type:"file",size:d.size,depth:c})}}}};return await o(r,0),{success:!0,message:`Successfully listed directory: ${e}`,files:s,totalFiles:n,totalDirectories:a}}catch(r){return{success:!1,message:`Failed to list directory: ${e}`,error:r instanceof Error?r.message:"Unknown error"}}}async grep(e,t){return nt(this,e,this.config.rgBinaryBasePath,t)}async glob(e,t){return ct(this,e,this.config.rgBinaryBasePath,t)}async searchAndReplace(e,t,r,s){try{let n=this.resolvePath(e),o=(await E.readFile(n,"utf-8")).split(`
9
+ `),l=[],c=0,u=[],h;if(s!=null&&s.regex)h=new RegExp(t,s!=null&&s.caseSensitive?"g":"gi");else{let f=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");s!=null&&s.wholeWord&&(f=`\\b${f}\\b`),h=new RegExp(f,s!=null&&s.caseSensitive?"g":"gi")}for(let f=0;f<o.length;f++){let d=o[f]??"",p=d,y,x=[];for(h.lastIndex=0,y=h.exec(d);y&&(x.push({index:y.index,length:y[0].length,text:y[0]}),!(s!=null&&s.maxReplacements&&c+x.length>=s.maxReplacements));)y=h.exec(d);for(let m=x.length-1;m>=0;m--){let w=x[m];if(!w)continue;let R=r;if(s!=null&&s.preserveCase&&!(s!=null&&s.regex)&&(R=this.preserveCase(w.text,R)),l.push({line:f+1,column:w.index+1,oldText:w.text,newText:R,lineContent:d.trim()}),p=p.slice(0,w.index)+R+p.slice(w.index+w.length),c++,s!=null&&s.maxReplacements&&c>=s.maxReplacements)break}if(u.push(p),s!=null&&s.maxReplacements&&c>=(s==null?void 0:s.maxReplacements)){u.push(...o.slice(f+1));break}}let g=c>0&&!(s!=null&&s.dryRun);return g&&await E.writeFile(n,u.join(`
10
+ `),"utf-8"),{success:!0,message:s!=null&&s.dryRun?`Found ${c} occurrences (dry run - no changes made)`:`Replaced ${c} occurrences`,replacements:l,totalReplacements:c,fileModified:g}}catch(n){return{success:!1,message:`Failed to search and replace: ${n instanceof Error?n.message:"Unknown error"}`,error:n instanceof Error?n.message:"Unknown error"}}}preserveCase(e,t){if(!e||!t)return t||"";if(e===e.toUpperCase())return t.toUpperCase();if(e===e.toLowerCase())return t.toLowerCase();let r=e.charAt(0);return r&&r===r.toUpperCase()?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():t}async deleteFile(e){try{let t=this.resolvePath(e);return await E.unlink(t),{success:!0,message:`Successfully deleted file: ${e}`}}catch(t){return{success:!1,message:`Failed to delete file: ${e}`,error:t instanceof Error?t.message:"Unknown error"}}}async copyFile(e,t){try{let r=this.resolvePath(e),s=this.resolvePath(t);return await this.createDirectory(se(s)),await E.copyFile(r,s),{success:!0,message:`Successfully copied ${e} to ${t}`}}catch(r){return{success:!1,message:"Failed to copy file",error:r instanceof Error?r.message:"Unknown error"}}}async moveFile(e,t){try{let r=this.resolvePath(e),s=this.resolvePath(t);return await this.createDirectory(se(s)),await E.rename(r,s),{success:!0,message:`Successfully moved ${e} to ${t}`}}catch(r){return{success:!1,message:"Failed to move file",error:r instanceof Error?r.message:"Unknown error"}}}async fileExists(e){try{let t=this.resolvePath(e);return await E.access(t),!0}catch{return!1}}async isDirectory(e){try{let t=this.resolvePath(e);return(await E.stat(t)).isDirectory()}catch{return!1}}async getFileStats(e){let t=this.resolvePath(e),r=await E.stat(t);return{size:r.size,modifiedTime:r.mtime}}resolvePath(e){return _t(e)===e?e:_t(this.config.workingDirectory,e)}getDirectoryName(e){return se(e)}joinPaths(...e){return ie(...e)}getRelativePath(e,t){return I(k(e,t))}getFileExtension(e){return ks(e)}async getGitignorePatterns(){await this.ensureGitignoreInitialized();let e=[];for(let t of this.gitignoreMap.values())e.push(...t.patterns);return e}async isIgnored(e){return await this.ensureGitignoreInitialized(),this.isIgnoredSync(e)}isIgnoredSync(e){if(!e||e.includes("*")||e.includes("?")||e.includes("[")||e.includes("]")||e==="."||e===".."||!this.gitignoreInitialized)return!1;let t=this.resolvePath(e);for(let r of this.sortedGitignoreEntries)if(t.startsWith(r.directory)){let s=k(r.directory,t);if(s==="")continue;if(r.ignore.ignores(s))return!0}return!1}async isBinary(e){try{let t=this.resolvePath(e),r=await E.open(t,"r");try{let s=Buffer.allocUnsafe(Z.CHECK_BUFFER_SIZE),{bytesRead:n}=await r.read(s,0,s.length,0);return n===0?!1:s.subarray(0,n).includes(0)}finally{await r.close()}}catch{return!1}}async ensureGitignoreInitialized(){if(this.gitignoreInitialized)return;let e=[".git","node_modules","dist","build",".next","out","coverage",".cache",".turbo",".vscode",".idea","*.log",".DS_Store","Thumbs.db"];if(await this.findAndLoadGitignoreFiles(this.config.workingDirectory,e),this.gitignoreMap.size===0){let t=(0,Se.default)().add(e);this.gitignoreMap.set(this.config.workingDirectory,{ignore:t,directory:this.config.workingDirectory,patterns:e})}this.sortedGitignoreEntries=Array.from(this.gitignoreMap.values()).sort((t,r)=>r.directory.length-t.directory.length),this.gitignoreInitialized=!0}async findAndLoadGitignoreFiles(e,t,r=0,s=50){if(!(r>s))try{let n=ie(e,".gitignore"),a=[],o=!1;try{a=(await E.readFile(n,"utf-8")).split(`
11
+ `).map(h=>h.trim()).filter(h=>h&&!h.startsWith("#")),o=!0}catch{}if(o||e===this.config.workingDirectory){let c=[...a];if(e===this.config.workingDirectory&&c.push(...t),c.length>0){let u=(0,Se.default)().add(c);this.gitignoreMap.set(e,{ignore:u,directory:e,patterns:c})}}let l=await E.readdir(e,{withFileTypes:!0});for(let c of l)if(c.isDirectory()){let u=ie(e,c.name);if(t.includes(c.name)||c.name===".git"||c.name==="node_modules")continue;await this.isDirectoryIgnoredByParent(u,e)||await this.findAndLoadGitignoreFiles(u,t,r+1,s)}}catch{}}async isDirectoryIgnoredByParent(e,t){for(let[r,s]of this.gitignoreMap.entries())if(r===t||e.startsWith(r)){let n=k(r,e);if(s.ignore.ignores(n))return!0}return!1}async watchFiles(e,t){await this.ensureGitignoreInitialized();let r=Os.watch(this.resolvePath(e),{persistent:!0,ignored:s=>this.isIgnoredSync(s)});return r.on("add",s=>{t({type:"create",file:{absolutePath:s,relativePath:k(this.config.workingDirectory,s)}})}),r.on("change",s=>{t({type:"update",file:{absolutePath:s,relativePath:k(this.config.workingDirectory,s)}})}),r.on("unlink",s=>{t({type:"delete",file:{absolutePath:s,relativePath:k(this.config.workingDirectory,s)}})}),r.close}},$t=class{fileSystem;constructor(e){this.fileSystem=new _e({workingDirectory:e.workingDirectory,rgBinaryBasePath:e.rgBinaryBasePath})}};export{$t as ClientRuntimeNode,_e as NodeFileSystemProvider,$s as ensureRipgrepInstalled,de as getRipgrepBinDir,N as getRipgrepPath};
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Resolves the path to the ripgrep binary for the current platform.
3
+ *
4
+ * The function looks for the binary in the following locations:
5
+ * 1. binaries/ripgrep/{platform-target}/ (relative to package root)
6
+ *
7
+ * @returns Absolute path to the ripgrep binary, or null if not found/not executable
8
+ */
9
+ export declare function getRipgrepBinaryPath(): Promise<string | null>;
10
+ //# sourceMappingURL=binary-resolver.d.ts.map
@@ -0,0 +1,33 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ import type { Readable } from 'node:stream';
3
+ /**
4
+ * Options for executing ripgrep, matching the grep function's options
5
+ */
6
+ export interface RipgrepOptions {
7
+ recursive?: boolean;
8
+ maxDepth?: number;
9
+ filePattern?: string;
10
+ caseSensitive?: boolean;
11
+ maxMatches?: number;
12
+ excludePatterns?: string[];
13
+ respectGitignore?: boolean;
14
+ searchBinaryFiles?: boolean;
15
+ }
16
+ /**
17
+ * Result of executing ripgrep process
18
+ */
19
+ export interface RipgrepExecutionResult {
20
+ stdout: Readable;
21
+ process: ChildProcess;
22
+ }
23
+ /**
24
+ * Executes ripgrep with the given options and returns the process and stdout stream.
25
+ *
26
+ * @param binaryPath - Absolute path to ripgrep binary
27
+ * @param pattern - Search pattern
28
+ * @param searchPath - Path to search in
29
+ * @param options - Search options
30
+ * @returns Promise resolving to execution result, or null if spawn fails
31
+ */
32
+ export declare function executeRipgrep(binaryPath: string, pattern: string, searchPath: string, options?: RipgrepOptions, onError?: (error: Error) => void): Promise<RipgrepExecutionResult | null>;
33
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1,25 @@
1
+ import type { BaseFileSystemProvider, GrepResult } from '@stagewise/agent-runtime-interface';
2
+ /**
3
+ * Executes grep using ripgrep binary for improved performance.
4
+ *
5
+ * This function attempts to use the platform-specific ripgrep binary for
6
+ * searching. If ripgrep is not available or fails, it returns null to
7
+ * allow fallback to the Node.js implementation.
8
+ *
9
+ * @param fileSystem - File system provider for path resolution
10
+ * @param relativePath - Path to search (file or directory)
11
+ * @param pattern - Search pattern (regex)
12
+ * @param options - Search options
13
+ * @returns GrepResult if successful, null if ripgrep unavailable/failed
14
+ */
15
+ export declare function grepWithRipgrep(fileSystem: BaseFileSystemProvider, relativePath: string, pattern: string, options?: {
16
+ recursive?: boolean;
17
+ maxDepth?: number;
18
+ filePattern?: string;
19
+ caseSensitive?: boolean;
20
+ maxMatches?: number;
21
+ excludePatterns?: string[];
22
+ respectGitignore?: boolean;
23
+ searchBinaryFiles?: boolean;
24
+ }, onError?: (error: Error) => void): Promise<GrepResult | null>;
25
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,17 @@
1
+ import type { GrepResult } from '@stagewise/agent-runtime-interface';
2
+ import type { Readable } from 'node:stream';
3
+ /**
4
+ * Parses ripgrep's JSON output stream and converts it to GrepResult format.
5
+ *
6
+ * Ripgrep outputs one JSON object per line with different message types:
7
+ * - 'begin': Indicates start of results for a file
8
+ * - 'match': Contains actual match data
9
+ * - 'end': Indicates end of results for a file
10
+ * - 'summary': Final summary statistics
11
+ *
12
+ * @param stdout - Readable stream from ripgrep process stdout
13
+ * @param workingDirectory - Base directory for calculating relative paths
14
+ * @returns Promise resolving to GrepResult
15
+ */
16
+ export declare function parseRipgrepOutput(stdout: Readable, workingDirectory: string, onError?: (error: Error) => void): Promise<GrepResult>;
17
+ //# sourceMappingURL=output-parser.d.ts.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Platform target identifiers that match our binary directory structure
3
+ */
4
+ export type PlatformTarget = 'darwin-x64' | 'darwin-arm64' | 'linux-x64' | 'linux-arm64' | 'win32-x64' | 'win32-arm64';
5
+ /**
6
+ * Detects the current platform and architecture and returns the corresponding
7
+ * platform target identifier, or null if the platform is not supported.
8
+ *
9
+ * Supported platforms:
10
+ * - macOS: Intel (x64) and Apple Silicon (arm64)
11
+ * - Linux: x64 and ARM64
12
+ * - Windows: x64 and ARM64
13
+ *
14
+ * @returns Platform target string or null if unsupported
15
+ */
16
+ export declare function getPlatformTarget(): PlatformTarget | null;
17
+ /**
18
+ * Returns the binary filename for the current platform
19
+ */
20
+ export declare function getBinaryName(): string;
21
+ //# sourceMappingURL=platform.d.ts.map
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Binary file detection settings
3
+ */
4
+ export declare const BINARY_DETECTION: {
5
+ /**
6
+ * Number of bytes to check at the beginning of a file for binary detection.
7
+ * 8–16KB catches most binaries while remaining cheap.
8
+ */
9
+ CHECK_BUFFER_SIZE: number;
10
+ };
11
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Configuration for file system providers
3
+ */
4
+ export interface FileSystemProviderConfig {
5
+ workingDirectory: string;
6
+ rgBinaryBasePath: string;
7
+ }
8
+ /**
9
+ * Minimal interface for file system operations needed by grep/glob
10
+ * This avoids circular imports while providing type safety
11
+ */
12
+ export interface FileSystemOperations {
13
+ getCurrentWorkingDirectory(): string;
14
+ isIgnored(relativePath: string): Promise<boolean>;
15
+ isDirectory(relativePath: string): Promise<boolean>;
16
+ resolvePath(relativePath: string): string;
17
+ }
18
+ /**
19
+ * File change event for file watching
20
+ */
21
+ export interface FileChangeEvent {
22
+ type: 'create' | 'update' | 'delete';
23
+ file: {
24
+ absolutePath: string;
25
+ relativePath: string;
26
+ };
27
+ }
28
+ /**
29
+ * Base result type for file operations
30
+ */
31
+ export interface FileOperationResult {
32
+ success: boolean;
33
+ message: string;
34
+ error?: string;
35
+ }
36
+ /**
37
+ * Result type for file content operations
38
+ */
39
+ export interface FileContentResult extends FileOperationResult {
40
+ content?: string;
41
+ totalLines?: number;
42
+ }
43
+ /**
44
+ * Directory entry type
45
+ */
46
+ export interface DirectoryEntry {
47
+ relativePath: string;
48
+ name: string;
49
+ type: 'file' | 'directory';
50
+ size?: number;
51
+ depth: number;
52
+ }
53
+ /**
54
+ * Result type for directory listing
55
+ */
56
+ export interface DirectoryListResult extends FileOperationResult {
57
+ files?: DirectoryEntry[];
58
+ totalFiles?: number;
59
+ totalDirectories?: number;
60
+ }
61
+ /**
62
+ * Options for grep operations
63
+ */
64
+ export interface GrepOptions {
65
+ recursive?: boolean;
66
+ maxDepth?: number;
67
+ filePattern?: string;
68
+ absoluteSearchPath?: string;
69
+ caseSensitive?: boolean;
70
+ maxMatches?: number;
71
+ excludePatterns?: string[];
72
+ respectGitignore?: boolean;
73
+ }
74
+ /**
75
+ * Single grep match
76
+ */
77
+ export interface GrepMatch {
78
+ relativePath: string;
79
+ absolutePath: string;
80
+ line: number;
81
+ column: number;
82
+ match: string;
83
+ preview: string;
84
+ }
85
+ /**
86
+ * Result type for grep operations
87
+ */
88
+ export interface GrepResult extends FileOperationResult {
89
+ matches?: GrepMatch[];
90
+ totalMatches?: number;
91
+ filesSearched?: number;
92
+ }
93
+ /**
94
+ * Options for glob operations
95
+ */
96
+ export interface GlobOptions {
97
+ absoluteSearchPath?: string;
98
+ excludePatterns?: string[];
99
+ respectGitignore?: boolean;
100
+ maxResults?: number;
101
+ }
102
+ /**
103
+ * Result type for glob operations
104
+ */
105
+ export interface GlobResult extends FileOperationResult {
106
+ relativePaths: string[];
107
+ absolutePaths: string[];
108
+ totalMatches?: number;
109
+ }
110
+ /**
111
+ * Single search/replace match
112
+ */
113
+ export interface SearchReplaceMatch {
114
+ line: number;
115
+ column: number;
116
+ oldText: string;
117
+ newText: string;
118
+ lineContent: string;
119
+ }
120
+ /**
121
+ * Result type for search/replace operations
122
+ */
123
+ export interface SearchReplaceResult extends FileOperationResult {
124
+ replacements?: SearchReplaceMatch[];
125
+ totalReplacements?: number;
126
+ fileModified?: boolean;
127
+ }
128
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,10 @@
1
+ export type DownloadRipgrepOptions = {
2
+ version: string;
3
+ target: string;
4
+ destDir: string;
5
+ force?: boolean;
6
+ token?: string;
7
+ onLog?: (message: string) => void;
8
+ };
9
+ export declare function downloadRipgrep(opts: DownloadRipgrepOptions): Promise<void>;
10
+ //# sourceMappingURL=download.d.ts.map
@@ -0,0 +1,21 @@
1
+ export type EnsureRipgrepResult = {
2
+ success: boolean;
3
+ rgPath: string | null;
4
+ error?: string;
5
+ };
6
+ export type EnsureRipgrepOptions = {
7
+ rgBinaryBasePath: string;
8
+ force?: boolean;
9
+ onLog?: (message: string) => void;
10
+ };
11
+ /**
12
+ * Ensures ripgrep binary is installed and available.
13
+ * This function can be called from application code to ensure ripgrep is available.
14
+ *
15
+ * @param options.rgBinaryBasePath - Base directory where ripgrep should be installed (e.g., ~/.stagewise)
16
+ * @param options.force - Force reinstallation even if binary exists
17
+ * @param options.onLog - Optional logging callback
18
+ * @returns Result object with success status, path to ripgrep binary, and optional error message
19
+ */
20
+ export declare function ensureRipgrepInstalled(options: EnsureRipgrepOptions): Promise<EnsureRipgrepResult>;
21
+ //# sourceMappingURL=ensure-ripgrep.d.ts.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Determines the ripgrep binary path based on a base directory and platform.
3
+ *
4
+ * @param rgBinaryBasePath - Base directory where ripgrep should be stored (e.g., ~/.stagewise)
5
+ * @returns Full path to the ripgrep binary
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const rgPath = getRipgrepPath('/home/user/.stagewise');
10
+ * // Returns: '/home/user/.stagewise/bin/rg' on Unix
11
+ * // Returns: 'C:\\Users\\user\\.stagewise\\bin\\rg.exe' on Windows
12
+ * ```
13
+ */
14
+ export declare function getRipgrepPath(rgBinaryBasePath: string): string;
15
+ /**
16
+ * Gets the directory where the ripgrep binary should be stored.
17
+ *
18
+ * @param rgBinaryBasePath - Base directory where ripgrep should be stored
19
+ * @returns Directory path for the ripgrep binary
20
+ */
21
+ export declare function getRipgrepBinDir(rgBinaryBasePath: string): string;
22
+ //# sourceMappingURL=get-path.d.ts.map
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@stagewise/agent-runtime-node",
3
+ "version": "0.2.0",
4
+ "author": "stagewise GmbH",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist/**/*.js",
17
+ "dist/**/*.d.ts"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "dependencies": {
23
+ "chokidar": "^4.0.3",
24
+ "https-proxy-agent": "^7.0.6",
25
+ "ignore": "^7.0.5",
26
+ "minimatch": "9.0.9",
27
+ "proxy-from-env": "^1.1.0",
28
+ "yauzl": "^3.3.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/express": "^5.0.3",
32
+ "@types/node": "^20.0.0",
33
+ "@types/proxy-from-env": "^1.0.4",
34
+ "@types/ws": "^8.18.1",
35
+ "@types/yauzl": "^2.10.3",
36
+ "@vitest/coverage-v8": "^3.2.4",
37
+ "esbuild": "0.25.9",
38
+ "rimraf": "^5.0.0",
39
+ "typescript": "^5.0.0",
40
+ "vitest": "^3.2.4"
41
+ },
42
+ "scripts": {
43
+ "build": "tsx build.ts && tsc --emitDeclarationOnly",
44
+ "dev": "tsx build.ts --watch",
45
+ "clean": "rimraf dist",
46
+ "lint": "biome check .",
47
+ "type-check": "tsc --noEmit",
48
+ "test": "vitest run",
49
+ "test:watch": "vitest",
50
+ "test:coverage": "vitest run --coverage"
51
+ }
52
+ }