@forsion/extend 0.10.7 → 0.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/SIGNATURE +8 -6
- package/dist/desktop.mjs +1 -1
- package/dist/main.js +83 -49
- package/manifest.json +1 -1
- package/package.json +3 -1
- package/tangu-plugins/agent-feedback/dist/index.mjs +2 -0
- package/tangu-plugins/agent-feedback/tangu-plugin.json +8 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## 0.10.8 — 2026-11-17
|
|
4
|
+
|
|
5
|
+
- 新增「反馈给 Forsion」:Agent 碰到 Forsion 自己的问题时(Forsion 自带工具出内部错误、行为和文档对不上、开发插件时宿主接口缺能力),会在对话里起草一张反馈卡,日志已经备好。卡上可以改标题和描述、逐项选附带的内容(缺省带这次运行的报错和运行日志,不带会话内容),点「发送」才发出。你之前报过同一个问题时,发送会补充到那一条。在「设置 → 插件 → 反馈给 Forsion」里可以改成「起草并直接发送」(不带会话内容,10 分钟内可以撤回)或「不用起草」。需要新版桌面与云端服务。
|
|
6
|
+
- 商店投稿页:插件声明要用内部接口(`internals-raw`)时,需要填写申请理由,审核时会看到。
|
|
7
|
+
|
|
8
|
+
- Adds Feedback to Forsion: when the agent runs into a problem in Forsion itself (an internal error from a built-in tool, behavior that doesn't match the documentation, or a missing host API while you build a plugin), it drafts a feedback card in the conversation with the logs ready. You can edit the title and description and choose what to include (errors from this run and runtime logs by default, never the conversation unless you tick it); nothing is sent until you click Send. If you already reported the same problem, sending adds to that report. In Settings → Plugins → Feedback to Forsion you can switch to "Draft and send automatically" (no conversation, withdraw within 10 minutes) or "Don't draft". Requires a newer desktop and server.
|
|
9
|
+
- Store submission: when a plugin declares internal interfaces (`internals-raw`), you now give a reason for the request, which reviewers see.
|
|
10
|
+
|
|
3
11
|
## 0.10.7 — 2026-11-16
|
|
4
12
|
|
|
5
13
|
- 修复 Windows 同步大量文件时,整个窗口间歇性无响应的问题;AI 输出文字或执行工具期间,界面不再被这类同步检查长时间卡住。
|
package/SIGNATURE
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"alg": "ed25519",
|
|
3
3
|
"files": {
|
|
4
|
-
"CHANGELOG.md": "
|
|
4
|
+
"CHANGELOG.md": "db1ae1e4d38405ec80c20303188fc3943079ff8ed080b3e46d1f35e1234002fb",
|
|
5
5
|
"LICENSE": "5594544ee08011ed5785ee26410f1f2ef005f66e9283833e8d435e34c10de1ed",
|
|
6
6
|
"README.md": "922bf69a9f41e77167d73b6d508b2a88c1e7e5c54f3ad746b57bc0d6d96098a8",
|
|
7
7
|
"dist/THIRD_PARTY_NOTICES.md": "0af426bcae1e6cd82d3f6255768ac232eea116c7079706ae237d2f1f494531b4",
|
|
8
|
-
"dist/desktop.mjs": "
|
|
9
|
-
"dist/main.js": "
|
|
10
|
-
"manifest.json": "
|
|
11
|
-
"package.json": "
|
|
8
|
+
"dist/desktop.mjs": "19f624f6a81094e679f91d0eb7a133c686c21b05f0484fd30a2cd2832eb54949",
|
|
9
|
+
"dist/main.js": "8ce62d557b57aaddb1cd397bf6b9bf54f24f1344207ec877ffdb0471fa490b0e",
|
|
10
|
+
"manifest.json": "3d010140610f6aaea78f7fae9b0040cb25fd773da69aa551591246583181cb15",
|
|
11
|
+
"package.json": "9825019d206cf7ce6f8d41aef2015eb3cee4c7c094474e8abb967fea35e4b53a",
|
|
12
12
|
"spaces/guide/space.json": "7da9fb9373278e9e1f75c65f697a21f25b0b45792def0ce94ed5e7f6473979b1",
|
|
13
13
|
"spaces/penzor/icon.svg": "3c212d9f121ae54a0a84042c19ff5573e22cb236718ae4de11fc3c19f0c3b634",
|
|
14
14
|
"spaces/penzor/space.json": "a3b6c4d86c54dca38b24d3efe352fed860ce7accc934f9f160600ff65ed4f0e6",
|
|
15
|
+
"tangu-plugins/agent-feedback/dist/index.mjs": "bc75faf38f6856f90ed9634cbc54e301eef5f5523be19aa724a78721d8744eb1",
|
|
16
|
+
"tangu-plugins/agent-feedback/tangu-plugin.json": "ef91d1cd9d5a9f760b35aab9e1d7da1141bbade9327a9200ea168e82db8a45f4",
|
|
15
17
|
"tangu-plugins/store-update/dist/index.mjs": "d8f531b7d6acf5d6369ac4d2383ec33b2b615a283d56b0087b467a123ac3bb8d",
|
|
16
18
|
"tangu-plugins/store-update/tangu-plugin.json": "a99e71329e705793eec46d9e8d4b790017136c328f670161cd4d57e49ee4dd0a",
|
|
17
19
|
"widgets/sync/manifest.json": "98c3165cb6c523223565283ba35d1069536181adc0a29f764a932ef543df677e"
|
|
18
20
|
},
|
|
19
|
-
"sig": "
|
|
21
|
+
"sig": "Kqg0KR2z+ggXGOIeAfuQwnY4OqCLcSWcLA9QStXEjytPXAK4nqUafyIkFIVh95Xjh+15I/8afbB7SAEKFMQjDg=="
|
|
20
22
|
}
|
package/dist/desktop.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Oo=null;function Yi(t){Oo=t}function ve(){if(!Oo)throw new Error("core host not set (call setCoreHost first)");return Oo}var Gi=new TextEncoder,rd=new TextDecoder("utf-8",{ignoreBOM:!0}),Rn=t=>Gi.encode(t),vt=t=>rd.decode(t),_r=t=>typeof t=="string"?Gi.encode(t).length:t.length;function Ji(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function Cr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),n=>n.charCodeAt(0))}async function Ki(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Ne(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let o=r.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(o),c=>c.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(s)),a=i.userId??i.sub;return typeof a!="string"&&typeof a!="number"||!String(a).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(a)}`}catch{return null}}function Mo(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(vt(Cr(e)));return n&&typeof n=="object"?n:null}catch{return null}}function Po(t,e=Date.now()){let n=Mo(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Xi(t,e=Date.now()){let n=Mo(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var od=36e5;function Ar(t,e=Date.now()){return!!t&&Po(t,e)>=od}async function xr(t,e,n=8e3,r){if(!t||!e)return null;let o=t.replace(/\/+$/,"");try{let s=await fetch(`${o}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!s.ok)return null;let i=await s.json().catch(()=>null),a=typeof i?.token=="string"?i.token:"";return a&&a!==e?a:null}catch{return null}}var Dn=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,sd=(t,e)=>new Promise((n,r)=>{let o=()=>{clearTimeout(s),r(new Error("Sign-in cancelled."))},s=setTimeout(()=>{e.removeEventListener("abort",o),n()},t);e.aborted?o():e.addEventListener("abort",o,{once:!0})});function Zi(t,e){let n=d=>e.write(JSON.stringify(d,null,2)),r=()=>{let d;try{d=e.read()}catch(g){return g?.code==="ENOENT"?[]:null}if(d===null)return[];try{let g=JSON.parse(d);return Array.isArray(g.accounts)?g.accounts.filter(h=>h&&typeof h.token=="string"&&h.id===Ne(h.cloudUrl,h.token)):null}catch{return null}},o=(d,g)=>{let h=Ne(d.cloudUrl||"",d.token||"");if(!h||!d.token||!d.cloudUrl)return;let m=r();if(!m)return;let y=m.find(k=>k.id===h),p=Mo(d.token),S={...y,id:h,cloudUrl:d.cloudUrl.replace(/\/+$/,""),token:d.token,username:g?.username||y?.username||p?.username,nickname:g?.nickname||y?.nickname};JSON.stringify(y)!==JSON.stringify(S)&&n({version:1,accounts:[...m.filter(k=>k.id!==h),S]})},s=()=>{let d=t.readCreds();o(d);let g=Ne(d.cloudUrl,d.token);return(r()??[]).map(({token:h,...m})=>({...m,active:m.id===g}))},i=d=>{let g=r()?.find(h=>h.id===d);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},a=d=>{let g=Ne(d.cloudUrl||"",d.token||""),h=r();g&&h&&n({version:1,accounts:h.filter(m=>m.id!==g)})},c=null;return{rememberForsionAccount:o,forsionAccounts:s,savedForsionAccount:i,forgetForsionAccount:a,cancelForsionLogin:()=>{c?.abort(),c=null},forsionDeviceLogin:async(d,g,h)=>{if(c)throw new Error("A sign-in is already in progress.");if(!d)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let m=new AbortController;c=m;let y=()=>{if(m.signal.aborted||c!==m)throw new Error("Sign-in cancelled.")};try{let p=d.replace(/\/+$/,""),S;try{S=await fetch(`${p}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(A=>A.json())}catch(A){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${p}:${A?.message||A}`)}if(y(),!S?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let k=S.verification_uri_complete||`${S.verification_uri}?code=${S.user_code}`,P=new URL(`${p}/auth`);P.searchParams.set("logout","1"),P.searchParams.set("app","forsion-desktop"),P.searchParams.set("redirect",k);let R=P.toString();g?.({url:R,userCode:String(S.user_code||"")}),t.openExternal(R);let O=Date.now()+(S.expires_in||600)*1e3,w=(S.interval||2)*1e3;for(;Date.now()<O;){await sd(w,m.signal),y();let A=null;try{A=await fetch(`${p}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:S.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),A.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let C=await A.json().catch(()=>({status:"pending"}));if(y(),C.status==="approved"&&C.token){let D={cloudUrl:p,token:C.token};return await h(D,y),y(),{token:C.token,cloudUrl:p}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{c===m&&(c=null)}},readAccounts:()=>r()??[]}}function kt(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,o;try{r=new URL(n),o=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||o.origin!==r.origin||!o.pathname.startsWith("/api/")?null:o.toString()}function On(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function He(t,e,n,r,o=6e4){let s=await(t.fetch??fetch)(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token&&!t.fetch?{Authorization:`Bearer ${t.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(o)}),i=await s.json().catch(()=>({}));return{status:s.status,json:i}}var id=50*1024*1024,ad=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms"]);function cd(t){if(!t||typeof t!="object")return null;let e=t;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let n=new FormData,r=0;for(let[o,s]of Object.entries(e.fields)){if(!ad.has(o)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms"].includes(o))return null;n.append(o,s)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>id)return null;n.append("zip",new Blob([new Uint8Array(e.zip.data)],{type:"application/zip"}),e.zip.name.replace(/[\\/]/g,"_").slice(-255))}return{path:`${e.id?`/market/mine/${e.id}/update`:"/market/submit"}${e.dryRun===!0?"?dryRun=1":""}`,body:n}}function Qi(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=cd(n);if(!r)return{status:400,json:{error:"invalid_request"}};let o=await t.getCloud();if(!o.token)return{status:401,error:"not_signed_in"};let s=kt(o.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let i=await On(o,s,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:i.status,json:await i.json().catch(()=>null)}}catch(i){return{status:0,error:String(i?.message||i)}}})}async function ea(t){if(!t.token)return"";try{let e=await He(t,"POST","/api/auth/handoff",{},5e3);if(e.status===200&&typeof e.json?.code=="string"&&e.json.code)return`code=${encodeURIComponent(e.json.code)}`;if((e.status===404||e.status===405)&&!t.fetch)return`token=${encodeURIComponent(t.token)}`}catch{}return""}var ta=["membership","credits","storefront"],na=["monthly","quarterly","yearly"],ld=/^[A-Za-z0-9_-]{1,64}$/;function ra(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(o,s)=>{if(!t.isTrustedSender(o))return n;let i=await t.getCloud(),a=i.base;if(!a)return{ok:!1};let c=s&&/^[a-z0-9-]+$/i.test(s)?`#${s}`:"",l=await ea(i),u=`${a}/account${l?`?${l}`:""}${c}`;return i.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(o,s,i,a)=>{if(!t.isTrustedSender(o))return n;if(s!==void 0&&!ta.includes(s))return{ok:!1,error:"invalid_tab"};if(i!==void 0&&(typeof i!="string"||!ld.test(i)))return{ok:!1,error:"invalid_plan"};if(a!==void 0&&!na.includes(a))return{ok:!1,error:"invalid_period"};let c=(s??"membership")==="membership"&&i?`&plan=${encodeURIComponent(i)}${a?`&period=${a}`:""}`:"",l=await t.getCloud(),u=l.base;if(!u)return{ok:!1};let d=await ea(l),g=`${u}/pay?tab=${s??"membership"}${c}${d?`&${d}`:""}&redirect=${encodeURIComponent(`${u}/account`)}`;return l.signal?.throwIfAborted(),await t.openExternal(g),{ok:!0}}),t.handle("profile:publicOrigin",async o=>{if(!t.isTrustedSender(o))return n;let{base:s}=await t.getCloud();if(!s)return{ok:!1};try{let i=await fetch(`${s}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});i.body?.cancel().catch(()=>{});let a=i.status>=300&&i.status<400?i.headers.get("location"):null;return a&&/^https?:\/\//i.test(a)?{ok:!0,origin:new URL(a).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async o=>{if(!t.isTrustedSender(o))return e;let s=await r();if(!s.token)return{status:401,json:null};try{return await He(s,"GET","/api/token-quota/my",void 0,15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),t.handle("account:useResetCard",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(s!==void 0&&s!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${s}`}};let a=s??"both";try{return await He(i,"POST","/api/token-quota/reset-card/use",{type:a},15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgConvert",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(!Number.isInteger(s)||s<1||s>100)return{status:400,json:{error:"invalid_percent"}};try{return await He(i,"POST","/api/token-quota/background/convert",{percent:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:pointsAutoDeduct",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await He(i,"POST","/api/token-quota/auto-deduct",{enabled:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:bgAutoMain",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await He(i,"POST","/api/token-quota/background/auto-main",{enabled:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("feedback:submit",async(o,s)=>{if(!t.isTrustedSender(o))return n;let i=await t.getCloud();if(!i.base||!i.token)return{ok:!1,error:"not-logged-in"};if(s?.expectedAccountId!==void 0){let u=s.expectedAccountId;if(typeof u!="string"||!u||Ne(i.base,i.token)!==u)return{ok:!1,error:"account-changed"}}let a=(s?.description||"").trim();if(!a)return{ok:!1,error:"empty"};if(a.length>1e4)return{ok:!1,error:"description-too-long"};let c=[],l=!1;if(s?.sessionLogJson){let u=Rn(s.sessionLogJson);if(u.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};c.push({filename:s.sessionLogName||"tangu-session.json",mime_type:"application/json",size:u.length,data_base64:Ji(u)})}try{let u=await On(i,`${i.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:a,attachments:c}),signal:AbortSignal.timeout(2e4)});if(!u.ok){let g=`HTTP ${u.status}`;try{g=(await u.json())?.detail||g}catch{}return{ok:!1,error:g}}return{ok:!0,id:(await u.json().catch(()=>({})))?.id??null,attachmentSkipped:l}}catch(u){return{ok:!1,error:u?.message||String(u)}}}),t.handle("cloud:fetch",async(o,s)=>{if(!t.isTrustedSender(o))return{status:0,error:"untrusted"};let i=s??{},a=typeof i.path=="string"?i.path:"",c=i.projectSource===void 0?null:i.projectSource;if(c!==null&&(typeof c!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(c)))return{status:0,error:"bad_project_source"};let l=Math.min(12e4,Math.max(1e3,Number(i.timeoutMs)||15e3)),u=typeof i.method=="string"?i.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(u))return{status:0,error:"bad_method"};if(!a.startsWith("/"))return{status:0,error:"bad_path"};let d=await t.getCloud();if(!String(d.base||""))return{status:0,error:"no_cloud_url"};let g=kt(d.base,a);if(!g)return{status:0,error:"bad_path"};if(!d.token)return{status:401,error:"not_signed_in"};let h=i.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,y=setTimeout(()=>m.abort(),l);try{let p=await On(d,g,{method:u,headers:{...h?{"Content-Type":"application/json"}:{},...c?{"X-Project-Source":c}:{}},body:h?JSON.stringify(i.body):void 0,signal:m.signal});return{status:p.status,json:await p.json().catch(()=>null)}}catch(p){return{status:0,error:String(p?.message||p)}}finally{clearTimeout(y)}}),Qi(t)}import{createHash as xa}from"node:crypto";import{existsSync as af,promises as cf,readFileSync as lf,renameSync as uf,statSync as df}from"node:fs";import ff from"node:path";import{EventEmitter as Fd}from"node:events";import{stat as Ld}from"node:fs";import{readdir as Ud,stat as Hd}from"node:fs/promises";import*as le from"node:path";import{lstat as oa,readdir as ud,realpath as dd,stat as fd}from"node:fs/promises";import{join as pd,resolve as hd,sep as sa}from"node:path";import{Readable as gd}from"node:stream";var Ve={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},tn={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Ve.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(tn);var la="READDIRP_RECURSIVE_ERROR",md=new Set(["ENOENT","EPERM","EACCES","ELOOP",la]),ia=[Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE],yd=new Set([Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE]),wd=new Set([Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE]),bd=t=>md.has(t.code),Sd=process.platform==="win32",aa=t=>!0,ca=t=>{if(t===void 0)return aa;if(typeof t=="function")return t;if(typeof t=="string"){let e=t.trim();return n=>n.basename===e}if(Array.isArray(t)){let e=t.map(n=>n.trim());return n=>e.some(r=>n.basename===r)}return aa},$o=class extends gd{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??tn.highWaterMark});let n={...tn,...e},r=n.root??tn.root,o=n.type??tn.type;this._fileFilter=ca(n.fileFilter),this._directoryFilter=ca(n.directoryFilter);let s=n.lstat?oa:fd;Sd?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:tn.depth,this._wantsDir=yd.has(o),this._wantsFile=wd.has(o),this._wantsEverything=o===Ve.EVERYTHING_TYPE,this._root=hd(r),this._relStart=this._root.endsWith(sa)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let i={path:this._root,depth:1};i.pending=this._exploreDir(this._root,1),this.parents=[i],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:o,depth:s}=n,i=r.splice(0,e).map(c=>this._formatEntry(c,o)),a=this._isDirent?i:await Promise.all(i);for(let c of a){if(!c)continue;if(this.destroyed)return;let l=this._getEntryType(c);typeof l!="string"&&(l=await l),l==="directory"&&this._directoryFilter(c)?(s<=this._maxDepth&&this.parents.push({path:c.fullPath,depth:s+1}),this._wantsDir&&(this.push(c),e--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let o=this.parents.pop();if(!o){this.push(null);break}let s=o.pending??this._exploreDir(o.path,o.depth),i=this.parents[this.parents.length-1];if(i&&!i.pending&&(i.pending=this._exploreDir(i.path,i.depth)),this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await ud(e,this._rdOptions)}catch(o){this._onError(o)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,o=pd(n,r),s={path:o.slice(this._relStart),fullPath:o,basename:r};return this._isDirent?(s.dirent=e,s):this._stat(o).then(i=>(s.stats=i,s),i=>{this._onError(i)})}_onError(e){bd(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let n=e[this._statsProp];return n.isFile()?"file":n.isDirectory()?"directory":n.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let n=e.fullPath;try{let r=await dd(n),o=await oa(r);if(o.isFile())return"file";if(o.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===sa){let i=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return i.code=la,this._onError(i),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function ua(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Ve.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!ia.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${ia.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:t};return n&&(r.type=n),new $o(r)}import{watch as vd,unwatchFile as da,watchFile as kd}from"node:fs";import{realpath as No,lstat as Ed,open as _d,stat as pa}from"node:fs/promises";import{type as Cd}from"node:os";import*as me from"node:path";var Ad="data",Lo="end",ha="close",Or=()=>{};var Mr=process.platform,Uo=Mr==="win32",xd=Mr==="darwin",Td=Mr==="linux",Id=Mr==="freebsd",ga=Cd()==="OS400",Se={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},it=Se,Rd="watch",Dd={lstat:Ed,stat:pa},zt="listeners",Tr="errHandlers",nn="rawEmitters",Od=[zt,Tr,nn],Md=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Pd=t=>Md.has(me.extname(t).slice(1).toLowerCase()),Fo=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Mn=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},$d=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},Pn=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ma=t=>t instanceof Set?t.size===0:!t,Ir=new Map;function fa(t,e,n,r,o){let s=(i,a)=>{n(t),o(i,a,{watchedPath:t}),a&&t!==a&&Rr(me.resolve(t,a),zt,me.join(t,a))};try{return vd(t,{persistent:e.persistent},s)}catch(i){r(i);return}}var Rr=(t,e,n,r,o)=>{let s=Ir.get(t);s&&Fo(s[e],i=>{i(n,r,o)})},Nd=(t,e,n,r)=>{let{listener:o,errHandler:s,rawEmitter:i}=r,a=Ir.get(e),c;if(!n.persistent)return c=fa(t,n,o,s,i),c?c.close.bind(c):void 0;if(a)Mn(a,zt,o),Mn(a,Tr,s),Mn(a,nn,i);else{if(c=fa(t,n,Rr.bind(null,e,zt),s,Rr.bind(null,e,nn)),!c)return;c.on(it.ERROR,async l=>{let u=Rr.bind(null,e,Tr);if(a&&(a.watcherUnusable=!0),Uo&&l.code==="EPERM")try{await(await _d(t,"r")).close(),u(l)}catch{}else u(l)}),a={listeners:o,errHandlers:s,rawEmitters:i,watcher:c},Ir.set(e,a)}return()=>{Pn(a,zt,o),Pn(a,Tr,s),Pn(a,nn,i),ma(a.listeners)&&(a.watcher.close(),Ir.delete(e),Od.forEach($d(a)),a.watcher=void 0,Object.freeze(a))}},jo=new Map,jd=(t,e,n,r)=>{let{listener:o,rawEmitter:s}=r,i=jo.get(e),a=i&&i.options;return a&&(a.persistent<n.persistent||a.interval>n.interval)&&(da(e),i=void 0),i?(Mn(i,zt,o),Mn(i,nn,s)):(i={listeners:o,rawEmitters:s,options:n,watcher:kd(e,n,(c,l)=>{Fo(i.rawEmitters,d=>{d(it.CHANGE,e,{curr:c,prev:l})});let u=c.mtimeMs;(c.size!==l.size||u>l.mtimeMs||u===0)&&Fo(i.listeners,d=>d(t,c))})},jo.set(e,i)),()=>{Pn(i,zt,o),Pn(i,nn,s),ma(i.listeners)&&(jo.delete(e),da(e),i.options=i.watcher=void 0,Object.freeze(i))}},Dr=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,o=me.dirname(e),s=me.basename(e);this.fsw._getWatchedDir(o).add(s);let a=me.resolve(e),c={persistent:r.persistent};n||(n=Or);let l;if(r.usePolling){let u=r.interval!==r.binaryInterval;c.interval=u&&Pd(s)?r.binaryInterval:r.interval,l=jd(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})}else l=Nd(e,a,c,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,n,r){if(this.fsw.closed)return;let o=me.dirname(e),s=me.basename(e),i=this.fsw._getWatchedDir(o),a=n;if(i.has(s))return;let c=async(u,d)=>{if(this.fsw._throttle(Rd,e,5)){if(!d||d.mtimeMs===0)try{let g=await pa(e);if(this.fsw.closed)return;let h=g.atimeMs,m=g.mtimeMs;if((!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(it.CHANGE,e,g),(xd||Td||Id)&&a.ino!==g.ino){this.fsw._closeFile(u),a=g;let y=this._watchWithNodeFs(e,c);y&&this.fsw._addPathCloser(u,y)}else a=g}catch{this.fsw._remove(o,s)}else if(i.has(s)){let g=d.atimeMs,h=d.mtimeMs;(!g||g<=h||h!==a.mtimeMs)&&this.fsw._emit(it.CHANGE,e,d),a=d}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(it.ADD,e,0))return;this.fsw._emit(it.ADD,e,n)}return l}async _handleSymlink(e,n,r,o){if(this.fsw.closed)return;let s=e.fullPath,i=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await No(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(i.has(o)?this.fsw._symlinkPaths.get(s)!==a&&(this.fsw._symlinkPaths.set(s,a),this.fsw._emit(it.CHANGE,r,e.stats)):(i.add(o),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(it.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,n,r,o,s,i,a){e=me.join(e,"");let c=o?`${e}:${o}`:e;if(a=this.fsw._throttle("readdir",c,1e3),!a)return;let l=this.fsw._getWatchedDir(r.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(d)return d.on(Ad,async g=>{if(this.fsw.closed){d=void 0;return}let h=g.path,m=me.join(e,h);if(u.add(h),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===o||!o&&!l.has(h))&&(this.fsw._incrReadyCount(),m=me.join(s,me.relative(s,m)),this._addToNodeFs(m,n,r,i+1))}}).on(it.ERROR,this._boundHandleError),new Promise((g,h)=>{if(!d)return h();d.once(Lo,()=>{if(this.fsw.closed){d=void 0;return}let m=a?a.clear():!1;g(void 0),l.getChildren().filter(y=>y!==e&&!u.has(y)).forEach(y=>{this.fsw._remove(e,y)}),d=void 0,m&&this._handleRead(e,!1,r,o,s,i,a)})})}async _handleDir(e,n,r,o,s,i,a){let c=this.fsw._getWatchedDir(me.dirname(e)),l=c.has(me.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!l&&this.fsw._emit(it.ADD_DIR,e,n),c.add(me.basename(e)),this.fsw._getWatchedDir(e);let u,d,g=this.fsw.options.depth;if((g==null||o<=g)&&!this.fsw._symlinkPaths.has(a)){if(!s&&(await this._handleRead(e,r,i,s,e,o,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(h,m)=>{m&&m.mtimeMs===0||this._handleRead(h,!1,i,s,e,o,u)})}return d}async _addToNodeFs(e,n,r,o,s){let i=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return i(),!1;let a=this.fsw._getWatchHelpers(e);r&&(a.filterPath=c=>r.filterPath(c),a.filterDir=c=>r.filterDir(c));try{let c=await Dd[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return i(),!1;let l=this.fsw.options.followSymlinks,u;if(c.isDirectory()){let d=me.resolve(e),g=l?await No(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,c,n,o,s,a,g),this.fsw.closed))return;d!==g&&g!==void 0&&this.fsw._symlinkPaths.set(d,g)}else if(c.isSymbolicLink()){let d=l?await No(e):e;if(this.fsw.closed)return;let g=me.dirname(a.watchPath);if(this.fsw._getWatchedDir(g).add(a.watchPath),this.fsw._emit(it.ADD,a.watchPath,c),u=await this._handleDir(g,c,n,o,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(me.resolve(e),d)}else u=this._handleFile(a.watchPath,c,n);return i(),u&&this.fsw._addPathCloser(e,u),!1}catch(c){if(this.fsw._handleError(c))return i(),e}}};var Ho="/",zd="//",va=".",Bd="..",qd="string",Wd=/\\/g,ka=/\/\//g,Vd=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Yd=/^\.[/\\]/;function Pr(t){return Array.isArray(t)?t:[t]}var zo=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Gd(t){return typeof t=="function"?t:typeof t=="string"?e=>t===e:t instanceof RegExp?e=>t.test(e):typeof t=="object"&&t!==null?e=>{if(t.path===e)return!0;if(t.recursive){let n=le.relative(t.path,e);return n?!n.startsWith("..")&&!le.isAbsolute(n):!1}return!1}:()=>!1}function Jd(t){if(typeof t!="string")throw new Error("string expected");t=le.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(ka,"/"),e&&(t="/"+t),t}function ya(t,e,n){let r=Jd(e);for(let o=0;o<t.length;o++){let s=t[o];if(s(r,n))return!0}return!1}function Kd(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Pr(t).map(o=>Gd(o));return e==null?(o,s)=>ya(r,o,s):ya(r,e)}var wa=t=>{let e=Pr(t).flat();if(!e.every(n=>typeof n===qd))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ea)},ba=t=>{let e=t.replace(Wd,Ho),n=!1;return e.startsWith(zd)&&(n=!0),e=e.replace(ka,Ho),n&&(e=Ho+e),e},Ea=t=>ba(le.normalize(ba(t))),Sa=(t="")=>e=>typeof e=="string"?Ea(le.isAbsolute(e)?e:le.join(t,e)):e,Xd=(t,e)=>le.isAbsolute(t)?t:le.join(e,t),Zd=Object.freeze(new Set),Bo=class{path;_removeWatcher;items;constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==va&&e!==Bd&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await Ud(r)}catch{this._removeWatcher&&this._removeWatcher(le.dirname(r),le.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Or,this.items=Zd,Object.freeze(this)}},Qd="stat",ef="lstat",qo=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let o=e;this.path=e=e.replace(Yd,""),this.watchPath=o,this.fullWatchPath=le.resolve(o),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?Qd:ef}entryPath(e){return le.join(this.watchPath,le.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},$r=class extends Fd{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},o={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Pr(e.ignored):Pr([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};ga&&(o.usePolling=!0),o.atomic===void 0&&(o.atomic=!o.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let c=s.toLowerCase();c==="false"||c==="0"?o.usePolling=!1:c==="true"||c==="1"?o.usePolling=!0:o.usePolling=!!c}let i=process.env.CHOKIDAR_INTERVAL;i&&(o.interval=Number.parseInt(i,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Or,this._readyEmitted=!0,process.nextTick(()=>this.emit(Se.READY)))},this._emitRaw=(...c)=>this.emit(Se.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=o,this._nodeFsHandler=new Dr(this),Object.freeze(o)}_addIgnoredPath(e){if(zo(e)){for(let n of this._ignoredPaths)if(zo(n)&&n.path===e.path&&n.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let n of this._ignoredPaths)zo(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:o}=this.options;this.closed=!1,this._closePromise=void 0;let s=wa(e);return o&&(s=s.map(i=>Xd(i,o))),s.forEach(i=>{this._removeIgnoredPath(i)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async i=>{let a=await this._nodeFsHandler._addToNodeFs(i,!r,void 0,0,n);return a&&this._emitReady(),a})).then(i=>{this.closed||i.forEach(a=>{a&&this.add(le.dirname(a),le.basename(n||a))})}),this}unwatch(e){if(this.closed)return this;let n=wa(e),{cwd:r}=this.options;return n.forEach(o=>{!le.isAbsolute(o)&&!this._closers.has(o)&&(r&&(o=le.join(r,o)),o=le.resolve(o)),this._closePath(o),this._addIgnoredPath(o),this._watched.has(o)&&this._addIgnoredPath({path:o,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let o=r();o instanceof Promise&&e.push(o)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let s=(this.options.cwd?le.relative(this.options.cwd,r):r)||va;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==Se.ERROR&&this.emit(Se.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let o=this.options;Uo&&(n=le.normalize(n)),o.cwd&&(n=le.relative(o.cwd,n));let s=[n];r!=null&&s.push(r);let i=o.awaitWriteFinish,a;if(i&&(a=this._pendingWrites.get(n)))return a.lastChange=new Date,this;if(o.atomic){if(e===Se.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(Se.ALL,...c),this._pendingUnlinks.delete(l)})},typeof o.atomic=="number"?o.atomic:100),this;e===Se.ADD&&this._pendingUnlinks.has(n)&&(e=Se.CHANGE,this._pendingUnlinks.delete(n))}if(i&&(e===Se.ADD||e===Se.CHANGE)&&this._readyEmitted){let c=(l,u)=>{l?(e=Se.ERROR,s[0]=l,this.emitWithAll(e,s)):u&&(s.length>1?s[1]=u:s.push(u),this.emitWithAll(e,s))};return this._awaitWriteFinish(n,i.stabilityThreshold,e,c),this}if(e===Se.CHANGE&&!this._throttle(Se.CHANGE,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===Se.ADD||e===Se.ADD_DIR||e===Se.CHANGE)){let c=o.cwd?le.join(o.cwd,n):n,l;try{l=await Hd(c)}catch{}if(!l||this.closed)return;s.push(l)}return this.emitWithAll(e,s),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(Se.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let o=this._throttled.get(e);if(!o)throw new Error("invalid throttle");let s=o.get(n);if(s)return s.count++,!1;let i,a=()=>{let l=o.get(n),u=l?l.count:0;return o.delete(n),clearTimeout(i),l&&clearTimeout(l.timeoutObject),u};i=setTimeout(a,r);let c={timeoutObject:i,clear:a,count:0};return o.set(n,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,o){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let i=s.pollInterval,a,c=e;this.options.cwd&&!le.isAbsolute(e)&&(c=le.join(this.options.cwd,e));let l=new Date,u=this._pendingWrites;function d(g){Ld(c,(h,m)=>{if(h||!u.has(e)){h&&h.code!=="ENOENT"&&o(h);return}let y=Number(new Date);g&&m.size!==g.size&&(u.get(e).lastChange=y);let p=u.get(e);y-p.lastChange>=n?(u.delete(e),o(void 0,m)):a=setTimeout(d,i,m)})}u.has(e)||(u.set(e,{lastChange:l,cancelWait:()=>(u.delete(e),clearTimeout(a),r)}),a=setTimeout(d,i))}_isIgnored(e,n){if(this.options.atomic&&Vd.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(Sa(r)),a=[...[...this._ignoredPaths].map(Sa(r)),...s];this._userIgnored=Kd(a,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new qo(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=le.resolve(e);return this._watched.has(n)||this._watched.set(n,new Bo(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let o=le.join(e,n),s=le.resolve(o);if(r=r??(this._watched.has(o)||this._watched.has(s)),!this._throttle("remove",o,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(o).getChildren().forEach(g=>this._remove(o,g));let c=this._getWatchedDir(e),l=c.has(n);c.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=o;if(this.options.cwd&&(u=le.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Se.ADD)return;this._watched.delete(o),this._watched.delete(s);let d=r?Se.UNLINK_DIR:Se.UNLINK;l&&!this._isIgnored(o)&&this._emit(d,o),this._closePath(o)}_closePath(e){this._closeFile(e);let n=le.dirname(e);this._getWatchedDir(n).remove(le.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:Se.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},o=ua(e,r);return this._streams.add(o),o.once(ha,()=>{o=void 0}),o.once(Lo,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function Wo(t,e={}){let n=new $r(e);return n.add(t),n}var _a={watch:Wo,FSWatcher:$r};import{execFile as tf}from"node:child_process";import{stat as Ca}from"node:fs/promises";import{resolve as nf}from"node:path";import{promisify as rf}from"node:util";function Bt(t){if(!t||typeof t!="object")return!1;let e=t;return Number.isInteger(e.dev)&&e.dev>=0&&Number.isInteger(e.ino)&&e.ino>0&&(e.birthtimeMs===void 0||Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0)&&(e.volumeId===void 0||typeof e.volumeId=="string"&&e.volumeId.length>0)}function rn(t,e){return t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)&&(t.volumeId===void 0?t.dev===e.dev:t.volumeId===e.volumeId)}function ft(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var Aa=rf(tf);function of(t){let e=t.match(/<key>VolumeUUID<\/key>\s*<string>([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})<\/string>/i)?.[1];return e?`darwin:${e.toLowerCase()}`:void 0}async function sf(t){if(process.platform!=="darwin")return;let{stdout:e}=await Aa("/bin/df",["-P",nf(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
|
|
1
|
+
var Oo=null;function Yi(t){Oo=t}function ve(){if(!Oo)throw new Error("core host not set (call setCoreHost first)");return Oo}var Gi=new TextEncoder,rd=new TextDecoder("utf-8",{ignoreBOM:!0}),Rn=t=>Gi.encode(t),vt=t=>rd.decode(t),_r=t=>typeof t=="string"?Gi.encode(t).length:t.length;function Ji(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function Cr(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),n=>n.charCodeAt(0))}async function Ki(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function Ne(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let o=r.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(o),c=>c.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(s)),a=i.userId??i.sub;return typeof a!="string"&&typeof a!="number"||!String(a).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(a)}`}catch{return null}}function Mo(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(vt(Cr(e)));return n&&typeof n=="object"?n:null}catch{return null}}function Po(t,e=Date.now()){let n=Mo(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Xi(t,e=Date.now()){let n=Mo(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var od=36e5;function Ar(t,e=Date.now()){return!!t&&Po(t,e)>=od}async function xr(t,e,n=8e3,r){if(!t||!e)return null;let o=t.replace(/\/+$/,"");try{let s=await fetch(`${o}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!s.ok)return null;let i=await s.json().catch(()=>null),a=typeof i?.token=="string"?i.token:"";return a&&a!==e?a:null}catch{return null}}var Dn=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,sd=(t,e)=>new Promise((n,r)=>{let o=()=>{clearTimeout(s),r(new Error("Sign-in cancelled."))},s=setTimeout(()=>{e.removeEventListener("abort",o),n()},t);e.aborted?o():e.addEventListener("abort",o,{once:!0})});function Zi(t,e){let n=d=>e.write(JSON.stringify(d,null,2)),r=()=>{let d;try{d=e.read()}catch(g){return g?.code==="ENOENT"?[]:null}if(d===null)return[];try{let g=JSON.parse(d);return Array.isArray(g.accounts)?g.accounts.filter(h=>h&&typeof h.token=="string"&&h.id===Ne(h.cloudUrl,h.token)):null}catch{return null}},o=(d,g)=>{let h=Ne(d.cloudUrl||"",d.token||"");if(!h||!d.token||!d.cloudUrl)return;let m=r();if(!m)return;let y=m.find(k=>k.id===h),p=Mo(d.token),S={...y,id:h,cloudUrl:d.cloudUrl.replace(/\/+$/,""),token:d.token,username:g?.username||y?.username||p?.username,nickname:g?.nickname||y?.nickname};JSON.stringify(y)!==JSON.stringify(S)&&n({version:1,accounts:[...m.filter(k=>k.id!==h),S]})},s=()=>{let d=t.readCreds();o(d);let g=Ne(d.cloudUrl,d.token);return(r()??[]).map(({token:h,...m})=>({...m,active:m.id===g}))},i=d=>{let g=r()?.find(h=>h.id===d);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},a=d=>{let g=Ne(d.cloudUrl||"",d.token||""),h=r();g&&h&&n({version:1,accounts:h.filter(m=>m.id!==g)})},c=null;return{rememberForsionAccount:o,forsionAccounts:s,savedForsionAccount:i,forgetForsionAccount:a,cancelForsionLogin:()=>{c?.abort(),c=null},forsionDeviceLogin:async(d,g,h)=>{if(c)throw new Error("A sign-in is already in progress.");if(!d)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let m=new AbortController;c=m;let y=()=>{if(m.signal.aborted||c!==m)throw new Error("Sign-in cancelled.")};try{let p=d.replace(/\/+$/,""),S;try{S=await fetch(`${p}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])}).then(A=>A.json())}catch(A){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${p}:${A?.message||A}`)}if(y(),!S?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let k=S.verification_uri_complete||`${S.verification_uri}?code=${S.user_code}`,P=new URL(`${p}/auth`);P.searchParams.set("logout","1"),P.searchParams.set("app","forsion-desktop"),P.searchParams.set("redirect",k);let R=P.toString();g?.({url:R,userCode:String(S.user_code||"")}),t.openExternal(R);let O=Date.now()+(S.expires_in||600)*1e3,w=(S.interval||2)*1e3;for(;Date.now()<O;){await sd(w,m.signal),y();let A=null;try{A=await fetch(`${p}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:S.device_code}),signal:AbortSignal.any([m.signal,AbortSignal.timeout(15e3)])})}catch{y();continue}if(y(),A.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let C=await A.json().catch(()=>({status:"pending"}));if(y(),C.status==="approved"&&C.token){let D={cloudUrl:p,token:C.token};return await h(D,y),y(),{token:C.token,cloudUrl:p}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{c===m&&(c=null)}},readAccounts:()=>r()??[]}}function kt(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,o;try{r=new URL(n),o=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||o.origin!==r.origin||!o.pathname.startsWith("/api/")?null:o.toString()}function On(t,e,n){return t.fetch?t.fetch(e,n):fetch(e,{...n,headers:{Authorization:`Bearer ${t.token}`,...n.headers}})}async function He(t,e,n,r,o=6e4){let s=await(t.fetch??fetch)(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token&&!t.fetch?{Authorization:`Bearer ${t.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(o)}),i=await s.json().catch(()=>({}));return{status:s.status,json:i}}var id=50*1024*1024,ad=new Set(["mode","type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"]);function cd(t){if(!t||typeof t!="object")return null;let e=t;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let n=new FormData,r=0;for(let[o,s]of Object.entries(e.fields)){if(!ad.has(o)||typeof s!="string"||(r+=s.length,r>25e4)||e.id&&!["mode","name","summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms","capabilityReason"].includes(o))return null;n.append(o,s)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>id)return null;n.append("zip",new Blob([new Uint8Array(e.zip.data)],{type:"application/zip"}),e.zip.name.replace(/[\\/]/g,"_").slice(-255))}return{path:`${e.id?`/market/mine/${e.id}/update`:"/market/submit"}${e.dryRun===!0?"?dryRun=1":""}`,body:n}}function Qi(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=cd(n);if(!r)return{status:400,json:{error:"invalid_request"}};let o=await t.getCloud();if(!o.token)return{status:401,error:"not_signed_in"};let s=kt(o.base,r.path);if(!s)return{status:0,error:"no_cloud_url"};try{let i=await On(o,s,{method:"POST",body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:i.status,json:await i.json().catch(()=>null)}}catch(i){return{status:0,error:String(i?.message||i)}}})}async function ea(t){if(!t.token)return"";try{let e=await He(t,"POST","/api/auth/handoff",{},5e3);if(e.status===200&&typeof e.json?.code=="string"&&e.json.code)return`code=${encodeURIComponent(e.json.code)}`;if((e.status===404||e.status===405)&&!t.fetch)return`token=${encodeURIComponent(t.token)}`}catch{}return""}var ta=["membership","credits","storefront"],na=["monthly","quarterly","yearly"],ld=/^[A-Za-z0-9_-]{1,64}$/;function ra(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(o,s)=>{if(!t.isTrustedSender(o))return n;let i=await t.getCloud(),a=i.base;if(!a)return{ok:!1};let c=s&&/^[a-z0-9-]+$/i.test(s)?`#${s}`:"",l=await ea(i),u=`${a}/account${l?`?${l}`:""}${c}`;return i.signal?.throwIfAborted(),await t.openExternal(u),{ok:!0}}),t.handle("auth:openPayCenter",async(o,s,i,a)=>{if(!t.isTrustedSender(o))return n;if(s!==void 0&&!ta.includes(s))return{ok:!1,error:"invalid_tab"};if(i!==void 0&&(typeof i!="string"||!ld.test(i)))return{ok:!1,error:"invalid_plan"};if(a!==void 0&&!na.includes(a))return{ok:!1,error:"invalid_period"};let c=(s??"membership")==="membership"&&i?`&plan=${encodeURIComponent(i)}${a?`&period=${a}`:""}`:"",l=await t.getCloud(),u=l.base;if(!u)return{ok:!1};let d=await ea(l),g=`${u}/pay?tab=${s??"membership"}${c}${d?`&${d}`:""}&redirect=${encodeURIComponent(`${u}/account`)}`;return l.signal?.throwIfAborted(),await t.openExternal(g),{ok:!0}}),t.handle("profile:publicOrigin",async o=>{if(!t.isTrustedSender(o))return n;let{base:s}=await t.getCloud();if(!s)return{ok:!1};try{let i=await fetch(`${s}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});i.body?.cancel().catch(()=>{});let a=i.status>=300&&i.status<400?i.headers.get("location"):null;return a&&/^https?:\/\//i.test(a)?{ok:!0,origin:new URL(a).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async o=>{if(!t.isTrustedSender(o))return e;let s=await r();if(!s.token)return{status:401,json:null};try{return await He(s,"GET","/api/token-quota/my",void 0,15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),t.handle("account:useResetCard",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(s!==void 0&&s!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${s}`}};let a=s??"both";try{return await He(i,"POST","/api/token-quota/reset-card/use",{type:a},15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgConvert",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(!Number.isInteger(s)||s<1||s>100)return{status:400,json:{error:"invalid_percent"}};try{return await He(i,"POST","/api/token-quota/background/convert",{percent:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:pointsAutoDeduct",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await He(i,"POST","/api/token-quota/auto-deduct",{enabled:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:bgAutoMain",async(o,s)=>{if(!t.isTrustedSender(o))return e;let i=await r();if(!i.token)return{status:401,json:null};if(typeof s!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await He(i,"POST","/api/token-quota/background/auto-main",{enabled:s},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("feedback:submit",async(o,s)=>{if(!t.isTrustedSender(o))return n;let i=await t.getCloud();if(!i.base||!i.token)return{ok:!1,error:"not-logged-in"};if(s?.expectedAccountId!==void 0){let u=s.expectedAccountId;if(typeof u!="string"||!u||Ne(i.base,i.token)!==u)return{ok:!1,error:"account-changed"}}let a=(s?.description||"").trim();if(!a)return{ok:!1,error:"empty"};if(a.length>1e4)return{ok:!1,error:"description-too-long"};let c=[],l=!1;if(s?.sessionLogJson){let u=Rn(s.sessionLogJson);if(u.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};c.push({filename:s.sessionLogName||"tangu-session.json",mime_type:"application/json",size:u.length,data_base64:Ji(u)})}try{let u=await On(i,`${i.base}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:a,attachments:c}),signal:AbortSignal.timeout(2e4)});if(!u.ok){let g=`HTTP ${u.status}`;try{g=(await u.json())?.detail||g}catch{}return{ok:!1,error:g}}return{ok:!0,id:(await u.json().catch(()=>({})))?.id??null,attachmentSkipped:l}}catch(u){return{ok:!1,error:u?.message||String(u)}}}),t.handle("cloud:fetch",async(o,s)=>{if(!t.isTrustedSender(o))return{status:0,error:"untrusted"};let i=s??{},a=typeof i.path=="string"?i.path:"",c=i.projectSource===void 0?null:i.projectSource;if(c!==null&&(typeof c!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(c)))return{status:0,error:"bad_project_source"};let l=Math.min(12e4,Math.max(1e3,Number(i.timeoutMs)||15e3)),u=typeof i.method=="string"?i.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(u))return{status:0,error:"bad_method"};if(!a.startsWith("/"))return{status:0,error:"bad_path"};let d=await t.getCloud();if(!String(d.base||""))return{status:0,error:"no_cloud_url"};let g=kt(d.base,a);if(!g)return{status:0,error:"bad_path"};if(!d.token)return{status:401,error:"not_signed_in"};let h=i.body!==void 0&&u!=="GET"&&u!=="DELETE",m=new AbortController,y=setTimeout(()=>m.abort(),l);try{let p=await On(d,g,{method:u,headers:{...h?{"Content-Type":"application/json"}:{},...c?{"X-Project-Source":c}:{}},body:h?JSON.stringify(i.body):void 0,signal:m.signal});return{status:p.status,json:await p.json().catch(()=>null)}}catch(p){return{status:0,error:String(p?.message||p)}}finally{clearTimeout(y)}}),Qi(t)}import{createHash as xa}from"node:crypto";import{existsSync as af,promises as cf,readFileSync as lf,renameSync as uf,statSync as df}from"node:fs";import ff from"node:path";import{EventEmitter as Fd}from"node:events";import{stat as Ld}from"node:fs";import{readdir as Ud,stat as Hd}from"node:fs/promises";import*as le from"node:path";import{lstat as oa,readdir as ud,realpath as dd,stat as fd}from"node:fs/promises";import{join as pd,resolve as hd,sep as sa}from"node:path";import{Readable as gd}from"node:stream";var Ve={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},tn={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Ve.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(tn);var la="READDIRP_RECURSIVE_ERROR",md=new Set(["ENOENT","EPERM","EACCES","ELOOP",la]),ia=[Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE],yd=new Set([Ve.DIR_TYPE,Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE]),wd=new Set([Ve.EVERYTHING_TYPE,Ve.FILE_DIR_TYPE,Ve.FILE_TYPE]),bd=t=>md.has(t.code),Sd=process.platform==="win32",aa=t=>!0,ca=t=>{if(t===void 0)return aa;if(typeof t=="function")return t;if(typeof t=="string"){let e=t.trim();return n=>n.basename===e}if(Array.isArray(t)){let e=t.map(n=>n.trim());return n=>e.some(r=>n.basename===r)}return aa},$o=class extends gd{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??tn.highWaterMark});let n={...tn,...e},r=n.root??tn.root,o=n.type??tn.type;this._fileFilter=ca(n.fileFilter),this._directoryFilter=ca(n.directoryFilter);let s=n.lstat?oa:fd;Sd?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:tn.depth,this._wantsDir=yd.has(o),this._wantsFile=wd.has(o),this._wantsEverything=o===Ve.EVERYTHING_TYPE,this._root=hd(r),this._relStart=this._root.endsWith(sa)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let i={path:this._root,depth:1};i.pending=this._exploreDir(this._root,1),this.parents=[i],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:o,depth:s}=n,i=r.splice(0,e).map(c=>this._formatEntry(c,o)),a=this._isDirent?i:await Promise.all(i);for(let c of a){if(!c)continue;if(this.destroyed)return;let l=this._getEntryType(c);typeof l!="string"&&(l=await l),l==="directory"&&this._directoryFilter(c)?(s<=this._maxDepth&&this.parents.push({path:c.fullPath,depth:s+1}),this._wantsDir&&(this.push(c),e--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let o=this.parents.pop();if(!o){this.push(null);break}let s=o.pending??this._exploreDir(o.path,o.depth),i=this.parents[this.parents.length-1];if(i&&!i.pending&&(i.pending=this._exploreDir(i.path,i.depth)),this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await ud(e,this._rdOptions)}catch(o){this._onError(o)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,o=pd(n,r),s={path:o.slice(this._relStart),fullPath:o,basename:r};return this._isDirent?(s.dirent=e,s):this._stat(o).then(i=>(s.stats=i,s),i=>{this._onError(i)})}_onError(e){bd(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let n=e[this._statsProp];return n.isFile()?"file":n.isDirectory()?"directory":n.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let n=e.fullPath;try{let r=await dd(n),o=await oa(r);if(o.isFile())return"file";if(o.isDirectory()){let s=r.length;if(n.startsWith(r)&&n[s]===sa){let i=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return i.code=la,this._onError(i),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function ua(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Ve.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!ia.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${ia.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:t};return n&&(r.type=n),new $o(r)}import{watch as vd,unwatchFile as da,watchFile as kd}from"node:fs";import{realpath as No,lstat as Ed,open as _d,stat as pa}from"node:fs/promises";import{type as Cd}from"node:os";import*as me from"node:path";var Ad="data",Lo="end",ha="close",Or=()=>{};var Mr=process.platform,Uo=Mr==="win32",xd=Mr==="darwin",Td=Mr==="linux",Id=Mr==="freebsd",ga=Cd()==="OS400",Se={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},it=Se,Rd="watch",Dd={lstat:Ed,stat:pa},zt="listeners",Tr="errHandlers",nn="rawEmitters",Od=[zt,Tr,nn],Md=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Pd=t=>Md.has(me.extname(t).slice(1).toLowerCase()),Fo=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Mn=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},$d=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},Pn=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ma=t=>t instanceof Set?t.size===0:!t,Ir=new Map;function fa(t,e,n,r,o){let s=(i,a)=>{n(t),o(i,a,{watchedPath:t}),a&&t!==a&&Rr(me.resolve(t,a),zt,me.join(t,a))};try{return vd(t,{persistent:e.persistent},s)}catch(i){r(i);return}}var Rr=(t,e,n,r,o)=>{let s=Ir.get(t);s&&Fo(s[e],i=>{i(n,r,o)})},Nd=(t,e,n,r)=>{let{listener:o,errHandler:s,rawEmitter:i}=r,a=Ir.get(e),c;if(!n.persistent)return c=fa(t,n,o,s,i),c?c.close.bind(c):void 0;if(a)Mn(a,zt,o),Mn(a,Tr,s),Mn(a,nn,i);else{if(c=fa(t,n,Rr.bind(null,e,zt),s,Rr.bind(null,e,nn)),!c)return;c.on(it.ERROR,async l=>{let u=Rr.bind(null,e,Tr);if(a&&(a.watcherUnusable=!0),Uo&&l.code==="EPERM")try{await(await _d(t,"r")).close(),u(l)}catch{}else u(l)}),a={listeners:o,errHandlers:s,rawEmitters:i,watcher:c},Ir.set(e,a)}return()=>{Pn(a,zt,o),Pn(a,Tr,s),Pn(a,nn,i),ma(a.listeners)&&(a.watcher.close(),Ir.delete(e),Od.forEach($d(a)),a.watcher=void 0,Object.freeze(a))}},jo=new Map,jd=(t,e,n,r)=>{let{listener:o,rawEmitter:s}=r,i=jo.get(e),a=i&&i.options;return a&&(a.persistent<n.persistent||a.interval>n.interval)&&(da(e),i=void 0),i?(Mn(i,zt,o),Mn(i,nn,s)):(i={listeners:o,rawEmitters:s,options:n,watcher:kd(e,n,(c,l)=>{Fo(i.rawEmitters,d=>{d(it.CHANGE,e,{curr:c,prev:l})});let u=c.mtimeMs;(c.size!==l.size||u>l.mtimeMs||u===0)&&Fo(i.listeners,d=>d(t,c))})},jo.set(e,i)),()=>{Pn(i,zt,o),Pn(i,nn,s),ma(i.listeners)&&(jo.delete(e),da(e),i.options=i.watcher=void 0,Object.freeze(i))}},Dr=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,o=me.dirname(e),s=me.basename(e);this.fsw._getWatchedDir(o).add(s);let a=me.resolve(e),c={persistent:r.persistent};n||(n=Or);let l;if(r.usePolling){let u=r.interval!==r.binaryInterval;c.interval=u&&Pd(s)?r.binaryInterval:r.interval,l=jd(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})}else l=Nd(e,a,c,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,n,r){if(this.fsw.closed)return;let o=me.dirname(e),s=me.basename(e),i=this.fsw._getWatchedDir(o),a=n;if(i.has(s))return;let c=async(u,d)=>{if(this.fsw._throttle(Rd,e,5)){if(!d||d.mtimeMs===0)try{let g=await pa(e);if(this.fsw.closed)return;let h=g.atimeMs,m=g.mtimeMs;if((!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(it.CHANGE,e,g),(xd||Td||Id)&&a.ino!==g.ino){this.fsw._closeFile(u),a=g;let y=this._watchWithNodeFs(e,c);y&&this.fsw._addPathCloser(u,y)}else a=g}catch{this.fsw._remove(o,s)}else if(i.has(s)){let g=d.atimeMs,h=d.mtimeMs;(!g||g<=h||h!==a.mtimeMs)&&this.fsw._emit(it.CHANGE,e,d),a=d}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(it.ADD,e,0))return;this.fsw._emit(it.ADD,e,n)}return l}async _handleSymlink(e,n,r,o){if(this.fsw.closed)return;let s=e.fullPath,i=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await No(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(i.has(o)?this.fsw._symlinkPaths.get(s)!==a&&(this.fsw._symlinkPaths.set(s,a),this.fsw._emit(it.CHANGE,r,e.stats)):(i.add(o),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(it.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,n,r,o,s,i,a){e=me.join(e,"");let c=o?`${e}:${o}`:e;if(a=this.fsw._throttle("readdir",c,1e3),!a)return;let l=this.fsw._getWatchedDir(r.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(d)return d.on(Ad,async g=>{if(this.fsw.closed){d=void 0;return}let h=g.path,m=me.join(e,h);if(u.add(h),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===o||!o&&!l.has(h))&&(this.fsw._incrReadyCount(),m=me.join(s,me.relative(s,m)),this._addToNodeFs(m,n,r,i+1))}}).on(it.ERROR,this._boundHandleError),new Promise((g,h)=>{if(!d)return h();d.once(Lo,()=>{if(this.fsw.closed){d=void 0;return}let m=a?a.clear():!1;g(void 0),l.getChildren().filter(y=>y!==e&&!u.has(y)).forEach(y=>{this.fsw._remove(e,y)}),d=void 0,m&&this._handleRead(e,!1,r,o,s,i,a)})})}async _handleDir(e,n,r,o,s,i,a){let c=this.fsw._getWatchedDir(me.dirname(e)),l=c.has(me.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!l&&this.fsw._emit(it.ADD_DIR,e,n),c.add(me.basename(e)),this.fsw._getWatchedDir(e);let u,d,g=this.fsw.options.depth;if((g==null||o<=g)&&!this.fsw._symlinkPaths.has(a)){if(!s&&(await this._handleRead(e,r,i,s,e,o,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(h,m)=>{m&&m.mtimeMs===0||this._handleRead(h,!1,i,s,e,o,u)})}return d}async _addToNodeFs(e,n,r,o,s){let i=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return i(),!1;let a=this.fsw._getWatchHelpers(e);r&&(a.filterPath=c=>r.filterPath(c),a.filterDir=c=>r.filterDir(c));try{let c=await Dd[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return i(),!1;let l=this.fsw.options.followSymlinks,u;if(c.isDirectory()){let d=me.resolve(e),g=l?await No(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,c,n,o,s,a,g),this.fsw.closed))return;d!==g&&g!==void 0&&this.fsw._symlinkPaths.set(d,g)}else if(c.isSymbolicLink()){let d=l?await No(e):e;if(this.fsw.closed)return;let g=me.dirname(a.watchPath);if(this.fsw._getWatchedDir(g).add(a.watchPath),this.fsw._emit(it.ADD,a.watchPath,c),u=await this._handleDir(g,c,n,o,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(me.resolve(e),d)}else u=this._handleFile(a.watchPath,c,n);return i(),u&&this.fsw._addPathCloser(e,u),!1}catch(c){if(this.fsw._handleError(c))return i(),e}}};var Ho="/",zd="//",va=".",Bd="..",qd="string",Wd=/\\/g,ka=/\/\//g,Vd=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Yd=/^\.[/\\]/;function Pr(t){return Array.isArray(t)?t:[t]}var zo=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Gd(t){return typeof t=="function"?t:typeof t=="string"?e=>t===e:t instanceof RegExp?e=>t.test(e):typeof t=="object"&&t!==null?e=>{if(t.path===e)return!0;if(t.recursive){let n=le.relative(t.path,e);return n?!n.startsWith("..")&&!le.isAbsolute(n):!1}return!1}:()=>!1}function Jd(t){if(typeof t!="string")throw new Error("string expected");t=le.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(ka,"/"),e&&(t="/"+t),t}function ya(t,e,n){let r=Jd(e);for(let o=0;o<t.length;o++){let s=t[o];if(s(r,n))return!0}return!1}function Kd(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Pr(t).map(o=>Gd(o));return e==null?(o,s)=>ya(r,o,s):ya(r,e)}var wa=t=>{let e=Pr(t).flat();if(!e.every(n=>typeof n===qd))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ea)},ba=t=>{let e=t.replace(Wd,Ho),n=!1;return e.startsWith(zd)&&(n=!0),e=e.replace(ka,Ho),n&&(e=Ho+e),e},Ea=t=>ba(le.normalize(ba(t))),Sa=(t="")=>e=>typeof e=="string"?Ea(le.isAbsolute(e)?e:le.join(t,e)):e,Xd=(t,e)=>le.isAbsolute(t)?t:le.join(e,t),Zd=Object.freeze(new Set),Bo=class{path;_removeWatcher;items;constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==va&&e!==Bd&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await Ud(r)}catch{this._removeWatcher&&this._removeWatcher(le.dirname(r),le.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Or,this.items=Zd,Object.freeze(this)}},Qd="stat",ef="lstat",qo=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let o=e;this.path=e=e.replace(Yd,""),this.watchPath=o,this.fullWatchPath=le.resolve(o),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?Qd:ef}entryPath(e){return le.join(this.watchPath,le.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},$r=class extends Fd{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},o={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Pr(e.ignored):Pr([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};ga&&(o.usePolling=!0),o.atomic===void 0&&(o.atomic=!o.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let c=s.toLowerCase();c==="false"||c==="0"?o.usePolling=!1:c==="true"||c==="1"?o.usePolling=!0:o.usePolling=!!c}let i=process.env.CHOKIDAR_INTERVAL;i&&(o.interval=Number.parseInt(i,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Or,this._readyEmitted=!0,process.nextTick(()=>this.emit(Se.READY)))},this._emitRaw=(...c)=>this.emit(Se.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=o,this._nodeFsHandler=new Dr(this),Object.freeze(o)}_addIgnoredPath(e){if(zo(e)){for(let n of this._ignoredPaths)if(zo(n)&&n.path===e.path&&n.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let n of this._ignoredPaths)zo(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:o}=this.options;this.closed=!1,this._closePromise=void 0;let s=wa(e);return o&&(s=s.map(i=>Xd(i,o))),s.forEach(i=>{this._removeIgnoredPath(i)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async i=>{let a=await this._nodeFsHandler._addToNodeFs(i,!r,void 0,0,n);return a&&this._emitReady(),a})).then(i=>{this.closed||i.forEach(a=>{a&&this.add(le.dirname(a),le.basename(n||a))})}),this}unwatch(e){if(this.closed)return this;let n=wa(e),{cwd:r}=this.options;return n.forEach(o=>{!le.isAbsolute(o)&&!this._closers.has(o)&&(r&&(o=le.join(r,o)),o=le.resolve(o)),this._closePath(o),this._addIgnoredPath(o),this._watched.has(o)&&this._addIgnoredPath({path:o,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let o=r();o instanceof Promise&&e.push(o)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let s=(this.options.cwd?le.relative(this.options.cwd,r):r)||va;e[s]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==Se.ERROR&&this.emit(Se.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let o=this.options;Uo&&(n=le.normalize(n)),o.cwd&&(n=le.relative(o.cwd,n));let s=[n];r!=null&&s.push(r);let i=o.awaitWriteFinish,a;if(i&&(a=this._pendingWrites.get(n)))return a.lastChange=new Date,this;if(o.atomic){if(e===Se.UNLINK)return this._pendingUnlinks.set(n,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(Se.ALL,...c),this._pendingUnlinks.delete(l)})},typeof o.atomic=="number"?o.atomic:100),this;e===Se.ADD&&this._pendingUnlinks.has(n)&&(e=Se.CHANGE,this._pendingUnlinks.delete(n))}if(i&&(e===Se.ADD||e===Se.CHANGE)&&this._readyEmitted){let c=(l,u)=>{l?(e=Se.ERROR,s[0]=l,this.emitWithAll(e,s)):u&&(s.length>1?s[1]=u:s.push(u),this.emitWithAll(e,s))};return this._awaitWriteFinish(n,i.stabilityThreshold,e,c),this}if(e===Se.CHANGE&&!this._throttle(Se.CHANGE,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===Se.ADD||e===Se.ADD_DIR||e===Se.CHANGE)){let c=o.cwd?le.join(o.cwd,n):n,l;try{l=await Hd(c)}catch{}if(!l||this.closed)return;s.push(l)}return this.emitWithAll(e,s),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(Se.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let o=this._throttled.get(e);if(!o)throw new Error("invalid throttle");let s=o.get(n);if(s)return s.count++,!1;let i,a=()=>{let l=o.get(n),u=l?l.count:0;return o.delete(n),clearTimeout(i),l&&clearTimeout(l.timeoutObject),u};i=setTimeout(a,r);let c={timeoutObject:i,clear:a,count:0};return o.set(n,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,o){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let i=s.pollInterval,a,c=e;this.options.cwd&&!le.isAbsolute(e)&&(c=le.join(this.options.cwd,e));let l=new Date,u=this._pendingWrites;function d(g){Ld(c,(h,m)=>{if(h||!u.has(e)){h&&h.code!=="ENOENT"&&o(h);return}let y=Number(new Date);g&&m.size!==g.size&&(u.get(e).lastChange=y);let p=u.get(e);y-p.lastChange>=n?(u.delete(e),o(void 0,m)):a=setTimeout(d,i,m)})}u.has(e)||(u.set(e,{lastChange:l,cancelWait:()=>(u.delete(e),clearTimeout(a),r)}),a=setTimeout(d,i))}_isIgnored(e,n){if(this.options.atomic&&Vd.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=(this.options.ignored||[]).map(Sa(r)),a=[...[...this._ignoredPaths].map(Sa(r)),...s];this._userIgnored=Kd(a,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new qo(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=le.resolve(e);return this._watched.has(n)||this._watched.set(n,new Bo(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let o=le.join(e,n),s=le.resolve(o);if(r=r??(this._watched.has(o)||this._watched.has(s)),!this._throttle("remove",o,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(o).getChildren().forEach(g=>this._remove(o,g));let c=this._getWatchedDir(e),l=c.has(n);c.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=o;if(this.options.cwd&&(u=le.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Se.ADD)return;this._watched.delete(o),this._watched.delete(s);let d=r?Se.UNLINK_DIR:Se.UNLINK;l&&!this._isIgnored(o)&&this._emit(d,o),this._closePath(o)}_closePath(e){this._closeFile(e);let n=le.dirname(e);this._getWatchedDir(n).remove(le.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:Se.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},o=ua(e,r);return this._streams.add(o),o.once(ha,()=>{o=void 0}),o.once(Lo,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function Wo(t,e={}){let n=new $r(e);return n.add(t),n}var _a={watch:Wo,FSWatcher:$r};import{execFile as tf}from"node:child_process";import{stat as Ca}from"node:fs/promises";import{resolve as nf}from"node:path";import{promisify as rf}from"node:util";function Bt(t){if(!t||typeof t!="object")return!1;let e=t;return Number.isInteger(e.dev)&&e.dev>=0&&Number.isInteger(e.ino)&&e.ino>0&&(e.birthtimeMs===void 0||Number.isFinite(e.birthtimeMs)&&e.birthtimeMs>0)&&(e.volumeId===void 0||typeof e.volumeId=="string"&&e.volumeId.length>0)}function rn(t,e){return t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)&&(t.volumeId===void 0?t.dev===e.dev:t.volumeId===e.volumeId)}function ft(t,e){return t.dev===e.dev&&t.ino===e.ino&&(t.birthtimeMs===void 0||t.birthtimeMs===e.birthtimeMs)}var Aa=rf(tf);function of(t){let e=t.match(/<key>VolumeUUID<\/key>\s*<string>([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})<\/string>/i)?.[1];return e?`darwin:${e.toLowerCase()}`:void 0}async function sf(t){if(process.platform!=="darwin")return;let{stdout:e}=await Aa("/bin/df",["-P",nf(t)],{timeout:5e3,maxBuffer:256*1024}),n=e.split(`
|
|
2
2
|
`).slice(1).map(o=>o.trim().split(/\s+/)[0]).find(o=>/^\/dev\/disk\d+(?:s\d+)*$/.test(o));if(!n)return;let{stdout:r}=await Aa("/usr/sbin/diskutil",["info","-plist",n],{timeout:5e3,maxBuffer:256*1024});return of(r)}async function $n(t,e=sf,n=process.platform){let r=await Ca(t);if(!r.isDirectory())throw Error("Sync root is not a directory");let o={dev:r.dev,ino:r.ino,...(n==="darwin"||n==="win32")&&r.birthtimeMs>0?{birthtimeMs:r.birthtimeMs}:{}},s=await e(t),i=await Ca(t);if(!i.isDirectory()||!ft(o,i))throw Error("Sync root changed while reading its identity");return{...o,...s?{volumeId:s}:{}}}var Vo;function Ta(t){Vo=t}var Ia={fs:cf,path:ff,directoryIdentity:$n,sha256Hex:t=>xa("sha256").update(t).digest("hex"),tmpTag:()=>process.pid,existsSync:af,async compareAndReplace(t,e,n,r,o){if(!Vo)throw new Error("This host needs the shared content write lock for safe cloud downloads");let s=!1;return await Vo(e,()=>{if(!r())return;if(o){let a;try{a=df(o.path)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||!ft(o.identity,a))return}let i=null;try{i=xa("sha256").update(lf(e)).digest("hex")}catch(a){if(a.code!=="ENOENT")throw a}i===n&&(uf(t,e),s=!0)}),s},watch(t,e,n){let r=_a.watch(t,{ignoreInitial:!0,depth:e.depth,ignored:e.ignored});return r.on("change",n.change),r.on("add",n.add),r.on("unlink",n.unlink),r.on("unlinkDir",n.unlinkDir),r}};import{readdirSync as pf,lstatSync as Jo,readFileSync as Ko,writeFileSync as hf,realpathSync as Ra,opendirSync as gf,openSync as mf,fstatSync as yf,readSync as wf,closeSync as bf,constants as Yo}from"node:fs";import{join as Nr,extname as Da,sep as Sf}from"node:path";var Xo=300,Oa=5*1024*1024,Ma=20*1024*1024,vf=50*1024*1024,Pa=new Set(["node_modules"]),kf=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function $a(t,e){let n=[],r=0,o=(s,i)=>{for(let a of pf(s)){if(a.startsWith("."))continue;let c=Nr(s,a),l;try{l=Jo(c)}catch{continue}if(l.isSymbolicLink())continue;let u=i?`${i}/${a}`:a;if(l.isDirectory()){Pa.has(a)||o(c,u);continue}if(!l.isFile()||a.endsWith(".d.ts"))continue;if(n.length>=Xo)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Xo}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let d=Da(a).toLowerCase(),g,h=e.mimeOf(d)??"application/octet-stream";if(kf.has(d)){let m=e.transpile(Ko(c,"utf8"),d,u);g=Buffer.from(m??"","utf8"),h="text/javascript"}else g=Ko(c);if(g.length>Oa)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${u}`);if(r+=g.length,r>Ma)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");n.push({path:u,content_b64:g.toString("base64"),content_type:h,size:g.length})}};if(o(t,""),!n.length)throw new Error("\u9879\u76EE\u4E3A\u7A7A\uFF0C\u6CA1\u6709\u53EF\u53D1\u5E03\u7684\u6587\u4EF6");return{files:n,totalBytes:r}}var Na=".forsion-connect.json";function ja(t){try{return JSON.parse(Ko(Nr(t,Na),"utf8"))}catch{return{}}}function Fa(t,e){try{hf(Nr(t,Na),JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf8")}catch{}}var Ef=new Set([".html",".htm",".js",".mjs",".cjs",".ts",".tsx",".jsx",".mts",".cts",".vue",".svelte"]),_f=400,Cf=5e3,Go=2*1024*1024,Af=12,xf=/\bforsion\.ai\.(chat|generateImage|agent|status)\b/g;function La(t){try{if(!Jo(t).isDirectory())return null}catch{return null}let e=!1,n=new Set,r=0,o=0,s=null,i=c=>{let l;try{l=mf(c,Yo.O_RDONLY|(Yo.O_NOFOLLOW||0)|(Yo.O_NONBLOCK||0))}catch{return null}try{if(!yf(l).isFile())return null;s??=Buffer.allocUnsafe(Go+1);let u=0;for(;u<s.length;){let d=wf(l,s,u,s.length-u,null);if(d<=0)break;u+=d}return u>Go?null:s.toString("utf8",0,u)}catch{return null}finally{try{bf(l)}catch{}}},a=(c,l)=>{let u;try{u=gf(c)}catch{return}try{for(;;){if(r>=_f||o>=Cf)return;let d;try{d=u.readSync()}catch{return}if(!d)return;o++;let g=d.name;if(g.startsWith(".")||Pa.has(g))continue;let h=Nr(c,g),m;try{m=Jo(h)}catch{continue}if(m.isSymbolicLink())continue;if(m.isDirectory()){l<Af&&a(h,l+1);continue}if(!m.isFile()||m.size>Go||!Ef.has(Da(g).toLowerCase()))continue;r++;let y=i(h);if(y!==null){!e&&y.includes("forsion-connect.js")&&(e=!0);for(let p of y.matchAll(xf))n.add(`forsion.ai.${p[1]}`)}}}finally{try{u.closeSync()}catch{}}};return a(t,0),{usesSdk:e,sdkMethods:[...n].sort()}}function Ua(t){let e=ja(t),n=La(t);return n?{...e,...n}:e}function Ha(t){let e={"/__forsion/chat":{method:"POST",path:"/api/chat/completions",auth:!0},"/__forsion/images":{method:"POST",path:"/api/images/generations",auth:!0},"/__forsion/user":{method:"GET",path:"/api/brain/users/me",auth:!0},"/__forsion/models":{method:"GET",path:"/api/models",auth:!1},"/__forsion/config":{method:"GET",path:"/api/connect/config",auth:!1},"/__forsion/agent":{method:"POST",path:"/api/agent/runs",auth:!0,agentRun:!0}};function n(r){if(e[r])return e[r];let o="/__forsion/agent-events/";if(r.startsWith(o)){let s=r.slice(o.length);if(/^[A-Za-z0-9-]{1,64}$/.test(s))return{method:"GET",path:`/api/agent/runs/${s}/events`,auth:!0,timeoutMs:9e5}}}return async(r,o)=>{let[s,i]=(r.url||"").split("?"),a=(m,y)=>{o.headersSent||(o.statusCode=m,o.setHeader("Content-Type","application/json")),o.end(JSON.stringify({detail:y}))},c=n(s);if(!c)return a(404,"unknown connect endpoint");if((r.method||"GET")!==c.method)return a(405,"method not allowed");let l="",u="";try{({base:l,token:u}=await t())}catch{}if(!l)return a(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(c.auth&&!u)return a(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let d;if(c.method==="POST"){let m=[],y=0;try{for await(let p of r){if(y+=p.length,y>vf)return r.destroy(),a(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");m.push(p)}}catch(p){return a(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${p?.message||String(p)}`)}d=Buffer.concat(m)}if(c.agentRun){let m;try{m=JSON.parse((d||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return a(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}d=Buffer.from(JSON.stringify({session_id:typeof m.session_id=="string"?m.session_id:"",message:typeof m.message=="string"?m.message:"",app_id:"connect",agent_config:{}}))}let g=new AbortController,h=setTimeout(()=>g.abort(new Error("proxy timeout")),c.timeoutMs??3e5);r.on("close",()=>g.abort());try{let m=await fetch(l+c.path+(i?`?${i}`:""),{method:c.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...u?{Authorization:`Bearer ${u}`}:{}},body:d&&d.length?new Uint8Array(d):void 0,signal:g.signal});if(o.statusCode=m.status,o.setHeader("Content-Type",m.headers.get("content-type")||"application/json"),o.setHeader("Cache-Control","no-store"),m.body)for await(let y of m.body)o.write(y);o.end()}catch(m){let y=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${m?.message||String(m)}`;if(o.headersSent){try{o.write(`data: ${JSON.stringify({error:y})}
|
|
4
4
|
|