@forsion/extend 0.5.1 → 0.6.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # 更新日志
2
2
 
3
+ ## 0.6.0 — 2026-09-29
4
+
5
+ - 「设备互联」的云端那一半改由本包提供:经 Forsion 云端中转让其他设备连上这台电脑、向设备列表报告这台电脑的状态,以及查看、改名、换图标、移除设备和在浏览器中打开设备。用法和之前一样。
6
+ - 服务器重启的那几秒里连不上时,不再清掉这台电脑的配对重新登记,设备列表里不会因此多出一台台离线的重复设备。
7
+ - 没装本包的桌面端不再列出账号下的其他设备,也不经云端中转接受连接;同一局域网直连和「允许其他设备连接本机」照常可用。
8
+ - 需要较新的 Forsion 桌面端才会启用;旧桌面端上本包照旧提供 0.5 的功能。
9
+
10
+ - Device connectivity's cloud half now comes from this package: the Forsion cloud relay that lets your other devices reach this computer, reporting this computer's status to your device list, and viewing, renaming, changing the icon of, removing and opening devices in your browser. Everything works as before.
11
+ - If the connection drops for a few seconds while the server restarts, this computer keeps its pairing instead of registering again, so your device list no longer fills up with offline duplicates.
12
+ - Desktops without this package no longer list the other devices on your account or accept connections through the cloud relay; same-network direct connections and "Allow other devices to connect" keep working.
13
+ - This needs a newer Forsion Desktop build; on older desktops this package keeps providing the 0.5 features.
14
+
3
15
  ## 0.5.1 — 2026-09-29
4
16
 
5
17
  - 从桌面端打开账号中心或充值页时,网址里不再带登录令牌,改为一次性交接码:60 秒内有效、只能用一次,不会留在浏览器历史里。需要服务端更新后才生效,在这之前照旧打开。
package/README.md CHANGED
@@ -12,6 +12,7 @@ Forsion Extend 是 Forsion 桌面端内置的扩展,负责和你的 Forsion
12
12
  - **用量记录**:最近 7、30、90 天的请求次数、成功率和 AI 额度消耗。
13
13
  - **反馈**:提交问题和建议,在桌面上查看回复。
14
14
  - **笔记云同步与协作**:云端笔记库、按条目同步、与我共享,以及页面分享、发布和在线成员。
15
+ - **设备互联**:让你的其他设备经 Forsion 云端连上这台电脑;账号下的设备可以查看、改名、换图标、移除,或在浏览器中打开。
15
16
  - **Forsion Connect**:把 Coding Space 里的项目发布成网页、申请上架应用商店;预览项目时也能用上 Forsion 的 AI。
16
17
 
17
18
  ## 设置在哪里
@@ -34,6 +35,7 @@ Forsion Extend is built into Forsion Desktop and takes care of everything to do
34
35
  - **Usage**: requests, success rate and AI quota used over the last 7, 30 or 90 days.
35
36
  - **Feedback**: send issues and suggestions, and read replies in the app.
36
37
  - **Note sync and collaboration**: the cloud vault, per-item sync, shared with me, and page sharing, publishing and presence.
38
+ - **Device connectivity**: let your other devices reach this computer through the Forsion cloud, and view, rename, change the icon of, remove or open in your browser the devices on your account.
37
39
  - **Forsion Connect**: publish Coding Space projects as web pages and apply for an app store listing; project previews can use Forsion's AI too.
38
40
 
39
41
  ## Where to find it
package/SIGNATURE CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "alg": "ed25519",
3
3
  "files": {
4
- "CHANGELOG.md": "86bbe37d56b75be32737d09382f6ab6c1d143e4f23a8d40aaaf04e69b8b16fd5",
4
+ "CHANGELOG.md": "29c061623d36d6b60173be493c4382050f8d3d762d27c2476d11a434bac15931",
5
5
  "LICENSE": "5594544ee08011ed5785ee26410f1f2ef005f66e9283833e8d435e34c10de1ed",
6
- "README.md": "a17ef4b3c8adefcbee2efda0c1bbca1fc8aa63dce323295708c321a9d322a80c",
6
+ "README.md": "aad572c14c09e58978393f1a56986720ba62daf74b537be5e70f4ed73c5f4a7a",
7
7
  "dist/THIRD_PARTY_NOTICES.md": "64dcf02385589a257abb72d1b5594a595359919c355e568a9ed5699678672e5e",
8
- "dist/desktop.mjs": "05af5ca236ef768d6b9cbb8016e5601d4af5ae52e48d786e42009a513aa9c03a",
8
+ "dist/desktop.mjs": "7f530ad1958abb41c3707b9745ebe721ceee65286390cd8de4ead706296b2f83",
9
9
  "dist/main.js": "72d709f10781063c74cdf2fc5e8965b5a34ac3e2e8274d27dc96f9176e2fd67c",
10
- "manifest.json": "151f9cc06ceac1c87829fc09bc6661399010db56e6ee708437ebfa922dca3ad8",
11
- "package.json": "32a08327f0ab617a0569c32a508bb6e2c5feb28a05badb9f2880b92d8d8e55fc"
10
+ "manifest.json": "0f5248737617a6c43ced5a774e2a4c3617e2cd6934f22c8b2c725b000598053f",
11
+ "package.json": "f240b715e01eaba7ba3c80632b1617cd32ab43cb5c81f7c74baaa00865e43f95"
12
12
  },
13
- "sig": "gqeF9eL3CPkSu252xMuzxINQUq7+X9rmiB9X5ST+xBEbIIO4dDT6HsYfOQ75t8nhaQlBpZYnMkUi4jk6mm7WCQ=="
13
+ "sig": "VTcCAA+44gnrECoV94+ZigbW3XgTRVKHQTY2r2tpmRHsrFeEu8d3AVXeDN2s+1NCrCHGuV6atQjiirxpVmxdDQ=="
14
14
  }
package/dist/desktop.mjs CHANGED
@@ -1,7 +1,7 @@
1
- function Tn(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let s,r;try{s=new URL(n),r=new URL(n+"/api"+e)}catch{return null}return s.protocol!=="http:"&&s.protocol!=="https:"||r.origin!==s.origin||!r.pathname.startsWith("/api/")?null:r.toString()}async function de(t,e,n,s,r=6e4){let o=await fetch(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:s===void 0?void 0:JSON.stringify(s),signal:AbortSignal.timeout(r)}),a=await o.json().catch(()=>({}));return{status:o.status,json:a}}import{readdirSync as Gr,lstatSync as Yr,readFileSync as Ft,writeFileSync as Jr,realpathSync as Rn}from"node:fs";import{join as Lt,extname as Kr,sep as Xr}from"node:path";var Ot=300,In=5*1024*1024,An=20*1024*1024,Qr=50*1024*1024,Zr=new Set(["node_modules"]),es=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function Pn(t,e){let n=[],s=0,r=(o,a)=>{for(let c of Gr(o)){if(c.startsWith("."))continue;let l=Lt(o,c),m;try{m=Yr(l)}catch{continue}if(m.isSymbolicLink())continue;let d=a?`${a}/${c}`:c;if(m.isDirectory()){Zr.has(c)||r(l,d);continue}if(!m.isFile()||c.endsWith(".d.ts"))continue;if(n.length>=Ot)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Ot}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let f=Kr(c).toLowerCase(),u,y=e.mimeOf(f)??"application/octet-stream";if(es.has(f)){let _=e.transpile(Ft(l,"utf8"),f,d);u=Buffer.from(_??"","utf8"),y="text/javascript"}else u=Ft(l);if(u.length>In)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${d}`);if(s+=u.length,s>An)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");n.push({path:d,content_b64:u.toString("base64"),content_type:y,size:u.length})}};if(r(t,""),!n.length)throw new Error("\u9879\u76EE\u4E3A\u7A7A\uFF0C\u6CA1\u6709\u53EF\u53D1\u5E03\u7684\u6587\u4EF6");return{files:n,totalBytes:s}}var Dn=".forsion-connect.json";function $n(t){try{return JSON.parse(Ft(Lt(t,Dn),"utf8"))}catch{return{}}}function Mn(t,e){try{Jr(Lt(t,Dn),JSON.stringify(e,null,2)+`
2
- `,"utf8")}catch{}}function Nn(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(s){if(e[s])return e[s];let r="/__forsion/agent-events/";if(s.startsWith(r)){let o=s.slice(r.length);if(/^[A-Za-z0-9-]{1,64}$/.test(o))return{method:"GET",path:`/api/agent/runs/${o}/events`,auth:!0,timeoutMs:9e5}}}return async(s,r)=>{let[o,a]=(s.url||"").split("?"),c=(_,T)=>{r.headersSent||(r.statusCode=_,r.setHeader("Content-Type","application/json")),r.end(JSON.stringify({detail:T}))},l=n(o);if(!l)return c(404,"unknown connect endpoint");if((s.method||"GET")!==l.method)return c(405,"method not allowed");let m="",d="";try{({base:m,token:d}=await t())}catch{}if(!m)return c(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(l.auth&&!d)return c(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let f;if(l.method==="POST"){let _=[],T=0;try{for await(let v of s){if(T+=v.length,T>Qr)return s.destroy(),c(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");_.push(v)}}catch(v){return c(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${v?.message||String(v)}`)}f=Buffer.concat(_)}if(l.agentRun){let _;try{_=JSON.parse((f||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return c(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}f=Buffer.from(JSON.stringify({session_id:typeof _.session_id=="string"?_.session_id:"",message:typeof _.message=="string"?_.message:"",app_id:"connect",agent_config:{}}))}let u=new AbortController,y=setTimeout(()=>u.abort(new Error("proxy timeout")),l.timeoutMs??3e5);s.on("close",()=>u.abort());try{let _=await fetch(m+l.path+(a?`?${a}`:""),{method:l.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...d?{Authorization:`Bearer ${d}`}:{}},body:f&&f.length?new Uint8Array(f):void 0,signal:u.signal});if(r.statusCode=_.status,r.setHeader("Content-Type",_.headers.get("content-type")||"application/json"),r.setHeader("Cache-Control","no-store"),_.body)for await(let T of _.body)r.write(T);r.end()}catch(_){let T=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${_?.message||String(_)}`;if(r.headersSent){try{r.write(`data: ${JSON.stringify({error:T})}
1
+ function Dn(n,e){if(typeof e!="string"||!e.startsWith("/"))return null;let t=String(n||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!t)return null;let s,r;try{s=new URL(t),r=new URL(t+"/api"+e)}catch{return null}return s.protocol!=="http:"&&s.protocol!=="https:"||r.origin!==s.origin||!r.pathname.startsWith("/api/")?null:r.toString()}async function de(n,e,t,s,r=6e4){let i=await fetch(n.base+t,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...n.token?{Authorization:`Bearer ${n.token}`}:{}},body:s===void 0?void 0:JSON.stringify(s),signal:AbortSignal.timeout(r)}),o=await i.json().catch(()=>({}));return{status:i.status,json:o}}import{readdirSync as ns,lstatSync as rs,readFileSync as jt,writeFileSync as ss,realpathSync as Mn}from"node:fs";import{join as Ht,extname as is,sep as os}from"node:path";var Lt=300,Nn=5*1024*1024,Un=20*1024*1024,as=50*1024*1024,ls=new Set(["node_modules"]),cs=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function Fn(n,e){let t=[],s=0,r=(i,o)=>{for(let a of ns(i)){if(a.startsWith("."))continue;let c=Ht(i,a),h;try{h=rs(c)}catch{continue}if(h.isSymbolicLink())continue;let d=o?`${o}/${a}`:a;if(h.isDirectory()){ls.has(a)||r(c,d);continue}if(!h.isFile()||a.endsWith(".d.ts"))continue;if(t.length>=Lt)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Lt}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let f=is(a).toLowerCase(),u,y=e.mimeOf(f)??"application/octet-stream";if(cs.has(f)){let v=e.transpile(jt(c,"utf8"),f,d);u=Buffer.from(v??"","utf8"),y="text/javascript"}else u=jt(c);if(u.length>Nn)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${d}`);if(s+=u.length,s>Un)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");t.push({path:d,content_b64:u.toString("base64"),content_type:y,size:u.length})}};if(r(n,""),!t.length)throw new Error("\u9879\u76EE\u4E3A\u7A7A\uFF0C\u6CA1\u6709\u53EF\u53D1\u5E03\u7684\u6587\u4EF6");return{files:t,totalBytes:s}}var On=".forsion-connect.json";function jn(n){try{return JSON.parse(jt(Ht(n,On),"utf8"))}catch{return{}}}function Ln(n,e){try{ss(Ht(n,On),JSON.stringify(e,null,2)+`
2
+ `,"utf8")}catch{}}function Hn(n){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 t(s){if(e[s])return e[s];let r="/__forsion/agent-events/";if(s.startsWith(r)){let i=s.slice(r.length);if(/^[A-Za-z0-9-]{1,64}$/.test(i))return{method:"GET",path:`/api/agent/runs/${i}/events`,auth:!0,timeoutMs:9e5}}}return async(s,r)=>{let[i,o]=(s.url||"").split("?"),a=(v,x)=>{r.headersSent||(r.statusCode=v,r.setHeader("Content-Type","application/json")),r.end(JSON.stringify({detail:x}))},c=t(i);if(!c)return a(404,"unknown connect endpoint");if((s.method||"GET")!==c.method)return a(405,"method not allowed");let h="",d="";try{({base:h,token:d}=await n())}catch{}if(!h)return a(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(c.auth&&!d)return a(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let f;if(c.method==="POST"){let v=[],x=0;try{for await(let E of s){if(x+=E.length,x>as)return s.destroy(),a(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");v.push(E)}}catch(E){return a(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${E?.message||String(E)}`)}f=Buffer.concat(v)}if(c.agentRun){let v;try{v=JSON.parse((f||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return a(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}f=Buffer.from(JSON.stringify({session_id:typeof v.session_id=="string"?v.session_id:"",message:typeof v.message=="string"?v.message:"",app_id:"connect",agent_config:{}}))}let u=new AbortController,y=setTimeout(()=>u.abort(new Error("proxy timeout")),c.timeoutMs??3e5);s.on("close",()=>u.abort());try{let v=await fetch(h+c.path+(o?`?${o}`:""),{method:c.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...d?{Authorization:`Bearer ${d}`}:{}},body:f&&f.length?new Uint8Array(f):void 0,signal:u.signal});if(r.statusCode=v.status,r.setHeader("Content-Type",v.headers.get("content-type")||"application/json"),r.setHeader("Cache-Control","no-store"),v.body)for await(let x of v.body)r.write(x);r.end()}catch(v){let x=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${v?.message||String(v)}`;if(r.headersSent){try{r.write(`data: ${JSON.stringify({error:x})}
3
3
 
4
- `)}catch{}r.end()}else c(502,T)}finally{clearTimeout(y)}}}var Fn=`
4
+ `)}catch{}r.end()}else a(502,x)}finally{clearTimeout(y)}}}var zn=`
5
5
  (function () {
6
6
  'use strict';
7
7
  if (window.forsion) return;
@@ -190,13 +190,17 @@ function Tn(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=Str
190
190
  ai: { chat: chat, agent: agentRun, generateImage: generateImage }
191
191
  };
192
192
  })();
193
- `,ts=t=>({transpile:(e,n,s)=>t.transpileForServe(e,n,s),mimeOf:e=>t.mimeOf(e)});function jt(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Ut(t){t.setPreviewHooks({sdkJs:Fn,proxy:Nn(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?$n(n):{}),t.handle("connect:list",async()=>{let e=await t.getCloud();if(!e.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:n,json:s}=await de(e,"GET","/api/connect/apps");return n===401||n===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:n!==200?{ok:!1,code:"error",detail:s?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,...s}}catch(n){return{ok:!1,code:"error",detail:n?.message||String(n)}}}),t.handle("connect:publish",async(e,n)=>{if(!n||typeof n.dir!="string"||!n.dir||!n.name||!n.slug||!n.entry)return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let s;try{let o=Rn(t.projectsRoot());if(s=Rn(n.dir),s!==o&&!s.startsWith(o+Xr))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:o,totalBytes:a}=Pn(s,ts(t));if(!o.some(m=>m.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:c,json:l}=await de(r,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:o},3e5);return c===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:c!==200?{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${c}`,used:l?.used,limit:l?.limit}:(Mn(s,{slug:String(l.slug)}),{ok:!0,slug:l.slug,handle:l.handle,url:`${r.base}${l.url}`,totalBytes:a})}catch(o){return{ok:!1,code:"error",detail:o?.message||String(o)}}}),t.handle("connect:unpublish",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let s=await t.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:r,json:o}=await de(s,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return r===401||r===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:r!==200&&r!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${r}`}:{ok:!0}}catch(r){return{ok:!1,code:"error",detail:r?.message||String(r)}}}),t.handle("connect:listingApply",async(e,n)=>{if(!n||typeof n.slug!="string"||!n.slug||typeof n.summary!="string"||!n.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let s=await t.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:r,json:o}=await de(s,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return r===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:r!==200?{ok:!1,code:o?.code||"error",detail:o?.detail||`HTTP ${r}`}:{ok:!0,status:o.status}}catch(r){return{ok:!1,code:"error",detail:r?.message||String(r)}}}),t.handle("connect:listingWithdraw",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let s=await t.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:r,json:o}=await de(s,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return r===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:r!==200&&r!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${r}`}:{ok:!0}}catch(r){return{ok:!1,code:"error",detail:r?.message||String(r)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:s}=await de(e,"GET","/api/connect/store");return n!==200?{ok:!1,detail:s?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,items:Array.isArray(s.items)?s.items:[]}}catch(n){return{ok:!1,detail:n?.message||String(n)}}}),t.log("[forsion-extend] connect handlers registered")}import{createHash as ns}from"node:crypto";async function nt(t,e){if(!t||!e)return{status:"offline"};let n=t.replace(/\/+$/,"");try{let s=await fetch(`${n}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(s.status===401||s.status===403)return{status:(s.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!s.ok)return{status:"offline"};let r=await s.json();if(!r)return{status:"offline"};let o=r.avatar||r.avatarUrl||r.avatar_url||void 0;return o&&/^\/(?!\/)/.test(o)&&(o=n+o),{status:"ok",user:{username:r.username||r.nickname||void 0,nickname:r.nickname||void 0,avatar:o,membershipTier:r.membershipTier||r.membership_tier||void 0}}}catch{return{status:"offline"}}}var On=t=>`${t.seq}:${t.hash}`,rs=t=>ns("sha256").update(t).digest("hex");function Ht(t){if(t===null)return{baseSeq:0,baseHash:null};if(typeof t!="string")return;let e=t.indexOf(":"),n=Number(e===-1?t:t.slice(0,e));if(!Number.isInteger(n)||n<=0)return;let s=e===-1?"":t.slice(e+1);return{baseSeq:n,baseHash:/^[0-9a-f]{64}$/.test(s)?s:null}}function jn(t){let e=t.baseUrl.replace(/\/+$/,""),n=r=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${r}`,s=async(r,o)=>{let a=t.getToken();if(!a)throw new Error("penzor-not-logged-in");let c=await fetch(r,{...o,headers:{...o.headers,Authorization:`Bearer ${a}`}});if(c.status===409){let l=await c.json().catch(()=>({}));throw new Error(`cas-conflict ${String(l.code??"")}: seq=${String(l.seq??"?")}`)}if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`penzor ${o.method??"GET"} ${c.status}: ${l.slice(0,200)}`)}return c};return{kind:"penzor",async walk(r){let o=await s(n("/manifest"),{method:"GET",signal:r}),{files:a}=await o.json();return a.map(c=>({key:c.path,size:c.size,mtimeMs:c.mtimeMs,id:On(c)}))},async readFile(r,o){let c=await(await s(n(`/file?path=${encodeURIComponent(r)}`),{method:"GET",signal:o})).json(),l=await fetch(c.url,{signal:o});if(!l.ok)throw new Error(`penzor blob GET ${l.status}: ${r}`);let m=Buffer.from(await l.arrayBuffer());if(rs(m)!==c.hash)throw new Error(`penzor hash mismatch: ${r}`);return m},async writeFile(r,o,a,c,l){let m=Ht(l),d=new URLSearchParams({path:r,mtimeMs:String(Math.floor(a)||0)});m&&(d.set("baseSeq",String(m.baseSeq)),m.baseHash&&d.set("baseHash",m.baseHash));let u=await(await s(n(`/file?${d.toString()}`),{method:"PUT",body:new Uint8Array(o),headers:{"Content-Type":"application/octet-stream"},signal:c})).json();return{key:r,size:u.size,mtimeMs:u.mtimeMs,id:On(u)}},async rm(r,o,a){let c=Ht(a),l=new URLSearchParams({path:r});c&&c.baseSeq>0&&(l.set("baseSeq",String(c.baseSeq)),c.baseHash&&l.set("baseHash",c.baseHash)),await s(n(`/file?${l.toString()}`),{method:"DELETE",signal:o})},async check(){try{return await s(n("/manifest"),{method:"GET"}),{ok:!0}}catch(r){return{ok:!1,error:String(r?.message||r)}}}}}var Un=50*1024*1024,Ln=new Map;async function ss(t,e){let n=Ln.get(e);if(n)return{id:n};let s=await nt(t,e);if(s.status==="offline")return{error:"penzor-offline"};if(s.status!=="ok")return{error:"penzor-not-logged-in"};let r=s.user?.username?.trim();return r?(Ln.set(e,r),{id:r}):{error:"penzor-auth-unverified"}}var zt=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function qt(t){t.registerRemoteSyncBackend("penzor",async e=>{let n=t.readCreds();if(!n.token||!n.cloudUrl)return{error:"penzor-not-logged-in"};let s=e?.vault,r=(typeof s=="string"?s:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(r))return{error:"penzor-bad-vault"};let o=await ss(n.cloudUrl,n.token);if("error"in o)return o;let a=n.token;return{remote:jn({baseUrl:n.cloudUrl,vault:r,getToken:()=>a}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${o.id}|${r}`,maxFileBytes:Un}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{readFileSync as os,writeFileSync as is,mkdirSync as as,chmodSync as ls,renameSync as cs}from"node:fs";import{join as us}from"node:path";function Se(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let s=e.split(".")[1];if(!s)return null;let r=s.replace(/-/g,"+").replace(/_/g,"/"),o=Uint8Array.from(atob(r),l=>l.charCodeAt(0)),a=JSON.parse(new TextDecoder().decode(o)),c=a.userId??a.sub;return typeof c!="string"&&typeof c!="number"||!String(c).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(c)}`}catch{return null}}function Wt(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return n&&typeof n=="object"?n:null}catch{return null}}function zn(t,e=Date.now()){let n=Wt(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function ds(t,e=Date.now()){let n=Wt(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var fs=36e5;function qn(t,e=Date.now()){return!!t&&zn(t,e)>=fs}async function Wn(t,e,n=8e3,s){if(!t||!e)return null;let r=t.replace(/\/+$/,"");try{let o=await fetch(`${r}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...s?{"X-Forsion-Client":s}:{}},signal:AbortSignal.timeout(n)});if(!o.ok)return null;let a=await o.json().catch(()=>null),c=typeof a?.token=="string"?a.token:"";return c&&c!==e?c:null}catch{return null}}var bt=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,hs=(t,e)=>new Promise((n,s)=>{let r=()=>{clearTimeout(o),s(new Error("Sign-in cancelled."))},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);e.aborted?r():e.addEventListener("abort",r,{once:!0})});function Bn(t){let e=()=>us(t.homeDir(),"auth-accounts.json"),n=(f,u)=>{as(t.homeDir(),{recursive:!0});let y=`${f}.tmp`;is(y,JSON.stringify(u,null,2),{encoding:"utf8",mode:384}),ls(y,384),cs(y,f)},s=()=>{try{let f=JSON.parse(os(e(),"utf8"));return Array.isArray(f.accounts)?f.accounts.filter(u=>u&&typeof u.token=="string"&&u.id===Se(u.cloudUrl,u.token)):[]}catch{return[]}},r=(f,u)=>{let y=Se(f.cloudUrl||"",f.token||"");if(!y||!f.token||!f.cloudUrl)return;let _=s(),T=_.find(N=>N.id===y),v=Wt(f.token),O={...T,id:y,cloudUrl:f.cloudUrl.replace(/\/+$/,""),token:f.token,username:u?.username||T?.username||v?.username,nickname:u?.nickname||T?.nickname};JSON.stringify(T)!==JSON.stringify(O)&&n(e(),{version:1,accounts:[..._.filter(N=>N.id!==y),O]})},o=()=>{let f=t.readCreds();r(f);let u=Se(f.cloudUrl,f.token);return s().map(({token:y,..._})=>({..._,active:_.id===u}))},a=f=>{let u=s().find(y=>y.id===f);if(!u)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:u.cloudUrl,token:u.token}},c=f=>{let u=Se(f.cloudUrl||"",f.token||"");u&&n(e(),{version:1,accounts:s().filter(y=>y.id!==u)})},l=null;return{rememberForsionAccount:r,forsionAccounts:o,savedForsionAccount:a,forgetForsionAccount:c,cancelForsionLogin:()=>{l?.abort(),l=null},forsionDeviceLogin:async(f,u,y)=>{if(l)throw new Error("A sign-in is already in progress.");if(!f)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let _=new AbortController;l=_;let T=()=>{if(_.signal.aborted||l!==_)throw new Error("Sign-in cancelled.")};try{let v=f.replace(/\/+$/,""),O;try{O=await fetch(`${v}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([_.signal,AbortSignal.timeout(15e3)])}).then(J=>J.json())}catch(J){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${v}:${J?.message||J}`)}if(T(),!O?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let N=O.verification_uri_complete||`${O.verification_uri}?code=${O.user_code}`,Y=new URL(`${v}/auth`);Y.searchParams.set("logout","1"),Y.searchParams.set("app","forsion-desktop"),Y.searchParams.set("redirect",N);let G=Y.toString();u?.({url:G,userCode:String(O.user_code||"")}),t.openExternal(G);let W=Date.now()+(O.expires_in||600)*1e3,Q=(O.interval||2)*1e3;for(;Date.now()<W;){await hs(Q,_.signal),T();let J=null;try{J=await fetch(`${v}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:O.device_code}),signal:AbortSignal.any([_.signal,AbortSignal.timeout(15e3)])})}catch{T();continue}if(T(),J.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let ne=await J.json().catch(()=>({status:"pending"}));if(T(),ne.status==="approved"&&ne.token){let ue={cloudUrl:v,token:ne.token};return await y(ue,T),T(),{token:ne.token,cloudUrl:v}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===_&&(l=null)}},readAccounts:s}}var Vn=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],Bt=t=>Vn.every(e=>typeof t[e]=="function");function Vt(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},s=Bn(t),r=0,o=()=>{let c=t.readCreds();return bt(c.cloudUrl,c.token)},a=null;t.handle("auth:status",async c=>{if(!t.isTrustedSender(c))return n;let l=r,m=o(),{base:d}=await t.getCloud(),f=t.readCreds().token,u=f?await nt(d,f):null,y=await t.accountBackendState(),{base:_}=await t.getCloud(),T=t.readCreds(),v=bt(_,T.token)!==bt(d,f),O=bt(d,f);!v&&u?.status==="ok"&&u.user&&(a={key:O,user:u.user},s.rememberForsionAccount({...T,cloudUrl:d},u.user));let N=v?void 0:u?.status==="ok"?u.user:u?.status==="offline"&&a?.key===O?a.user:void 0;if(v)return{loggedIn:!!T.token,tokenValid:null,cloudUrl:_,accountId:Se(_,T.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:T.token?"tangu-login":null,backendState:y};if(u?.status==="expired"){await t.accountTransition(async()=>{if(l!==r||o()!==m)return;let G=()=>{if(l!==r||o()!==m)throw Hn};try{await t.accountClear(G,()=>{t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++r,s.cancelForsionLogin(),s.forgetForsionAccount(t.readCreds()),a=null})}catch(W){if(W!==Hn)throw W}});let Y=t.readCreds();return{loggedIn:!!Y.token,tokenValid:null,cloudUrl:Y.cloudUrl||d,accountId:Se(Y.cloudUrl||d,Y.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:Y.token?"tangu-login":null,backendState:y}}return{loggedIn:!!f,tokenValid:u&&u.status==="ok"?!0:null,cloudUrl:d,accountId:Se(d,f),username:N?.username||null,nickname:N?.nickname||null,avatar:N?.avatar||null,membershipTier:N?.membershipTier||null,tokenSource:f?"tangu-login":null,backendState:y}}),t.handle("auth:accounts",c=>t.isTrustedSender(c)?s.forsionAccounts():[]),t.handle("auth:switchAccount",async(c,l)=>{if(!t.isTrustedSender(c))return e;if(typeof l!="string")throw new Error("Invalid account.");let m=++r;return s.cancelForsionLogin(),t.accountTransition(async()=>{let d=s.savedForsionAccount(l);return await t.accountCommit(d,()=>{if(m!==r)throw new Error("Account switch cancelled.")},()=>{s.rememberForsionAccount(d),a=null}),{ok:!0,cloudUrl:d.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(c,l)=>{if(!t.isTrustedSender(c))return e;let m=++r;s.cancelForsionLogin();let{base:d}=await t.getCloud();if(m!==r)throw new Error("Sign-in cancelled.");let f=(l||d||"").trim();return{ok:!0,cloudUrl:(await s.forsionDeviceLogin(f,y=>t.broadcast("auth:device",y),(y,_)=>t.accountTransition(()=>t.accountCommit(y,()=>{if(_(),m!==r)throw new Error("Sign-in cancelled.")},()=>{s.rememberForsionAccount(y),a=null})))).cloudUrl}}),t.handle("auth:logout",async c=>t.isTrustedSender(c)?(++r,s.cancelForsionLogin(),t.accountTransition(async()=>{let{base:l}=await t.getCloud(),m=t.readCreds();return await t.accountClear(void 0,()=>{s.forgetForsionAccount(m),a=null,l&&m.token&&fetch(`${l}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${m.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:c,current:l})=>{++r,s.cancelForsionLogin(),c.token&&!l.token&&s.forgetForsionAccount(c),a=null,s.rememberForsionAccount(l)}),t.setTokenRefresher(async c=>{let l=r,m=o(),d=t.readCreds().token;if(!qn(d))return;let{base:f}=await t.getCloud(),u=await Wn(f,d,c,`desktop/${t.appVersion()}`);if(!u){t.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}l!==r||o()!==m||(s.rememberForsionAccount({cloudUrl:f,token:u}),t.writeCreds({cloudUrl:f,token:u}),t.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),t.log("[forsion-extend] account core registered")}var Hn=Symbol("stale-auth-intent");import{promises as Xe}from"node:fs";import je from"node:path";import{createHash as ms}from"node:crypto";var Gt=null;function Gn(t){Gt=t}function fe(){if(!Gt)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return Gt}var he=()=>fe().accountId();function rt(t=he()){return t?ms("sha256").update(t).digest("hex"):"signed-out"}var Ee=(t=he())=>fe().readConfig(t),Ae=(t,e=he())=>fe().writeConfig(t,e),qe=(t,e=he())=>fe().updateConfig(t,e),De=(t=he())=>fe().cloudVaultDir(t),St=t=>fe().isManagedCloudVault(t);import{createHash as bo}from"node:crypto";import{promises as te,existsSync as Cr}from"node:fs";import se from"node:path";import{EventEmitter as qs}from"node:events";import{stat as Ws}from"node:fs";import{readdir as Bs,stat as Vs}from"node:fs/promises";import*as z from"node:path";import{lstat as Yn,readdir as ps,realpath as gs,stat as ys}from"node:fs/promises";import{join as ws,resolve as bs,sep as Jn}from"node:path";import{Readable as Ss}from"node:stream";var pe={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},We={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:pe.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(We);var Zn="READDIRP_RECURSIVE_ERROR",Es=new Set(["ENOENT","EPERM","EACCES","ELOOP",Zn]),Kn=[pe.DIR_TYPE,pe.EVERYTHING_TYPE,pe.FILE_DIR_TYPE,pe.FILE_TYPE],vs=new Set([pe.DIR_TYPE,pe.EVERYTHING_TYPE,pe.FILE_DIR_TYPE]),_s=new Set([pe.EVERYTHING_TYPE,pe.FILE_DIR_TYPE,pe.FILE_TYPE]),ks=t=>Es.has(t.code),Cs=process.platform==="win32",Xn=t=>!0,Qn=t=>{if(t===void 0)return Xn;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(s=>n.basename===s)}return Xn},Yt=class extends Ss{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??We.highWaterMark});let n={...We,...e},s=n.root??We.root,r=n.type??We.type;this._fileFilter=Qn(n.fileFilter),this._directoryFilter=Qn(n.directoryFilter);let o=n.lstat?Yn:ys;Cs?this._stat=c=>o(c,{bigint:!0}):this._stat=o,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:We.depth,this._wantsDir=vs.has(r),this._wantsFile=_s.has(r),this._wantsEverything=r===pe.EVERYTHING_TYPE,this._root=bs(s),this._relStart=this._root.endsWith(Jn)?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 a={path:this._root,depth:1};a.pending=this._exploreDir(this._root,1),this.parents=[a],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,s=n&&n.files;if(s&&s.length>0){let{path:r,depth:o}=n,a=s.splice(0,e).map(l=>this._formatEntry(l,r)),c=this._isDirent?a:await Promise.all(a);for(let l of c){if(!l)continue;if(this.destroyed)return;let m=this._getEntryType(l);typeof m!="string"&&(m=await m),m==="directory"&&this._directoryFilter(l)?(o<=this._maxDepth&&this.parents.push({path:l.fullPath,depth:o+1}),this._wantsDir&&(this.push(l),e--)):(m==="file"||this._includeAsFile(l))&&this._fileFilter(l)&&this._wantsFile&&(this.push(l),e--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}let o=r.pending??this._exploreDir(r.path,r.depth),a=this.parents[this.parents.length-1];if(a&&!a.pending&&(a.pending=this._exploreDir(a.path,a.depth)),this.parent=await o,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let s;try{s=await ps(e,this._rdOptions)}catch(r){this._onError(r)}return{files:s,depth:n,path:e}}_formatEntry(e,n){let s=this._isDirent?e.name:e,r=ws(n,s),o={path:r.slice(this._relStart),fullPath:r,basename:s};return this._isDirent?(o.dirent=e,o):this._stat(r).then(a=>(o.stats=a,o),a=>{this._onError(a)})}_onError(e){ks(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 s=await gs(n),r=await Yn(s);if(r.isFile())return"file";if(r.isDirectory()){let o=s.length;if(n.startsWith(s)&&n[o]===Jn){let a=new Error(`Circular symlink detected: "${n}" points to "${s}"`);return a.code=Zn,this._onError(a),""}return"directory"}}catch(s){this._onError(s)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function er(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=pe.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!Kn.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${Kn.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let s={...e,root:t};return n&&(s.type=n),new Yt(s)}import{watch as xs,unwatchFile as tr,watchFile as Ts}from"node:fs";import{realpath as Jt,lstat as Rs,open as Is,stat as rr}from"node:fs/promises";import{type as As}from"node:os";import*as X from"node:path";var Ps="data",Qt="end",sr="close",Ct=()=>{};var xt=process.platform,Zt=xt==="win32",Ds=xt==="darwin",$s=xt==="linux",Ms=xt==="freebsd",or=As()==="OS400",ee={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},ve=ee,Ns="watch",Fs={lstat:Rs,stat:rr},Le="listeners",Et="errHandlers",Be="rawEmitters",Os=[Le,Et,Be],Ls=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"]),js=t=>Ls.has(X.extname(t).slice(1).toLowerCase()),Xt=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},st=(t,e,n)=>{let s=t[e];s instanceof Set||(t[e]=s=new Set([s])),s.add(n)},Us=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},ot=(t,e,n)=>{let s=t[e];s instanceof Set?s.delete(n):s===n&&delete t[e]},ir=t=>t instanceof Set?t.size===0:!t,vt=new Map;function nr(t,e,n,s,r){let o=(a,c)=>{n(t),r(a,c,{watchedPath:t}),c&&t!==c&&_t(X.resolve(t,c),Le,X.join(t,c))};try{return xs(t,{persistent:e.persistent},o)}catch(a){s(a);return}}var _t=(t,e,n,s,r)=>{let o=vt.get(t);o&&Xt(o[e],a=>{a(n,s,r)})},Hs=(t,e,n,s)=>{let{listener:r,errHandler:o,rawEmitter:a}=s,c=vt.get(e),l;if(!n.persistent)return l=nr(t,n,r,o,a),l?l.close.bind(l):void 0;if(c)st(c,Le,r),st(c,Et,o),st(c,Be,a);else{if(l=nr(t,n,_t.bind(null,e,Le),o,_t.bind(null,e,Be)),!l)return;l.on(ve.ERROR,async m=>{let d=_t.bind(null,e,Et);if(c&&(c.watcherUnusable=!0),Zt&&m.code==="EPERM")try{await(await Is(t,"r")).close(),d(m)}catch{}else d(m)}),c={listeners:r,errHandlers:o,rawEmitters:a,watcher:l},vt.set(e,c)}return()=>{ot(c,Le,r),ot(c,Et,o),ot(c,Be,a),ir(c.listeners)&&(c.watcher.close(),vt.delete(e),Os.forEach(Us(c)),c.watcher=void 0,Object.freeze(c))}},Kt=new Map,zs=(t,e,n,s)=>{let{listener:r,rawEmitter:o}=s,a=Kt.get(e),c=a&&a.options;return c&&(c.persistent<n.persistent||c.interval>n.interval)&&(tr(e),a=void 0),a?(st(a,Le,r),st(a,Be,o)):(a={listeners:r,rawEmitters:o,options:n,watcher:Ts(e,n,(l,m)=>{Xt(a.rawEmitters,f=>{f(ve.CHANGE,e,{curr:l,prev:m})});let d=l.mtimeMs;(l.size!==m.size||d>m.mtimeMs||d===0)&&Xt(a.listeners,f=>f(t,l))})},Kt.set(e,a)),()=>{ot(a,Le,r),ot(a,Be,o),ir(a.listeners)&&(Kt.delete(e),tr(e),a.options=a.watcher=void 0,Object.freeze(a))}},kt=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let s=this.fsw.options,r=X.dirname(e),o=X.basename(e);this.fsw._getWatchedDir(r).add(o);let c=X.resolve(e),l={persistent:s.persistent};n||(n=Ct);let m;if(s.usePolling){let d=s.interval!==s.binaryInterval;l.interval=d&&js(o)?s.binaryInterval:s.interval,m=zs(e,c,l,{listener:n,rawEmitter:this.fsw._emitRaw})}else m=Hs(e,c,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return m}_handleFile(e,n,s){if(this.fsw.closed)return;let r=X.dirname(e),o=X.basename(e),a=this.fsw._getWatchedDir(r),c=n;if(a.has(o))return;let l=async(d,f)=>{if(this.fsw._throttle(Ns,e,5)){if(!f||f.mtimeMs===0)try{let u=await rr(e);if(this.fsw.closed)return;let y=u.atimeMs,_=u.mtimeMs;if((!y||y<=_||_!==c.mtimeMs)&&this.fsw._emit(ve.CHANGE,e,u),(Ds||$s||Ms)&&c.ino!==u.ino){this.fsw._closeFile(d),c=u;let T=this._watchWithNodeFs(e,l);T&&this.fsw._addPathCloser(d,T)}else c=u}catch{this.fsw._remove(r,o)}else if(a.has(o)){let u=f.atimeMs,y=f.mtimeMs;(!u||u<=y||y!==c.mtimeMs)&&this.fsw._emit(ve.CHANGE,e,f),c=f}}},m=this._watchWithNodeFs(e,l);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(ve.ADD,e,0))return;this.fsw._emit(ve.ADD,e,n)}return m}async _handleSymlink(e,n,s,r){if(this.fsw.closed)return;let o=e.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await Jt(s)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(o)!==c&&(this.fsw._symlinkPaths.set(o,c),this.fsw._emit(ve.CHANGE,s,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(o,c),this.fsw._emit(ve.ADD,s,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(o))return!0;this.fsw._symlinkPaths.set(o,!0)}_handleRead(e,n,s,r,o,a,c){e=X.join(e,"");let l=r?`${e}:${r}`:e;if(c=this.fsw._throttle("readdir",l,1e3),!c)return;let m=this.fsw._getWatchedDir(s.path),d=new Set,f=this.fsw._readdirp(e,{fileFilter:u=>s.filterPath(u),directoryFilter:u=>s.filterDir(u)});if(f)return f.on(Ps,async u=>{if(this.fsw.closed){f=void 0;return}let y=u.path,_=X.join(e,y);if(d.add(y),!(u.stats.isSymbolicLink()&&await this._handleSymlink(u,e,_,y))){if(this.fsw.closed){f=void 0;return}(y===r||!r&&!m.has(y))&&(this.fsw._incrReadyCount(),_=X.join(o,X.relative(o,_)),this._addToNodeFs(_,n,s,a+1))}}).on(ve.ERROR,this._boundHandleError),new Promise((u,y)=>{if(!f)return y();f.once(Qt,()=>{if(this.fsw.closed){f=void 0;return}let _=c?c.clear():!1;u(void 0),m.getChildren().filter(T=>T!==e&&!d.has(T)).forEach(T=>{this.fsw._remove(e,T)}),f=void 0,_&&this._handleRead(e,!1,s,r,o,a,c)})})}async _handleDir(e,n,s,r,o,a,c){let l=this.fsw._getWatchedDir(X.dirname(e)),m=l.has(X.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!o&&!m&&this.fsw._emit(ve.ADD_DIR,e,n),l.add(X.basename(e)),this.fsw._getWatchedDir(e);let d,f,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(c)){if(!o&&(await this._handleRead(e,s,a,o,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(y,_)=>{_&&_.mtimeMs===0||this._handleRead(y,!1,a,o,e,r,d)})}return f}async _addToNodeFs(e,n,s,r,o){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);s&&(c.filterPath=l=>s.filterPath(l),c.filterDir=l=>s.filterDir(l));try{let l=await Fs[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,l))return a(),!1;let m=this.fsw.options.followSymlinks,d;if(l.isDirectory()){let f=X.resolve(e),u=m?await Jt(e):e;if(this.fsw.closed||(d=await this._handleDir(c.watchPath,l,n,r,o,c,u),this.fsw.closed))return;f!==u&&u!==void 0&&this.fsw._symlinkPaths.set(f,u)}else if(l.isSymbolicLink()){let f=m?await Jt(e):e;if(this.fsw.closed)return;let u=X.dirname(c.watchPath);if(this.fsw._getWatchedDir(u).add(c.watchPath),this.fsw._emit(ve.ADD,c.watchPath,l),d=await this._handleDir(u,l,n,r,e,c,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(X.resolve(e),f)}else d=this._handleFile(c.watchPath,l,n);return a(),d&&this.fsw._addPathCloser(e,d),!1}catch(l){if(this.fsw._handleError(l))return a(),e}}};var en="/",Gs="//",dr=".",Ys="..",Js="string",Ks=/\\/g,fr=/\/\//g,Xs=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Qs=/^\.[/\\]/;function Tt(t){return Array.isArray(t)?t:[t]}var tn=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Zs(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=z.relative(t.path,e);return n?!n.startsWith("..")&&!z.isAbsolute(n):!1}return!1}:()=>!1}function eo(t){if(typeof t!="string")throw new Error("string expected");t=z.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(fr,"/"),e&&(t="/"+t),t}function ar(t,e,n){let s=eo(e);for(let r=0;r<t.length;r++){let o=t[r];if(o(s,n))return!0}return!1}function to(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let s=Tt(t).map(r=>Zs(r));return e==null?(r,o)=>ar(s,r,o):ar(s,e)}var lr=t=>{let e=Tt(t).flat();if(!e.every(n=>typeof n===Js))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(hr)},cr=t=>{let e=t.replace(Ks,en),n=!1;return e.startsWith(Gs)&&(n=!0),e=e.replace(fr,en),n&&(e=en+e),e},hr=t=>cr(z.normalize(cr(t))),ur=(t="")=>e=>typeof e=="string"?hr(z.isAbsolute(e)?e:z.join(t,e)):e,no=(t,e)=>z.isAbsolute(t)?t:z.join(e,t),ro=Object.freeze(new Set),nn=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!==dr&&e!==Ys&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let s=this.path;try{await Bs(s)}catch{this._removeWatcher&&this._removeWatcher(z.dirname(s),z.basename(s))}}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=Ct,this.items=ro,Object.freeze(this)}},so="stat",oo="lstat",rn=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,s){this.fsw=s;let r=e;this.path=e=e.replace(Qs,""),this.watchPath=r,this.fullWatchPath=z.resolve(r),this.dirParts=[],this.dirParts.forEach(o=>{o.length>1&&o.pop()}),this.followSymlinks=n,this.statMethod=n?so:oo}entryPath(e){return z.join(this.watchPath,z.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let s=this.entryPath(e);return this.fsw._isntIgnored(s,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Rt=class extends qs{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,s={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Tt(e.ignored):Tt([]),awaitWriteFinish:n===!0?s:typeof n=="object"?{...s,...n}:!1};or&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let o=process.env.CHOKIDAR_USEPOLLING;if(o!==void 0){let l=o.toLowerCase();l==="false"||l==="0"?r.usePolling=!1:l==="true"||l==="1"?r.usePolling=!0:r.usePolling=!!l}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=Ct,this._readyEmitted=!0,process.nextTick(()=>this.emit(ee.READY)))},this._emitRaw=(...l)=>this.emit(ee.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new kt(this),Object.freeze(r)}_addIgnoredPath(e){if(tn(e)){for(let n of this._ignoredPaths)if(tn(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)tn(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,s){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let o=lr(e);return r&&(o=o.map(a=>no(a,r))),o.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!s,void 0,0,n);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(z.dirname(c),z.basename(n||c))})}),this}unwatch(e){if(this.closed)return this;let n=lr(e),{cwd:s}=this.options;return n.forEach(r=>{!z.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=z.join(s,r)),r=z.resolve(r)),this._closePath(r),this._addIgnoredPath(r),this._watched.has(r)&&this._addIgnoredPath({path:r,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(s=>{let r=s();r instanceof Promise&&e.push(r)})),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,s)=>{let o=(this.options.cwd?z.relative(this.options.cwd,s):s)||dr;e[o]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==ee.ERROR&&this.emit(ee.ALL,e,...n)}async _emit(e,n,s){if(this.closed)return;let r=this.options;Zt&&(n=z.normalize(n)),r.cwd&&(n=z.relative(r.cwd,n));let o=[n];s!=null&&o.push(s);let a=r.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(n)))return c.lastChange=new Date,this;if(r.atomic){if(e===ee.UNLINK)return this._pendingUnlinks.set(n,[e,...o]),setTimeout(()=>{this._pendingUnlinks.forEach((l,m)=>{this.emit(...l),this.emit(ee.ALL,...l),this._pendingUnlinks.delete(m)})},typeof r.atomic=="number"?r.atomic:100),this;e===ee.ADD&&this._pendingUnlinks.has(n)&&(e=ee.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(e===ee.ADD||e===ee.CHANGE)&&this._readyEmitted){let l=(m,d)=>{m?(e=ee.ERROR,o[0]=m,this.emitWithAll(e,o)):d&&(o.length>1?o[1]=d:o.push(d),this.emitWithAll(e,o))};return this._awaitWriteFinish(n,a.stabilityThreshold,e,l),this}if(e===ee.CHANGE&&!this._throttle(ee.CHANGE,n,50))return this;if(r.alwaysStat&&s===void 0&&(e===ee.ADD||e===ee.ADD_DIR||e===ee.CHANGE)){let l=r.cwd?z.join(r.cwd,n):n,m;try{m=await Vs(l)}catch{}if(!m||this.closed)return;o.push(m)}return this.emitWithAll(e,o),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(ee.ERROR,e),e||this.closed}_throttle(e,n,s){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw new Error("invalid throttle");let o=r.get(n);if(o)return o.count++,!1;let a,c=()=>{let m=r.get(n),d=m?m.count:0;return r.delete(n),clearTimeout(a),m&&clearTimeout(m.timeoutObject),d};a=setTimeout(c,s);let l={timeoutObject:a,clear:c,count:0};return r.set(n,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,s,r){let o=this.options.awaitWriteFinish;if(typeof o!="object")return;let a=o.pollInterval,c,l=e;this.options.cwd&&!z.isAbsolute(e)&&(l=z.join(this.options.cwd,e));let m=new Date,d=this._pendingWrites;function f(u){Ws(l,(y,_)=>{if(y||!d.has(e)){y&&y.code!=="ENOENT"&&r(y);return}let T=Number(new Date);u&&_.size!==u.size&&(d.get(e).lastChange=T);let v=d.get(e);T-v.lastChange>=n?(d.delete(e),r(void 0,_)):c=setTimeout(f,a,_)})}d.has(e)||(d.set(e,{lastChange:m,cancelWait:()=>(d.delete(e),clearTimeout(c),s)}),c=setTimeout(f,a))}_isIgnored(e,n){if(this.options.atomic&&Xs.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,o=(this.options.ignored||[]).map(ur(s)),c=[...[...this._ignoredPaths].map(ur(s)),...o];this._userIgnored=to(c,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new rn(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=z.resolve(e);return this._watched.has(n)||this._watched.set(n,new nn(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,s){let r=z.join(e,n),o=z.resolve(r);if(s=s??(this._watched.has(r)||this._watched.has(o)),!this._throttle("remove",r,100))return;!s&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(r).getChildren().forEach(u=>this._remove(r,u));let l=this._getWatchedDir(e),m=l.has(n);l.remove(n),this._symlinkPaths.has(o)&&this._symlinkPaths.delete(o);let d=r;if(this.options.cwd&&(d=z.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===ee.ADD)return;this._watched.delete(r),this._watched.delete(o);let f=s?ee.UNLINK_DIR:ee.UNLINK;m&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(e){this._closeFile(e);let n=z.dirname(e);this._getWatchedDir(n).remove(z.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(s=>s()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let s=this._closers.get(e);s||(s=[],this._closers.set(e,s)),s.push(n)}_readdirp(e,n){if(this.closed)return;let s={type:ee.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},r=er(e,s);return this._streams.add(r),r.once(sr,()=>{r=void 0}),r.once(Qt,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function io(t,e={}){let n=new Rt(e);return n.add(t),n}var mr={watch:io,FSWatcher:Rt};function ao(t,e){let n=Object.create(null);for(let o=0;o<e.length;o++){let a=e[o];n[a]?n[a].push(o):n[a]=[o]}let r=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let o=0;o<t.length;o++){let a=t[o],c=n[a]||[],l=0,m=r[0];for(let d of c){let f;for(f=l;f<r.length&&!(r[f].buffer2index<d&&(f===r.length-1||r[f+1].buffer2index>d));f++);if(f<r.length){let u={buffer1index:o,buffer2index:d,chain:r[f]};if(l===r.length?r.push(m):r[l]=m,l=f+1,m=u,l===r.length)break}}r[l]=m}return r[r.length-1]}function pr(t,e){let n=ao(t,e),s=[],r=t.length,o=e.length;for(let a=n;a!==null;a=a.chain){let c=r-a.buffer1index-1,l=o-a.buffer2index-1;r=a.buffer1index,o=a.buffer2index,(c||l)&&s.push({buffer1:[r+1,c],buffer1Content:t.slice(r+1,r+1+c),buffer2:[o+1,l],buffer2Content:e.slice(o+1,o+1+l)})}return s.reverse(),s}function lo(t,e,n){let s=[];function r(l,m){s.push({ab:m,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}pr(e,t).forEach(l=>r(l,"a")),pr(e,n).forEach(l=>r(l,"b")),s.sort((l,m)=>l.oStart-m.oStart);let o=[],a=0;function c(l){l>a&&(o.push({stable:!0,buffer:"o",bufferStart:a,bufferLength:l-a,bufferContent:e.slice(a,l)}),a=l)}for(;s.length;){let l=s.shift(),m=l.oStart,d=l.oStart+l.oLength,f=[l];for(c(m);s.length;){let u=s[0],y=u.oStart;if(y>d)break;d=Math.max(d,y+u.oLength),f.push(s.shift())}if(f.length===1){if(l.abLength>0){let u=l.ab==="a"?t:n;o.push({stable:!0,buffer:l.ab,bufferStart:l.abStart,bufferLength:l.abLength,bufferContent:u.slice(l.abStart,l.abStart+l.abLength)})}}else{let u={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;f.length;){l=f.shift();let N=l.oStart,Y=N+l.oLength,G=l.abStart,W=G+l.abLength,Q=u[l.ab];Q[0]=Math.min(G,Q[0]),Q[1]=Math.max(W,Q[1]),Q[2]=Math.min(N,Q[2]),Q[3]=Math.max(Y,Q[3])}let y=u.a[0]+(m-u.a[2]),_=u.a[1]+(d-u.a[3]),T=u.b[0]+(m-u.b[2]),v=u.b[1]+(d-u.b[3]),O={stable:!1,aStart:y,aLength:_-y,aContent:t.slice(y,_),oStart:m,oLength:d-m,oContent:e.slice(m,d),bStart:T,bLength:v-T,bContent:n.slice(T,v)};o.push(O)}a=d}return c(e.length),o}function gr(t,e,n,s){s=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},s),typeof t=="string"&&(t=t.split(s.stringSeparator)),typeof e=="string"&&(e=e.split(s.stringSeparator)),typeof n=="string"&&(n=n.split(s.stringSeparator));let o=[],a=lo(t,e,n),c=[];function l(){c.length&&o.push({ok:c}),c=[]}function m(d,f){if(d.length!==f.length)return!1;for(let u=0;u<d.length;u++)if(d[u]!==f[u])return!1;return!0}return a.forEach(d=>{d.stable?c.push(...d.bufferContent):s.excludeFalseConflicts&&m(d.aContent,d.bContent)?c.push(...d.aContent):(l(),o.push({conflict:{a:d.aContent,aIndex:d.aStart,o:d.oContent,oIndex:d.oStart,b:d.bContent,bIndex:d.bStart}}))}),l(),o}function It(t,e){let n=t.lastIndexOf("/"),s=n<0?"":t.slice(0,n+1),r=n<0?t:t.slice(n+1),o=r.lastIndexOf("."),a=o>0?r.slice(0,o):r,c=o>0?r.slice(o):"",l=d=>String(d).padStart(2,"0"),m=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}`;return`${s}${a} (conflict ${m})${c}`}function co(t,e){if(e<2)return t;let n=t.lastIndexOf("."),s=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),r=s?t.slice(0,n):t,o=s?t.slice(n):"";return`${r}-${e}${o}`}function uo(t){let e=3735928559,n=1103547991;for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);e=Math.imul(e^o,2654435761),n=Math.imul(n^o,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let s=4294967296*(2097151&n)+(e>>>0);return`${t.length.toString(36)}-${s.toString(36)}`}function At(t,e,n){if(t===null&&e===null&&n===null)return{kind:"none"};if(n===null)return t===null?e?{kind:"dropShadow"}:{kind:"none"}:e?t===e.hash?{kind:"deleteLocal"}:{kind:"pushCreate"}:{kind:"pushCreate"};if(t===null)return e?n.seq===e.seq?{kind:"pushDelete"}:{kind:"pull"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"conflict"};let s=t!==e.hash,r=n.seq!==e.seq;return!s&&!r?{kind:"none"}:s?r?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function yr(t,e,n){let s=gr(t.split(`
193
+ `,us=n=>({transpile:(e,t,s)=>n.transpileForServe(e,t,s),mimeOf:e=>n.mimeOf(e)});function zt(n){let e=n;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Wt(n){n.setPreviewHooks({sdkJs:zn,proxy:Hn(()=>n.getCloud())}),n.handle("connect:meta",(e,t)=>typeof t=="string"&&t?jn(t):{}),n.handle("connect:list",async()=>{let e=await n.getCloud();if(!e.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:t,json:s}=await de(e,"GET","/api/connect/apps");return t===401||t===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:t!==200?{ok:!1,code:"error",detail:s?.detail||`HTTP ${t}`}:{ok:!0,base:e.base,...s}}catch(t){return{ok:!1,code:"error",detail:t?.message||String(t)}}}),n.handle("connect:publish",async(e,t)=>{if(!t||typeof t.dir!="string"||!t.dir||!t.name||!t.slug||!t.entry)return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let s;try{let i=Mn(n.projectsRoot());if(s=Mn(t.dir),s!==i&&!s.startsWith(i+os))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let r=await n.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:i,totalBytes:o}=Fn(s,us(n));if(!i.some(h=>h.path===t.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${t.entry}`};let{status:a,json:c}=await de(r,"POST","/api/connect/apps",{slug:t.slug,name:t.name,entry:t.entry,files:i},3e5);return a===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:a!==200?{ok:!1,code:c?.code||"error",detail:c?.detail||`HTTP ${a}`,used:c?.used,limit:c?.limit}:(Ln(s,{slug:String(c.slug)}),{ok:!0,slug:c.slug,handle:c.handle,url:`${r.base}${c.url}`,totalBytes:o})}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),n.handle("connect:unpublish",async(e,t)=>{if(!t||typeof t!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let s=await n.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:r,json:i}=await de(s,"DELETE",`/api/connect/apps/${encodeURIComponent(t)}`);return r===401||r===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:r!==200&&r!==404?{ok:!1,code:"error",detail:i?.detail||`HTTP ${r}`}:{ok:!0}}catch(r){return{ok:!1,code:"error",detail:r?.message||String(r)}}}),n.handle("connect:listingApply",async(e,t)=>{if(!t||typeof t.slug!="string"||!t.slug||typeof t.summary!="string"||!t.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let s=await n.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:r,json:i}=await de(s,"PUT",`/api/connect/apps/${encodeURIComponent(t.slug)}/listing`,{summary:t.summary});return r===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:r!==200?{ok:!1,code:i?.code||"error",detail:i?.detail||`HTTP ${r}`}:{ok:!0,status:i.status}}catch(r){return{ok:!1,code:"error",detail:r?.message||String(r)}}}),n.handle("connect:listingWithdraw",async(e,t)=>{if(!t||typeof t!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let s=await n.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:r,json:i}=await de(s,"DELETE",`/api/connect/apps/${encodeURIComponent(t)}/listing`);return r===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:r!==200&&r!==404?{ok:!1,code:"error",detail:i?.detail||`HTTP ${r}`}:{ok:!0}}catch(r){return{ok:!1,code:"error",detail:r?.message||String(r)}}}),n.handle("connect:store",async()=>{let e=await n.getCloud();try{let{status:t,json:s}=await de(e,"GET","/api/connect/store");return t!==200?{ok:!1,detail:s?.detail||`HTTP ${t}`}:{ok:!0,base:e.base,items:Array.isArray(s.items)?s.items:[]}}catch(t){return{ok:!1,detail:t?.message||String(t)}}}),n.log("[forsion-extend] connect handlers registered")}import{createHash as ds}from"node:crypto";async function nt(n,e){if(!n||!e)return{status:"offline"};let t=n.replace(/\/+$/,"");try{let s=await fetch(`${t}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(s.status===401||s.status===403)return{status:(s.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!s.ok)return{status:"offline"};let r=await s.json();if(!r)return{status:"offline"};let i=r.avatar||r.avatarUrl||r.avatar_url||void 0;return i&&/^\/(?!\/)/.test(i)&&(i=t+i),{status:"ok",user:{username:r.username||r.nickname||void 0,nickname:r.nickname||void 0,avatar:i,membershipTier:r.membershipTier||r.membership_tier||void 0}}}catch{return{status:"offline"}}}var Wn=n=>`${n.seq}:${n.hash}`,fs=n=>ds("sha256").update(n).digest("hex");function qt(n){if(n===null)return{baseSeq:0,baseHash:null};if(typeof n!="string")return;let e=n.indexOf(":"),t=Number(e===-1?n:n.slice(0,e));if(!Number.isInteger(t)||t<=0)return;let s=e===-1?"":n.slice(e+1);return{baseSeq:t,baseHash:/^[0-9a-f]{64}$/.test(s)?s:null}}function Bn(n){let e=n.baseUrl.replace(/\/+$/,""),t=r=>`${e}/api/remotesync/vaults/${encodeURIComponent(n.vault)}${r}`,s=async(r,i)=>{let o=n.getToken();if(!o)throw new Error("penzor-not-logged-in");let a=await fetch(r,{...i,headers:{...i.headers,Authorization:`Bearer ${o}`}});if(a.status===409){let c=await a.json().catch(()=>({}));throw new Error(`cas-conflict ${String(c.code??"")}: seq=${String(c.seq??"?")}`)}if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`penzor ${i.method??"GET"} ${a.status}: ${c.slice(0,200)}`)}return a};return{kind:"penzor",async walk(r){let i=await s(t("/manifest"),{method:"GET",signal:r}),{files:o}=await i.json();return o.map(a=>({key:a.path,size:a.size,mtimeMs:a.mtimeMs,id:Wn(a)}))},async readFile(r,i){let a=await(await s(t(`/file?path=${encodeURIComponent(r)}`),{method:"GET",signal:i})).json(),c=await fetch(a.url,{signal:i});if(!c.ok)throw new Error(`penzor blob GET ${c.status}: ${r}`);let h=Buffer.from(await c.arrayBuffer());if(fs(h)!==a.hash)throw new Error(`penzor hash mismatch: ${r}`);return h},async writeFile(r,i,o,a,c){let h=qt(c),d=new URLSearchParams({path:r,mtimeMs:String(Math.floor(o)||0)});h&&(d.set("baseSeq",String(h.baseSeq)),h.baseHash&&d.set("baseHash",h.baseHash));let u=await(await s(t(`/file?${d.toString()}`),{method:"PUT",body:new Uint8Array(i),headers:{"Content-Type":"application/octet-stream"},signal:a})).json();return{key:r,size:u.size,mtimeMs:u.mtimeMs,id:Wn(u)}},async rm(r,i,o){let a=qt(o),c=new URLSearchParams({path:r});a&&a.baseSeq>0&&(c.set("baseSeq",String(a.baseSeq)),a.baseHash&&c.set("baseHash",a.baseHash)),await s(t(`/file?${c.toString()}`),{method:"DELETE",signal:i})},async check(){try{return await s(t("/manifest"),{method:"GET"}),{ok:!0}}catch(r){return{ok:!1,error:String(r?.message||r)}}}}}var Vn=50*1024*1024,qn=new Map;async function hs(n,e){let t=qn.get(e);if(t)return{id:t};let s=await nt(n,e);if(s.status==="offline")return{error:"penzor-offline"};if(s.status!=="ok")return{error:"penzor-not-logged-in"};let r=s.user?.username?.trim();return r?(qn.set(e,r),{id:r}):{error:"penzor-auth-unverified"}}var Bt=n=>typeof n.registerRemoteSyncBackend=="function"&&typeof n.readCreds=="function";function Vt(n){n.registerRemoteSyncBackend("penzor",async e=>{let t=n.readCreds();if(!t.token||!t.cloudUrl)return{error:"penzor-not-logged-in"};let s=e?.vault,r=(typeof s=="string"?s:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(r))return{error:"penzor-bad-vault"};let i=await hs(t.cloudUrl,t.token);if("error"in i)return i;let o=t.token;return{remote:Bn({baseUrl:t.cloudUrl,vault:r,getToken:()=>o}),fingerprint:`penzor:${t.cloudUrl.replace(/\/+$/,"")}|u:${i.id}|${r}`,maxFileBytes:Vn}}),n.log('[forsion-extend] remote-sync backend "penzor" registered')}import{readFileSync as ps,writeFileSync as ms,mkdirSync as gs,chmodSync as ys,renameSync as ws}from"node:fs";import{join as bs}from"node:path";function Se(n,e){try{let t=new URL(n);if(t.protocol!=="https:"&&t.protocol!=="http:")return null;let s=e.split(".")[1];if(!s)return null;let r=s.replace(/-/g,"+").replace(/_/g,"/"),i=Uint8Array.from(atob(r),c=>c.charCodeAt(0)),o=JSON.parse(new TextDecoder().decode(i)),a=o.userId??o.sub;return typeof a!="string"&&typeof a!="number"||!String(a).trim()?null:`${t.origin}${t.pathname.replace(/\/+$/,"")}::${String(a)}`}catch{return null}}function Gt(n){try{let e=n.split(".")[1];if(!e)return null;let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Yn(n,e=Date.now()){let t=Gt(n)?.iat;return typeof t=="number"?e-t*1e3:1/0}function Ss(n,e=Date.now()){let t=Gt(n)?.exp;return typeof t=="number"?t*1e3-e:1/0}var vs=36e5;function Jn(n,e=Date.now()){return!!n&&Yn(n,e)>=vs}async function Xn(n,e,t=8e3,s){if(!n||!e)return null;let r=n.replace(/\/+$/,"");try{let i=await fetch(`${r}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...s?{"X-Forsion-Client":s}:{}},signal:AbortSignal.timeout(t)});if(!i.ok)return null;let o=await i.json().catch(()=>null),a=typeof o?.token=="string"?o.token:"";return a&&a!==e?a:null}catch{return null}}var vt=(n,e)=>`${n.replace(/\/+$/,"")}\0${e}`,Es=(n,e)=>new Promise((t,s)=>{let r=()=>{clearTimeout(i),s(new Error("Sign-in cancelled."))},i=setTimeout(()=>{e.removeEventListener("abort",r),t()},n);e.aborted?r():e.addEventListener("abort",r,{once:!0})});function Kn(n){let e=()=>bs(n.homeDir(),"auth-accounts.json"),t=(f,u)=>{gs(n.homeDir(),{recursive:!0});let y=`${f}.tmp`;ms(y,JSON.stringify(u,null,2),{encoding:"utf8",mode:384}),ys(y,384),ws(y,f)},s=()=>{try{let f=JSON.parse(ps(e(),"utf8"));return Array.isArray(f.accounts)?f.accounts.filter(u=>u&&typeof u.token=="string"&&u.id===Se(u.cloudUrl,u.token)):[]}catch{return[]}},r=(f,u)=>{let y=Se(f.cloudUrl||"",f.token||"");if(!y||!f.token||!f.cloudUrl)return;let v=s(),x=v.find(M=>M.id===y),E=Gt(f.token),U={...x,id:y,cloudUrl:f.cloudUrl.replace(/\/+$/,""),token:f.token,username:u?.username||x?.username||E?.username,nickname:u?.nickname||x?.nickname};JSON.stringify(x)!==JSON.stringify(U)&&t(e(),{version:1,accounts:[...v.filter(M=>M.id!==y),U]})},i=()=>{let f=n.readCreds();r(f);let u=Se(f.cloudUrl,f.token);return s().map(({token:y,...v})=>({...v,active:v.id===u}))},o=f=>{let u=s().find(y=>y.id===f);if(!u)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:u.cloudUrl,token:u.token}},a=f=>{let u=Se(f.cloudUrl||"",f.token||"");u&&t(e(),{version:1,accounts:s().filter(y=>y.id!==u)})},c=null;return{rememberForsionAccount:r,forsionAccounts:i,savedForsionAccount:o,forgetForsionAccount:a,cancelForsionLogin:()=>{c?.abort(),c=null},forsionDeviceLogin:async(f,u,y)=>{if(c)throw new Error("A sign-in is already in progress.");if(!f)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let v=new AbortController;c=v;let x=()=>{if(v.signal.aborted||c!==v)throw new Error("Sign-in cancelled.")};try{let E=f.replace(/\/+$/,""),U;try{U=await fetch(`${E}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([v.signal,AbortSignal.timeout(15e3)])}).then(J=>J.json())}catch(J){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${E}:${J?.message||J}`)}if(x(),!U?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let M=U.verification_uri_complete||`${U.verification_uri}?code=${U.user_code}`,Y=new URL(`${E}/auth`);Y.searchParams.set("logout","1"),Y.searchParams.set("app","forsion-desktop"),Y.searchParams.set("redirect",M);let B=Y.toString();u?.({url:B,userCode:String(U.user_code||"")}),n.openExternal(B);let q=Date.now()+(U.expires_in||600)*1e3,Q=(U.interval||2)*1e3;for(;Date.now()<q;){await Es(Q,v.signal),x();let J=null;try{J=await fetch(`${E}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:U.device_code}),signal:AbortSignal.any([v.signal,AbortSignal.timeout(15e3)])})}catch{x();continue}if(x(),J.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let ne=await J.json().catch(()=>({status:"pending"}));if(x(),ne.status==="approved"&&ne.token){let ue={cloudUrl:E,token:ne.token};return await y(ue,x),x(),{token:ne.token,cloudUrl:E}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{c===v&&(c=null)}},readAccounts:s}}var Qn=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],Yt=n=>Qn.every(e=>typeof n[e]=="function");function Jt(n){let e={ok:!1,error:"untrusted"},t={loggedIn:!1,error:"untrusted"},s=Kn(n),r=0,i=()=>{let a=n.readCreds();return vt(a.cloudUrl,a.token)},o=null;n.handle("auth:status",async a=>{if(!n.isTrustedSender(a))return t;let c=r,h=i(),{base:d}=await n.getCloud(),f=n.readCreds().token,u=f?await nt(d,f):null,y=await n.accountBackendState(),{base:v}=await n.getCloud(),x=n.readCreds(),E=vt(v,x.token)!==vt(d,f),U=vt(d,f);!E&&u?.status==="ok"&&u.user&&(o={key:U,user:u.user},s.rememberForsionAccount({...x,cloudUrl:d},u.user));let M=E?void 0:u?.status==="ok"?u.user:u?.status==="offline"&&o?.key===U?o.user:void 0;if(E)return{loggedIn:!!x.token,tokenValid:null,cloudUrl:v,accountId:Se(v,x.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:x.token?"tangu-login":null,backendState:y};if(u?.status==="expired"){await n.accountTransition(async()=>{if(c!==r||i()!==h)return;let B=()=>{if(c!==r||i()!==h)throw Gn};try{await n.accountClear(B,()=>{n.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++r,s.cancelForsionLogin(),s.forgetForsionAccount(n.readCreds()),o=null})}catch(q){if(q!==Gn)throw q}});let Y=n.readCreds();return{loggedIn:!!Y.token,tokenValid:null,cloudUrl:Y.cloudUrl||d,accountId:Se(Y.cloudUrl||d,Y.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:Y.token?"tangu-login":null,backendState:y}}return{loggedIn:!!f,tokenValid:u&&u.status==="ok"?!0:null,cloudUrl:d,accountId:Se(d,f),username:M?.username||null,nickname:M?.nickname||null,avatar:M?.avatar||null,membershipTier:M?.membershipTier||null,tokenSource:f?"tangu-login":null,backendState:y}}),n.handle("auth:accounts",a=>n.isTrustedSender(a)?s.forsionAccounts():[]),n.handle("auth:switchAccount",async(a,c)=>{if(!n.isTrustedSender(a))return e;if(typeof c!="string")throw new Error("Invalid account.");let h=++r;return s.cancelForsionLogin(),n.accountTransition(async()=>{let d=s.savedForsionAccount(c);return await n.accountCommit(d,()=>{if(h!==r)throw new Error("Account switch cancelled.")},()=>{s.rememberForsionAccount(d),o=null}),{ok:!0,cloudUrl:d.cloudUrl||""}})}),n.handle("auth:forsionLogin",async(a,c)=>{if(!n.isTrustedSender(a))return e;let h=++r;s.cancelForsionLogin();let{base:d}=await n.getCloud();if(h!==r)throw new Error("Sign-in cancelled.");let f=(c||d||"").trim();return{ok:!0,cloudUrl:(await s.forsionDeviceLogin(f,y=>n.broadcast("auth:device",y),(y,v)=>n.accountTransition(()=>n.accountCommit(y,()=>{if(v(),h!==r)throw new Error("Sign-in cancelled.")},()=>{s.rememberForsionAccount(y),o=null})))).cloudUrl}}),n.handle("auth:logout",async a=>n.isTrustedSender(a)?(++r,s.cancelForsionLogin(),n.accountTransition(async()=>{let{base:c}=await n.getCloud(),h=n.readCreds();return await n.accountClear(void 0,()=>{s.forgetForsionAccount(h),o=null,c&&h.token&&fetch(`${c}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${h.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),n.onExternalCredsChange(({previous:a,current:c})=>{++r,s.cancelForsionLogin(),a.token&&!c.token&&s.forgetForsionAccount(a),o=null,s.rememberForsionAccount(c)}),n.setTokenRefresher(async a=>{let c=r,h=i(),d=n.readCreds().token;if(!Jn(d))return;let{base:f}=await n.getCloud(),u=await Xn(f,d,a,`desktop/${n.appVersion()}`);if(!u){n.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}c!==r||i()!==h||(s.rememberForsionAccount({cloudUrl:f,token:u}),n.writeCreds({cloudUrl:f,token:u}),n.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),n.log("[forsion-extend] account core registered")}var Gn=Symbol("stale-auth-intent");import{promises as Ke}from"node:fs";import je from"node:path";import{createHash as _s}from"node:crypto";var Xt=null;function Zn(n){Xt=n}function fe(){if(!Xt)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return Xt}var he=()=>fe().accountId();function rt(n=he()){return n?_s("sha256").update(n).digest("hex"):"signed-out"}var ve=(n=he())=>fe().readConfig(n),Pe=(n,e=he())=>fe().writeConfig(n,e),We=(n,e=he())=>fe().updateConfig(n,e),$e=(n=he())=>fe().cloudVaultDir(n),Et=n=>fe().isManagedCloudVault(n);import{createHash as Ti}from"node:crypto";import{promises as te,existsSync as Ar}from"node:fs";import se from"node:path";import{EventEmitter as Qs}from"node:events";import{stat as Zs}from"node:fs";import{readdir as ei,stat as ti}from"node:fs/promises";import*as z from"node:path";import{lstat as er,readdir as ks,realpath as Cs,stat as xs}from"node:fs/promises";import{join as Ts,resolve as Rs,sep as tr}from"node:path";import{Readable as Is}from"node:stream";var me={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},qe={root:".",fileFilter:n=>!0,directoryFilter:n=>!0,type:me.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(qe);var ir="READDIRP_RECURSIVE_ERROR",Ps=new Set(["ENOENT","EPERM","EACCES","ELOOP",ir]),nr=[me.DIR_TYPE,me.EVERYTHING_TYPE,me.FILE_DIR_TYPE,me.FILE_TYPE],As=new Set([me.DIR_TYPE,me.EVERYTHING_TYPE,me.FILE_DIR_TYPE]),$s=new Set([me.EVERYTHING_TYPE,me.FILE_DIR_TYPE,me.FILE_TYPE]),Ds=n=>Ps.has(n.code),Ms=process.platform==="win32",rr=n=>!0,sr=n=>{if(n===void 0)return rr;if(typeof n=="function")return n;if(typeof n=="string"){let e=n.trim();return t=>t.basename===e}if(Array.isArray(n)){let e=n.map(t=>t.trim());return t=>e.some(s=>t.basename===s)}return rr},Kt=class extends Is{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??qe.highWaterMark});let t={...qe,...e},s=t.root??qe.root,r=t.type??qe.type;this._fileFilter=sr(t.fileFilter),this._directoryFilter=sr(t.directoryFilter);let i=t.lstat?er:xs;Ms?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:qe.depth,this._wantsDir=As.has(r),this._wantsFile=$s.has(r),this._wantsEverything=r===me.EVERYTHING_TYPE,this._root=Rs(s),this._relStart=this._root.endsWith(tr)?this._root.length:this._root.length+1,this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let o={path:this._root,depth:1};o.pending=this._exploreDir(this._root,1),this.parents=[o],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,s=t&&t.files;if(s&&s.length>0){let{path:r,depth:i}=t,o=s.splice(0,e).map(c=>this._formatEntry(c,r)),a=this._isDirent?o:await Promise.all(o);for(let c of a){if(!c)continue;if(this.destroyed)return;let h=this._getEntryType(c);typeof h!="string"&&(h=await h),h==="directory"&&this._directoryFilter(c)?(i<=this._maxDepth&&this.parents.push({path:c.fullPath,depth:i+1}),this._wantsDir&&(this.push(c),e--)):(h==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}let i=r.pending??this._exploreDir(r.path,r.depth),o=this.parents[this.parents.length-1];if(o&&!o.pending&&(o.pending=this._exploreDir(o.path,o.depth)),this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let s;try{s=await ks(e,this._rdOptions)}catch(r){this._onError(r)}return{files:s,depth:t,path:e}}_formatEntry(e,t){let s=this._isDirent?e.name:e,r=Ts(t,s),i={path:r.slice(this._relStart),fullPath:r,basename:s};return this._isDirent?(i.dirent=e,i):this._stat(r).then(o=>(i.stats=o,i),o=>{this._onError(o)})}_onError(e){Ds(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let t=e[this._statsProp];return t.isFile()?"file":t.isDirectory()?"directory":t.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let t=e.fullPath;try{let s=await Cs(t),r=await er(s);if(r.isFile())return"file";if(r.isDirectory()){let i=s.length;if(t.startsWith(s)&&t[i]===tr){let o=new Error(`Circular symlink detected: "${t}" points to "${s}"`);return o.code=ir,this._onError(o),""}return"directory"}}catch(s){this._onError(s)}return""}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function or(n,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=me.FILE_DIR_TYPE),n){if(typeof n!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!nr.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${nr.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let s={...e,root:n};return t&&(s.type=t),new Kt(s)}import{watch as Ns,unwatchFile as ar,watchFile as Us}from"node:fs";import{realpath as Qt,lstat as Fs,open as Os,stat as cr}from"node:fs/promises";import{type as js}from"node:os";import*as K from"node:path";var Ls="data",tn="end",ur="close",Tt=()=>{};var Rt=process.platform,nn=Rt==="win32",Hs=Rt==="darwin",zs=Rt==="linux",Ws=Rt==="freebsd",dr=js()==="OS400",ee={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ee=ee,qs="watch",Bs={lstat:Fs,stat:cr},Oe="listeners",_t="errHandlers",Be="rawEmitters",Vs=[Oe,_t,Be],Gs=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"]),Ys=n=>Gs.has(K.extname(n).slice(1).toLowerCase()),en=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},st=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},Js=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},it=(n,e,t)=>{let s=n[e];s instanceof Set?s.delete(t):s===t&&delete n[e]},fr=n=>n instanceof Set?n.size===0:!n,kt=new Map;function lr(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&Ct(K.resolve(n,a),Oe,K.join(n,a))};try{return Ns(n,{persistent:e.persistent},i)}catch(o){s(o);return}}var Ct=(n,e,t,s,r)=>{let i=kt.get(n);i&&en(i[e],o=>{o(t,s,r)})},Xs=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=kt.get(e),c;if(!t.persistent)return c=lr(n,t,r,i,o),c?c.close.bind(c):void 0;if(a)st(a,Oe,r),st(a,_t,i),st(a,Be,o);else{if(c=lr(n,t,Ct.bind(null,e,Oe),i,Ct.bind(null,e,Be)),!c)return;c.on(Ee.ERROR,async h=>{let d=Ct.bind(null,e,_t);if(a&&(a.watcherUnusable=!0),nn&&h.code==="EPERM")try{await(await Os(n,"r")).close(),d(h)}catch{}else d(h)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:c},kt.set(e,a)}return()=>{it(a,Oe,r),it(a,_t,i),it(a,Be,o),fr(a.listeners)&&(a.watcher.close(),kt.delete(e),Vs.forEach(Js(a)),a.watcher=void 0,Object.freeze(a))}},Zt=new Map,Ks=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=Zt.get(e),a=o&&o.options;return a&&(a.persistent<t.persistent||a.interval>t.interval)&&(ar(e),o=void 0),o?(st(o,Oe,r),st(o,Be,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:Us(e,t,(c,h)=>{en(o.rawEmitters,f=>{f(Ee.CHANGE,e,{curr:c,prev:h})});let d=c.mtimeMs;(c.size!==h.size||d>h.mtimeMs||d===0)&&en(o.listeners,f=>f(n,c))})},Zt.set(e,o)),()=>{it(o,Oe,r),it(o,Be,i),fr(o.listeners)&&(Zt.delete(e),ar(e),o.options=o.watcher=void 0,Object.freeze(o))}},xt=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=K.dirname(e),i=K.basename(e);this.fsw._getWatchedDir(r).add(i);let a=K.resolve(e),c={persistent:s.persistent};t||(t=Tt);let h;if(s.usePolling){let d=s.interval!==s.binaryInterval;c.interval=d&&Ys(i)?s.binaryInterval:s.interval,h=Ks(e,a,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else h=Xs(e,a,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return h}_handleFile(e,t,s){if(this.fsw.closed)return;let r=K.dirname(e),i=K.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let c=async(d,f)=>{if(this.fsw._throttle(qs,e,5)){if(!f||f.mtimeMs===0)try{let u=await cr(e);if(this.fsw.closed)return;let y=u.atimeMs,v=u.mtimeMs;if((!y||y<=v||v!==a.mtimeMs)&&this.fsw._emit(Ee.CHANGE,e,u),(Hs||zs||Ws)&&a.ino!==u.ino){this.fsw._closeFile(d),a=u;let x=this._watchWithNodeFs(e,c);x&&this.fsw._addPathCloser(d,x)}else a=u}catch{this.fsw._remove(r,i)}else if(o.has(i)){let u=f.atimeMs,y=f.mtimeMs;(!u||u<=y||y!==a.mtimeMs)&&this.fsw._emit(Ee.CHANGE,e,f),a=f}}},h=this._watchWithNodeFs(e,c);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Ee.ADD,e,0))return;this.fsw._emit(Ee.ADD,e,t)}return h}async _handleSymlink(e,t,s,r){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Qt(s)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(r)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Ee.CHANGE,s,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Ee.ADD,s,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,s,r,i,o,a){e=K.join(e,"");let c=r?`${e}:${r}`:e;if(a=this.fsw._throttle("readdir",c,1e3),!a)return;let h=this.fsw._getWatchedDir(s.path),d=new Set,f=this.fsw._readdirp(e,{fileFilter:u=>s.filterPath(u),directoryFilter:u=>s.filterDir(u)});if(f)return f.on(Ls,async u=>{if(this.fsw.closed){f=void 0;return}let y=u.path,v=K.join(e,y);if(d.add(y),!(u.stats.isSymbolicLink()&&await this._handleSymlink(u,e,v,y))){if(this.fsw.closed){f=void 0;return}(y===r||!r&&!h.has(y))&&(this.fsw._incrReadyCount(),v=K.join(i,K.relative(i,v)),this._addToNodeFs(v,t,s,o+1))}}).on(Ee.ERROR,this._boundHandleError),new Promise((u,y)=>{if(!f)return y();f.once(tn,()=>{if(this.fsw.closed){f=void 0;return}let v=a?a.clear():!1;u(void 0),h.getChildren().filter(x=>x!==e&&!d.has(x)).forEach(x=>{this.fsw._remove(e,x)}),f=void 0,v&&this._handleRead(e,!1,s,r,i,o,a)})})}async _handleDir(e,t,s,r,i,o,a){let c=this.fsw._getWatchedDir(K.dirname(e)),h=c.has(K.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!h&&this.fsw._emit(Ee.ADD_DIR,e,t),c.add(K.basename(e)),this.fsw._getWatchedDir(e);let d,f,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,s,o,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(y,v)=>{v&&v.mtimeMs===0||this._handleRead(y,!1,o,i,e,r,d)})}return f}async _addToNodeFs(e,t,s,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e);s&&(a.filterPath=c=>s.filterPath(c),a.filterDir=c=>s.filterDir(c));try{let c=await Bs[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return o(),!1;let h=this.fsw.options.followSymlinks,d;if(c.isDirectory()){let f=K.resolve(e),u=h?await Qt(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,c,t,r,i,a,u),this.fsw.closed))return;f!==u&&u!==void 0&&this.fsw._symlinkPaths.set(f,u)}else if(c.isSymbolicLink()){let f=h?await Qt(e):e;if(this.fsw.closed)return;let u=K.dirname(a.watchPath);if(this.fsw._getWatchedDir(u).add(a.watchPath),this.fsw._emit(Ee.ADD,a.watchPath,c),d=await this._handleDir(u,c,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(K.resolve(e),f)}else d=this._handleFile(a.watchPath,c,t);return o(),d&&this.fsw._addPathCloser(e,d),!1}catch(c){if(this.fsw._handleError(c))return o(),e}}};var rn="/",ni="//",yr=".",ri="..",si="string",ii=/\\/g,wr=/\/\//g,oi=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,ai=/^\.[/\\]/;function It(n){return Array.isArray(n)?n:[n]}var sn=n=>typeof n=="object"&&n!==null&&!(n instanceof RegExp);function li(n){return typeof n=="function"?n:typeof n=="string"?e=>n===e:n instanceof RegExp?e=>n.test(e):typeof n=="object"&&n!==null?e=>{if(n.path===e)return!0;if(n.recursive){let t=z.relative(n.path,e);return t?!t.startsWith("..")&&!z.isAbsolute(t):!1}return!1}:()=>!1}function ci(n){if(typeof n!="string")throw new Error("string expected");n=z.normalize(n),n=n.replace(/\\/g,"/");let e=!1;return n.startsWith("//")&&(e=!0),n=n.replace(wr,"/"),e&&(n="/"+n),n}function hr(n,e,t){let s=ci(e);for(let r=0;r<n.length;r++){let i=n[r];if(i(s,t))return!0}return!1}function ui(n,e){if(n==null)throw new TypeError("anymatch: specify first argument");let s=It(n).map(r=>li(r));return e==null?(r,i)=>hr(s,r,i):hr(s,e)}var pr=n=>{let e=It(n).flat();if(!e.every(t=>typeof t===si))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(br)},mr=n=>{let e=n.replace(ii,rn),t=!1;return e.startsWith(ni)&&(t=!0),e=e.replace(wr,rn),t&&(e=rn+e),e},br=n=>mr(z.normalize(mr(n))),gr=(n="")=>e=>typeof e=="string"?br(z.isAbsolute(e)?e:z.join(n,e)):e,di=(n,e)=>z.isAbsolute(n)?n:z.join(e,n),fi=Object.freeze(new Set),on=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==yr&&e!==ri&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let s=this.path;try{await ei(s)}catch{this._removeWatcher&&this._removeWatcher(z.dirname(s),z.basename(s))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Tt,this.items=fi,Object.freeze(this)}},hi="stat",pi="lstat",an=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,s){this.fsw=s;let r=e;this.path=e=e.replace(ai,""),this.watchPath=r,this.fullWatchPath=z.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=t,this.statMethod=t?hi:pi}entryPath(e){return z.join(this.watchPath,z.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let s=this.entryPath(e);return this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Pt=class extends Qs{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 t=e.awaitWriteFinish,s={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?It(e.ignored):It([]),awaitWriteFinish:t===!0?s:typeof t=="object"?{...s,...t}:!1};dr&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?r.usePolling=!1:c==="true"||c==="1"?r.usePolling=!0:r.usePolling=!!c}let o=process.env.CHOKIDAR_INTERVAL;o&&(r.interval=Number.parseInt(o,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Tt,this._readyEmitted=!0,process.nextTick(()=>this.emit(ee.READY)))},this._emitRaw=(...c)=>this.emit(ee.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new xt(this),Object.freeze(r)}_addIgnoredPath(e){if(sn(e)){for(let t of this._ignoredPaths)if(sn(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)sn(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,s){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=pr(e);return r&&(i=i.map(o=>di(o,r))),i.forEach(o=>{this._removeIgnoredPath(o)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async o=>{let a=await this._nodeFsHandler._addToNodeFs(o,!s,void 0,0,t);return a&&this._emitReady(),a})).then(o=>{this.closed||o.forEach(a=>{a&&this.add(z.dirname(a),z.basename(t||a))})}),this}unwatch(e){if(this.closed)return this;let t=pr(e),{cwd:s}=this.options;return t.forEach(r=>{!z.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=z.join(s,r)),r=z.resolve(r)),this._closePath(r),this._addIgnoredPath(r),this._watched.has(r)&&this._addIgnoredPath({path:r,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(t=>t.forEach(s=>{let r=s();r instanceof Promise&&e.push(r)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.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((t,s)=>{let i=(this.options.cwd?z.relative(this.options.cwd,s):s)||yr;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==ee.ERROR&&this.emit(ee.ALL,e,...t)}async _emit(e,t,s){if(this.closed)return;let r=this.options;nn&&(t=z.normalize(t)),r.cwd&&(t=z.relative(r.cwd,t));let i=[t];s!=null&&i.push(s);let o=r.awaitWriteFinish,a;if(o&&(a=this._pendingWrites.get(t)))return a.lastChange=new Date,this;if(r.atomic){if(e===ee.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,h)=>{this.emit(...c),this.emit(ee.ALL,...c),this._pendingUnlinks.delete(h)})},typeof r.atomic=="number"?r.atomic:100),this;e===ee.ADD&&this._pendingUnlinks.has(t)&&(e=ee.CHANGE,this._pendingUnlinks.delete(t))}if(o&&(e===ee.ADD||e===ee.CHANGE)&&this._readyEmitted){let c=(h,d)=>{h?(e=ee.ERROR,i[0]=h,this.emitWithAll(e,i)):d&&(i.length>1?i[1]=d:i.push(d),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,o.stabilityThreshold,e,c),this}if(e===ee.CHANGE&&!this._throttle(ee.CHANGE,t,50))return this;if(r.alwaysStat&&s===void 0&&(e===ee.ADD||e===ee.ADD_DIR||e===ee.CHANGE)){let c=r.cwd?z.join(r.cwd,t):t,h;try{h=await ti(c)}catch{}if(!h||this.closed)return;i.push(h)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(ee.ERROR,e),e||this.closed}_throttle(e,t,s){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw new Error("invalid throttle");let i=r.get(t);if(i)return i.count++,!1;let o,a=()=>{let h=r.get(t),d=h?h.count:0;return r.delete(t),clearTimeout(o),h&&clearTimeout(h.timeoutObject),d};o=setTimeout(a,s);let c={timeoutObject:o,clear:a,count:0};return r.set(t,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,s,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let o=i.pollInterval,a,c=e;this.options.cwd&&!z.isAbsolute(e)&&(c=z.join(this.options.cwd,e));let h=new Date,d=this._pendingWrites;function f(u){Zs(c,(y,v)=>{if(y||!d.has(e)){y&&y.code!=="ENOENT"&&r(y);return}let x=Number(new Date);u&&v.size!==u.size&&(d.get(e).lastChange=x);let E=d.get(e);x-E.lastChange>=t?(d.delete(e),r(void 0,v)):a=setTimeout(f,o,v)})}d.has(e)||(d.set(e,{lastChange:h,cancelWait:()=>(d.delete(e),clearTimeout(a),s)}),a=setTimeout(f,o))}_isIgnored(e,t){if(this.options.atomic&&oi.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,i=(this.options.ignored||[]).map(gr(s)),a=[...[...this._ignoredPaths].map(gr(s)),...i];this._userIgnored=ui(a,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new an(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=z.resolve(e);return this._watched.has(t)||this._watched.set(t,new on(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,s){let r=z.join(e,t),i=z.resolve(r);if(s=s??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!s&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(u=>this._remove(r,u));let c=this._getWatchedDir(e),h=c.has(t);c.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=z.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===ee.ADD)return;this._watched.delete(r),this._watched.delete(i);let f=s?ee.UNLINK_DIR:ee.UNLINK;h&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=z.dirname(e);this._getWatchedDir(t).remove(z.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(s=>s()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let s=this._closers.get(e);s||(s=[],this._closers.set(e,s)),s.push(t)}_readdirp(e,t){if(this.closed)return;let s={type:ee.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},r=or(e,s);return this._streams.add(r),r.once(ur,()=>{r=void 0}),r.once(tn,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function mi(n,e={}){let t=new Pt(e);return t.add(n),t}var Sr={watch:mi,FSWatcher:Pt};function gi(n,e){let t=Object.create(null);for(let i=0;i<e.length;i++){let o=e[i];t[o]?t[o].push(i):t[o]=[i]}let r=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let i=0;i<n.length;i++){let o=n[i],a=t[o]||[],c=0,h=r[0];for(let d of a){let f;for(f=c;f<r.length&&!(r[f].buffer2index<d&&(f===r.length-1||r[f+1].buffer2index>d));f++);if(f<r.length){let u={buffer1index:i,buffer2index:d,chain:r[f]};if(c===r.length?r.push(h):r[c]=h,c=f+1,h=u,c===r.length)break}}r[c]=h}return r[r.length-1]}function vr(n,e){let t=gi(n,e),s=[],r=n.length,i=e.length;for(let o=t;o!==null;o=o.chain){let a=r-o.buffer1index-1,c=i-o.buffer2index-1;r=o.buffer1index,i=o.buffer2index,(a||c)&&s.push({buffer1:[r+1,a],buffer1Content:n.slice(r+1,r+1+a),buffer2:[i+1,c],buffer2Content:e.slice(i+1,i+1+c)})}return s.reverse(),s}function yi(n,e,t){let s=[];function r(c,h){s.push({ab:h,oStart:c.buffer1[0],oLength:c.buffer1[1],abStart:c.buffer2[0],abLength:c.buffer2[1]})}vr(e,n).forEach(c=>r(c,"a")),vr(e,t).forEach(c=>r(c,"b")),s.sort((c,h)=>c.oStart-h.oStart);let i=[],o=0;function a(c){c>o&&(i.push({stable:!0,buffer:"o",bufferStart:o,bufferLength:c-o,bufferContent:e.slice(o,c)}),o=c)}for(;s.length;){let c=s.shift(),h=c.oStart,d=c.oStart+c.oLength,f=[c];for(a(h);s.length;){let u=s[0],y=u.oStart;if(y>d)break;d=Math.max(d,y+u.oLength),f.push(s.shift())}if(f.length===1){if(c.abLength>0){let u=c.ab==="a"?n:t;i.push({stable:!0,buffer:c.ab,bufferStart:c.abStart,bufferLength:c.abLength,bufferContent:u.slice(c.abStart,c.abStart+c.abLength)})}}else{let u={a:[n.length,-1,e.length,-1],b:[t.length,-1,e.length,-1]};for(;f.length;){c=f.shift();let M=c.oStart,Y=M+c.oLength,B=c.abStart,q=B+c.abLength,Q=u[c.ab];Q[0]=Math.min(B,Q[0]),Q[1]=Math.max(q,Q[1]),Q[2]=Math.min(M,Q[2]),Q[3]=Math.max(Y,Q[3])}let y=u.a[0]+(h-u.a[2]),v=u.a[1]+(d-u.a[3]),x=u.b[0]+(h-u.b[2]),E=u.b[1]+(d-u.b[3]),U={stable:!1,aStart:y,aLength:v-y,aContent:n.slice(y,v),oStart:h,oLength:d-h,oContent:e.slice(h,d),bStart:x,bLength:E-x,bContent:t.slice(x,E)};i.push(U)}o=d}return a(e.length),i}function Er(n,e,t,s){s=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},s),typeof n=="string"&&(n=n.split(s.stringSeparator)),typeof e=="string"&&(e=e.split(s.stringSeparator)),typeof t=="string"&&(t=t.split(s.stringSeparator));let i=[],o=yi(n,e,t),a=[];function c(){a.length&&i.push({ok:a}),a=[]}function h(d,f){if(d.length!==f.length)return!1;for(let u=0;u<d.length;u++)if(d[u]!==f[u])return!1;return!0}return o.forEach(d=>{d.stable?a.push(...d.bufferContent):s.excludeFalseConflicts&&h(d.aContent,d.bContent)?a.push(...d.aContent):(c(),i.push({conflict:{a:d.aContent,aIndex:d.aStart,o:d.oContent,oIndex:d.oStart,b:d.bContent,bIndex:d.bStart}}))}),c(),i}function At(n,e){let t=n.lastIndexOf("/"),s=t<0?"":n.slice(0,t+1),r=t<0?n:n.slice(t+1),i=r.lastIndexOf("."),o=i>0?r.slice(0,i):r,a=i>0?r.slice(i):"",c=d=>String(d).padStart(2,"0"),h=`${e.getFullYear()}-${c(e.getMonth()+1)}-${c(e.getDate())} ${c(e.getHours())}${c(e.getMinutes())}`;return`${s}${o} (conflict ${h})${a}`}function wi(n,e){if(e<2)return n;let t=n.lastIndexOf("."),s=t>n.lastIndexOf("/")&&t>n.lastIndexOf(")"),r=s?n.slice(0,t):n,i=s?n.slice(t):"";return`${r}-${e}${i}`}function bi(n){let e=3735928559,t=1103547991;for(let r=0;r<n.length;r++){let i=n.charCodeAt(r);e=Math.imul(e^i,2654435761),t=Math.imul(t^i,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let s=4294967296*(2097151&t)+(e>>>0);return`${n.length.toString(36)}-${s.toString(36)}`}function $t(n,e,t){if(n===null&&e===null&&t===null)return{kind:"none"};if(t===null)return n===null?e?{kind:"dropShadow"}:{kind:"none"}:e?n===e.hash?{kind:"deleteLocal"}:{kind:"pushCreate"}:{kind:"pushCreate"};if(n===null)return e?t.seq===e.seq?{kind:"pushDelete"}:{kind:"pull"}:{kind:"pull"};if(!e)return n===t.hash?{kind:"adopt"}:{kind:"conflict"};let s=n!==e.hash,r=t.seq!==e.seq;return!s&&!r?{kind:"none"}:s?r?n===t.hash?{kind:"adopt"}:t.hash===e.hash?{kind:"push",baseSeq:t.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function _r(n,e,t){let s=Er(n.split(`
194
194
  `),e.split(`
195
- `),n.split(`
196
- `),{excludeFalseConflicts:!0}),r=[];for(let o of s){if(o.conflict)return null;o.ok&&r.push(...o.ok)}return r.join(`
197
- `)}function sn(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var fo=/[\u0000-\u001f\u007f]/;function Ve(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||fo.test(e))return null;let n=e.split("/");for(let s of n)if(!s||s==="."||s==="..")return null;return n.join("/")}function on(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Ve(n):n.startsWith(`${e}/`)?Ve(n.slice(e.length+1)):null}function wr(t,e){return e===""?t:`${e}/${t}`}function it(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function Ce(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var $e=t=>t==="page"||t==="db";import{gzip as ho}from"node:zlib";import{promisify as mo}from"node:util";var po=mo(ho),go=1024,le=class extends Error{status;body;constructor(e,n,s){super(`cloud http ${e} on ${s}`),this.status=e,this.body=n}},br=t=>12e4+Math.ceil(t/256);function Sr(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=async(r,o,a)=>{let c={Authorization:`Bearer ${t.token}`,...a?.headers};r!=="GET"&&(c["X-Amadeus-Client"]=t.clientId);let l;a?.json!==void 0?(c["Content-Type"]="application/json",l=JSON.stringify(a.json),l.length>=go&&(c["Content-Encoding"]="gzip",l=await po(l))):a?.form&&(l=a.form);let m=await fetch(o,{method:r,headers:c,body:l,signal:AbortSignal.timeout(a?.timeoutMs??3e4)});if(!m.ok){let d=null;try{d=await m.json()}catch{}throw new le(m.status,d,o)}return m.json()},s=r=>new URLSearchParams(r).toString();return{clientId:t.clientId,async listVaults(){return((await n("GET",`${e}/vaults`)).vaults??[]).map(o=>({id:String(o.id),name:String(o.name),lastChangeSeq:Number(o.lastChangeSeq??0)}))},async tree(r){let o=await n("GET",`${e}/vaults/${r}/tree`);if(!Array.isArray(o.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:o.folders??[],seq:Number(o.seq??0),maxFileBytes:Number.isInteger(o.maxFileBytes)&&o.maxFileBytes>0?o.maxFileBytes:void 0,entries:o.entries.map(a=>({path:String(a.path),kind:a.kind,seq:Number(a.seq??0),hash:a.hash??null,size:Number(a.size??0)}))}},async getFile(r,o){let a=await n("GET",`${e}/vaults/${r}/file?${s({path:o})}`);return{content:String(a.content??""),seq:Number(a.seq??0),hash:a.hash??null}},putFile(r,o,a,c,l=!1){return n("PUT",`${e}/vaults/${r}/file`,{json:{path:o,content:a,baseSeq:c,...l?{force:!0}:{}}})},async deleteFile(r,o,a,c){let l={path:o};a!==void 0&&(l.baseSeq=String(a)),await n("DELETE",`${e}/vaults/${r}/file?${s(l)}`,c?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(r,o,a){return n("POST",`${e}/vaults/${r}/move`,{json:{from:o,to:a}})},renameFolder(r,o,a){return n("POST",`${e}/vaults/${r}/folders/rename`,{json:{path:o,newName:a}})},moveFolder(r,o,a){return n("POST",`${e}/vaults/${r}/folders/move`,{json:{path:o,dest:a}})},async deleteFolder(r,o){await n("DELETE",`${e}/vaults/${r}/folders?${s({path:o})}`)},putBinary(r,o,a,c){let l=new FormData;return l.set("path",o),c?.ifAbsent&&l.set("ifAbsent","true"),c?.baseSeq!==void 0&&l.set("baseSeq",String(c.baseSeq)),l.set("file",new Blob([new Uint8Array(a)]),o.split("/").pop()||"file"),n("POST",`${e}/vaults/${r}/binary`,{form:l,timeoutMs:br(a.length)})},async listVersions(r,o){return((await n("GET",`${e}/vaults/${r}/file/versions?${s({path:o})}`)).versions??[]).map(c=>({id:String(c.id),seq:Number(c.seq??0)}))},async getVersion(r,o){let a=await n("GET",`${e}/vaults/${r}/file/versions/${o}`);return String(a.content??"")},async getAsset(r,o){let a=new AbortController,c=setTimeout(()=>a.abort(),12e4);try{let l=await fetch(`${e}/vaults/${r}/asset?${s({ref:o})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:a.signal});if(!l.ok)throw new le(l.status,null,"asset:"+o);return clearTimeout(c),c=setTimeout(()=>a.abort(),br(Number(l.headers.get("content-length"))||0)),Buffer.from(await l.arrayBuffer())}finally{clearTimeout(c)}},async changes(r,o){let a=await n("GET",`${e}/vaults/${r}/changes?${s({since:String(o)})}`);return{changes:a.changes??[],seq:Number(a.seq??0)}}}}function Er(t,e){let n=!1,s=0,r=null,o=null,a=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,c=m=>{if(n)return;e.onDown(m);let d=Math.min(3e4,1e3*2**s)*(.7+Math.random()*.6);s++,o=setTimeout(()=>void l(),d)},l=async()=>{if(n)return;r=new AbortController;let m;try{m=await fetch(a(),{headers:{Authorization:`Bearer ${t.token}`,Accept:"text/event-stream"},signal:r.signal})}catch(v){c(v);return}if(!m.ok||!m.body){c(new Error(`sse http ${m.status}`));return}s=0,e.onOpen();let d=m.body.getReader(),f=new TextDecoder,u="",y="",_=[],T=()=>{if(!_.length&&!y)return;let v=_.join(`
198
- `),O=y||"message";y="",_=[];let N=null;try{N=v?JSON.parse(v):null}catch{return}O==="hello"?e.onHello(Number(N?.seq??0)):O==="change"?e.onChange(N):O==="reset"?e.onReset():O==="presence"?e.onPresence?.(N):O==="presence-roster"&&e.onPresenceRoster?.(N)};try{for(;;){let{done:v,value:O}=await d.read();if(v)break;for(u+=f.decode(O,{stream:!0});;){let N=u.indexOf(`
199
- `);if(N<0)break;let Y=u.slice(0,N).replace(/\r$/,"");if(u=u.slice(N+1),Y==="")T();else{if(Y.startsWith(":"))continue;Y.startsWith("event:")?y=Y.slice(6).trim():Y.startsWith("data:")&&_.push(Y.slice(5).replace(/^ /,""))}}}}catch(v){n||c(v);return}c(new Error("sse stream ended"))};return l(),{stop:()=>{n=!0,o&&clearTimeout(o),r?.abort()}}}import{constants as yo,promises as Ye}from"node:fs";import wo from"node:path";var Ge=t=>wo.join(fe().userDataDir(),fe().isDevMode()?`${t}.dev.json`:`${t}.json`);async function an(t){try{let e=JSON.parse(await Ye.readFile(Ge(t),"utf8"));return!e||typeof e.vaultRoot!="string"||typeof e.vaultId!="string"?null:(e.files=e.files??{},e.cursor=Number(e.cursor??0),e.lastSyncAt=e.lastSyncAt??null,e)}catch{return null}}function vr(t){let e=null,n=null,s=Promise.resolve(),r=null,o=()=>{if(!e)return s;let a=e,c=JSON.stringify(e);return e=null,s=s.then(async()=>{try{let l=Ge(t),m=`${l}.tmp-${process.pid}-${Date.now()}-0`;await Ye.writeFile(m,c,"utf8"),await Ye.rename(m,l),r=null}catch(l){e??=a,r=l}}),s};return{save(a){e=a,!n&&(n=setTimeout(()=>{n=null,o()},500))},async flush(a=!1){if(n&&(clearTimeout(n),n=null),await o(),a&&r)throw r}}}async function _r(t){try{await Ye.unlink(Ge(t))}catch{}}async function kr(t,e){try{await Ye.copyFile(Ge(t),Ge(e),yo.COPYFILE_EXCL)}catch(n){let s=n?.code;if(s==="EEXIST"||s==="ENOENT")return!1;throw n}return await Ye.unlink(Ge(t)).catch(()=>{}),!0}var So=5*1024*1024,Eo=5*1024*1024,vo=3e4,_o=2500,ko=3e3,Co=5,xo=256*1024,To=5,xr=1024*1024,Tr=200,Ro=6e4,Io=50,Ao=".sync-trash",Je=t=>bo("sha256").update(t).digest("hex");function at(t,e={localRoot:De(),shadowName:`amadeus-sync-${rt()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let n=i=>{let h=on(i,"");if(!h)return null;for(let p of e.excludePrefixes??[])if(h===p.replace(/\/$/,"")||h.startsWith(p))return null;if(e.ignoreNames?.length&&h.split("/").some(p=>e.ignoreNames.includes(p)))return null;let g=e.serverDir?`${e.serverDir}/${h}`:h;return e.inScope&&!e.inScope(g,Ce(g))?null:g},s=i=>{let h;if(e.serverDir){if(!i.startsWith(`${e.serverDir}/`))return null;h=i.slice(e.serverDir.length+1)}else{for(let g of e.excludePrefixes??[])if(i.startsWith(g))return null;h=i}return h.split("/").some(g=>it(g)||!!e.ignoreNames?.includes(g))?null:h},r=(i,h)=>!e.inScope||e.inScope(i,h),o=e.accountId??he(),a=!1,c=0,l=Promise.resolve(),m=new Set,d="disabled",f=null,u=null,y=null,_=null,T=null,v=null,O=0,N=new Map,Y=null,G=vr(e.shadowName),W=new Map,Q=!1,J=!1,ne=[],ue=()=>{u&&(u.pending=W.size?Object.fromEntries(W):void 0,G.save(u))},ut=()=>{J=!1,ne.length=0},Qe=()=>{if(J)return!0;let i=Date.now();for(;ne.length&&i-ne[0]>Ro;)ne.shift();return ne.length>=Io?(J=!0,!0):!1},xe=[],Ne=new Set,Ze=!1,E=null,C=null,w=null,b=()=>{!a||w||(w=setTimeout(()=>{w=null,t.onStatus(Oe())},200))},A=(i,h)=>{d=i,h!==void 0&&(f=h),b()},S=(i,h=!1)=>{if(a){if(i.key){if(Ne.has(i.key))return;Ne.add(i.key)}h?xe.unshift(i):xe.push(i),V()}},x=new Map,D=i=>{if(!a)return;let h=(u?.files[i]?.size??0)>xo,g=(e.pushQuietMs??ko)*(h?To:1),p=Date.now(),k=x.get(i);k&&clearTimeout(k.timer);let I=k?.since??p,$=Math.max(0,Math.min(g,I+g*Co-p)),R=setTimeout(()=>{x.delete(i),S({key:i,run:()=>ae(i,!0)})},$);x.set(i,{timer:R,since:I}),b()},U=()=>{for(let{timer:i}of x.values())clearTimeout(i);x.clear()},F=i=>!(i instanceof le)||i.status>=500||i.status===0,L=i=>i instanceof le&&(i.status===401||i.status===403),V=async()=>{if(!Ze){Ze=!0;try{for(;xe.length;){(d==="idle"||d==="starting")&&A("syncing");let i=xe.shift();i.key&&Ne.delete(i.key);try{await i.run()}catch(h){if(!a)return;if(L(h)){xe.length=0,Ne.clear(),gt(),A("auth-required","login-expired");return}if(F(h)){S(i,!0),gt(),A("offline",h?.message||"network error"),B();return}let g=i.key??"(op)";N.set(g,h?.body?.code||`http ${h?.status}`),b()}}a&&d==="syncing"&&(u&&(u.lastSyncAt=Date.now(),G.save(u)),A("idle",null))}finally{Ze=!1;for(let i of m)i();m.clear()}}},B=()=>{!a||E||(E=setTimeout(()=>{E=null,tt()},vo))},q=i=>{if(!v||!u)throw new Error("engine not bound");let h=s(i);if(h===null)throw new Error("path outside binding: "+i);let g=se.resolve(v,wr(h,u.folder)),p=se.relative(v,g);if(p.startsWith("..")||se.isAbsolute(p))throw new Error("path escapes vault: "+i);return g},Z=i=>({size:i,mtimeMs:-1}),K=async i=>{try{let h=await te.stat(i);return h.isFile()?{size:h.size,mtimeMs:Math.floor(h.mtimeMs)}:null}catch{return null}},we=0,Fe=async(i,h,g=()=>!0)=>{await te.mkdir(se.dirname(i),{recursive:!0});let p=`${i}.tmp-${process.pid}-${Date.now()}-${we++}`;await te.writeFile(p,h);let k=await K(p)??Z(Buffer.byteLength(h));return g()?(await te.rename(p,i),k):(await te.rm(p,{force:!0}),null)},Ue=async i=>{let h;try{h=await te.readdir(i,{withFileTypes:!0})}catch{return}for(let g of h)g.isDirectory()&&await Ue(se.join(i,g.name));try{await te.rmdir(i)}catch{}},oe=async i=>{let h=q(i),g=await K(h),p;try{p=await te.readFile(h)}catch{return null}return{hash:$e(Ce(i))?Je(p.toString("utf8")):Je(p),size:g?.size??p.length,mtimeMs:g?.mtimeMs??-1,buf:p}},_e=async(i,h,g,p)=>{u&&(u.files[i]={seq:h,hash:g,size:p.size,mtimeMs:p.mtimeMs},G.save(u))},ye=i=>{u&&i in u.files&&(delete u.files[i],G.save(u))},Te=async(i,h)=>{if(!y||!u||be(i))return;let g=re,p=Ce(i),k,I,$;if($e(p)){let j;try{j=await y.getFile(u.vaultId,i)}catch(H){if(H instanceof le&&H.status===404){await $t(i);return}throw H}k=j.content,I=j.seq,$=j.hash??Je(j.content)}else{let j;try{j=await y.getAsset(u.vaultId,i)}catch(H){if(H instanceof le&&H.status===404){N.set(i,"ASSET_404"),b();return}throw H}k=j,I=h??0,$=Je(j)}let R=await oe(i);if(g!==re||be(i))return;if(R&&R.hash===$){await _e(i,I,$,R);return}let M=u.files[i];if(R&&M&&$===M.hash&&R.hash!==M.hash){await _e(i,I,$,Z(M.size)),S({key:i,run:()=>ae(i)});return}if(R&&(!M||R.hash!==M.hash)){if(M&&p==="page"&&typeof k=="string"&&await Lr(i,M,R,k,I,$,()=>g===re&&!be(i))||g!==re||be(i))return;await jr(i)}let P=await Fe(q(i),k,()=>g===re&&!be(i));P&&await _e(i,I,$,P)},Lr=async(i,h,g,p,k,I,$)=>{try{if(!y||!u||g.buf.length>xr||p.length>xr)return!1;let M=(await y.listVersions(u.vaultId,i)).find(H=>H.seq===h.seq);if(!M)return!1;let P=await y.getVersion(u.vaultId,M.id);if(Je(P)!==h.hash)return!1;let j=yr(g.buf.toString("utf8"),P,p);return j===null?!1:(await Fe(q(i),j,$)&&(await _e(i,k,I,Z(Buffer.byteLength(j))),S({key:i,run:()=>ae(i)})),!0)}catch{return!1}},jr=async i=>{let h=Ve(It(i,new Date));if(!h)return;let g=h.lastIndexOf("."),p=g>h.lastIndexOf("/"),k=p?h.slice(0,g):h,I=p?h.slice(g):"",$=h;for(let R=2;Cr(q($));R++)$=`${k}-${R}${I}`;try{await te.rename(q(i),q($))}catch(R){if(R?.code==="ENOENT")return;throw R}O++,S({key:$,run:()=>ae($)}),b()},yn=async i=>{if(!v)return;let h=q(i),g=s(i)??i,p=se.join(v,Ao,new Date().toISOString().slice(0,10),...g.split("/")),k=Cr(p)?`${p}.${Date.now()}`:p;try{await te.mkdir(se.dirname(k),{recursive:!0}),await te.rename(h,k)}catch(I){if(I?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${h}: ${I?.message??String(I)}`)}},$t=async i=>{if(!u)return;let h=await oe(i);if(be(i))return;let g=u.files[i]??null,p=At(h?.hash??null,g,null);if(p.kind==="deleteLocal"){if(!Q&&Qe()){W.set(i,"local"),ue(),b();return}ne.push(Date.now()),await yn(i),ye(i)}else p.kind==="pushCreate"?(ye(i),S({key:i,run:()=>ae(i)})):ye(i)},wn=(i,h)=>{if(u){for(let g of Object.keys(u.files))if(g===i||g.startsWith(`${i}/`)){let p=h+g.slice(i.length);u.files[p]=u.files[g],delete u.files[g]}G.save(u)}},bn=async i=>{if(!y||!u||i.seq<=u.cursor||!await ht())return;if(i.origin.client&&y.clientId===i.origin.client){u.cursor=i.seq,G.save(u);return}let h=i.type==="structure"?"folder":i.type,g=k=>s(k)!==null&&r(k,h);if(!g(i.path)&&!(i.newPath&&g(i.newPath))){u.cursor=i.seq,G.save(u);return}let p=i.path;switch(i.op){case"write":await Te(p,i.fileSeq);break;case"delete":await $t(p);break;case"move":{let k=i.newPath;if(!k)break;let I=u.files[p];if(await oe(p)&&I)try{await te.mkdir(se.dirname(q(k)),{recursive:!0}),await te.rename(q(p),q(k)),u.files[k]={...I,seq:i.fileSeq??I.seq},delete u.files[p],G.save(u)}catch{await Te(k,i.fileSeq)}else ye(p),await Te(k,i.fileSeq);break}case"mkdir":await te.mkdir(q(p),{recursive:!0});break;case"rename-folder":case"move-folder":{let k=i.newPath;if(!k)break;try{await te.mkdir(se.dirname(q(k)),{recursive:!0}),await te.rename(q(p),q(k))}catch{}wn(p,k);break}case"delete-folder":{let k=`${p}/`;for(let I of Object.keys(u.files))(I===p||I.startsWith(k))&&await $t(I);await Ue(q(p));break}}if(u.cursor=i.seq,G.save(u),i.op==="move"||i.op==="rename-folder"||i.op==="move-folder"||i.op==="delete"||i.op==="delete-folder")try{await t.onRemoteApplied?.(i)}catch{}},Ur=async(i,h,g)=>{let p=Number(h?.seq??0),k=h?.content??null;if(k!==null&&Je(k)===g.hash){await _e(i,p,g.hash,g);return}if(k===null&&p===0){if(!u?.files[i]){N.set(i,h?.code||"EXISTS"),b();return}ye(i),S({key:i,run:()=>ae(i)});return}await Te(i,p)},dt=async(i,h)=>{if(!y||!u)return;let g=await oe(i);if(!g){S({key:i,run:()=>ae(i)});return}if(g.size>So){N.set(i,"TOO_LARGE"),b();return}let p=g.buf.toString("utf8");try{let k=await y.putFile(u.vaultId,i,p,h);N.delete(i),await _e(i,k.seq,k.hash??g.hash,g)}catch(k){if(k instanceof le&&k.status===409){await Ur(i,k.body,g);return}throw k}},ft=async(i,h)=>{if(!y||!u)return;let g=await oe(i);if(!g){S({key:i,run:()=>ae(i)});return}if(g.size>(Y??Eo)){N.set(i,"TOO_LARGE"),b();return}try{let p=await y.putBinary(u.vaultId,i,g.buf,{baseSeq:h});N.delete(i),await _e(i,p.seq,g.hash,g)}catch(p){if(p instanceof le&&p.status===409){let k=Number(p.body?.seq??0),I=p.body?.hash??null;if(I!==null&&I===g.hash){await _e(i,k,g.hash,g);return}if(k===0){if(!u.files[i]){N.set(i,p.body?.code||"EXISTS"),b();return}ye(i),S({key:i,run:()=>ae(i)});return}await Te(i,k);return}throw p}},Sn=async i=>{if(!y||!u||be(i))return;let h=re,g=u.files[i];if(g){if($e(Ce(i)))try{let p=await y.getFile(u.vaultId,i);if(p.seq!==g.seq){await Te(i,p.seq);return}}catch(p){if(p instanceof le&&p.status===404){ye(i);return}throw p}if(!(h!==re||be(i))){try{await y.deleteFile(u.vaultId,i,g.seq,{confirmed:Q})}catch(p){if(p instanceof le&&p.status===409){await Te(i,Number(p.body?.seq??0)||null);return}if(p instanceof le&&p.status===429&&p.body?.code==="MASS_DELETE_BLOCKED"){W.set(i,"remote"),J=!0,ue(),b();return}throw p}ye(i)}}},ht=async()=>v?await te.stat(v).then(h=>h.isDirectory()).catch(()=>!1)||!e.requireRootExists&&!Object.keys(u?.files??{}).length?!0:(A("error",`vault-missing: ${v}`),B(),!1):!1,re=0,mt=new Set,pt=new Map,me=i=>JSON.stringify([i.from,i.to]),Pe=(i,h)=>i===h||i.startsWith(`${h}/`),be=i=>[...u?.moves??[],...mt].some(h=>Pe(i,h.from)||Pe(i,h.to)),Re=()=>!!(u?.moves?.length||mt.size),Mt=async i=>{if(!y||!u)return;let{from:h,to:g,kind:p}=i;if(s(h)===null||s(g)===null)throw new Error("Invalid queued cloud move");i.hashes??=Object.fromEntries(Object.entries(u.files).filter(([R])=>Pe(R,h)).map(([R,M])=>[R.slice(h.length),M.hash])),G.save(u),await G.flush(!0);let k,I=!1;try{if(p==="folder"){let R=se.posix.dirname(h)==="."?"":se.posix.dirname(h),M=se.posix.dirname(g)==="."?"":se.posix.dirname(g);R===M?await y.renameFolder(u.vaultId,h,se.posix.basename(g)):await y.moveFolder(u.vaultId,h,M)}else{let R=await y.move(u.vaultId,h,g);k=Number(R.seq)}}catch(R){if(!(R instanceof le)||R.status!==404)throw R;let M=await y.tree(u.vaultId);if(M.entries.some(H=>Pe(H.path,h))||M.folders.some(H=>Pe(H,h)))throw R;let j=M.entries.find(H=>H.path===g);if(k=j?.seq,I=!j&&!M.entries.some(H=>Pe(H.path,g))&&!M.folders.some(H=>Pe(H,g)),!I){let H=Object.entries(i.hashes);if(!(H.length>0&&H.every(([ke,He])=>M.entries.some(ze=>ze.path===g+ke&&ze.hash===He))))throw new le(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(I)for(let R of Object.keys(u.files))Pe(R,h)&&delete u.files[R];else wn(h,g),k!==void 0&&u.files[g]&&(u.files[g].seq=k);u.moves=(u.moves??[]).filter(R=>me(R)!==me(i)),G.save(u);try{await G.flush(!0)}catch(R){throw u.moves.unshift(i),G.save(u),R}let $=pt.get(me(i));pt.delete(me(i)),$?.(),be(g)||(p==="folder"?await Nt():await ae(g))},ae=async(i,h=!1)=>{if(!u||be(i))return;if(!r(i,Ce(i))){ye(i);return}if(!await ht())return;let g=await oe(i);if(be(i))return;let p=u.files[i]??null,k=At(g?.hash??null,p,p?{seq:p.seq,hash:p.hash}:null);switch(k.kind){case"push":$e(Ce(i))?await dt(i,k.baseSeq):await ft(i,k.baseSeq);break;case"pushCreate":$e(Ce(i))?await dt(i,0):await ft(i,0);break;case"pushDelete":if(h){wt();break}if(!Q&&(W.has(i)||Qe())){W.set(i,"remote"),ue(),b();break}ne.push(Date.now()),await Sn(i);break;case"dropShadow":ye(i);break;default:g&&p&&g.hash===p.hash&&g.mtimeMs>=0&&(p.size!==g.size||p.mtimeMs!==g.mtimeMs)&&await _e(i,p.seq,p.hash,g);break}},En=async()=>{let i=new Map;if(!v||!u)return i;let h=v,g=null,p=async k=>{if(g)return;let I;try{I=await te.readdir(k,{withFileTypes:!0})}catch($){g=`${k}: ${$?.message??String($)}`;return}for(let $ of I){if(it($.name)||$.isDirectory()&&e.ignoreNames?.includes($.name))continue;let R=se.join(k,$.name);if($.isDirectory())await p(R);else if($.isFile()){let M=se.relative(h,R).split(se.sep).join("/"),P=n(M);if(!P)continue;try{let j=await te.stat(R);if(!j.isFile())continue;i.set(P,{size:j.size,mtimeMs:Math.floor(j.mtimeMs)})}catch(j){if(j?.code==="ENOENT")continue;g=`${R}: ${j?.message??String(j)}`;return}}}};return await p(h),g?(A("error",`scan-failed: ${g}`),B(),null):i},Nt=async()=>{let i=re;if(Re()||i!==re||!u||!await ht())return;let h=await En();if(!h||Re()||i!==re)return;let g=!1;for(let[I,$]of[...W])($==="remote"&&h.has(I)||$==="local"&&!h.has(I))&&(W.delete(I),g=!0);W.size||ut();for(let[I,$]of h){let R=u.files[I];R&&R.size===$.size&&R.mtimeMs===$.mtimeMs||S({key:I,run:()=>ae(I)})}let p=Object.keys(u.files),k=p.filter(I=>!h.has(I));if(k.length&&!Q&&(J||sn(k.length,p.length,Tr))){J=!0;for(let I of k)W.set(I,"remote");ue(),b();return}g&&(ue(),b());for(let I of k)W.has(I)||S({key:I,run:()=>ae(I)})},et=async()=>{let i=re;if(Re()||i!==re||!y||!u||!v||!await ht())return;let h=await y.tree(u.vaultId);if(h.maxFileBytes!==void 0&&h.maxFileBytes!==Y&&(Y=h.maxFileBytes,b()),Re()||i!==re)return;let g=new Map;for(let P of h.entries)s(P.path)===null||!r(P.path,P.kind)||g.set(P.path,P);let p=await En();if(!p||Re()||i!==re)return;let k=new Set([...g.keys(),...p.keys(),...Object.keys(u.files)]),I=Object.keys(u.files).length,$=[];for(let P of k){if(Re()||i!==re)return;let j=u.files[P]??null,H=g.get(P)??null,ce=p.get(P)??null,ke=null,He=Z(ce?.size??0);if(ce)if(j&&j.size===ce.size&&j.mtimeMs===ce.mtimeMs)ke=j.hash,He=ce;else{let ze=await oe(P);ze&&(ke=ze.hash,He=ze)}$.push({sp:P,d:At(ke,j,H?{seq:H.seq,hash:H.hash}:null),rSeq:H?.seq??null,localHash:ke,localStat:He})}if(Re()||i!==re)return;let R=$.filter(P=>P.d.kind==="deleteLocal"||P.d.kind==="pushDelete").length,M=!Q&&(J||sn(R,I,Tr));M&&R&&(J=!0),W.clear();for(let{sp:P,d:j,rSeq:H,localHash:ce,localStat:ke}of $){if(Re()||i!==re)return;if(M&&(j.kind==="deleteLocal"||j.kind==="pushDelete")){W.set(P,j.kind==="deleteLocal"?"local":"remote");continue}if((j.kind==="deleteLocal"||j.kind==="pushDelete")&&((await oe(P))?.hash??null)!==ce){S({key:P,run:()=>ae(P)});continue}if(Re()||i!==re)return;switch(j.kind){case"adopt":await _e(P,H,ce,ke);break;case"pull":await Te(P,H);break;case"push":$e(Ce(P))?await dt(P,j.baseSeq):await ft(P,j.baseSeq);break;case"pushCreate":$e(Ce(P))?await dt(P,0):await ft(P,0);break;case"pushDelete":await Sn(P);break;case"deleteLocal":await yn(P),ye(P);break;case"conflict":await Te(P,H);break;case"dropShadow":ye(P);break;case"none":break}}Q&&(Q=!1,ne.length=0),W.size||ut(),ue(),M&&b();for(let P of h.folders)if(!(s(P)===null||!r(P,"folder")))try{await te.mkdir(q(P),{recursive:!0})}catch{}u.cursor=h.seq,u.lastSyncAt=Date.now(),G.save(u)},Hr=async()=>{if(!y||!u)return;let i=u.cursor,h=await y.changes(u.vaultId,i);if(h.changes.length===0&&h.seq>i||h.changes.length>0&&h.changes[0].seq!==i+1){await et();return}for(let p of h.changes)await bn(p)},Ie=null,vn=[],_n=()=>{Ie&&vn.push(Ie.close()),Ie=null},zr=()=>{if(!a||Ie||!v)return;Ie=mr.watch(v,{ignoreInitial:!0,depth:12,ignored:h=>{let g=se.basename(h);return it(g)||!!e.ignoreNames?.includes(g)}});let i=h=>{if(!v)return;let g=se.relative(v,h);if(!g||g.startsWith(".."))return;let p=n(g);p&&D(p)};Ie.on("change",i),Ie.on("add",i),Ie.on("unlink",()=>wt()),Ie.on("unlinkDir",()=>wt())},gt=()=>{_?.stop(),_=null},qr=()=>{if(!a||!y||!u||_)return;let i=T;i&&(_=Er({baseUrl:i.cloudUrl,vaultId:u.vaultId,token:i.token},{getSince:()=>u?.cursor??0,onHello:h=>{u&&h>u.cursor&&S({run:Hr})},onChange:h=>{S({run:()=>bn(h)})},onReset:()=>{S({run:et})},onOpen:()=>{(d==="offline"||d==="starting")&&A("idle",null),S({run:Nt})},onDown:()=>{(d==="idle"||d==="syncing")&&A("offline")},onPresence:h=>t.onPresence?.(u?.vaultId??"",h),onPresenceRoster:h=>t.onPresenceRoster?.(u?.vaultId??"",h)}))},Wr=async()=>{let i=await Ee(o);if(i.cloudSync?.deviceId)return i.cloudSync.deviceId;let h=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Ae({cloudSync:{...i.cloudSync??{},deviceId:h}},o),h},Br=async i=>{gt(),_n(),xe.length=0,Ne.clear(),W.clear(),Q=!1,J=!1,ne.length=0;let h=await Ee(o);if(i!==c)return;let g=h.cloudSync;if(g?.enabled===!1){v=null,y=null,A("disabled",null);return}if(!o||o!==he()){A("auth-required","not-logged-in");return}if(v=e.localRoot,e.requireRootExists){let $=await te.stat(v).then(R=>R.isDirectory()).catch(()=>!1);if(i!==c)return;if(!$){A("error",`vault-missing: ${v}`),B();return}}if(i!==c)return;let p=t.loadCreds();if(!p.cloudUrl||!p.token){y=null,A("auth-required","not-logged-in");return}A("starting",null);let k=g?.deviceId??await Wr();if(i!==c)return;let I=e.clientIdSuffix?`${k}#${e.clientIdSuffix}`:k;T={cloudUrl:p.cloudUrl,token:p.token},y=Sr({baseUrl:p.cloudUrl,token:p.token,clientId:I});try{let $=e.vaultId==="first"?g?.vaultId:e.vaultId;if(!$){let M=await y.listVaults();if(i!==c)return;if(!M.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");$=M[0].id,await Ae({cloudSync:{...g??{},vaultId:$}},o)}if(i!==c)return;let R=await an(e.shadowName);if(i!==c||(u=R&&R.vaultRoot===v&&R.vaultId===$&&R.folder===""?R:{vaultRoot:v,folder:"",vaultId:$,cursor:0,lastSyncAt:null,files:{}},i!==c))return;for(let[M,P]of Object.entries(u.pending??{}))W.set(M,P);if(W.size&&(J=!0),!e.requireRootExists){let M=await te.stat(v).then(P=>P.isDirectory()).catch(()=>!1);if(i!==c)return;if(!M){if(Object.keys(u.files).length){A("error",`mirror-missing: ${v}`),B();return}if(await te.mkdir(v,{recursive:!0}),i!==c)return}}zr();for(let M of u.moves??[])S({key:`move:${me(M)}`,run:()=>Mt(M)});S({run:et}),S({run:async()=>{qr()}})}catch($){if(i!==c)return;L($)?A("auth-required","login-expired"):(A("offline",$?.message||String($)),B())}},kn=()=>{a=!1,gt(),_n(),xe.length=0,Ne.clear(),U();for(let i of[E,C,w])i&&clearTimeout(i);E=C=w=null},Cn=async()=>{Ze&&await new Promise(i=>m.add(i)),await Promise.all(vn.splice(0)),await G.flush(),u=null,y=null,T=null,v=null,O=0,N.clear(),Y=null,W.clear(),Q=!1,J=!1,ne.length=0,d="disabled",f=null},Vr=()=>{xn()},yt=null,tt=()=>{yt?.(),yt=fe().onBeforeQuit(Vr);let i=++c;kn();let h=l.catch(()=>{}).then(async()=>{await Cn(),i===c&&(a=!0,await Br(i))});return l=h,h},xn=()=>{yt?.(),yt=null,++c,kn();let i=l.catch(()=>{}).then(Cn);return l=i,i},Oe=()=>({enabled:d!=="disabled",state:d==="idle"&&x.size?"syncing":d,lastSyncAt:u?.lastSyncAt??null,pending:xe.length+x.size,conflicts:O,skipped:[...N].map(([i,h])=>({path:i,reason:h})),error:f,pendingDeletions:W.size,maxFileBytes:Y});return{getStatus:Oe,start(){tt()},notifyLocal(i,h,g){if(!u||d==="disabled"||d==="auth-required")return;let p=n(i),k=g?n(g):null;if(h==="write"&&p){it(p.split("/").pop()||"")||D(p);return}if(h==="remove"){if(!p)return;let I=`${p}/`,$=!1;for(let R of Object.keys(u.files))(R===p||R.startsWith(I))&&($=!0,S({key:R,run:()=>ae(R)}));!$&&p&&S({key:p,run:()=>ae(p)})}},holdLocalMove(i,h){let g=k=>e.serverDir?`${e.serverDir}/${k.replace(/\\/g,"/").normalize("NFC")}`:k.replace(/\\/g,"/").normalize("NFC"),p={from:g(i),to:g(h)};return++re,mt.add(p),()=>{mt.delete(p)}},async notifyLocalMove(i,h,g,p){let k=n(i),I=n(h),$=u??await an(e.shadowName),R=on(i,""),M=R&&(e.serverDir?`${e.serverDir}/${R}`:R);if(!k&&I&&M&&$&&Object.keys($.files).some(P=>P===M||P.startsWith(`${M}/`))&&(k=M),!k&&!I){g?.();return}if(k&&I){let P=u??$;if(!P){g?.();return}let j=p??(Object.keys(P.files).some(ce=>ce.startsWith(`${k}/`))?"folder":"file"),H={from:k,to:I,kind:j};P.moves??=[],P.moves.some(ce=>me(ce)===me(H))||(P.moves.push(H),++re),g&&pt.set(me(H),g),G.save(P);try{await G.flush(!0)}catch(ce){throw P.moves=P.moves.filter(ke=>me(ke)!==me(H)),pt.delete(me(H)),G.save(P),ce}u===P&&a&&d!=="disabled"&&d!=="auth-required"&&S({key:`move:${me(H)}`,run:()=>Mt(H)});return}k&&this.notifyLocal(i,"remove"),I&&(S({key:I,run:()=>ae(I)}),wt()),g?.()},async setEnabled(i){let h=await Ee(o);return await Ae({cloudSync:{...h.cloudSync??{},enabled:i}},o),await tt(),Oe()},async restart(){return await tt(),Oe()},async syncNow(){if(N.clear(),d==="disabled"||d==="auth-required"||!y)await tt();else{for(let i of u?.moves??[])S({key:`move:${me(i)}`,run:()=>Mt(i)});S({run:et})}return Oe()},confirmMassDeletions(){return W.size&&(Q=!0,J=!1,W.clear(),ne.length=0,ue(),S({run:et})),Oe()},stop:xn};function wt(){a&&(C&&clearTimeout(C),C=setTimeout(()=>{C=null,S({run:Nt})},_o))}}import{createHash as Po}from"node:crypto";function Rr(t){let e=t.replace(/\.md$/i,""),n=t.lastIndexOf("/"),s=n<0?"":t.slice(0,n);return{root:t,fdPrefix:`${e}.fd/`,assetPrefix:s?`${s}/.amadeus/`:".amadeus/"}}function Ir(t,e,n){return!!(e===t.root||e.startsWith(t.fdPrefix)||`${e}/`===t.fdPrefix||n==="binary"&&e.startsWith(t.assetPrefix)||n==="folder"&&(`${e}/`===t.assetPrefix||e.startsWith(t.assetPrefix)))}var Do=t=>Po("sha256").update(t).digest("hex").slice(0,8),$o=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Pt="\u4E0E\u6211\u5171\u4EAB";function ln(t){let e=Do(`${t.vaultId}:${t.path}`),n=Rr(t.path),s=t.path.includes("/")?t.path.slice(0,t.path.lastIndexOf("/")):"";return{key:e,vaultId:t.vaultId,rootPath:t.path,title:t.title,localRelDir:`${Pt}/${$o(t.title)}-${e}`,serverDir:s,inScope:(r,o)=>Ir(n,r,o)}}function cn(){let t=fe().readCreds(),e=Se(t.cloudUrl??"",t.token??""),n=new AbortController,s=()=>{let f=fe().readCreds();if(n.signal.aborted||!e||Se(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},r=()=>{let f=s();if(!f.cloudUrl||!f.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return f.cloudUrl.replace(/\/+$/,"")},o=async(f,u,y)=>{let _=s();if(!_.cloudUrl||!_.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let T=await fetch(`${_.cloudUrl.replace(/\/+$/,"")}/api/amadeus${u}`,{method:f,headers:{Authorization:`Bearer ${_.token}`,...y!==void 0?{"Content-Type":"application/json"}:{}},body:y!==void 0?JSON.stringify(y):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!T.ok){let O=null;try{O=await T.json()}catch{}throw Object.assign(new Error(O?.detail||`http ${T.status}`),{status:T.status,code:O?.code})}let v=await T.json();return s(),v},a=null,c=async()=>(s(),a||(a=(await o("GET","/vaults")).vaults[0]?.id??"default",a)),l=()=>{try{let f=(s().token??"").split(".")[1],u=JSON.parse(Buffer.from(f.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());return typeof u.userId=="string"?u.userId:null}catch{return null}},m=async()=>(await o("GET","/shared-with-me")).items.map(u=>{let y=ln(u),_=u.path.split("/").pop()??u.path;return{...u,localPath:`${y.localRelDir}/${_}`}}),d=null;return{stop:()=>n.abort(),call:o,ensureOwnVault:c,myUserId:l,sharedWithMe:m,linkBase:async()=>{if(s(),d)return d;try{d=((await o("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||r()}catch{d=r()}return d},async heartbeat(f,u){let y=(f??"").replace(/\\/g,"/"),_,T=null,v=u.find(O=>y.startsWith(`${O.localRelDir}/`));v?(_=v.vaultId,T=v.serverDir?`${v.serverDir}/${y.slice(v.localRelDir.length+1)}`:y.slice(v.localRelDir.length+1)):(_=await c(),T=y||null),await o("POST",`/vaults/${encodeURIComponent(_)}/presence`,{page:T})}}}import{promises as Ar}from"node:fs";import Mo from"node:path";var un=".forsion-vault.md",dn=t=>`${t}/${un}`;var ge=t=>t.replace(/\\/g,"/").normalize("NFC");function fn(t){let e=ge(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function Ke(t,e,n){let s=ge(n);if(!s)return!1;if(t.some(r=>ge(r.path)===s))return!0;for(let r of e??[]){let o=ge(r);if(!o)continue;let a=`${o.replace(/\.md$/i,"")}.fd`;if(s===o||s.startsWith(`${o}/`)||s===a||s.startsWith(`${a}/`))return!1}return t.some(r=>{let o=fn(r);return!!o&&s.startsWith(o)})}function hn(t,e,n){let s=ge(t),r=ge(e);return s===r?ge(n):s.startsWith(`${r}/`)?ge(n)+s.slice(r.length):null}function lt(t,e,n){let s=!1,r=t.map(o=>{let a=hn(o,e,n);return a===null?o:(s=!0,a)});return{changed:s,next:r}}async function Pr(t){let e=await Ar.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[];for(let s of e)!s.isDirectory()||s.name.startsWith(".")||await Ar.access(Mo.join(t,s.name,un)).then(()=>!0,()=>!1)&&n.push(s.name);return n.sort()}var ie={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",status:"amadeus:sync:status",switchSide:"amadeus:sync:switch-side",collabCall:"amadeus:collab:call",presence:"amadeus:collab:presence",entryGet:"amadeus:entry-sync:get",entryEnable:"amadeus:entry-sync:enable",entryDisable:"amadeus:entry-sync:disable",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};import{createHash as No}from"node:crypto";var Dt=t=>No("sha256").update(t).digest("hex").slice(0,8);function Dr(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Me(t,e=[]){let n=[],s=[];for(let r of t){let o=ge(r.path);if(!o)continue;s.push(o);let a=fn(r);a&&n.push(a)}return{entries:t,exclude:e,prefixes:n,paths:s}}function $r(t,e){let n=Dr(ge(e));if(!n)return!1;if(Ke(t.entries,t.exclude,n))return!0;let s=`${n}/`;for(let r of t.paths)if(r.startsWith(s))return!0;for(let r of t.prefixes)if(r.startsWith(s))return!0;return!1}function ct(t,e,n){let s=!1,r=t.map(o=>{let a=hn(o.path,e,n);return a===null?o:(s=!0,{...o,path:a})});return{changed:s,next:r}}function Mr(t,e,n,s){if(e==="delete"||e==="delete-folder"){let r=ge(n),o=t.filter(a=>{let c=ge(a.path);return!(c===r||e==="delete-folder"&&c.startsWith(`${r}/`))});return{changed:o.length!==t.length,next:o}}return s?ct(t,n,s):{changed:!1,next:t}}function mn(t,e){let n=Ve(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Pt?`\u300C${Pt}\u300D\u662F\u4FDD\u7559\u540D\u79F0`:e.includes(n)?"\u8BE5\u540D\u79F0\u5DF2\u88AB\u5176\u4ED6\u667A\u5E93\u7684\u4E91\u540C\u6B65\u5360\u7528":null}var Nr=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],pn=t=>Nr.every(e=>typeof t[e]=="function"),Fo=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function gn(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(ie.get,()=>e?e.get():Fo()),t.handle(ie.setEnabled,(s,r)=>n().setEnabled(r)),t.handle(ie.syncNow,()=>n().syncNow()),t.handle(ie.confirmDeletions,()=>n().confirmDeletions()),t.handle(ie.entryGet,()=>n().entryGet()),t.handle(ie.otherSideDbs,()=>n().otherSideDbs()),t.handle(ie.entryEnable,(s,r)=>n().entryEnable(r)),t.handle(ie.entryDisable,(s,r)=>n().entryDisable(r)),t.handle(ie.entryClosure,(s,r,o)=>n().entryClosure(r,o)),t.handle(ie.collabCall,(s,r,o)=>n().collabCall(r,o)),t.handle(ie.switchSide,(s,r)=>n().switchSide(s.sender.id,r)),t.setAmadeusSyncFactory(s=>{Gn(s);let r=Fr(s);return e=r.handlers,r.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function Fr(t){let e=t.notifyAll,n=()=>t.vaultRoot(),s=0,r=!1,o=cn(),a=new Map,c=()=>{let E=Date.now();for(let[C,w]of a)E-w.at>7e4&&a.delete(C);e(ie.presence,[...a.values()])},l={loadCreds:()=>t.readCreds(),onStatus:E=>e(ie.status,{...E,pendingDeletions:ne(),side:_()?"cloud":"local"}),onPresence:(E,C)=>{let w=C;w?.userId&&(a.set(w.userId,{userId:w.userId,username:String(w.username??"user"),page:w.page??null,at:Number(w.at)||Date.now()}),c())},onPresenceRoster:(E,C)=>{if(Array.isArray(C)){for(let w of C){let b=w;b?.userId&&a.set(b.userId,{userId:b.userId,username:String(b.username??"user"),page:b.page??null,at:Number(b.at)||Date.now()})}c()}}},m=()=>{let E=s;return{...l,onStatus:C=>{E===s&&l.onStatus(C)},onPresence:(C,w)=>{E===s&&l.onPresence(C,w)},onPresenceRoster:(C,w)=>{E===s&&l.onPresenceRoster(C,w)}}},d=at(m()),f=new Map,u=[],y=async()=>{if(!r||!he())return;let E=s,C=o,w;try{w=await C.sharedWithMe()}catch{return}if(E!==s||!r)return;let b=w.map(S=>ln(S));u=b;let A=new Set(b.map(S=>S.key));for(let[S,x]of f)if(!A.has(S)){if(await x.engine.stop(),E!==s)return;f.delete(S)}for(let S of b){if(f.has(S.key))continue;let x=at(m(),{localRoot:je.join(De(),...S.localRelDir.split("/")),shadowName:`amadeus-sync-${rt()}-share-${S.key}`,vaultId:S.vaultId,serverDir:S.serverDir,inScope:S.inScope});f.set(S.key,{engine:x,plan:S}),x.start()}},_=()=>n()===De(),T=(E,C=E.base)=>{E.base=C;let w=[C,...E.pendingMoves];E.scope.current=Me(w.flatMap(b=>b.entries),w.flatMap(b=>b.exclude))},v=new Map,O=new Set,N=()=>{e(ie.entryChange)},Y=async(E,C)=>{let w=v.get(E);if(!w)return;let b=x=>x&&x.startsWith(`${w.cloudName}/`)?x.slice(w.cloudName.length+1):null,A=b(C.path);if(!A)return;let S=!1;await qe(x=>{if(v.get(E)!==w)return!1;let D=(x.entrySync??[]).find(B=>B.vaultRoot===E);if(!D)return!1;let U=C.op,F=b(C.newPath),L=Mr(D.entries,U,A,F),V=F?lt(D.exclude??[],A,F):{changed:!1,next:D.exclude??[]};if(!L.changed&&!V.changed)return!1;S=!0,D.entries=L.next,V.changed&&(D.exclude=V.next),T(w,Me(D.entries,D.exclude??[]))}),S&&v.get(E)===w&&N()},G=E=>{let C=s;return{...m(),onStatus:w=>{C===s&&e(ie.status,{...w,pendingDeletions:ne(),side:"local",binding:E})},onRemoteApplied:async w=>{C===s&&await Y(E,w)}}},W=async()=>{let E=he();if(!r||!E)return;let C=s,w=o,b=rt(E);await t.adoptLegacyCloudState(E,kr);let A=await Ee(E),S=A.entrySync??[];if(C!==s||!r||E!==he())return;let x=new Map(S.map(D=>[D.vaultRoot,D]));for(let[D,U]of v){let F=x.get(D);if(!(F&&F.cloudName===U.cloudName)&&(await U.engine.stop(),C!==s||(v.delete(D),F&&await _r(`amadeus-sync-${b}-entry-${Dt(D)}`),C!==s)))return}for(let D of S){let U=v.get(D.vaultRoot);if(U){T(U,Me(D.entries,D.exclude??[]));continue}let F={current:Me(D.entries,D.exclude??[])},L=D.cloudName,V=at(G(D.vaultRoot),{accountId:E,localRoot:D.vaultRoot,shadowName:`amadeus-sync-${b}-entry-${Dt(D.vaultRoot)}`,vaultId:"first",serverDir:L,clientIdSuffix:`entry-${Dt(D.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:B=>B===L?!0:B.startsWith(`${L}/`)?$r(F.current,B.slice(L.length+1)):!1});v.set(D.vaultRoot,{engine:V,scope:F,cloudName:L,base:F.current,pendingMoves:new Set}),V.start()}if(A.cloudSync?.enabled!==!1)for(let D of S)O.has(D.cloudName)||(async()=>{try{let U=await w.ensureOwnVault();await w.call("PUT",`/vaults/${encodeURIComponent(U)}/file`,{path:dn(D.cloudName),content:"",baseSeq:0}),C===s&&O.add(D.cloudName)}catch(U){U?.status===409&&C===s&&O.add(D.cloudName)}})()},Q=async(E,C,w,b,A)=>{let S=C.replace(/\\/g,"/").normalize("NFC"),x=w.replace(/\\/g,"/").normalize("NFC"),D=!1,U,F,L,V=A??"file";try{await qe(async B=>{if(v.get(E)!==b)return!1;let q=(B.entrySync??[]).find(oe=>oe.vaultRoot===E);if(!q)return!1;let Z=ct(q.entries,S,x),K=lt(q.exclude??[],S,x),we=Ke(q.entries,q.exclude,S);!A&&await Xe.stat(je.join(E,...x.split("/"))).then(oe=>oe.isDirectory(),()=>!1)&&(V="folder");let Fe=V==="folder"?"folder":/\.md$/i.test(x)?"page":"asset";we&&!Ke(Z.next,K.next,x)&&(Z.next.push({path:x,kind:Fe}),Z.changed=!0),D=Z.changed||K.changed;let Ue=q.entries.filter(oe=>ct([oe],S,x).changed);return we&&!Ue.some(oe=>oe.path===S)&&Ue.push({path:S,kind:Fe}),U=Me(Ue,(q.exclude??[]).filter(oe=>lt([oe],S,x).changed)),F=b.base,b.pendingMoves.add(U),q.entries=Z.next,q.exclude=K.next,L=Me(q.entries,q.exclude),T(b,L),D})}catch(B){throw U&&b.pendingMoves.delete(U),T(b,b.base===L&&F?F:b.base),B}try{U&&await b.engine.notifyLocalMove(S,x,()=>{b.pendingMoves.delete(U),T(b)},V)}catch(B){throw U&&b.pendingMoves.delete(U),await qe(q=>{let Z=q.entrySync?.find(K=>K.vaultRoot===E);if(!Z)return!1;Z.entries=ct(Z.entries,x,S).next,Z.exclude=lt(Z.exclude??[],x,S).next,T(b,Me(Z.entries,Z.exclude))}),B}D&&v.get(E)===b&&N()},J=E=>{let C=E.replace(/\\/g,"/");for(let{engine:w,plan:b}of f.values())if(C.startsWith(`${b.localRelDir}/`))return{engine:w,rel:C.slice(b.localRelDir.length+1)};return{engine:d,rel:C}};t.setMutationHooks((E,C)=>{if(_()){let w=J(E);w.engine.notifyLocal(w.rel,C);return}v.get(n()??"")?.engine.notifyLocal(E,C)},(E,C,w)=>{if(_()){let S=J(E),x=J(C);if(S.engine===x.engine)return S.engine.notifyLocalMove(S.rel,x.rel,void 0,w);S.engine.notifyLocal(S.rel,"remove"),x.engine.notifyLocal(x.rel,"write");return}let b=n()??"",A=v.get(b);if(A)return Q(b,E,C,A,w)},(E,C)=>{if(_()){let w=J(E),b=J(C),A=[w.engine.holdLocalMove(w.rel,b.rel)];return w.engine!==b.engine&&A.push(b.engine.holdLocalMove(w.rel,b.rel)),()=>{for(let S of A)S()}}return v.get(n()??"")?.engine.holdLocalMove(E,C)});let ne=()=>{let E=d.getStatus().pendingDeletions;for(let{engine:C}of f.values())E+=C.getStatus().pendingDeletions;for(let{engine:C}of v.values())E+=C.getStatus().pendingDeletions;return E},ue=E=>({...E,pendingDeletions:ne(),side:_()?"cloud":"local"}),ut=()=>{if(!r)return Promise.resolve(d.getStatus());y();for(let{engine:E}of f.values())E.syncNow();for(let{engine:E}of v.values())E.syncNow();return d.syncNow()},Qe=async()=>{++s,r=!1,o.stop();let E=[d.stop(),...[...f.values()].map(({engine:w})=>w.stop()),...[...v.values()].map(({engine:w})=>w.stop())];f.clear(),v.clear(),u=[],O.clear(),a.clear(),c(),await Promise.all(E),await t.awaitPendingVaultWrites();let C=n();if(C&&St(C)){let w=await Ee(),b=w.localVault&&!St(w.localVault)?w.localVault:je.join(t.workspaceDir(),"Amadeus");await Xe.mkdir(b,{recursive:!0}),await Ae({lastVault:b,localVault:b,lastPage:void 0}),await t.activateRoot(b,!1)}N()};return{handlers:{get:()=>ue(d.getStatus()),setEnabled:async E=>{if(!r)throw new Error("Cloud account is changing");let C=s;return await d.setEnabled(E),C!==s?d.getStatus():(await Promise.all([...f.values(),...v.values()].map(({engine:w})=>w.restart())),ue(d.getStatus()))},syncNow:()=>ut(),confirmDeletions:()=>{for(let{engine:E}of f.values())E.confirmMassDeletions();for(let{engine:E}of v.values())E.confirmMassDeletions();return ue(d.confirmMassDeletions())},entryGet:async()=>{let E=await Ee(),C=De();return{vaults:E.entrySync??[],activeRoot:n(),cloudRoot:C,mirrorVaults:await Pr(C)}},otherSideDbs:async()=>{let E=n();if(!E)return null;let C=De(),w=await Ee(),b=E===C?w.localVault&&w.localVault!==C?w.localVault:null:C;if(!b)return null;let A=[],S=500,x=async(D,U)=>{if(A.length>=S)return;let F;try{F=await Xe.readdir(D,{withFileTypes:!0})}catch{return}for(let L of F){if(A.length>=S)break;if(L.name.startsWith(".")||L.isSymbolicLink())continue;let V=U?`${U}/${L.name}`:L.name;if(L.isDirectory())await x(je.join(D,L.name),V);else if(L.isFile()&&/\.db$/i.test(L.name))try{A.push({rel:V,source:await Xe.readFile(je.join(D,L.name),"utf8")})}catch{}}};return await x(b,""),{root:b,vaultName:b===C?"\u4E91\u7AEF":je.basename(b),dbs:A}},entryEnable:async E=>{let C=s,w=o;if(!r||!he())return{error:"Sign in to enable cloud sync"};let b=n();if(!b||_())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let A=await Ee(),S=A.entrySync??[],x=S.find(D=>D.vaultRoot===b);if(!x){let D=(E.cloudName??je.basename(b)).normalize("NFC").trim(),U=mn(D,S.map(F=>F.cloudName));if(U)return{error:U};if(!E.merge)try{let F=await w.ensureOwnVault(),L=await w.call("GET",`/vaults/${encodeURIComponent(F)}/tree`);if((L.folders??[]).some(B=>B===D||B.startsWith(`${D}/`))||(L.entries??[]).some(B=>B.path===D||B.path.startsWith(`${D}/`)))return{conflict:D}}catch(F){return{error:F?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}x={vaultRoot:b,cloudName:D,entries:[]},S.push(x),(async()=>{try{let F=await w.ensureOwnVault();await w.call("PUT",`/vaults/${encodeURIComponent(F)}/file`,{path:dn(x.cloudName),content:"",baseSeq:0})}catch{}})()}return C!==s||!r?{error:"Cloud account changed; retry from the current account"}:(await qe(D=>{if(C!==s||!r)return!1;let U=D.entrySync??[],F=U.find(K=>K.vaultRoot===b);if(!F){let K=mn(x.cloudName,U.map(we=>we.cloudName));if(K)throw new Error(K);F={vaultRoot:b,cloudName:x.cloudName,entries:[]},U.push(F)}let L=K=>String(K??"").replace(/\\/g,"/").normalize("NFC"),V=new Set;for(let K of E.entries??[]){let we=L(K.path);we&&(V.add(we),!F.entries.some(Fe=>Fe.path===we)&&F.entries.push({path:we,kind:K.kind==="folder"||K.kind==="asset"?K.kind:"page"}))}let B=(E.exclude??[]).map(L).filter(Boolean),q=new Set([...V,...(E.include??[]).map(L).filter(Boolean)]);F.exclude=[...new Set([...(F.exclude??[]).filter(K=>!q.has(K)),...B])];let Z=new Set(B);F.entries=F.entries.filter(K=>!Z.has(K.path)),D.entrySync=U,x=F},A.cloudAccountId),C!==s?{error:"Cloud account changed; retry from the current account"}:(await W(),v.get(b)?.engine.syncNow(),N(),{ok:!0,cloudName:x.cloudName}))},entryDisable:async E=>{let C=n(),w=!1,b=s;return await qe(A=>{if(b!==s||!r)return!1;let S=(A.entrySync??[]).find(U=>U.vaultRoot===C);if(!C||!S)return!1;let x=String(E??"").replace(/\\/g,"/").normalize("NFC"),D=S.entries.length;if(S.entries=S.entries.filter(U=>U.path!==x),Ke(S.entries,S.exclude,x))S.exclude=[...new Set([...S.exclude??[],x])];else if(S.entries.length===D)return!1;w=!0}),!w||b!==s?{ok:!1}:(await W(),N(),{ok:!0})},entryClosure:(E,C)=>t.relatedClosure(String(E??""),C==="folder"?"folder":"page"),collabCall:async(E,C)=>{let w=o,b=async()=>w.ensureOwnVault(),A=x=>String((C??[])[x]??""),S=x=>(C??[])[x]??{};switch(E){case"listVaults":return(await w.call("GET","/vaults")).vaults;case"activeVaultId":return b();case"pageShare":return w.call("GET",`/vaults/${encodeURIComponent(await b())}/page-shares?path=${encodeURIComponent(A(0))}`);case"createPageShare":return w.call("POST",`/vaults/${encodeURIComponent(await b())}/page-shares`,{path:A(0),...S(1)});case"updatePageShare":return w.call("PATCH",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(A(0))}`,S(1));case"revokePageShare":return w.call("DELETE",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(A(0))}`);case"setParticipantRole":return w.call("PATCH",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(A(0))}/members/${encodeURIComponent(A(1))}`,{role:A(2)});case"removeParticipant":return w.call("DELETE",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(A(0))}/members/${encodeURIComponent(A(1))}`);case"sharedWithMe":{let x=await w.sharedWithMe();return y(),x}case"leaveShare":{let x=w.myUserId();if(!x)throw new Error("\u672A\u767B\u5F55");return w.call("DELETE",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(A(0))}/members/${encodeURIComponent(x)}`)}case"publishes":return w.call("GET",`/vaults/${encodeURIComponent(await b())}/shares`);case"listAllShares":{let x=(await w.call("GET","/vaults")).vaults||[],D=w.myUserId(),U=[],F=[];for(let L of x){try{let V=await w.call("GET",`/vaults/${encodeURIComponent(L.id)}/shares`);for(let B of V.shares||[])U.push({...B,vaultId:L.id,vaultName:L.name||""})}catch(V){t.log(`[connect] listAllShares publishes vault ${L.id} failed: ${V?.message}`)}try{let V=await w.call("GET",`/vaults/${encodeURIComponent(L.id)}/page-shares`),B=V?.shares||V?.pageShares||(Array.isArray(V)?V:[]);for(let q of B){let Z=q.created_by??q.createdBy;(!D||!Z||Z===D)&&F.push({...q,vaultId:L.id,vaultName:L.name||""})}}catch(V){t.log(`[connect] listAllShares pageShares vault ${L.id} failed: ${V?.message}`)}}return{publishes:U,pageShares:F,linkBase:await w.linkBase()}}case"createPublish":{let x=await w.call("POST",`/vaults/${encodeURIComponent(await b())}/shares`,{mode:A(0),path:A(1)});return{...x,url:`${await w.linkBase()}/share/${x.token}`}}case"revokePublish":return w.call("DELETE",`/vaults/${encodeURIComponent(await b())}/shares/${encodeURIComponent(A(0))}`);case"revokePublishIn":return w.call("DELETE",`/vaults/${encodeURIComponent(A(0))}/shares/${encodeURIComponent(A(1))}`);case"revokePageShareIn":return w.call("DELETE",`/vaults/${encodeURIComponent(A(0))}/page-shares/${encodeURIComponent(A(1))}`);case"myUserId":return w.myUserId();case"linkBase":return w.linkBase();case"heartbeat":return w.heartbeat((C??[])[0]??null,u);default:throw new Error(`unknown collab fn: ${E}`)}},switchSide:async(E,C)=>{let w=await Ee();if(C==="cloud"){if(!r||!he())throw new Error("Sign in to open cloud notes");let S=De();await Xe.mkdir(S,{recursive:!0}),w.lastVault&&!St(w.lastVault)&&await Ae({localVault:w.lastVault}),await Ae({lastVault:S});let x=await t.activateRoot(S,!1);return t.bindRenderer(E,S),{...x,side:"cloud"}}let b=w.localVault&&await Xe.stat(w.localVault).then(S=>S.isDirectory()).catch(()=>!1)?w.localVault:null;if(!b){let S=await t.ensureDefaultVault();return t.bindRenderer(E,S.root),{...S,side:"local"}}await Ae({lastVault:b});let A=await t.activateRoot(b,!1);return t.bindRenderer(E,b),{...A,side:"local"}}},instance:{start:()=>{r=!0,d.start(),y(),W()},stopAllSync:Qe,restartAllSync:async()=>{await Qe(),o=cn(),d=at(m()),r=!0,await Promise.all([d.restart(),y(),W()]),N(),e(ie.status,ue(d.getStatus()))}}}}async function Or(t,e){if(!e)return"";try{let n=await de({base:t,token:e},"POST","/api/auth/handoff",{},5e3);if(n.status===200&&typeof n.json?.code=="string"&&n.json.code)return`code=${encodeURIComponent(n.json.code)}`;if(n.status===404||n.status===405)return`token=${encodeURIComponent(e)}`}catch{}return""}var Oo=["membership","credits"];function _a(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(r,o)=>{if(!t.isTrustedSender(r))return n;let{base:a,token:c}=await t.getCloud();if(!a)return{ok:!1};let l=o&&/^[a-z0-9-]+$/i.test(o)?`#${o}`:"",m=await Or(a,c),d=`${a}/account${m?`?${m}`:""}${l}`;return await t.openExternal(d),{ok:!0}}),t.handle("auth:openPayCenter",async(r,o)=>{if(!t.isTrustedSender(r))return n;if(o!==void 0&&!Oo.includes(o))return{ok:!1,error:"invalid_tab"};let{base:a,token:c}=await t.getCloud();if(!a)return{ok:!1};let l=await Or(a,c),m=`${a}/pay?tab=${o??"membership"}${l?`&${l}`:""}&redirect=${encodeURIComponent(`${a}/account`)}`;return await t.openExternal(m),{ok:!0}});let s=()=>t.getCloud();t.handle("account:quota",async r=>{if(!t.isTrustedSender(r))return e;let o=await s();if(!o.token)return{status:401,json:null};try{return await de(o,"GET","/api/token-quota/my",void 0,15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:useResetCard",async(r,o)=>{if(!t.isTrustedSender(r))return e;let a=await s();if(!a.token)return{status:401,json:null};if(o!==void 0&&o!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${o}`}};let c=o??"both";try{return await de(a,"POST","/api/token-quota/reset-card/use",{type:c},15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgConvert",async(r,o)=>{if(!t.isTrustedSender(r))return e;let a=await s();if(!a.token)return{status:401,json:null};if(!Number.isInteger(o)||o<1||o>100)return{status:400,json:{error:"invalid_percent"}};try{return await de(a,"POST","/api/token-quota/background/convert",{percent:o},15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("account:bgAutoMain",async(r,o)=>{if(!t.isTrustedSender(r))return e;let a=await s();if(!a.token)return{status:401,json:null};if(typeof o!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await de(a,"POST","/api/token-quota/background/auto-main",{enabled:o},15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),t.handle("feedback:submit",async(r,o)=>{if(!t.isTrustedSender(r))return n;let{base:a,token:c}=await t.getCloud();if(!a||!c)return{ok:!1,error:"not-logged-in"};let l=(o?.description||"").trim();if(!l)return{ok:!1,error:"empty"};if(l.length>1e4)return{ok:!1,error:"description-too-long"};let m=[],d=!1;if(o?.sessionLogJson){let f=Buffer.from(o.sessionLogJson,"utf8");if(f.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};m.push({filename:o.sessionLogName||"tangu-session.json",mime_type:"application/json",size:f.length,data_base64:f.toString("base64")})}try{let f=await fetch(`${a}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({description:l,attachments:m}),signal:AbortSignal.timeout(2e4)});if(!f.ok){let y=`HTTP ${f.status}`;try{y=(await f.json())?.detail||y}catch{}return{ok:!1,error:y}}return{ok:!0,id:(await f.json().catch(()=>({})))?.id??null,attachmentSkipped:d}}catch(f){return{ok:!1,error:f?.message||String(f)}}}),t.handle("cloud:fetch",async(r,o)=>{if(!t.isTrustedSender(r))return{status:0,error:"untrusted"};let a=o??{},c=typeof a.path=="string"?a.path:"",l=Math.min(12e4,Math.max(1e3,Number(a.timeoutMs)||15e3)),m=typeof a.method=="string"?a.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(m))return{status:0,error:"bad_method"};if(!c.startsWith("/"))return{status:0,error:"bad_path"};let{base:d,token:f}=await t.getCloud();if(!String(d||""))return{status:0,error:"no_cloud_url"};let u=Tn(d,c);if(!u)return{status:0,error:"bad_path"};if(!f)return{status:401,error:"not_signed_in"};let y=a.body!==void 0&&m!=="GET"&&m!=="DELETE",_=new AbortController,T=setTimeout(()=>_.abort(),l);try{let v=await fetch(u,{method:m,headers:{Authorization:`Bearer ${f}`,...y?{"Content-Type":"application/json"}:{}},body:y?JSON.stringify(a.body):void 0,signal:_.signal});return{status:v.status,json:await v.json().catch(()=>null)}}catch(v){return{status:0,error:String(v?.message||v)}}finally{clearTimeout(T)}}),t.log("[forsion-extend] cloud account handlers registered"),jt(t)?Ut(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),zt(t)?qt(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),Bt(t)?Vt(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),pn(t)?gn(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host")}export{Vn as ACCOUNT_SEAM,Nr as AMADEUS_SEAM,Ot as CONNECT_MAX_FILES,In as CONNECT_MAX_FILE_BYTES,An as CONNECT_MAX_TOTAL_BYTES,Fn as FORSION_CONNECT_LOCAL_SDK,Oo as PAY_TABS,Un as PENZOR_MAX_FILE,ie as SYNC_IPC,de as cloudJson,Pn as collectProjectFiles,It as conflictCopyPath,co as conflictCopyVariant,Bn as createAccountCloud,Fr as createAmadeusCloud,jn as createPenzorRemote,Ht as expectedPartsOf,Se as forsionAccountId,Wn as forsionRefreshToken,nt as forsionWhoami,Bt as hasAccountHost,pn as hasAmadeusHost,jt as hasConnectHost,zt as hasRemoteSyncHost,Nn as makePreviewProxy,$n as readConnectMeta,Vt as registerAccount,gn as registerAmadeus,_a as registerCloud,Ut as registerConnect,qt as registerPenzor,qn as shouldRefreshToken,Dr as stripConflictSuffix,uo as textFingerprint,zn as tokenAgeMs,ds as tokenRemainingMs,Mn as writeConnectMeta};
195
+ `),t.split(`
196
+ `),{excludeFalseConflicts:!0}),r=[];for(let i of s){if(i.conflict)return null;i.ok&&r.push(...i.ok)}return r.join(`
197
+ `)}function ln(n,e,t=200){return n>=t||e>=5&&n>=Math.max(5,Math.ceil(e/2))}var Si=/[\u0000-\u001f\u007f]/;function Ve(n){let e=n.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||Si.test(e))return null;let t=e.split("/");for(let s of t)if(!s||s==="."||s==="..")return null;return t.join("/")}function cn(n,e){let t=n.replace(/\\/g,"/").normalize("NFC");return e===""?Ve(t):t.startsWith(`${e}/`)?Ve(t.slice(e.length+1)):null}function kr(n,e){return e===""?n:`${e}/${n}`}function ot(n){return!!(n===".DS_Store"||n==="Icon\r"||n===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(n)||/^\..+\.lock$/.test(n))}function Ce(n){return/\.md$/i.test(n)?"page":/\.db$/i.test(n)?"db":"binary"}var De=n=>n==="page"||n==="db";import{gzip as vi}from"node:zlib";import{promisify as Ei}from"node:util";var _i=Ei(vi),ki=1024,le=class extends Error{status;body;constructor(e,t,s){super(`cloud http ${e} on ${s}`),this.status=e,this.body=t}},Cr=n=>12e4+Math.ceil(n/256);function xr(n){let e=`${n.baseUrl.replace(/\/+$/,"")}/api/amadeus`,t=async(r,i,o)=>{let a={Authorization:`Bearer ${n.token}`,...o?.headers};r!=="GET"&&(a["X-Amadeus-Client"]=n.clientId);let c;o?.json!==void 0?(a["Content-Type"]="application/json",c=JSON.stringify(o.json),c.length>=ki&&(a["Content-Encoding"]="gzip",c=await _i(c))):o?.form&&(c=o.form);let h=await fetch(i,{method:r,headers:a,body:c,signal:AbortSignal.timeout(o?.timeoutMs??3e4)});if(!h.ok){let d=null;try{d=await h.json()}catch{}throw new le(h.status,d,i)}return h.json()},s=r=>new URLSearchParams(r).toString();return{clientId:n.clientId,async listVaults(){return((await t("GET",`${e}/vaults`)).vaults??[]).map(i=>({id:String(i.id),name:String(i.name),lastChangeSeq:Number(i.lastChangeSeq??0)}))},async tree(r){let i=await t("GET",`${e}/vaults/${r}/tree`);if(!Array.isArray(i.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:i.folders??[],seq:Number(i.seq??0),maxFileBytes:Number.isInteger(i.maxFileBytes)&&i.maxFileBytes>0?i.maxFileBytes:void 0,entries:i.entries.map(o=>({path:String(o.path),kind:o.kind,seq:Number(o.seq??0),hash:o.hash??null,size:Number(o.size??0)}))}},async getFile(r,i){let o=await t("GET",`${e}/vaults/${r}/file?${s({path:i})}`);return{content:String(o.content??""),seq:Number(o.seq??0),hash:o.hash??null}},putFile(r,i,o,a,c=!1){return t("PUT",`${e}/vaults/${r}/file`,{json:{path:i,content:o,baseSeq:a,...c?{force:!0}:{}}})},async deleteFile(r,i,o,a){let c={path:i};o!==void 0&&(c.baseSeq=String(o)),await t("DELETE",`${e}/vaults/${r}/file?${s(c)}`,a?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(r,i,o){return t("POST",`${e}/vaults/${r}/move`,{json:{from:i,to:o}})},renameFolder(r,i,o){return t("POST",`${e}/vaults/${r}/folders/rename`,{json:{path:i,newName:o}})},moveFolder(r,i,o){return t("POST",`${e}/vaults/${r}/folders/move`,{json:{path:i,dest:o}})},async deleteFolder(r,i){await t("DELETE",`${e}/vaults/${r}/folders?${s({path:i})}`)},putBinary(r,i,o,a){let c=new FormData;return c.set("path",i),a?.ifAbsent&&c.set("ifAbsent","true"),a?.baseSeq!==void 0&&c.set("baseSeq",String(a.baseSeq)),c.set("file",new Blob([new Uint8Array(o)]),i.split("/").pop()||"file"),t("POST",`${e}/vaults/${r}/binary`,{form:c,timeoutMs:Cr(o.length)})},async listVersions(r,i){return((await t("GET",`${e}/vaults/${r}/file/versions?${s({path:i})}`)).versions??[]).map(a=>({id:String(a.id),seq:Number(a.seq??0)}))},async getVersion(r,i){let o=await t("GET",`${e}/vaults/${r}/file/versions/${i}`);return String(o.content??"")},async getAsset(r,i){let o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{let c=await fetch(`${e}/vaults/${r}/asset?${s({ref:i})}`,{headers:{Authorization:`Bearer ${n.token}`},signal:o.signal});if(!c.ok)throw new le(c.status,null,"asset:"+i);return clearTimeout(a),a=setTimeout(()=>o.abort(),Cr(Number(c.headers.get("content-length"))||0)),Buffer.from(await c.arrayBuffer())}finally{clearTimeout(a)}},async changes(r,i){let o=await t("GET",`${e}/vaults/${r}/changes?${s({since:String(i)})}`);return{changes:o.changes??[],seq:Number(o.seq??0)}}}}function Tr(n,e){let t=!1,s=0,r=null,i=null,o=()=>`${n.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${n.vaultId}/events?since=${e.getSince()}`,a=h=>{if(t)return;e.onDown(h);let d=Math.min(3e4,1e3*2**s)*(.7+Math.random()*.6);s++,i=setTimeout(()=>void c(),d)},c=async()=>{if(t)return;r=new AbortController;let h;try{h=await fetch(o(),{headers:{Authorization:`Bearer ${n.token}`,Accept:"text/event-stream"},signal:r.signal})}catch(E){a(E);return}if(!h.ok||!h.body){a(new Error(`sse http ${h.status}`));return}s=0,e.onOpen();let d=h.body.getReader(),f=new TextDecoder,u="",y="",v=[],x=()=>{if(!v.length&&!y)return;let E=v.join(`
198
+ `),U=y||"message";y="",v=[];let M=null;try{M=E?JSON.parse(E):null}catch{return}U==="hello"?e.onHello(Number(M?.seq??0)):U==="change"?e.onChange(M):U==="reset"?e.onReset():U==="presence"?e.onPresence?.(M):U==="presence-roster"&&e.onPresenceRoster?.(M)};try{for(;;){let{done:E,value:U}=await d.read();if(E)break;for(u+=f.decode(U,{stream:!0});;){let M=u.indexOf(`
199
+ `);if(M<0)break;let Y=u.slice(0,M).replace(/\r$/,"");if(u=u.slice(M+1),Y==="")x();else{if(Y.startsWith(":"))continue;Y.startsWith("event:")?y=Y.slice(6).trim():Y.startsWith("data:")&&v.push(Y.slice(5).replace(/^ /,""))}}}}catch(E){t||a(E);return}a(new Error("sse stream ended"))};return c(),{stop:()=>{t=!0,i&&clearTimeout(i),r?.abort()}}}import{constants as Ci,promises as Ye}from"node:fs";import xi from"node:path";var Ge=n=>xi.join(fe().userDataDir(),fe().isDevMode()?`${n}.dev.json`:`${n}.json`);async function un(n){try{let e=JSON.parse(await Ye.readFile(Ge(n),"utf8"));return!e||typeof e.vaultRoot!="string"||typeof e.vaultId!="string"?null:(e.files=e.files??{},e.cursor=Number(e.cursor??0),e.lastSyncAt=e.lastSyncAt??null,e)}catch{return null}}function Rr(n){let e=null,t=null,s=Promise.resolve(),r=null,i=()=>{if(!e)return s;let o=e,a=JSON.stringify(e);return e=null,s=s.then(async()=>{try{let c=Ge(n),h=`${c}.tmp-${process.pid}-${Date.now()}-0`;await Ye.writeFile(h,a,"utf8"),await Ye.rename(h,c),r=null}catch(c){e??=o,r=c}}),s};return{save(o){e=o,!t&&(t=setTimeout(()=>{t=null,i()},500))},async flush(o=!1){if(t&&(clearTimeout(t),t=null),await i(),o&&r)throw r}}}async function Ir(n){try{await Ye.unlink(Ge(n))}catch{}}async function Pr(n,e){try{await Ye.copyFile(Ge(n),Ge(e),Ci.COPYFILE_EXCL)}catch(t){let s=t?.code;if(s==="EEXIST"||s==="ENOENT")return!1;throw t}return await Ye.unlink(Ge(n)).catch(()=>{}),!0}var Ri=5*1024*1024,Ii=5*1024*1024,Pi=3e4,Ai=2500,$i=3e3,Di=5,Mi=256*1024,Ni=5,$r=1024*1024,Dr=200,Ui=6e4,Fi=50,Oi=".sync-trash",Je=n=>Ti("sha256").update(n).digest("hex");function at(n,e={localRoot:$e(),shadowName:`amadeus-sync-${rt()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let t=l=>{let p=cn(l,"");if(!p)return null;for(let m of e.excludePrefixes??[])if(p===m.replace(/\/$/,"")||p.startsWith(m))return null;if(e.ignoreNames?.length&&p.split("/").some(m=>e.ignoreNames.includes(m)))return null;let g=e.serverDir?`${e.serverDir}/${p}`:p;return e.inScope&&!e.inScope(g,Ce(g))?null:g},s=l=>{let p;if(e.serverDir){if(!l.startsWith(`${e.serverDir}/`))return null;p=l.slice(e.serverDir.length+1)}else{for(let g of e.excludePrefixes??[])if(l.startsWith(g))return null;p=l}return p.split("/").some(g=>ot(g)||!!e.ignoreNames?.includes(g))?null:p},r=(l,p)=>!e.inScope||e.inScope(l,p),i=e.accountId??he(),o=!1,a=0,c=Promise.resolve(),h=new Set,d="disabled",f=null,u=null,y=null,v=null,x=null,E=null,U=0,M=new Map,Y=null,B=Rr(e.shadowName),q=new Map,Q=!1,J=!1,ne=[],ue=()=>{u&&(u.pending=q.size?Object.fromEntries(q):void 0,B.save(u))},ft=()=>{J=!1,ne.length=0},Qe=()=>{if(J)return!0;let l=Date.now();for(;ne.length&&l-ne[0]>Ui;)ne.shift();return ne.length>=Fi?(J=!0,!0):!1},xe=[],Ne=new Set,Ze=!1,_=null,C=null,w=null,b=()=>{!o||w||(w=setTimeout(()=>{w=null,n.onStatus(Fe())},200))},P=(l,p)=>{d=l,p!==void 0&&(f=p),b()},S=(l,p=!1)=>{if(o){if(l.key){if(Ne.has(l.key))return;Ne.add(l.key)}p?xe.unshift(l):xe.push(l),G()}},T=new Map,$=l=>{if(!o)return;let p=(u?.files[l]?.size??0)>Mi,g=(e.pushQuietMs??$i)*(p?Ni:1),m=Date.now(),k=T.get(l);k&&clearTimeout(k.timer);let I=k?.since??m,D=Math.max(0,Math.min(g,I+g*Di-m)),R=setTimeout(()=>{T.delete(l),S({key:l,run:()=>ae(l,!0)})},D);T.set(l,{timer:R,since:I}),b()},L=()=>{for(let{timer:l}of T.values())clearTimeout(l);T.clear()},F=l=>!(l instanceof le)||l.status>=500||l.status===0,O=l=>l instanceof le&&(l.status===401||l.status===403),G=async()=>{if(!Ze){Ze=!0;try{for(;xe.length;){(d==="idle"||d==="starting")&&P("syncing");let l=xe.shift();l.key&&Ne.delete(l.key);try{await l.run()}catch(p){if(!o)return;if(O(p)){xe.length=0,Ne.clear(),wt(),P("auth-required","login-expired");return}if(F(p)){S(l,!0),wt(),P("offline",p?.message||"network error"),V();return}let g=l.key??"(op)";M.set(g,p?.body?.code||`http ${p?.status}`),b()}}o&&d==="syncing"&&(u&&(u.lastSyncAt=Date.now(),B.save(u)),P("idle",null))}finally{Ze=!1;for(let l of h)l();h.clear()}}},V=()=>{!o||_||(_=setTimeout(()=>{_=null,tt()},Pi))},W=l=>{if(!E||!u)throw new Error("engine not bound");let p=s(l);if(p===null)throw new Error("path outside binding: "+l);let g=se.resolve(E,kr(p,u.folder)),m=se.relative(E,g);if(m.startsWith("..")||se.isAbsolute(m))throw new Error("path escapes vault: "+l);return g},Z=l=>({size:l,mtimeMs:-1}),X=async l=>{try{let p=await te.stat(l);return p.isFile()?{size:p.size,mtimeMs:Math.floor(p.mtimeMs)}:null}catch{return null}},we=0,Ue=async(l,p,g=()=>!0)=>{await te.mkdir(se.dirname(l),{recursive:!0});let m=`${l}.tmp-${process.pid}-${Date.now()}-${we++}`;await te.writeFile(m,p);let k=await X(m)??Z(Buffer.byteLength(p));return g()?(await te.rename(m,l),k):(await te.rm(m,{force:!0}),null)},Le=async l=>{let p;try{p=await te.readdir(l,{withFileTypes:!0})}catch{return}for(let g of p)g.isDirectory()&&await Le(se.join(l,g.name));try{await te.rmdir(l)}catch{}},ie=async l=>{let p=W(l),g=await X(p),m;try{m=await te.readFile(p)}catch{return null}return{hash:De(Ce(l))?Je(m.toString("utf8")):Je(m),size:g?.size??m.length,mtimeMs:g?.mtimeMs??-1,buf:m}},_e=async(l,p,g,m)=>{u&&(u.files[l]={seq:p,hash:g,size:m.size,mtimeMs:m.mtimeMs},B.save(u))},ye=l=>{u&&l in u.files&&(delete u.files[l],B.save(u))},Te=async(l,p)=>{if(!y||!u||be(l))return;let g=re,m=Ce(l),k,I,D;if(De(m)){let j;try{j=await y.getFile(u.vaultId,l)}catch(H){if(H instanceof le&&H.status===404){await Ut(l);return}throw H}k=j.content,I=j.seq,D=j.hash??Je(j.content)}else{let j;try{j=await y.getAsset(u.vaultId,l)}catch(H){if(H instanceof le&&H.status===404){M.set(l,"ASSET_404"),b();return}throw H}k=j,I=p??0,D=Je(j)}let R=await ie(l);if(g!==re||be(l))return;if(R&&R.hash===D){await _e(l,I,D,R);return}let N=u.files[l];if(R&&N&&D===N.hash&&R.hash!==N.hash){await _e(l,I,D,Z(N.size)),S({key:l,run:()=>ae(l)});return}if(R&&(!N||R.hash!==N.hash)){if(N&&m==="page"&&typeof k=="string"&&await Gr(l,N,R,k,I,D,()=>g===re&&!be(l))||g!==re||be(l))return;await Yr(l)}let A=await Ue(W(l),k,()=>g===re&&!be(l));A&&await _e(l,I,D,A)},Gr=async(l,p,g,m,k,I,D)=>{try{if(!y||!u||g.buf.length>$r||m.length>$r)return!1;let N=(await y.listVersions(u.vaultId,l)).find(H=>H.seq===p.seq);if(!N)return!1;let A=await y.getVersion(u.vaultId,N.id);if(Je(A)!==p.hash)return!1;let j=_r(g.buf.toString("utf8"),A,m);return j===null?!1:(await Ue(W(l),j,D)&&(await _e(l,k,I,Z(Buffer.byteLength(j))),S({key:l,run:()=>ae(l)})),!0)}catch{return!1}},Yr=async l=>{let p=Ve(At(l,new Date));if(!p)return;let g=p.lastIndexOf("."),m=g>p.lastIndexOf("/"),k=m?p.slice(0,g):p,I=m?p.slice(g):"",D=p;for(let R=2;Ar(W(D));R++)D=`${k}-${R}${I}`;try{await te.rename(W(l),W(D))}catch(R){if(R?.code==="ENOENT")return;throw R}U++,S({key:D,run:()=>ae(D)}),b()},_n=async l=>{if(!E)return;let p=W(l),g=s(l)??l,m=se.join(E,Oi,new Date().toISOString().slice(0,10),...g.split("/")),k=Ar(m)?`${m}.${Date.now()}`:m;try{await te.mkdir(se.dirname(k),{recursive:!0}),await te.rename(p,k)}catch(I){if(I?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${p}: ${I?.message??String(I)}`)}},Ut=async l=>{if(!u)return;let p=await ie(l);if(be(l))return;let g=u.files[l]??null,m=$t(p?.hash??null,g,null);if(m.kind==="deleteLocal"){if(!Q&&Qe()){q.set(l,"local"),ue(),b();return}ne.push(Date.now()),await _n(l),ye(l)}else m.kind==="pushCreate"?(ye(l),S({key:l,run:()=>ae(l)})):ye(l)},kn=(l,p)=>{if(u){for(let g of Object.keys(u.files))if(g===l||g.startsWith(`${l}/`)){let m=p+g.slice(l.length);u.files[m]=u.files[g],delete u.files[g]}B.save(u)}},Cn=async l=>{if(!y||!u||l.seq<=u.cursor||!await mt())return;if(l.origin.client&&y.clientId===l.origin.client){u.cursor=l.seq,B.save(u);return}let p=l.type==="structure"?"folder":l.type,g=k=>s(k)!==null&&r(k,p);if(!g(l.path)&&!(l.newPath&&g(l.newPath))){u.cursor=l.seq,B.save(u);return}let m=l.path;switch(l.op){case"write":await Te(m,l.fileSeq);break;case"delete":await Ut(m);break;case"move":{let k=l.newPath;if(!k)break;let I=u.files[m];if(await ie(m)&&I)try{await te.mkdir(se.dirname(W(k)),{recursive:!0}),await te.rename(W(m),W(k)),u.files[k]={...I,seq:l.fileSeq??I.seq},delete u.files[m],B.save(u)}catch{await Te(k,l.fileSeq)}else ye(m),await Te(k,l.fileSeq);break}case"mkdir":await te.mkdir(W(m),{recursive:!0});break;case"rename-folder":case"move-folder":{let k=l.newPath;if(!k)break;try{await te.mkdir(se.dirname(W(k)),{recursive:!0}),await te.rename(W(m),W(k))}catch{}kn(m,k);break}case"delete-folder":{let k=`${m}/`;for(let I of Object.keys(u.files))(I===m||I.startsWith(k))&&await Ut(I);await Le(W(m));break}}if(u.cursor=l.seq,B.save(u),l.op==="move"||l.op==="rename-folder"||l.op==="move-folder"||l.op==="delete"||l.op==="delete-folder")try{await n.onRemoteApplied?.(l)}catch{}},Jr=async(l,p,g)=>{let m=Number(p?.seq??0),k=p?.content??null;if(k!==null&&Je(k)===g.hash){await _e(l,m,g.hash,g);return}if(k===null&&m===0){if(!u?.files[l]){M.set(l,p?.code||"EXISTS"),b();return}ye(l),S({key:l,run:()=>ae(l)});return}await Te(l,m)},ht=async(l,p)=>{if(!y||!u)return;let g=await ie(l);if(!g){S({key:l,run:()=>ae(l)});return}if(g.size>Ri){M.set(l,"TOO_LARGE"),b();return}let m=g.buf.toString("utf8");try{let k=await y.putFile(u.vaultId,l,m,p);M.delete(l),await _e(l,k.seq,k.hash??g.hash,g)}catch(k){if(k instanceof le&&k.status===409){await Jr(l,k.body,g);return}throw k}},pt=async(l,p)=>{if(!y||!u)return;let g=await ie(l);if(!g){S({key:l,run:()=>ae(l)});return}if(g.size>(Y??Ii)){M.set(l,"TOO_LARGE"),b();return}try{let m=await y.putBinary(u.vaultId,l,g.buf,{baseSeq:p});M.delete(l),await _e(l,m.seq,g.hash,g)}catch(m){if(m instanceof le&&m.status===409){let k=Number(m.body?.seq??0),I=m.body?.hash??null;if(I!==null&&I===g.hash){await _e(l,k,g.hash,g);return}if(k===0){if(!u.files[l]){M.set(l,m.body?.code||"EXISTS"),b();return}ye(l),S({key:l,run:()=>ae(l)});return}await Te(l,k);return}throw m}},xn=async l=>{if(!y||!u||be(l))return;let p=re,g=u.files[l];if(g){if(De(Ce(l)))try{let m=await y.getFile(u.vaultId,l);if(m.seq!==g.seq){await Te(l,m.seq);return}}catch(m){if(m instanceof le&&m.status===404){ye(l);return}throw m}if(!(p!==re||be(l))){try{await y.deleteFile(u.vaultId,l,g.seq,{confirmed:Q})}catch(m){if(m instanceof le&&m.status===409){await Te(l,Number(m.body?.seq??0)||null);return}if(m instanceof le&&m.status===429&&m.body?.code==="MASS_DELETE_BLOCKED"){q.set(l,"remote"),J=!0,ue(),b();return}throw m}ye(l)}}},mt=async()=>E?await te.stat(E).then(p=>p.isDirectory()).catch(()=>!1)||!e.requireRootExists&&!Object.keys(u?.files??{}).length?!0:(P("error",`vault-missing: ${E}`),V(),!1):!1,re=0,gt=new Set,yt=new Map,pe=l=>JSON.stringify([l.from,l.to]),Ae=(l,p)=>l===p||l.startsWith(`${p}/`),be=l=>[...u?.moves??[],...gt].some(p=>Ae(l,p.from)||Ae(l,p.to)),Re=()=>!!(u?.moves?.length||gt.size),Ft=async l=>{if(!y||!u)return;let{from:p,to:g,kind:m}=l;if(s(p)===null||s(g)===null)throw new Error("Invalid queued cloud move");l.hashes??=Object.fromEntries(Object.entries(u.files).filter(([R])=>Ae(R,p)).map(([R,N])=>[R.slice(p.length),N.hash])),B.save(u),await B.flush(!0);let k,I=!1;try{if(m==="folder"){let R=se.posix.dirname(p)==="."?"":se.posix.dirname(p),N=se.posix.dirname(g)==="."?"":se.posix.dirname(g);R===N?await y.renameFolder(u.vaultId,p,se.posix.basename(g)):await y.moveFolder(u.vaultId,p,N)}else{let R=await y.move(u.vaultId,p,g);k=Number(R.seq)}}catch(R){if(!(R instanceof le)||R.status!==404)throw R;let N=await y.tree(u.vaultId);if(N.entries.some(H=>Ae(H.path,p))||N.folders.some(H=>Ae(H,p)))throw R;let j=N.entries.find(H=>H.path===g);if(k=j?.seq,I=!j&&!N.entries.some(H=>Ae(H.path,g))&&!N.folders.some(H=>Ae(H,g)),!I){let H=Object.entries(l.hashes);if(!(H.length>0&&H.every(([ke,He])=>N.entries.some(ze=>ze.path===g+ke&&ze.hash===He))))throw new le(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(I)for(let R of Object.keys(u.files))Ae(R,p)&&delete u.files[R];else kn(p,g),k!==void 0&&u.files[g]&&(u.files[g].seq=k);u.moves=(u.moves??[]).filter(R=>pe(R)!==pe(l)),B.save(u);try{await B.flush(!0)}catch(R){throw u.moves.unshift(l),B.save(u),R}let D=yt.get(pe(l));yt.delete(pe(l)),D?.(),be(g)||(m==="folder"?await Ot():await ae(g))},ae=async(l,p=!1)=>{if(!u||be(l))return;if(!r(l,Ce(l))){ye(l);return}if(!await mt())return;let g=await ie(l);if(be(l))return;let m=u.files[l]??null,k=$t(g?.hash??null,m,m?{seq:m.seq,hash:m.hash}:null);switch(k.kind){case"push":De(Ce(l))?await ht(l,k.baseSeq):await pt(l,k.baseSeq);break;case"pushCreate":De(Ce(l))?await ht(l,0):await pt(l,0);break;case"pushDelete":if(p){St();break}if(!Q&&(q.has(l)||Qe())){q.set(l,"remote"),ue(),b();break}ne.push(Date.now()),await xn(l);break;case"dropShadow":ye(l);break;default:g&&m&&g.hash===m.hash&&g.mtimeMs>=0&&(m.size!==g.size||m.mtimeMs!==g.mtimeMs)&&await _e(l,m.seq,m.hash,g);break}},Tn=async()=>{let l=new Map;if(!E||!u)return l;let p=E,g=null,m=async k=>{if(g)return;let I;try{I=await te.readdir(k,{withFileTypes:!0})}catch(D){g=`${k}: ${D?.message??String(D)}`;return}for(let D of I){if(ot(D.name)||D.isDirectory()&&e.ignoreNames?.includes(D.name))continue;let R=se.join(k,D.name);if(D.isDirectory())await m(R);else if(D.isFile()){let N=se.relative(p,R).split(se.sep).join("/"),A=t(N);if(!A)continue;try{let j=await te.stat(R);if(!j.isFile())continue;l.set(A,{size:j.size,mtimeMs:Math.floor(j.mtimeMs)})}catch(j){if(j?.code==="ENOENT")continue;g=`${R}: ${j?.message??String(j)}`;return}}}};return await m(p),g?(P("error",`scan-failed: ${g}`),V(),null):l},Ot=async()=>{let l=re;if(Re()||l!==re||!u||!await mt())return;let p=await Tn();if(!p||Re()||l!==re)return;let g=!1;for(let[I,D]of[...q])(D==="remote"&&p.has(I)||D==="local"&&!p.has(I))&&(q.delete(I),g=!0);q.size||ft();for(let[I,D]of p){let R=u.files[I];R&&R.size===D.size&&R.mtimeMs===D.mtimeMs||S({key:I,run:()=>ae(I)})}let m=Object.keys(u.files),k=m.filter(I=>!p.has(I));if(k.length&&!Q&&(J||ln(k.length,m.length,Dr))){J=!0;for(let I of k)q.set(I,"remote");ue(),b();return}g&&(ue(),b());for(let I of k)q.has(I)||S({key:I,run:()=>ae(I)})},et=async()=>{let l=re;if(Re()||l!==re||!y||!u||!E||!await mt())return;let p=await y.tree(u.vaultId);if(p.maxFileBytes!==void 0&&p.maxFileBytes!==Y&&(Y=p.maxFileBytes,b()),Re()||l!==re)return;let g=new Map;for(let A of p.entries)s(A.path)===null||!r(A.path,A.kind)||g.set(A.path,A);let m=await Tn();if(!m||Re()||l!==re)return;let k=new Set([...g.keys(),...m.keys(),...Object.keys(u.files)]),I=Object.keys(u.files).length,D=[];for(let A of k){if(Re()||l!==re)return;let j=u.files[A]??null,H=g.get(A)??null,ce=m.get(A)??null,ke=null,He=Z(ce?.size??0);if(ce)if(j&&j.size===ce.size&&j.mtimeMs===ce.mtimeMs)ke=j.hash,He=ce;else{let ze=await ie(A);ze&&(ke=ze.hash,He=ze)}D.push({sp:A,d:$t(ke,j,H?{seq:H.seq,hash:H.hash}:null),rSeq:H?.seq??null,localHash:ke,localStat:He})}if(Re()||l!==re)return;let R=D.filter(A=>A.d.kind==="deleteLocal"||A.d.kind==="pushDelete").length,N=!Q&&(J||ln(R,I,Dr));N&&R&&(J=!0),q.clear();for(let{sp:A,d:j,rSeq:H,localHash:ce,localStat:ke}of D){if(Re()||l!==re)return;if(N&&(j.kind==="deleteLocal"||j.kind==="pushDelete")){q.set(A,j.kind==="deleteLocal"?"local":"remote");continue}if((j.kind==="deleteLocal"||j.kind==="pushDelete")&&((await ie(A))?.hash??null)!==ce){S({key:A,run:()=>ae(A)});continue}if(Re()||l!==re)return;switch(j.kind){case"adopt":await _e(A,H,ce,ke);break;case"pull":await Te(A,H);break;case"push":De(Ce(A))?await ht(A,j.baseSeq):await pt(A,j.baseSeq);break;case"pushCreate":De(Ce(A))?await ht(A,0):await pt(A,0);break;case"pushDelete":await xn(A);break;case"deleteLocal":await _n(A),ye(A);break;case"conflict":await Te(A,H);break;case"dropShadow":ye(A);break;case"none":break}}Q&&(Q=!1,ne.length=0),q.size||ft(),ue(),N&&b();for(let A of p.folders)if(!(s(A)===null||!r(A,"folder")))try{await te.mkdir(W(A),{recursive:!0})}catch{}u.cursor=p.seq,u.lastSyncAt=Date.now(),B.save(u)},Xr=async()=>{if(!y||!u)return;let l=u.cursor,p=await y.changes(u.vaultId,l);if(p.changes.length===0&&p.seq>l||p.changes.length>0&&p.changes[0].seq!==l+1){await et();return}for(let m of p.changes)await Cn(m)},Ie=null,Rn=[],In=()=>{Ie&&Rn.push(Ie.close()),Ie=null},Kr=()=>{if(!o||Ie||!E)return;Ie=Sr.watch(E,{ignoreInitial:!0,depth:12,ignored:p=>{let g=se.basename(p);return ot(g)||!!e.ignoreNames?.includes(g)}});let l=p=>{if(!E)return;let g=se.relative(E,p);if(!g||g.startsWith(".."))return;let m=t(g);m&&$(m)};Ie.on("change",l),Ie.on("add",l),Ie.on("unlink",()=>St()),Ie.on("unlinkDir",()=>St())},wt=()=>{v?.stop(),v=null},Qr=()=>{if(!o||!y||!u||v)return;let l=x;l&&(v=Tr({baseUrl:l.cloudUrl,vaultId:u.vaultId,token:l.token},{getSince:()=>u?.cursor??0,onHello:p=>{u&&p>u.cursor&&S({run:Xr})},onChange:p=>{S({run:()=>Cn(p)})},onReset:()=>{S({run:et})},onOpen:()=>{(d==="offline"||d==="starting")&&P("idle",null),S({run:Ot})},onDown:()=>{(d==="idle"||d==="syncing")&&P("offline")},onPresence:p=>n.onPresence?.(u?.vaultId??"",p),onPresenceRoster:p=>n.onPresenceRoster?.(u?.vaultId??"",p)}))},Zr=async()=>{let l=await ve(i);if(l.cloudSync?.deviceId)return l.cloudSync.deviceId;let p=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Pe({cloudSync:{...l.cloudSync??{},deviceId:p}},i),p},es=async l=>{wt(),In(),xe.length=0,Ne.clear(),q.clear(),Q=!1,J=!1,ne.length=0;let p=await ve(i);if(l!==a)return;let g=p.cloudSync;if(g?.enabled===!1){E=null,y=null,P("disabled",null);return}if(!i||i!==he()){P("auth-required","not-logged-in");return}if(E=e.localRoot,e.requireRootExists){let D=await te.stat(E).then(R=>R.isDirectory()).catch(()=>!1);if(l!==a)return;if(!D){P("error",`vault-missing: ${E}`),V();return}}if(l!==a)return;let m=n.loadCreds();if(!m.cloudUrl||!m.token){y=null,P("auth-required","not-logged-in");return}P("starting",null);let k=g?.deviceId??await Zr();if(l!==a)return;let I=e.clientIdSuffix?`${k}#${e.clientIdSuffix}`:k;x={cloudUrl:m.cloudUrl,token:m.token},y=xr({baseUrl:m.cloudUrl,token:m.token,clientId:I});try{let D=e.vaultId==="first"?g?.vaultId:e.vaultId;if(!D){let N=await y.listVaults();if(l!==a)return;if(!N.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");D=N[0].id,await Pe({cloudSync:{...g??{},vaultId:D}},i)}if(l!==a)return;let R=await un(e.shadowName);if(l!==a||(u=R&&R.vaultRoot===E&&R.vaultId===D&&R.folder===""?R:{vaultRoot:E,folder:"",vaultId:D,cursor:0,lastSyncAt:null,files:{}},l!==a))return;for(let[N,A]of Object.entries(u.pending??{}))q.set(N,A);if(q.size&&(J=!0),!e.requireRootExists){let N=await te.stat(E).then(A=>A.isDirectory()).catch(()=>!1);if(l!==a)return;if(!N){if(Object.keys(u.files).length){P("error",`mirror-missing: ${E}`),V();return}if(await te.mkdir(E,{recursive:!0}),l!==a)return}}Kr();for(let N of u.moves??[])S({key:`move:${pe(N)}`,run:()=>Ft(N)});S({run:et}),S({run:async()=>{Qr()}})}catch(D){if(l!==a)return;O(D)?P("auth-required","login-expired"):(P("offline",D?.message||String(D)),V())}},Pn=()=>{o=!1,wt(),In(),xe.length=0,Ne.clear(),L();for(let l of[_,C,w])l&&clearTimeout(l);_=C=w=null},An=async()=>{Ze&&await new Promise(l=>h.add(l)),await Promise.all(Rn.splice(0)),await B.flush(),u=null,y=null,x=null,E=null,U=0,M.clear(),Y=null,q.clear(),Q=!1,J=!1,ne.length=0,d="disabled",f=null},ts=()=>{$n()},bt=null,tt=()=>{bt?.(),bt=fe().onBeforeQuit(ts);let l=++a;Pn();let p=c.catch(()=>{}).then(async()=>{await An(),l===a&&(o=!0,await es(l))});return c=p,p},$n=()=>{bt?.(),bt=null,++a,Pn();let l=c.catch(()=>{}).then(An);return c=l,l},Fe=()=>({enabled:d!=="disabled",state:d==="idle"&&T.size?"syncing":d,lastSyncAt:u?.lastSyncAt??null,pending:xe.length+T.size,conflicts:U,skipped:[...M].map(([l,p])=>({path:l,reason:p})),error:f,pendingDeletions:q.size,maxFileBytes:Y});return{getStatus:Fe,start(){tt()},notifyLocal(l,p,g){if(!u||d==="disabled"||d==="auth-required")return;let m=t(l),k=g?t(g):null;if(p==="write"&&m){ot(m.split("/").pop()||"")||$(m);return}if(p==="remove"){if(!m)return;let I=`${m}/`,D=!1;for(let R of Object.keys(u.files))(R===m||R.startsWith(I))&&(D=!0,S({key:R,run:()=>ae(R)}));!D&&m&&S({key:m,run:()=>ae(m)})}},holdLocalMove(l,p){let g=k=>e.serverDir?`${e.serverDir}/${k.replace(/\\/g,"/").normalize("NFC")}`:k.replace(/\\/g,"/").normalize("NFC"),m={from:g(l),to:g(p)};return++re,gt.add(m),()=>{gt.delete(m)}},async notifyLocalMove(l,p,g,m){let k=t(l),I=t(p),D=u??await un(e.shadowName),R=cn(l,""),N=R&&(e.serverDir?`${e.serverDir}/${R}`:R);if(!k&&I&&N&&D&&Object.keys(D.files).some(A=>A===N||A.startsWith(`${N}/`))&&(k=N),!k&&!I){g?.();return}if(k&&I){let A=u??D;if(!A){g?.();return}let j=m??(Object.keys(A.files).some(ce=>ce.startsWith(`${k}/`))?"folder":"file"),H={from:k,to:I,kind:j};A.moves??=[],A.moves.some(ce=>pe(ce)===pe(H))||(A.moves.push(H),++re),g&&yt.set(pe(H),g),B.save(A);try{await B.flush(!0)}catch(ce){throw A.moves=A.moves.filter(ke=>pe(ke)!==pe(H)),yt.delete(pe(H)),B.save(A),ce}u===A&&o&&d!=="disabled"&&d!=="auth-required"&&S({key:`move:${pe(H)}`,run:()=>Ft(H)});return}k&&this.notifyLocal(l,"remove"),I&&(S({key:I,run:()=>ae(I)}),St()),g?.()},async setEnabled(l){let p=await ve(i);return await Pe({cloudSync:{...p.cloudSync??{},enabled:l}},i),await tt(),Fe()},async restart(){return await tt(),Fe()},async syncNow(){if(M.clear(),d==="disabled"||d==="auth-required"||!y)await tt();else{for(let l of u?.moves??[])S({key:`move:${pe(l)}`,run:()=>Ft(l)});S({run:et})}return Fe()},confirmMassDeletions(){return q.size&&(Q=!0,J=!1,q.clear(),ne.length=0,ue(),S({run:et})),Fe()},stop:$n};function St(){o&&(C&&clearTimeout(C),C=setTimeout(()=>{C=null,S({run:Ot})},Ai))}}import{createHash as ji}from"node:crypto";function Mr(n){let e=n.replace(/\.md$/i,""),t=n.lastIndexOf("/"),s=t<0?"":n.slice(0,t);return{root:n,fdPrefix:`${e}.fd/`,assetPrefix:s?`${s}/.amadeus/`:".amadeus/"}}function Nr(n,e,t){return!!(e===n.root||e.startsWith(n.fdPrefix)||`${e}/`===n.fdPrefix||t==="binary"&&e.startsWith(n.assetPrefix)||t==="folder"&&(`${e}/`===n.assetPrefix||e.startsWith(n.assetPrefix)))}var Li=n=>ji("sha256").update(n).digest("hex").slice(0,8),Hi=n=>n.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Dt="\u4E0E\u6211\u5171\u4EAB";function dn(n){let e=Li(`${n.vaultId}:${n.path}`),t=Mr(n.path),s=n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"";return{key:e,vaultId:n.vaultId,rootPath:n.path,title:n.title,localRelDir:`${Dt}/${Hi(n.title)}-${e}`,serverDir:s,inScope:(r,i)=>Nr(t,r,i)}}function fn(){let n=fe().readCreds(),e=Se(n.cloudUrl??"",n.token??""),t=new AbortController,s=()=>{let f=fe().readCreds();if(t.signal.aborted||!e||Se(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},r=()=>{let f=s();if(!f.cloudUrl||!f.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return f.cloudUrl.replace(/\/+$/,"")},i=async(f,u,y)=>{let v=s();if(!v.cloudUrl||!v.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let x=await fetch(`${v.cloudUrl.replace(/\/+$/,"")}/api/amadeus${u}`,{method:f,headers:{Authorization:`Bearer ${v.token}`,...y!==void 0?{"Content-Type":"application/json"}:{}},body:y!==void 0?JSON.stringify(y):void 0,signal:AbortSignal.any([t.signal,AbortSignal.timeout(2e4)])});if(!x.ok){let U=null;try{U=await x.json()}catch{}throw Object.assign(new Error(U?.detail||`http ${x.status}`),{status:x.status,code:U?.code})}let E=await x.json();return s(),E},o=null,a=async()=>(s(),o||(o=(await i("GET","/vaults")).vaults[0]?.id??"default",o)),c=()=>{try{let f=(s().token??"").split(".")[1],u=JSON.parse(Buffer.from(f.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());return typeof u.userId=="string"?u.userId:null}catch{return null}},h=async()=>(await i("GET","/shared-with-me")).items.map(u=>{let y=dn(u),v=u.path.split("/").pop()??u.path;return{...u,localPath:`${y.localRelDir}/${v}`}}),d=null;return{stop:()=>t.abort(),call:i,ensureOwnVault:a,myUserId:c,sharedWithMe:h,linkBase:async()=>{if(s(),d)return d;try{d=((await i("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||r()}catch{d=r()}return d},async heartbeat(f,u){let y=(f??"").replace(/\\/g,"/"),v,x=null,E=u.find(U=>y.startsWith(`${U.localRelDir}/`));E?(v=E.vaultId,x=E.serverDir?`${E.serverDir}/${y.slice(E.localRelDir.length+1)}`:y.slice(E.localRelDir.length+1)):(v=await a(),x=y||null),await i("POST",`/vaults/${encodeURIComponent(v)}/presence`,{page:x})}}}import{promises as Ur}from"node:fs";import zi from"node:path";var hn=".forsion-vault.md",pn=n=>`${n}/${hn}`;var ge=n=>n.replace(/\\/g,"/").normalize("NFC");function mn(n){let e=ge(n.path);return e?n.kind==="folder"?`${e}/`:n.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function Xe(n,e,t){let s=ge(t);if(!s)return!1;if(n.some(r=>ge(r.path)===s))return!0;for(let r of e??[]){let i=ge(r);if(!i)continue;let o=`${i.replace(/\.md$/i,"")}.fd`;if(s===i||s.startsWith(`${i}/`)||s===o||s.startsWith(`${o}/`))return!1}return n.some(r=>{let i=mn(r);return!!i&&s.startsWith(i)})}function gn(n,e,t){let s=ge(n),r=ge(e);return s===r?ge(t):s.startsWith(`${r}/`)?ge(t)+s.slice(r.length):null}function lt(n,e,t){let s=!1,r=n.map(i=>{let o=gn(i,e,t);return o===null?i:(s=!0,o)});return{changed:s,next:r}}async function Fr(n){let e=await Ur.readdir(n,{withFileTypes:!0}).catch(()=>[]),t=[];for(let s of e)!s.isDirectory()||s.name.startsWith(".")||await Ur.access(zi.join(n,s.name,hn)).then(()=>!0,()=>!1)&&t.push(s.name);return t.sort()}var oe={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",status:"amadeus:sync:status",switchSide:"amadeus:sync:switch-side",collabCall:"amadeus:collab:call",presence:"amadeus:collab:presence",entryGet:"amadeus:entry-sync:get",entryEnable:"amadeus:entry-sync:enable",entryDisable:"amadeus:entry-sync:disable",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};import{createHash as Wi}from"node:crypto";var Mt=n=>Wi("sha256").update(n).digest("hex").slice(0,8);function Or(n){return n.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Me(n,e=[]){let t=[],s=[];for(let r of n){let i=ge(r.path);if(!i)continue;s.push(i);let o=mn(r);o&&t.push(o)}return{entries:n,exclude:e,prefixes:t,paths:s}}function jr(n,e){let t=Or(ge(e));if(!t)return!1;if(Xe(n.entries,n.exclude,t))return!0;let s=`${t}/`;for(let r of n.paths)if(r.startsWith(s))return!0;for(let r of n.prefixes)if(r.startsWith(s))return!0;return!1}function ct(n,e,t){let s=!1,r=n.map(i=>{let o=gn(i.path,e,t);return o===null?i:(s=!0,{...i,path:o})});return{changed:s,next:r}}function Lr(n,e,t,s){if(e==="delete"||e==="delete-folder"){let r=ge(t),i=n.filter(o=>{let a=ge(o.path);return!(a===r||e==="delete-folder"&&a.startsWith(`${r}/`))});return{changed:i.length!==n.length,next:i}}return s?ct(n,t,s):{changed:!1,next:n}}function yn(n,e){let t=Ve(n);return!t||t!==n.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":t.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":t===Dt?`\u300C${Dt}\u300D\u662F\u4FDD\u7559\u540D\u79F0`:e.includes(t)?"\u8BE5\u540D\u79F0\u5DF2\u88AB\u5176\u4ED6\u667A\u5E93\u7684\u4E91\u540C\u6B65\u5360\u7528":null}var Hr=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],wn=n=>Hr.every(e=>typeof n[e]=="function"),qi=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function bn(n){let e=null,t=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};n.handle(oe.get,()=>e?e.get():qi()),n.handle(oe.setEnabled,(s,r)=>t().setEnabled(r)),n.handle(oe.syncNow,()=>t().syncNow()),n.handle(oe.confirmDeletions,()=>t().confirmDeletions()),n.handle(oe.entryGet,()=>t().entryGet()),n.handle(oe.otherSideDbs,()=>t().otherSideDbs()),n.handle(oe.entryEnable,(s,r)=>t().entryEnable(r)),n.handle(oe.entryDisable,(s,r)=>t().entryDisable(r)),n.handle(oe.entryClosure,(s,r,i)=>t().entryClosure(r,i)),n.handle(oe.collabCall,(s,r,i)=>t().collabCall(r,i)),n.handle(oe.switchSide,(s,r)=>t().switchSide(s.sender.id,r)),n.setAmadeusSyncFactory(s=>{Zn(s);let r=zr(s);return e=r.handlers,r.instance}),n.log("[forsion-extend] amadeus cloud sync registered")}function zr(n){let e=n.notifyAll,t=()=>n.vaultRoot(),s=0,r=!1,i=fn(),o=new Map,a=()=>{let _=Date.now();for(let[C,w]of o)_-w.at>7e4&&o.delete(C);e(oe.presence,[...o.values()])},c={loadCreds:()=>n.readCreds(),onStatus:_=>e(oe.status,{..._,pendingDeletions:ne(),side:v()?"cloud":"local"}),onPresence:(_,C)=>{let w=C;w?.userId&&(o.set(w.userId,{userId:w.userId,username:String(w.username??"user"),page:w.page??null,at:Number(w.at)||Date.now()}),a())},onPresenceRoster:(_,C)=>{if(Array.isArray(C)){for(let w of C){let b=w;b?.userId&&o.set(b.userId,{userId:b.userId,username:String(b.username??"user"),page:b.page??null,at:Number(b.at)||Date.now()})}a()}}},h=()=>{let _=s;return{...c,onStatus:C=>{_===s&&c.onStatus(C)},onPresence:(C,w)=>{_===s&&c.onPresence(C,w)},onPresenceRoster:(C,w)=>{_===s&&c.onPresenceRoster(C,w)}}},d=at(h()),f=new Map,u=[],y=async()=>{if(!r||!he())return;let _=s,C=i,w;try{w=await C.sharedWithMe()}catch{return}if(_!==s||!r)return;let b=w.map(S=>dn(S));u=b;let P=new Set(b.map(S=>S.key));for(let[S,T]of f)if(!P.has(S)){if(await T.engine.stop(),_!==s)return;f.delete(S)}for(let S of b){if(f.has(S.key))continue;let T=at(h(),{localRoot:je.join($e(),...S.localRelDir.split("/")),shadowName:`amadeus-sync-${rt()}-share-${S.key}`,vaultId:S.vaultId,serverDir:S.serverDir,inScope:S.inScope});f.set(S.key,{engine:T,plan:S}),T.start()}},v=()=>t()===$e(),x=(_,C=_.base)=>{_.base=C;let w=[C,..._.pendingMoves];_.scope.current=Me(w.flatMap(b=>b.entries),w.flatMap(b=>b.exclude))},E=new Map,U=new Set,M=()=>{e(oe.entryChange)},Y=async(_,C)=>{let w=E.get(_);if(!w)return;let b=T=>T&&T.startsWith(`${w.cloudName}/`)?T.slice(w.cloudName.length+1):null,P=b(C.path);if(!P)return;let S=!1;await We(T=>{if(E.get(_)!==w)return!1;let $=(T.entrySync??[]).find(V=>V.vaultRoot===_);if(!$)return!1;let L=C.op,F=b(C.newPath),O=Lr($.entries,L,P,F),G=F?lt($.exclude??[],P,F):{changed:!1,next:$.exclude??[]};if(!O.changed&&!G.changed)return!1;S=!0,$.entries=O.next,G.changed&&($.exclude=G.next),x(w,Me($.entries,$.exclude??[]))}),S&&E.get(_)===w&&M()},B=_=>{let C=s;return{...h(),onStatus:w=>{C===s&&e(oe.status,{...w,pendingDeletions:ne(),side:"local",binding:_})},onRemoteApplied:async w=>{C===s&&await Y(_,w)}}},q=async()=>{let _=he();if(!r||!_)return;let C=s,w=i,b=rt(_);await n.adoptLegacyCloudState(_,Pr);let P=await ve(_),S=P.entrySync??[];if(C!==s||!r||_!==he())return;let T=new Map(S.map($=>[$.vaultRoot,$]));for(let[$,L]of E){let F=T.get($);if(!(F&&F.cloudName===L.cloudName)&&(await L.engine.stop(),C!==s||(E.delete($),F&&await Ir(`amadeus-sync-${b}-entry-${Mt($)}`),C!==s)))return}for(let $ of S){let L=E.get($.vaultRoot);if(L){x(L,Me($.entries,$.exclude??[]));continue}let F={current:Me($.entries,$.exclude??[])},O=$.cloudName,G=at(B($.vaultRoot),{accountId:_,localRoot:$.vaultRoot,shadowName:`amadeus-sync-${b}-entry-${Mt($.vaultRoot)}`,vaultId:"first",serverDir:O,clientIdSuffix:`entry-${Mt($.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:V=>V===O?!0:V.startsWith(`${O}/`)?jr(F.current,V.slice(O.length+1)):!1});E.set($.vaultRoot,{engine:G,scope:F,cloudName:O,base:F.current,pendingMoves:new Set}),G.start()}if(P.cloudSync?.enabled!==!1)for(let $ of S)U.has($.cloudName)||(async()=>{try{let L=await w.ensureOwnVault();await w.call("PUT",`/vaults/${encodeURIComponent(L)}/file`,{path:pn($.cloudName),content:"",baseSeq:0}),C===s&&U.add($.cloudName)}catch(L){L?.status===409&&C===s&&U.add($.cloudName)}})()},Q=async(_,C,w,b,P)=>{let S=C.replace(/\\/g,"/").normalize("NFC"),T=w.replace(/\\/g,"/").normalize("NFC"),$=!1,L,F,O,G=P??"file";try{await We(async V=>{if(E.get(_)!==b)return!1;let W=(V.entrySync??[]).find(ie=>ie.vaultRoot===_);if(!W)return!1;let Z=ct(W.entries,S,T),X=lt(W.exclude??[],S,T),we=Xe(W.entries,W.exclude,S);!P&&await Ke.stat(je.join(_,...T.split("/"))).then(ie=>ie.isDirectory(),()=>!1)&&(G="folder");let Ue=G==="folder"?"folder":/\.md$/i.test(T)?"page":"asset";we&&!Xe(Z.next,X.next,T)&&(Z.next.push({path:T,kind:Ue}),Z.changed=!0),$=Z.changed||X.changed;let Le=W.entries.filter(ie=>ct([ie],S,T).changed);return we&&!Le.some(ie=>ie.path===S)&&Le.push({path:S,kind:Ue}),L=Me(Le,(W.exclude??[]).filter(ie=>lt([ie],S,T).changed)),F=b.base,b.pendingMoves.add(L),W.entries=Z.next,W.exclude=X.next,O=Me(W.entries,W.exclude),x(b,O),$})}catch(V){throw L&&b.pendingMoves.delete(L),x(b,b.base===O&&F?F:b.base),V}try{L&&await b.engine.notifyLocalMove(S,T,()=>{b.pendingMoves.delete(L),x(b)},G)}catch(V){throw L&&b.pendingMoves.delete(L),await We(W=>{let Z=W.entrySync?.find(X=>X.vaultRoot===_);if(!Z)return!1;Z.entries=ct(Z.entries,T,S).next,Z.exclude=lt(Z.exclude??[],T,S).next,x(b,Me(Z.entries,Z.exclude))}),V}$&&E.get(_)===b&&M()},J=_=>{let C=_.replace(/\\/g,"/");for(let{engine:w,plan:b}of f.values())if(C.startsWith(`${b.localRelDir}/`))return{engine:w,rel:C.slice(b.localRelDir.length+1)};return{engine:d,rel:C}};n.setMutationHooks((_,C)=>{if(v()){let w=J(_);w.engine.notifyLocal(w.rel,C);return}E.get(t()??"")?.engine.notifyLocal(_,C)},(_,C,w)=>{if(v()){let S=J(_),T=J(C);if(S.engine===T.engine)return S.engine.notifyLocalMove(S.rel,T.rel,void 0,w);S.engine.notifyLocal(S.rel,"remove"),T.engine.notifyLocal(T.rel,"write");return}let b=t()??"",P=E.get(b);if(P)return Q(b,_,C,P,w)},(_,C)=>{if(v()){let w=J(_),b=J(C),P=[w.engine.holdLocalMove(w.rel,b.rel)];return w.engine!==b.engine&&P.push(b.engine.holdLocalMove(w.rel,b.rel)),()=>{for(let S of P)S()}}return E.get(t()??"")?.engine.holdLocalMove(_,C)});let ne=()=>{let _=d.getStatus().pendingDeletions;for(let{engine:C}of f.values())_+=C.getStatus().pendingDeletions;for(let{engine:C}of E.values())_+=C.getStatus().pendingDeletions;return _},ue=_=>({..._,pendingDeletions:ne(),side:v()?"cloud":"local"}),ft=()=>{if(!r)return Promise.resolve(d.getStatus());y();for(let{engine:_}of f.values())_.syncNow();for(let{engine:_}of E.values())_.syncNow();return d.syncNow()},Qe=async()=>{++s,r=!1,i.stop();let _=[d.stop(),...[...f.values()].map(({engine:w})=>w.stop()),...[...E.values()].map(({engine:w})=>w.stop())];f.clear(),E.clear(),u=[],U.clear(),o.clear(),a(),await Promise.all(_),await n.awaitPendingVaultWrites();let C=t();if(C&&Et(C)){let w=await ve(),b=w.localVault&&!Et(w.localVault)?w.localVault:je.join(n.workspaceDir(),"Amadeus");await Ke.mkdir(b,{recursive:!0}),await Pe({lastVault:b,localVault:b,lastPage:void 0}),await n.activateRoot(b,!1)}M()};return{handlers:{get:()=>ue(d.getStatus()),setEnabled:async _=>{if(!r)throw new Error("Cloud account is changing");let C=s;return await d.setEnabled(_),C!==s?d.getStatus():(await Promise.all([...f.values(),...E.values()].map(({engine:w})=>w.restart())),ue(d.getStatus()))},syncNow:()=>ft(),confirmDeletions:()=>{for(let{engine:_}of f.values())_.confirmMassDeletions();for(let{engine:_}of E.values())_.confirmMassDeletions();return ue(d.confirmMassDeletions())},entryGet:async()=>{let _=await ve(),C=$e();return{vaults:_.entrySync??[],activeRoot:t(),cloudRoot:C,mirrorVaults:await Fr(C)}},otherSideDbs:async()=>{let _=t();if(!_)return null;let C=$e(),w=await ve(),b=_===C?w.localVault&&w.localVault!==C?w.localVault:null:C;if(!b)return null;let P=[],S=500,T=async($,L)=>{if(P.length>=S)return;let F;try{F=await Ke.readdir($,{withFileTypes:!0})}catch{return}for(let O of F){if(P.length>=S)break;if(O.name.startsWith(".")||O.isSymbolicLink())continue;let G=L?`${L}/${O.name}`:O.name;if(O.isDirectory())await T(je.join($,O.name),G);else if(O.isFile()&&/\.db$/i.test(O.name))try{P.push({rel:G,source:await Ke.readFile(je.join($,O.name),"utf8")})}catch{}}};return await T(b,""),{root:b,vaultName:b===C?"\u4E91\u7AEF":je.basename(b),dbs:P}},entryEnable:async _=>{let C=s,w=i;if(!r||!he())return{error:"Sign in to enable cloud sync"};let b=t();if(!b||v())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let P=await ve(),S=P.entrySync??[],T=S.find($=>$.vaultRoot===b);if(!T){let $=(_.cloudName??je.basename(b)).normalize("NFC").trim(),L=yn($,S.map(F=>F.cloudName));if(L)return{error:L};if(!_.merge)try{let F=await w.ensureOwnVault(),O=await w.call("GET",`/vaults/${encodeURIComponent(F)}/tree`);if((O.folders??[]).some(V=>V===$||V.startsWith(`${$}/`))||(O.entries??[]).some(V=>V.path===$||V.path.startsWith(`${$}/`)))return{conflict:$}}catch(F){return{error:F?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}T={vaultRoot:b,cloudName:$,entries:[]},S.push(T),(async()=>{try{let F=await w.ensureOwnVault();await w.call("PUT",`/vaults/${encodeURIComponent(F)}/file`,{path:pn(T.cloudName),content:"",baseSeq:0})}catch{}})()}return C!==s||!r?{error:"Cloud account changed; retry from the current account"}:(await We($=>{if(C!==s||!r)return!1;let L=$.entrySync??[],F=L.find(X=>X.vaultRoot===b);if(!F){let X=yn(T.cloudName,L.map(we=>we.cloudName));if(X)throw new Error(X);F={vaultRoot:b,cloudName:T.cloudName,entries:[]},L.push(F)}let O=X=>String(X??"").replace(/\\/g,"/").normalize("NFC"),G=new Set;for(let X of _.entries??[]){let we=O(X.path);we&&(G.add(we),!F.entries.some(Ue=>Ue.path===we)&&F.entries.push({path:we,kind:X.kind==="folder"||X.kind==="asset"?X.kind:"page"}))}let V=(_.exclude??[]).map(O).filter(Boolean),W=new Set([...G,...(_.include??[]).map(O).filter(Boolean)]);F.exclude=[...new Set([...(F.exclude??[]).filter(X=>!W.has(X)),...V])];let Z=new Set(V);F.entries=F.entries.filter(X=>!Z.has(X.path)),$.entrySync=L,T=F},P.cloudAccountId),C!==s?{error:"Cloud account changed; retry from the current account"}:(await q(),E.get(b)?.engine.syncNow(),M(),{ok:!0,cloudName:T.cloudName}))},entryDisable:async _=>{let C=t(),w=!1,b=s;return await We(P=>{if(b!==s||!r)return!1;let S=(P.entrySync??[]).find(L=>L.vaultRoot===C);if(!C||!S)return!1;let T=String(_??"").replace(/\\/g,"/").normalize("NFC"),$=S.entries.length;if(S.entries=S.entries.filter(L=>L.path!==T),Xe(S.entries,S.exclude,T))S.exclude=[...new Set([...S.exclude??[],T])];else if(S.entries.length===$)return!1;w=!0}),!w||b!==s?{ok:!1}:(await q(),M(),{ok:!0})},entryClosure:(_,C)=>n.relatedClosure(String(_??""),C==="folder"?"folder":"page"),collabCall:async(_,C)=>{let w=i,b=async()=>w.ensureOwnVault(),P=T=>String((C??[])[T]??""),S=T=>(C??[])[T]??{};switch(_){case"listVaults":return(await w.call("GET","/vaults")).vaults;case"activeVaultId":return b();case"pageShare":return w.call("GET",`/vaults/${encodeURIComponent(await b())}/page-shares?path=${encodeURIComponent(P(0))}`);case"createPageShare":return w.call("POST",`/vaults/${encodeURIComponent(await b())}/page-shares`,{path:P(0),...S(1)});case"updatePageShare":return w.call("PATCH",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(P(0))}`,S(1));case"revokePageShare":return w.call("DELETE",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(P(0))}`);case"setParticipantRole":return w.call("PATCH",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(P(0))}/members/${encodeURIComponent(P(1))}`,{role:P(2)});case"removeParticipant":return w.call("DELETE",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(P(0))}/members/${encodeURIComponent(P(1))}`);case"sharedWithMe":{let T=await w.sharedWithMe();return y(),T}case"leaveShare":{let T=w.myUserId();if(!T)throw new Error("\u672A\u767B\u5F55");return w.call("DELETE",`/vaults/${encodeURIComponent(await b())}/page-shares/${encodeURIComponent(P(0))}/members/${encodeURIComponent(T)}`)}case"publishes":return w.call("GET",`/vaults/${encodeURIComponent(await b())}/shares`);case"listAllShares":{let T=(await w.call("GET","/vaults")).vaults||[],$=w.myUserId(),L=[],F=[];for(let O of T){try{let G=await w.call("GET",`/vaults/${encodeURIComponent(O.id)}/shares`);for(let V of G.shares||[])L.push({...V,vaultId:O.id,vaultName:O.name||""})}catch(G){n.log(`[connect] listAllShares publishes vault ${O.id} failed: ${G?.message}`)}try{let G=await w.call("GET",`/vaults/${encodeURIComponent(O.id)}/page-shares`),V=G?.shares||G?.pageShares||(Array.isArray(G)?G:[]);for(let W of V){let Z=W.created_by??W.createdBy;(!$||!Z||Z===$)&&F.push({...W,vaultId:O.id,vaultName:O.name||""})}}catch(G){n.log(`[connect] listAllShares pageShares vault ${O.id} failed: ${G?.message}`)}}return{publishes:L,pageShares:F,linkBase:await w.linkBase()}}case"createPublish":{let T=await w.call("POST",`/vaults/${encodeURIComponent(await b())}/shares`,{mode:P(0),path:P(1)});return{...T,url:`${await w.linkBase()}/share/${T.token}`}}case"revokePublish":return w.call("DELETE",`/vaults/${encodeURIComponent(await b())}/shares/${encodeURIComponent(P(0))}`);case"revokePublishIn":return w.call("DELETE",`/vaults/${encodeURIComponent(P(0))}/shares/${encodeURIComponent(P(1))}`);case"revokePageShareIn":return w.call("DELETE",`/vaults/${encodeURIComponent(P(0))}/page-shares/${encodeURIComponent(P(1))}`);case"myUserId":return w.myUserId();case"linkBase":return w.linkBase();case"heartbeat":return w.heartbeat((C??[])[0]??null,u);default:throw new Error(`unknown collab fn: ${_}`)}},switchSide:async(_,C)=>{let w=await ve();if(C==="cloud"){if(!r||!he())throw new Error("Sign in to open cloud notes");let S=$e();await Ke.mkdir(S,{recursive:!0}),w.lastVault&&!Et(w.lastVault)&&await Pe({localVault:w.lastVault}),await Pe({lastVault:S});let T=await n.activateRoot(S,!1);return n.bindRenderer(_,S),{...T,side:"cloud"}}let b=w.localVault&&await Ke.stat(w.localVault).then(S=>S.isDirectory()).catch(()=>!1)?w.localVault:null;if(!b){let S=await n.ensureDefaultVault();return n.bindRenderer(_,S.root),{...S,side:"local"}}await Pe({lastVault:b});let P=await n.activateRoot(b,!1);return n.bindRenderer(_,b),{...P,side:"local"}}},instance:{start:()=>{r=!0,d.start(),y(),q()},stopAllSync:Qe,restartAllSync:async()=>{await Qe(),i=fn(),d=at(h()),r=!0,await Promise.all([d.restart(),y(),q()]),M(),e(oe.status,ue(d.getStatus()))}}}}import{hostname as Bi}from"node:os";var Vi=256*1024;function Wr(n,e,t){if(t?.hasSecHeaders&&!t.gatewayStreamsSecHeaders)return!1;if(n.includes("text/event-stream"))return!0;let s=Number(e||NaN);return!Number.isFinite(s)||s>Vi}var Sn=45e3,Gi=3e3,Yi=16*1024,Ji=6e4,Nt=n=>`${n.replace(/\/+$/,"")}/api`,ut=class{deps;ctrl=null;conn=null;wake=null;redialNow=!1;inflight=new Map;connected=!1;lastError=null;hubCaps=new Set;constructor(e){this.deps=e}hubFetch(e,t){return(this.deps.hubFetch??fetch)(e,t)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??Ji}status(){return{running:!!this.ctrl,connected:this.connected,unitId:this.deps.getPairing()?.unitId??null,lastError:this.lastError}}start(){if(this.ctrl)return;let e=new AbortController;this.ctrl=e,this.loop(e)}stop(){this.ctrl?.abort(),this.ctrl=null,this.markDown(),this.abortEnvelopes(),this.wake?.()}reconnect(e){this.ctrl&&(this.deps.log(`[unit-host] \u7ACB\u5373\u91CD\u8FDE\u901A\u9053(${e})`),this.redialNow=!0,this.conn?.abort(),this.wake?.())}markDown(){this.connected=!1,this.hook(this.deps.onChannelDown)}hook(e){try{e?.()}catch(t){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${t?.message||t}`)}}abortEnvelope(e){let t=this.inflight.get(e);return t?(this.inflight.delete(e),t.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[t,s]of[...this.inflight])e&&s.conn!==e||(this.inflight.delete(t),s.ctrl.abort())}sleep(e){return new Promise(t=>{let s=setTimeout(r,e);function r(){clearTimeout(s),t()}this.wake=()=>{this.wake=null,r()}})}async loop(e){let t=1e3;for(;!e.signal.aborted;){let s=new AbortController,r=()=>s.abort();e.signal.addEventListener("abort",r,{once:!0}),this.conn=s;try{let{cloudUrl:i,token:o}=this.deps.getCreds();if(!o)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let a=this.deps.getPairing();if(!a){if(a=await this.register(i,o,s),s.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(a),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${a.unitId}`)}let c=this.deps.getLanUrl();this.hubCaps=new Set;let h=this.deps.readIdleMs??Sn,d=h?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(h/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),s.abort()},h):null,f;try{f=await this.hubFetch(`${Nt(i)}/units/${a.unitId}/channel`,{headers:{Authorization:`Bearer ${o}`,"X-Unit-Secret":a.secret,...c?{"X-Unit-Lan-Url":c}:{}},signal:s.signal})}finally{d&&clearTimeout(d)}if(f.status===403||f.status===404){let u=Number(f.headers.get("content-length"))>Yi,y=setTimeout(()=>s.abort(),u?0:Gi),v=await f.json().then(x=>x?.code,()=>null);throw clearTimeout(y),v==="UNIT_NOT_FOUND"||v==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${f.status} ${v}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${f.status} (not a hub verdict; keeping pairing and retrying)`)}if(!f.ok||!f.body)throw new Error(`channel HTTP ${f.status}`);this.connected=!0,this.lastError=null,t=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(f.body,s),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(i){if(this.markDown(),e.signal.aborted)return;this.lastError=s.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(i?.message||i),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(t/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",r),this.conn===s&&(this.conn=null),s.abort(),this.abortEnvelopes(s)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,t=1e3;continue}if(await this.sleep(t),this.redialNow){this.redialNow=!1,t=1e3;continue}t=Math.min(t*2,3e4)}}async register(e,t,s){let r=this.deps.readIdleMs??Sn,i=r?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(r/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),s.abort()},r):null;try{let o=await this.hubFetch(`${Nt(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:Bi(),platform:process.platform}),signal:s.signal});if(!o.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${o.status}`);let a=await o.json();if(!a.unitId||!a.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:a.unitId,secret:a.secret}}finally{i&&clearTimeout(i)}}async consume(e,t){let s=e.getReader(),r=new TextDecoder,i="",o=this.deps.readIdleMs??Sn,a=null,c=()=>{o&&(a&&clearTimeout(a),a=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(o/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),t.abort(),s.cancel().catch(()=>{})},o))};c();try{for(;;){let{done:h,value:d}=await s.read();if(h||t.signal.aborted)return;c(),i=this.parseFrames(i+r.decode(d,{stream:!0}),t)}}finally{a&&clearTimeout(a)}}parseFrames(e,t){let s=e,r;for(;(r=s.indexOf(`
200
+
201
+ `))>=0;){let i=s.slice(0,r);if(s=s.slice(r+2),i.includes("event: ready")){let a=i.split(`
202
+ `).find(c=>c.startsWith("data: "))?.slice(6);try{let c=JSON.parse(a||"{}").caps;this.hubCaps=new Set(Array.isArray(c)?c.map(String):[])}catch{this.hubCaps=new Set}t.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!i.includes("event: dispatch"))continue;let o=i.split(`
203
+ `).find(a=>a.startsWith("data: "))?.slice(6);if(o)try{let a=JSON.parse(o);this.dispatch(a,t).catch(c=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${c?.message||c}`))}catch{}}return s}async dispatch(e,t){let s=new AbortController;if(t.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let r={ctrl:s,conn:t};this.inflight.set(e.id,r);try{await this.handle(e,s)}finally{this.inflight.get(e.id)===r&&this.inflight.delete(e.id)}}async handle(e,t){let s=this.deps.getUnitWeb();if(!s.url){await this.respond(e.id,503,"application/json",Buffer.from(JSON.stringify({detail:"\u672C\u673A\u4E92\u8054\u670D\u52A1\u672A\u5C31\u7EEA",code:"UNIT_WEB_NOT_READY"})),void 0,t.signal);return}let r={"x-unit-internal":s.internalSecret};e.ct&&(r["Content-Type"]=e.ct),e.accept&&(r.Accept=e.accept);let i;try{let d=new URL(`${s.url}${e.path}`);Object.assign(r,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:d,proxyCaller:e.proxyCaller})),i=await fetch(d,{method:e.method,headers:r,body:e.body??void 0,signal:t.signal})}catch(d){if(t.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${d?.message||d}`})),void 0,t.signal);return}let o=i.headers.get("content-type")||"",a={};for(let d of["content-security-policy","x-content-type-options"]){let f=i.headers.get(d);f&&(a[d]=f)}let c=o||"application/octet-stream";i.body&&Wr(o,i.headers.get("content-length"),{hasSecHeaders:Object.keys(a).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,i,t,c,a):await this.respond(e.id,i.status,c,Buffer.from(await i.arrayBuffer()),a,t.signal)}async respond(e,t,s,r,i,o){if(o?.aborted)return;let{cloudUrl:a,token:c}=this.deps.getCreds(),h=this.deps.getPairing();if(!h)return;let d=this.requestTimeoutMs*2,f=[...d?[AbortSignal.timeout(d)]:[],...o?[o]:[]],u=f.length>1?AbortSignal.any(f):f[0];await this.hubFetch(`${Nt(a)}/units/${h.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"X-Unit-Secret":h.secret,"Content-Type":"application/json"},body:JSON.stringify({status:t,headers:{"content-type":s,...i},bodyB64:r.toString("base64")}),...u?{signal:u}:{}}).then(y=>{y.body?.cancel().catch(()=>{})}).catch(y=>{o?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${y?.name==="TimeoutError"?`${Math.round(d/1e3)}s \u672A\u5B8C\u6210`:y?.message||y}`)})}async streamBack(e,t,s,r,i){let{cloudUrl:o,token:a}=this.deps.getCreds(),c=this.deps.getPairing();if(!c)return;let h=i?.["content-security-policy"],d=i?.["x-content-type-options"],f=`${Nt(o)}/units/${c.unitId}/stream/${e}?status=${t.status}&ct=${encodeURIComponent(r)}`+(h?`&csp=${encodeURIComponent(h)}`:"")+(d?`&xcto=${encodeURIComponent(d)}`:""),u=t.body;if(!u)return;let y=u.getReader(),v=0,x=this.requestTimeoutMs,E=x?setTimeout(()=>{v>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(x/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),s.abort())},x):null,U=new ReadableStream({async pull(M){++v===2&&E&&clearTimeout(E);let{done:Y,value:B}=await y.read();Y?M.close():M.enqueue(B)},cancel(M){return y.cancel(M)}},{highWaterMark:0});try{await this.hubFetch(f,{method:"POST",headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":c.secret,"Content-Type":"application/octet-stream"},body:U,signal:s.signal,duplex:"half"})}catch(M){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${M?.message||M}`);try{await y.cancel()}catch{}}finally{E&&clearTimeout(E)}}};var dt=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(a){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${a?.message||a}`);return}if(e===this.lastSent)return;let t=this.d.getPairing(),s;try{s=this.d.getCreds()}catch{return}if(!t||!s.token||!s.cloudUrl)return;let r=this.gen;this.inflight=!0;let i=new AbortController,o=setTimeout(()=>i.abort(),this.d.timeoutMs??1e4);try{let a=`${s.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(t.unitId)}/caps`,c=await(this.d.hubFetch??fetch)(a,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"X-Unit-Secret":t.secret,"Content-Type":"application/json"},body:JSON.stringify({engine:e,tools:[]}),signal:i.signal});try{await c.text()}catch{}if(r!==this.gen)return;c.ok?(this.lastSent=e,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}`)):c.status===404||c.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${c.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):c.status===400||c.status===401||c.status===403?this.warned.has(c.status)||(this.warned.add(c.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${c.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${c.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(a){r===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${i.signal.aborted?"\u8D85\u65F6":a?.message||a}`)}finally{clearTimeout(o),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var qr=["setUnitHubFactory"],vn=n=>qr.every(e=>typeof n[e]=="function");function Br(n){let e=new dt({getCreds:()=>n.getCreds(),getPairing:()=>n.getPairing(),current:()=>n.engineCaps(),log:s=>n.log(s)}),t=new ut({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>n.getCreds(),getUnitWeb:()=>n.getUnitWeb(),callerHeaders:s=>n.callerHeaders(s),getLanUrl:()=>n.getLanUrl(),getPairing:()=>n.getPairing(),savePairing:s=>n.savePairing(s),clearPairing:()=>n.clearPairing(),log:s=>n.log(s)});return{start:()=>t.start(),stop:()=>t.stop(),reconnect:s=>t.reconnect(s),status:()=>t.status(),engineChanged:()=>e.engineChanged()}}function En(n){let e=async(t,s,r)=>{let{base:i,token:o}=await n.getCloud();if(!o)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let a=await fetch(`${i}/api${s}`,{method:t,headers:{Authorization:`Bearer ${o}`,...r!==void 0?{"Content-Type":"application/json"}:{}},body:r!==void 0?JSON.stringify(r):void 0});return{status:a.status,json:await a.json().catch(()=>null)}}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}};n.handle("units:list",()=>e("GET","/units")),n.handle("units:update",(t,s,r)=>e("PATCH",`/units/${encodeURIComponent(String(s))}`,{name:r?.name,icon:r?.icon})),n.handle("units:remove",(t,s)=>e("DELETE",`/units/${encodeURIComponent(String(s))}`)),n.handle("units:openInBrowser",async(t,s)=>{if(typeof s!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(s))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:r,token:i}=await n.getCloud();await n.openExternal(`${r}/api/units/${s}/open${i?`#token=${encodeURIComponent(i)}`:""}`)}),n.setUnitHubFactory(Br),n.log("[forsion-extend] unit hub registered")}async function Vr(n,e){if(!e)return"";try{let t=await de({base:n,token:e},"POST","/api/auth/handoff",{},5e3);if(t.status===200&&typeof t.json?.code=="string"&&t.json.code)return`code=${encodeURIComponent(t.json.code)}`;if(t.status===404||t.status===405)return`token=${encodeURIComponent(e)}`}catch{}return""}var Xi=["membership","credits"];function qa(n){let e={status:0,error:"untrusted"},t={ok:!1,error:"untrusted"};n.handle("auth:openAccountCenter",async(r,i)=>{if(!n.isTrustedSender(r))return t;let{base:o,token:a}=await n.getCloud();if(!o)return{ok:!1};let c=i&&/^[a-z0-9-]+$/i.test(i)?`#${i}`:"",h=await Vr(o,a),d=`${o}/account${h?`?${h}`:""}${c}`;return await n.openExternal(d),{ok:!0}}),n.handle("auth:openPayCenter",async(r,i)=>{if(!n.isTrustedSender(r))return t;if(i!==void 0&&!Xi.includes(i))return{ok:!1,error:"invalid_tab"};let{base:o,token:a}=await n.getCloud();if(!o)return{ok:!1};let c=await Vr(o,a),h=`${o}/pay?tab=${i??"membership"}${c?`&${c}`:""}&redirect=${encodeURIComponent(`${o}/account`)}`;return await n.openExternal(h),{ok:!0}});let s=()=>n.getCloud();n.handle("account:quota",async r=>{if(!n.isTrustedSender(r))return e;let i=await s();if(!i.token)return{status:401,json:null};try{return await de(i,"GET","/api/token-quota/my",void 0,15e3)}catch(o){return{status:0,json:{detail:String(o?.message||o)}}}}),n.handle("account:useResetCard",async(r,i)=>{if(!n.isTrustedSender(r))return e;let o=await s();if(!o.token)return{status:401,json:null};if(i!==void 0&&i!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${i}`}};let a=i??"both";try{return await de(o,"POST","/api/token-quota/reset-card/use",{type:a},15e3)}catch(c){return{status:0,json:{detail:String(c?.message||c)}}}}),n.handle("account:bgConvert",async(r,i)=>{if(!n.isTrustedSender(r))return e;let o=await s();if(!o.token)return{status:401,json:null};if(!Number.isInteger(i)||i<1||i>100)return{status:400,json:{error:"invalid_percent"}};try{return await de(o,"POST","/api/token-quota/background/convert",{percent:i},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),n.handle("account:bgAutoMain",async(r,i)=>{if(!n.isTrustedSender(r))return e;let o=await s();if(!o.token)return{status:401,json:null};if(typeof i!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await de(o,"POST","/api/token-quota/background/auto-main",{enabled:i},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),n.handle("feedback:submit",async(r,i)=>{if(!n.isTrustedSender(r))return t;let{base:o,token:a}=await n.getCloud();if(!o||!a)return{ok:!1,error:"not-logged-in"};let c=(i?.description||"").trim();if(!c)return{ok:!1,error:"empty"};if(c.length>1e4)return{ok:!1,error:"description-too-long"};let h=[],d=!1;if(i?.sessionLogJson){let f=Buffer.from(i.sessionLogJson,"utf8");if(f.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};h.push({filename:i.sessionLogName||"tangu-session.json",mime_type:"application/json",size:f.length,data_base64:f.toString("base64")})}try{let f=await fetch(`${o}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({description:c,attachments:h}),signal:AbortSignal.timeout(2e4)});if(!f.ok){let y=`HTTP ${f.status}`;try{y=(await f.json())?.detail||y}catch{}return{ok:!1,error:y}}return{ok:!0,id:(await f.json().catch(()=>({})))?.id??null,attachmentSkipped:d}}catch(f){return{ok:!1,error:f?.message||String(f)}}}),n.handle("cloud:fetch",async(r,i)=>{if(!n.isTrustedSender(r))return{status:0,error:"untrusted"};let o=i??{},a=typeof o.path=="string"?o.path:"",c=Math.min(12e4,Math.max(1e3,Number(o.timeoutMs)||15e3)),h=typeof o.method=="string"?o.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(h))return{status:0,error:"bad_method"};if(!a.startsWith("/"))return{status:0,error:"bad_path"};let{base:d,token:f}=await n.getCloud();if(!String(d||""))return{status:0,error:"no_cloud_url"};let u=Dn(d,a);if(!u)return{status:0,error:"bad_path"};if(!f)return{status:401,error:"not_signed_in"};let y=o.body!==void 0&&h!=="GET"&&h!=="DELETE",v=new AbortController,x=setTimeout(()=>v.abort(),c);try{let E=await fetch(u,{method:h,headers:{Authorization:`Bearer ${f}`,...y?{"Content-Type":"application/json"}:{}},body:y?JSON.stringify(o.body):void 0,signal:v.signal});return{status:E.status,json:await E.json().catch(()=>null)}}catch(E){return{status:0,error:String(E?.message||E)}}finally{clearTimeout(x)}}),n.log("[forsion-extend] cloud account handlers registered"),zt(n)?Wt(n):n.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Bt(n)?Vt(n):n.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),Yt(n)?Jt(n):n.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),wn(n)?bn(n):n.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),vn(n)?En(n):n.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host")}export{Qn as ACCOUNT_SEAM,Hr as AMADEUS_SEAM,Lt as CONNECT_MAX_FILES,Nn as CONNECT_MAX_FILE_BYTES,Un as CONNECT_MAX_TOTAL_BYTES,zn as FORSION_CONNECT_LOCAL_SDK,Xi as PAY_TABS,Vn as PENZOR_MAX_FILE,oe as SYNC_IPC,qr as UNIT_SEAM,dt as UnitCapsReporter,ut as UnitHost,de as cloudJson,Fn as collectProjectFiles,At as conflictCopyPath,wi as conflictCopyVariant,Kn as createAccountCloud,zr as createAmadeusCloud,Bn as createPenzorRemote,Br as createUnitHub,qt as expectedPartsOf,Se as forsionAccountId,Xn as forsionRefreshToken,nt as forsionWhoami,Yt as hasAccountHost,wn as hasAmadeusHost,zt as hasConnectHost,Bt as hasRemoteSyncHost,vn as hasUnitHost,Hn as makePreviewProxy,jn as readConnectMeta,Jt as registerAccount,bn as registerAmadeus,qa as registerCloud,Wt as registerConnect,Vt as registerPenzor,En as registerUnit,Jn as shouldRefreshToken,Wr as streamWorthy,Or as stripConflictSuffix,bi as textFingerprint,Yn as tokenAgeMs,Ss as tokenRemainingMs,Ln as writeConnectMeta};
200
204
  /*! Bundled license information:
201
205
 
202
206
  chokidar/index.js:
package/manifest.json CHANGED
@@ -2,11 +2,11 @@
2
2
  "id": "forsion-extend",
3
3
  "name": "Forsion 扩展",
4
4
  "nameEn": "Forsion Extend",
5
- "version": "0.5.1",
5
+ "version": "0.6.0",
6
6
  "apiVersion": 1,
7
7
  "minAppVersion": "2.11.4",
8
8
  "main": "dist/main.js",
9
- "description": "Forsion 云端账号在桌面端的功能:登录与切换账号,设置里的「Forsion 云端」(账号、额度与积分、安全、用量记录、反馈),笔记云同步与分享,以及 Forsion Connect 发布。随 Forsion 桌面端内置,自动更新。",
10
- "descriptionEn": "Your Forsion cloud account on the desktop: signing in and switching accounts, the Forsion Cloud pages in Settings (account, quota & points, security, usage, feedback), note cloud sync and sharing, and Forsion Connect publishing. Built into Forsion Desktop and updated automatically.",
9
+ "description": "Forsion 云端账号在桌面端的功能:登录与切换账号,设置里的「Forsion 云端」(账号、额度与积分、安全、用量记录、反馈),笔记云同步与分享,设备互联的云端中转与设备列表,以及 Forsion Connect 发布。随 Forsion 桌面端内置,自动更新。",
10
+ "descriptionEn": "Your Forsion cloud account on the desktop: signing in and switching accounts, the Forsion Cloud pages in Settings (account, quota & points, security, usage, feedback), note cloud sync and sharing, the cloud relay and device list for connecting your devices, and Forsion Connect publishing. Built into Forsion Desktop and updated automatically.",
11
11
  "author": "Forsion"
12
12
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forsion/extend",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Forsion Extend: the cloud-account half of Forsion Desktop plus Forsion Connect (Coding Space publishing and the preview-mode AI proxy), shipped as a built-in bundle (signed, updated through npm).",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",