@forsion/extend 0.8.2 → 0.9.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/dist/desktop.mjs CHANGED
@@ -1,7 +1,7 @@
1
- function Jn(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 ge(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 Os,lstatSync as Us,readFileSync as Kt,writeFileSync as Fs,realpathSync as Kn}from"node:fs";import{join as Zt,extname as js,sep as Ls}from"node:path";var Xt=300,Xn=5*1024*1024,Zn=20*1024*1024,Hs=50*1024*1024,zs=new Set(["node_modules"]),qs=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function Qn(t,e){let n=[],s=0,r=(o,a)=>{for(let i of Os(o)){if(i.startsWith("."))continue;let l=Zt(o,i),h;try{h=Us(l)}catch{continue}if(h.isSymbolicLink())continue;let d=a?`${a}/${i}`:i;if(h.isDirectory()){zs.has(i)||r(l,d);continue}if(!h.isFile()||i.endsWith(".d.ts"))continue;if(n.length>=Xt)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Xt}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let f=js(i).toLowerCase(),u,g=e.mimeOf(f)??"application/octet-stream";if(qs.has(f)){let S=e.transpile(Kt(l,"utf8"),f,d);u=Buffer.from(S??"","utf8"),g="text/javascript"}else u=Kt(l);if(u.length>Xn)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${d}`);if(s+=u.length,s>Zn)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:g,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 er=".forsion-connect.json";function tr(t){try{return JSON.parse(Kt(Zt(t,er),"utf8"))}catch{return{}}}function nr(t,e){try{Fs(Zt(t,er),JSON.stringify(e,null,2)+`
2
- `,"utf8")}catch{}}function rr(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("?"),i=(S,x)=>{r.headersSent||(r.statusCode=S,r.setHeader("Content-Type","application/json")),r.end(JSON.stringify({detail:x}))},l=n(o);if(!l)return i(404,"unknown connect endpoint");if((s.method||"GET")!==l.method)return i(405,"method not allowed");let h="",d="";try{({base:h,token:d}=await t())}catch{}if(!h)return i(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(l.auth&&!d)return i(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let f;if(l.method==="POST"){let S=[],x=0;try{for await(let w of s){if(x+=w.length,x>Hs)return s.destroy(),i(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");S.push(w)}}catch(w){return i(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${w?.message||String(w)}`)}f=Buffer.concat(S)}if(l.agentRun){let S;try{S=JSON.parse((f||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return i(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}f=Buffer.from(JSON.stringify({session_id:typeof S.session_id=="string"?S.session_id:"",message:typeof S.message=="string"?S.message:"",app_id:"connect",agent_config:{}}))}let u=new AbortController,g=setTimeout(()=>u.abort(new Error("proxy timeout")),l.timeoutMs??3e5);s.on("close",()=>u.abort());try{let S=await fetch(h+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=S.status,r.setHeader("Content-Type",S.headers.get("content-type")||"application/json"),r.setHeader("Cache-Control","no-store"),S.body)for await(let x of S.body)r.write(x);r.end()}catch(S){let x=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${S?.message||String(S)}`;if(r.headersSent){try{r.write(`data: ${JSON.stringify({error:x})}
1
+ var Dn=null;function Ur(t){Dn=t}function Se(){if(!Dn)throw new Error("core host not set (call setCoreHost first)");return Dn}var jr=new TextEncoder,Ko=new TextDecoder("utf-8",{ignoreBOM:!0}),vt=t=>jr.encode(t),Ke=t=>Ko.decode(t),Rn=t=>typeof t=="string"?jr.encode(t).length:t.length;function Fr(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}function Zt(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return Uint8Array.from(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),n=>n.charCodeAt(0))}async function Lr(t){let e=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}function We(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,s;try{r=new URL(n),s=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||s.origin!==r.origin||!s.pathname.startsWith("/api/")?null:s.toString()}async function Ae(t,e,n,r,s=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:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(s)}),i=await o.json().catch(()=>({}));return{status:o.status,json:i}}var Zo=50*1024*1024,Qo=new Set(["type","source","name","summary","githubRepoUrl","npmPackage","version","readme","description","tags","minAppVersion","maxAppVersion","platforms"]);function ei(t){if(!t||typeof t!="object")return null;let e=t;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let n=new FormData,r=0;for(let[s,o]of Object.entries(e.fields)){if(!Qo.has(s)||typeof o!="string"||(r+=o.length,r>25e4)||e.id&&!["summary","version","readme","description","tags","minAppVersion","maxAppVersion","platforms"].includes(s))return null;n.append(s,o)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>Zo)return null;n.append("zip",new Blob([new Uint8Array(e.zip.data)],{type:"application/zip"}),e.zip.name.replace(/[\\/]/g,"_").slice(-255))}return{path:e.id?`/market/mine/${e.id}/update`:"/market/submit",body:n}}function Hr(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=ei(n);if(!r)return{status:400,json:{error:"invalid_request"}};let{base:s,token:o}=await t.getCloud();if(!o)return{status:401,error:"not_signed_in"};let i=We(s,r.path);if(!i)return{status:0,error:"no_cloud_url"};try{let l=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:l.status,json:await l.json().catch(()=>null)}}catch(l){return{status:0,error:String(l?.message||l)}}})}async function zr(t,e){if(!e)return"";try{let n=await Ae({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 qr=["membership","credits","storefront"],Br=["monthly","quarterly","yearly"],ti=/^[A-Za-z0-9_-]{1,64}$/;function Wr(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(s,o)=>{if(!t.isTrustedSender(s))return n;let{base:i,token:l}=await t.getCloud();if(!i)return{ok:!1};let a=o&&/^[a-z0-9-]+$/i.test(o)?`#${o}`:"",u=await zr(i,l),d=`${i}/account${u?`?${u}`:""}${a}`;return await t.openExternal(d),{ok:!0}}),t.handle("auth:openPayCenter",async(s,o,i,l)=>{if(!t.isTrustedSender(s))return n;if(o!==void 0&&!qr.includes(o))return{ok:!1,error:"invalid_tab"};if(i!==void 0&&(typeof i!="string"||!ti.test(i)))return{ok:!1,error:"invalid_plan"};if(l!==void 0&&!Br.includes(l))return{ok:!1,error:"invalid_period"};let a=(o??"membership")==="membership"&&i?`&plan=${encodeURIComponent(i)}${l?`&period=${l}`:""}`:"",{base:u,token:d}=await t.getCloud();if(!u)return{ok:!1};let m=await zr(u,d),g=`${u}/pay?tab=${o??"membership"}${a}${m?`&${m}`:""}&redirect=${encodeURIComponent(`${u}/account`)}`;return await t.openExternal(g),{ok:!0}}),t.handle("profile:publicOrigin",async s=>{if(!t.isTrustedSender(s))return n;let{base:o}=await t.getCloud();if(!o)return{ok:!1};try{let i=await fetch(`${o}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});i.body?.cancel().catch(()=>{});let l=i.status>=300&&i.status<400?i.headers.get("location"):null;return l&&/^https?:\/\//i.test(l)?{ok:!0,origin:new URL(l).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async s=>{if(!t.isTrustedSender(s))return e;let o=await r();if(!o.token)return{status:401,json:null};try{return await Ae(o,"GET","/api/token-quota/my",void 0,15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),t.handle("account:useResetCard",async(s,o)=>{if(!t.isTrustedSender(s))return e;let i=await r();if(!i.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 l=o??"both";try{return await Ae(i,"POST","/api/token-quota/reset-card/use",{type:l},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:bgConvert",async(s,o)=>{if(!t.isTrustedSender(s))return e;let i=await r();if(!i.token)return{status:401,json:null};if(!Number.isInteger(o)||o<1||o>100)return{status:400,json:{error:"invalid_percent"}};try{return await Ae(i,"POST","/api/token-quota/background/convert",{percent:o},15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgAutoMain",async(s,o)=>{if(!t.isTrustedSender(s))return e;let i=await r();if(!i.token)return{status:401,json:null};if(typeof o!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await Ae(i,"POST","/api/token-quota/background/auto-main",{enabled:o},15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("feedback:submit",async(s,o)=>{if(!t.isTrustedSender(s))return n;let{base:i,token:l}=await t.getCloud();if(!i||!l)return{ok:!1,error:"not-logged-in"};let a=(o?.description||"").trim();if(!a)return{ok:!1,error:"empty"};if(a.length>1e4)return{ok:!1,error:"description-too-long"};let u=[],d=!1;if(o?.sessionLogJson){let m=vt(o.sessionLogJson);if(m.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};u.push({filename:o.sessionLogName||"tangu-session.json",mime_type:"application/json",size:m.length,data_base64:Fr(m)})}try{let m=await fetch(`${i}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({description:a,attachments:u}),signal:AbortSignal.timeout(2e4)});if(!m.ok){let p=`HTTP ${m.status}`;try{p=(await m.json())?.detail||p}catch{}return{ok:!1,error:p}}return{ok:!0,id:(await m.json().catch(()=>({})))?.id??null,attachmentSkipped:d}}catch(m){return{ok:!1,error:m?.message||String(m)}}}),t.handle("cloud:fetch",async(s,o)=>{if(!t.isTrustedSender(s))return{status:0,error:"untrusted"};let i=o??{},l=typeof i.path=="string"?i.path:"",a=i.projectSource===void 0?null:i.projectSource;if(a!==null&&(typeof a!="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(a)))return{status:0,error:"bad_project_source"};let u=Math.min(12e4,Math.max(1e3,Number(i.timeoutMs)||15e3)),d=typeof i.method=="string"?i.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(d))return{status:0,error:"bad_method"};if(!l.startsWith("/"))return{status:0,error:"bad_path"};let{base:m,token:g}=await t.getCloud();if(!String(m||""))return{status:0,error:"no_cloud_url"};let p=We(m,l);if(!p)return{status:0,error:"bad_path"};if(!g)return{status:401,error:"not_signed_in"};let y=i.body!==void 0&&d!=="GET"&&d!=="DELETE",f=new AbortController,w=setTimeout(()=>f.abort(),u);try{let P=await fetch(p,{method:d,headers:{Authorization:`Bearer ${g}`,...y?{"Content-Type":"application/json"}:{},...a?{"X-Project-Source":a}:{}},body:y?JSON.stringify(i.body):void 0,signal:f.signal});return{status:P.status,json:await P.json().catch(()=>null)}}catch(P){return{status:0,error:String(P?.message||P)}}finally{clearTimeout(w)}}),Hr(t)}import{createHash as Gi}from"node:crypto";import{existsSync as Ji,promises as Xi}from"node:fs";import Ki from"node:path";import{EventEmitter as Pi}from"node:events";import{stat as Di}from"node:fs";import{readdir as Ri,stat as $i}from"node:fs/promises";import*as re from"node:path";import{lstat as Vr,readdir as ni,realpath as ri,stat as si}from"node:fs/promises";import{join as oi,resolve as ii,sep as Yr}from"node:path";import{Readable as ai}from"node:stream";var Re={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},ut={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Re.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(ut);var Kr="READDIRP_RECURSIVE_ERROR",li=new Set(["ENOENT","EPERM","EACCES","ELOOP",Kr]),Gr=[Re.DIR_TYPE,Re.EVERYTHING_TYPE,Re.FILE_DIR_TYPE,Re.FILE_TYPE],ci=new Set([Re.DIR_TYPE,Re.EVERYTHING_TYPE,Re.FILE_DIR_TYPE]),ui=new Set([Re.EVERYTHING_TYPE,Re.FILE_DIR_TYPE,Re.FILE_TYPE]),di=t=>li.has(t.code),fi=process.platform==="win32",Jr=t=>!0,Xr=t=>{if(t===void 0)return Jr;if(typeof t=="function")return t;if(typeof t=="string"){let e=t.trim();return n=>n.basename===e}if(Array.isArray(t)){let e=t.map(n=>n.trim());return n=>e.some(r=>n.basename===r)}return Jr},$n=class extends ai{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??ut.highWaterMark});let n={...ut,...e},r=n.root??ut.root,s=n.type??ut.type;this._fileFilter=Xr(n.fileFilter),this._directoryFilter=Xr(n.directoryFilter);let o=n.lstat?Vr:si;fi?this._stat=l=>o(l,{bigint:!0}):this._stat=o,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:ut.depth,this._wantsDir=ci.has(s),this._wantsFile=ui.has(s),this._wantsEverything=s===Re.EVERYTHING_TYPE,this._root=ii(r),this._relStart=this._root.endsWith(Yr)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let i={path:this._root,depth:1};i.pending=this._exploreDir(this._root,1),this.parents=[i],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:s,depth:o}=n,i=r.splice(0,e).map(a=>this._formatEntry(a,s)),l=this._isDirent?i:await Promise.all(i);for(let a of l){if(!a)continue;if(this.destroyed)return;let u=this._getEntryType(a);typeof u!="string"&&(u=await u),u==="directory"&&this._directoryFilter(a)?(o<=this._maxDepth&&this.parents.push({path:a.fullPath,depth:o+1}),this._wantsDir&&(this.push(a),e--)):(u==="file"||this._includeAsFile(a))&&this._fileFilter(a)&&this._wantsFile&&(this.push(a),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}let o=s.pending??this._exploreDir(s.path,s.depth),i=this.parents[this.parents.length-1];if(i&&!i.pending&&(i.pending=this._exploreDir(i.path,i.depth)),this.parent=await o,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await ni(e,this._rdOptions)}catch(s){this._onError(s)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,s=oi(n,r),o={path:s.slice(this._relStart),fullPath:s,basename:r};return this._isDirent?(o.dirent=e,o):this._stat(s).then(i=>(o.stats=i,o),i=>{this._onError(i)})}_onError(e){di(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let n=e[this._statsProp];return n.isFile()?"file":n.isDirectory()?"directory":n.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let n=e.fullPath;try{let r=await ri(n),s=await Vr(r);if(s.isFile())return"file";if(s.isDirectory()){let o=r.length;if(n.startsWith(r)&&n[o]===Yr){let i=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return i.code=Kr,this._onError(i),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function Zr(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Re.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!Gr.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${Gr.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:t};return n&&(r.type=n),new $n(r)}import{watch as mi,unwatchFile as Qr,watchFile as pi}from"node:fs";import{realpath as Mn,lstat as gi,open as hi,stat as ts}from"node:fs/promises";import{type as yi}from"node:os";import*as ge from"node:path";var wi="data",Un="end",ns="close",rn=()=>{};var sn=process.platform,jn=sn==="win32",bi=sn==="darwin",Si=sn==="linux",ki=sn==="freebsd",rs=yi()==="OS400",he={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},je=he,Ei="watch",_i={lstat:gi,stat:ts},rt="listeners",Qt="errHandlers",dt="rawEmitters",vi=[rt,Qt,dt],xi=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"]),Ci=t=>xi.has(ge.extname(t).slice(1).toLowerCase()),Nn=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},xt=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},Ti=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},Ct=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},ss=t=>t instanceof Set?t.size===0:!t,en=new Map;function es(t,e,n,r,s){let o=(i,l)=>{n(t),s(i,l,{watchedPath:t}),l&&t!==l&&tn(ge.resolve(t,l),rt,ge.join(t,l))};try{return mi(t,{persistent:e.persistent},o)}catch(i){r(i);return}}var tn=(t,e,n,r,s)=>{let o=en.get(t);o&&Nn(o[e],i=>{i(n,r,s)})},Ai=(t,e,n,r)=>{let{listener:s,errHandler:o,rawEmitter:i}=r,l=en.get(e),a;if(!n.persistent)return a=es(t,n,s,o,i),a?a.close.bind(a):void 0;if(l)xt(l,rt,s),xt(l,Qt,o),xt(l,dt,i);else{if(a=es(t,n,tn.bind(null,e,rt),o,tn.bind(null,e,dt)),!a)return;a.on(je.ERROR,async u=>{let d=tn.bind(null,e,Qt);if(l&&(l.watcherUnusable=!0),jn&&u.code==="EPERM")try{await(await hi(t,"r")).close(),d(u)}catch{}else d(u)}),l={listeners:s,errHandlers:o,rawEmitters:i,watcher:a},en.set(e,l)}return()=>{Ct(l,rt,s),Ct(l,Qt,o),Ct(l,dt,i),ss(l.listeners)&&(l.watcher.close(),en.delete(e),vi.forEach(Ti(l)),l.watcher=void 0,Object.freeze(l))}},On=new Map,Ii=(t,e,n,r)=>{let{listener:s,rawEmitter:o}=r,i=On.get(e),l=i&&i.options;return l&&(l.persistent<n.persistent||l.interval>n.interval)&&(Qr(e),i=void 0),i?(xt(i,rt,s),xt(i,dt,o)):(i={listeners:s,rawEmitters:o,options:n,watcher:pi(e,n,(a,u)=>{Nn(i.rawEmitters,m=>{m(je.CHANGE,e,{curr:a,prev:u})});let d=a.mtimeMs;(a.size!==u.size||d>u.mtimeMs||d===0)&&Nn(i.listeners,m=>m(t,a))})},On.set(e,i)),()=>{Ct(i,rt,s),Ct(i,dt,o),ss(i.listeners)&&(On.delete(e),Qr(e),i.options=i.watcher=void 0,Object.freeze(i))}},nn=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,s=ge.dirname(e),o=ge.basename(e);this.fsw._getWatchedDir(s).add(o);let l=ge.resolve(e),a={persistent:r.persistent};n||(n=rn);let u;if(r.usePolling){let d=r.interval!==r.binaryInterval;a.interval=d&&Ci(o)?r.binaryInterval:r.interval,u=Ii(e,l,a,{listener:n,rawEmitter:this.fsw._emitRaw})}else u=Ai(e,l,a,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return u}_handleFile(e,n,r){if(this.fsw.closed)return;let s=ge.dirname(e),o=ge.basename(e),i=this.fsw._getWatchedDir(s),l=n;if(i.has(o))return;let a=async(d,m)=>{if(this.fsw._throttle(Ei,e,5)){if(!m||m.mtimeMs===0)try{let g=await ts(e);if(this.fsw.closed)return;let p=g.atimeMs,y=g.mtimeMs;if((!p||p<=y||y!==l.mtimeMs)&&this.fsw._emit(je.CHANGE,e,g),(bi||Si||ki)&&l.ino!==g.ino){this.fsw._closeFile(d),l=g;let f=this._watchWithNodeFs(e,a);f&&this.fsw._addPathCloser(d,f)}else l=g}catch{this.fsw._remove(s,o)}else if(i.has(o)){let g=m.atimeMs,p=m.mtimeMs;(!g||g<=p||p!==l.mtimeMs)&&this.fsw._emit(je.CHANGE,e,m),l=m}}},u=this._watchWithNodeFs(e,a);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(je.ADD,e,0))return;this.fsw._emit(je.ADD,e,n)}return u}async _handleSymlink(e,n,r,s){if(this.fsw.closed)return;let o=e.fullPath,i=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let l;try{l=await Mn(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(i.has(s)?this.fsw._symlinkPaths.get(o)!==l&&(this.fsw._symlinkPaths.set(o,l),this.fsw._emit(je.CHANGE,r,e.stats)):(i.add(s),this.fsw._symlinkPaths.set(o,l),this.fsw._emit(je.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(o))return!0;this.fsw._symlinkPaths.set(o,!0)}_handleRead(e,n,r,s,o,i,l){e=ge.join(e,"");let a=s?`${e}:${s}`:e;if(l=this.fsw._throttle("readdir",a,1e3),!l)return;let u=this.fsw._getWatchedDir(r.path),d=new Set,m=this.fsw._readdirp(e,{fileFilter:g=>r.filterPath(g),directoryFilter:g=>r.filterDir(g)});if(m)return m.on(wi,async g=>{if(this.fsw.closed){m=void 0;return}let p=g.path,y=ge.join(e,p);if(d.add(p),!(g.stats.isSymbolicLink()&&await this._handleSymlink(g,e,y,p))){if(this.fsw.closed){m=void 0;return}(p===s||!s&&!u.has(p))&&(this.fsw._incrReadyCount(),y=ge.join(o,ge.relative(o,y)),this._addToNodeFs(y,n,r,i+1))}}).on(je.ERROR,this._boundHandleError),new Promise((g,p)=>{if(!m)return p();m.once(Un,()=>{if(this.fsw.closed){m=void 0;return}let y=l?l.clear():!1;g(void 0),u.getChildren().filter(f=>f!==e&&!d.has(f)).forEach(f=>{this.fsw._remove(e,f)}),m=void 0,y&&this._handleRead(e,!1,r,s,o,i,l)})})}async _handleDir(e,n,r,s,o,i,l){let a=this.fsw._getWatchedDir(ge.dirname(e)),u=a.has(ge.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!o&&!u&&this.fsw._emit(je.ADD_DIR,e,n),a.add(ge.basename(e)),this.fsw._getWatchedDir(e);let d,m,g=this.fsw.options.depth;if((g==null||s<=g)&&!this.fsw._symlinkPaths.has(l)){if(!o&&(await this._handleRead(e,r,i,o,e,s,d),this.fsw.closed))return;m=this._watchWithNodeFs(e,(p,y)=>{y&&y.mtimeMs===0||this._handleRead(p,!1,i,o,e,s,d)})}return m}async _addToNodeFs(e,n,r,s,o){let i=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return i(),!1;let l=this.fsw._getWatchHelpers(e);r&&(l.filterPath=a=>r.filterPath(a),l.filterDir=a=>r.filterDir(a));try{let a=await _i[l.statMethod](l.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(l.watchPath,a))return i(),!1;let u=this.fsw.options.followSymlinks,d;if(a.isDirectory()){let m=ge.resolve(e),g=u?await Mn(e):e;if(this.fsw.closed||(d=await this._handleDir(l.watchPath,a,n,s,o,l,g),this.fsw.closed))return;m!==g&&g!==void 0&&this.fsw._symlinkPaths.set(m,g)}else if(a.isSymbolicLink()){let m=u?await Mn(e):e;if(this.fsw.closed)return;let g=ge.dirname(l.watchPath);if(this.fsw._getWatchedDir(g).add(l.watchPath),this.fsw._emit(je.ADD,l.watchPath,a),d=await this._handleDir(g,a,n,s,e,l,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(ge.resolve(e),m)}else d=this._handleFile(l.watchPath,a,n);return i(),d&&this.fsw._addPathCloser(e,d),!1}catch(a){if(this.fsw._handleError(a))return i(),e}}};var Fn="/",Mi="//",cs=".",Oi="..",Ni="string",Ui=/\\/g,us=/\/\//g,ji=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Fi=/^\.[/\\]/;function on(t){return Array.isArray(t)?t:[t]}var Ln=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Li(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=re.relative(t.path,e);return n?!n.startsWith("..")&&!re.isAbsolute(n):!1}return!1}:()=>!1}function Hi(t){if(typeof t!="string")throw new Error("string expected");t=re.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(us,"/"),e&&(t="/"+t),t}function os(t,e,n){let r=Hi(e);for(let s=0;s<t.length;s++){let o=t[s];if(o(r,n))return!0}return!1}function zi(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=on(t).map(s=>Li(s));return e==null?(s,o)=>os(r,s,o):os(r,e)}var is=t=>{let e=on(t).flat();if(!e.every(n=>typeof n===Ni))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(ds)},as=t=>{let e=t.replace(Ui,Fn),n=!1;return e.startsWith(Mi)&&(n=!0),e=e.replace(us,Fn),n&&(e=Fn+e),e},ds=t=>as(re.normalize(as(t))),ls=(t="")=>e=>typeof e=="string"?ds(re.isAbsolute(e)?e:re.join(t,e)):e,qi=(t,e)=>re.isAbsolute(t)?t:re.join(e,t),Bi=Object.freeze(new Set),Hn=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!==cs&&e!==Oi&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await Ri(r)}catch{this._removeWatcher&&this._removeWatcher(re.dirname(r),re.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=rn,this.items=Bi,Object.freeze(this)}},Wi="stat",Vi="lstat",zn=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let s=e;this.path=e=e.replace(Fi,""),this.watchPath=s,this.fullWatchPath=re.resolve(s),this.dirParts=[],this.dirParts.forEach(o=>{o.length>1&&o.pop()}),this.followSymlinks=n,this.statMethod=n?Wi:Vi}entryPath(e){return re.join(this.watchPath,re.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},an=class extends Pi{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?on(e.ignored):on([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};rs&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let o=process.env.CHOKIDAR_USEPOLLING;if(o!==void 0){let a=o.toLowerCase();a==="false"||a==="0"?s.usePolling=!1:a==="true"||a==="1"?s.usePolling=!0:s.usePolling=!!a}let i=process.env.CHOKIDAR_INTERVAL;i&&(s.interval=Number.parseInt(i,10));let l=0;this._emitReady=()=>{l++,l>=this._readyCount&&(this._emitReady=rn,this._readyEmitted=!0,process.nextTick(()=>this.emit(he.READY)))},this._emitRaw=(...a)=>this.emit(he.RAW,...a),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new nn(this),Object.freeze(s)}_addIgnoredPath(e){if(Ln(e)){for(let n of this._ignoredPaths)if(Ln(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)Ln(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let o=is(e);return s&&(o=o.map(i=>qi(i,s))),o.forEach(i=>{this._removeIgnoredPath(i)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async i=>{let l=await this._nodeFsHandler._addToNodeFs(i,!r,void 0,0,n);return l&&this._emitReady(),l})).then(i=>{this.closed||i.forEach(l=>{l&&this.add(re.dirname(l),re.basename(n||l))})}),this}unwatch(e){if(this.closed)return this;let n=is(e),{cwd:r}=this.options;return n.forEach(s=>{!re.isAbsolute(s)&&!this._closers.has(s)&&(r&&(s=re.join(r,s)),s=re.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let s=r();s instanceof Promise&&e.push(s)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let o=(this.options.cwd?re.relative(this.options.cwd,r):r)||cs;e[o]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==he.ERROR&&this.emit(he.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let s=this.options;jn&&(n=re.normalize(n)),s.cwd&&(n=re.relative(s.cwd,n));let o=[n];r!=null&&o.push(r);let i=s.awaitWriteFinish,l;if(i&&(l=this._pendingWrites.get(n)))return l.lastChange=new Date,this;if(s.atomic){if(e===he.UNLINK)return this._pendingUnlinks.set(n,[e,...o]),setTimeout(()=>{this._pendingUnlinks.forEach((a,u)=>{this.emit(...a),this.emit(he.ALL,...a),this._pendingUnlinks.delete(u)})},typeof s.atomic=="number"?s.atomic:100),this;e===he.ADD&&this._pendingUnlinks.has(n)&&(e=he.CHANGE,this._pendingUnlinks.delete(n))}if(i&&(e===he.ADD||e===he.CHANGE)&&this._readyEmitted){let a=(u,d)=>{u?(e=he.ERROR,o[0]=u,this.emitWithAll(e,o)):d&&(o.length>1?o[1]=d:o.push(d),this.emitWithAll(e,o))};return this._awaitWriteFinish(n,i.stabilityThreshold,e,a),this}if(e===he.CHANGE&&!this._throttle(he.CHANGE,n,50))return this;if(s.alwaysStat&&r===void 0&&(e===he.ADD||e===he.ADD_DIR||e===he.CHANGE)){let a=s.cwd?re.join(s.cwd,n):n,u;try{u=await $i(a)}catch{}if(!u||this.closed)return;o.push(u)}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(he.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let o=s.get(n);if(o)return o.count++,!1;let i,l=()=>{let u=s.get(n),d=u?u.count:0;return s.delete(n),clearTimeout(i),u&&clearTimeout(u.timeoutObject),d};i=setTimeout(l,r);let a={timeoutObject:i,clear:l,count:0};return s.set(n,a),a}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,s){let o=this.options.awaitWriteFinish;if(typeof o!="object")return;let i=o.pollInterval,l,a=e;this.options.cwd&&!re.isAbsolute(e)&&(a=re.join(this.options.cwd,e));let u=new Date,d=this._pendingWrites;function m(g){Di(a,(p,y)=>{if(p||!d.has(e)){p&&p.code!=="ENOENT"&&s(p);return}let f=Number(new Date);g&&y.size!==g.size&&(d.get(e).lastChange=f);let w=d.get(e);f-w.lastChange>=n?(d.delete(e),s(void 0,y)):l=setTimeout(m,i,y)})}d.has(e)||(d.set(e,{lastChange:u,cancelWait:()=>(d.delete(e),clearTimeout(l),r)}),l=setTimeout(m,i))}_isIgnored(e,n){if(this.options.atomic&&ji.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,o=(this.options.ignored||[]).map(ls(r)),l=[...[...this._ignoredPaths].map(ls(r)),...o];this._userIgnored=zi(l,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new zn(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=re.resolve(e);return this._watched.has(n)||this._watched.set(n,new Hn(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let s=re.join(e,n),o=re.resolve(s);if(r=r??(this._watched.has(s)||this._watched.has(o)),!this._throttle("remove",s,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(s).getChildren().forEach(g=>this._remove(s,g));let a=this._getWatchedDir(e),u=a.has(n);a.remove(n),this._symlinkPaths.has(o)&&this._symlinkPaths.delete(o);let d=s;if(this.options.cwd&&(d=re.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===he.ADD)return;this._watched.delete(s),this._watched.delete(o);let m=r?he.UNLINK_DIR:he.UNLINK;u&&!this._isIgnored(s)&&this._emit(m,s),this._closePath(s)}_closePath(e){this._closeFile(e);let n=re.dirname(e);this._getWatchedDir(n).remove(re.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:he.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},s=Zr(e,r);return this._streams.add(s),s.once(ns,()=>{s=void 0}),s.once(Un,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Yi(t,e={}){let n=new an(e);return n.add(t),n}var fs={watch:Yi,FSWatcher:an};var ms={fs:Xi,path:Ki,sha256Hex:t=>Gi("sha256").update(t).digest("hex"),tmpTag:()=>process.pid,existsSync:Ji,watch(t,e,n){let r=fs.watch(t,{ignoreInitial:!0,depth:e.depth,ignored:e.ignored});return r.on("change",n.change),r.on("add",n.add),r.on("unlink",n.unlink),r.on("unlinkDir",n.unlinkDir),r}};import{readdirSync as Zi,lstatSync as Qi,readFileSync as qn,writeFileSync as ea,realpathSync as ps}from"node:fs";import{join as Wn,extname as ta,sep as na}from"node:path";var Bn=300,gs=5*1024*1024,hs=20*1024*1024,ra=50*1024*1024,sa=new Set(["node_modules"]),oa=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function ys(t,e){let n=[],r=0,s=(o,i)=>{for(let l of Zi(o)){if(l.startsWith("."))continue;let a=Wn(o,l),u;try{u=Qi(a)}catch{continue}if(u.isSymbolicLink())continue;let d=i?`${i}/${l}`:l;if(u.isDirectory()){sa.has(l)||s(a,d);continue}if(!u.isFile()||l.endsWith(".d.ts"))continue;if(n.length>=Bn)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Bn}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let m=ta(l).toLowerCase(),g,p=e.mimeOf(m)??"application/octet-stream";if(oa.has(m)){let y=e.transpile(qn(a,"utf8"),m,d);g=Buffer.from(y??"","utf8"),p="text/javascript"}else g=qn(a);if(g.length>gs)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${d}`);if(r+=g.length,r>hs)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");n.push({path:d,content_b64:g.toString("base64"),content_type:p,size:g.length})}};if(s(t,""),!n.length)throw new Error("\u9879\u76EE\u4E3A\u7A7A\uFF0C\u6CA1\u6709\u53EF\u53D1\u5E03\u7684\u6587\u4EF6");return{files:n,totalBytes:r}}var ws=".forsion-connect.json";function bs(t){try{return JSON.parse(qn(Wn(t,ws),"utf8"))}catch{return{}}}function Ss(t,e){try{ea(Wn(t,ws),JSON.stringify(e,null,2)+`
2
+ `,"utf8")}catch{}}function ks(t){let e={"/__forsion/chat":{method:"POST",path:"/api/chat/completions",auth:!0},"/__forsion/images":{method:"POST",path:"/api/images/generations",auth:!0},"/__forsion/user":{method:"GET",path:"/api/brain/users/me",auth:!0},"/__forsion/models":{method:"GET",path:"/api/models",auth:!1},"/__forsion/config":{method:"GET",path:"/api/connect/config",auth:!1},"/__forsion/agent":{method:"POST",path:"/api/agent/runs",auth:!0,agentRun:!0}};function n(r){if(e[r])return e[r];let s="/__forsion/agent-events/";if(r.startsWith(s)){let o=r.slice(s.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(r,s)=>{let[o,i]=(r.url||"").split("?"),l=(y,f)=>{s.headersSent||(s.statusCode=y,s.setHeader("Content-Type","application/json")),s.end(JSON.stringify({detail:f}))},a=n(o);if(!a)return l(404,"unknown connect endpoint");if((r.method||"GET")!==a.method)return l(405,"method not allowed");let u="",d="";try{({base:u,token:d}=await t())}catch{}if(!u)return l(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(a.auth&&!d)return l(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let m;if(a.method==="POST"){let y=[],f=0;try{for await(let w of r){if(f+=w.length,f>ra)return r.destroy(),l(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");y.push(w)}}catch(w){return l(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${w?.message||String(w)}`)}m=Buffer.concat(y)}if(a.agentRun){let y;try{y=JSON.parse((m||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return l(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}m=Buffer.from(JSON.stringify({session_id:typeof y.session_id=="string"?y.session_id:"",message:typeof y.message=="string"?y.message:"",app_id:"connect",agent_config:{}}))}let g=new AbortController,p=setTimeout(()=>g.abort(new Error("proxy timeout")),a.timeoutMs??3e5);r.on("close",()=>g.abort());try{let y=await fetch(u+a.path+(i?`?${i}`:""),{method:a.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...d?{Authorization:`Bearer ${d}`}:{}},body:m&&m.length?new Uint8Array(m):void 0,signal:g.signal});if(s.statusCode=y.status,s.setHeader("Content-Type",y.headers.get("content-type")||"application/json"),s.setHeader("Cache-Control","no-store"),y.body)for await(let f of y.body)s.write(f);s.end()}catch(y){let f=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${y?.message||String(y)}`;if(s.headersSent){try{s.write(`data: ${JSON.stringify({error:f})}
3
3
 
4
- `)}catch{}r.end()}else i(502,x)}finally{clearTimeout(g)}}}var sr=`
4
+ `)}catch{}s.end()}else l(502,f)}finally{clearTimeout(p)}}}var Es=`
5
5
  (function () {
6
6
  'use strict';
7
7
  if (window.forsion) return;
@@ -190,26 +190,105 @@ function Jn(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
- `,Bs=t=>({transpile:(e,n,s)=>t.transpileForServe(e,n,s),mimeOf:e=>t.mimeOf(e)});function Qt(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function en(t){t.setPreviewHooks({sdkJs:sr,proxy:rr(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?tr(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 ge(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=Kn(t.projectsRoot());if(s=Kn(n.dir),s!==o&&!s.startsWith(o+Ls))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}=Qn(s,Bs(t));if(!o.some(h=>h.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:i,json:l}=await ge(r,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:o},3e5);return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200?{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${i}`,used:l?.used,limit:l?.limit}:(nr(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 ge(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 ge(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 ge(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 ge(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 Ws}from"node:crypto";async function lt(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 or=t=>`${t.seq}:${t.hash}`,Vs=t=>Ws("sha256").update(t).digest("hex");function tn(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 Tt(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 i=await fetch(r,{...o,headers:{...o.headers,Authorization:`Bearer ${a}`}});if(i.status===409){let l=await i.json().catch(()=>({}));throw new Error(`cas-conflict ${String(l.code??"")}: seq=${String(l.seq??"?")}`)}if(!i.ok){let l=await i.text().catch(()=>"");throw new Error(`penzor ${o.method??"GET"} ${i.status}: ${l.slice(0,200)}`)}return i};return{kind:"penzor",async walk(r){let o=await s(n("/manifest"),{method:"GET",signal:r}),{files:a}=await o.json();return a.map(i=>({key:i.path,size:i.size,mtimeMs:i.mtimeMs,id:or(i)}))},async readFile(r,o){let i=await(await s(n(`/file?path=${encodeURIComponent(r)}`),{method:"GET",signal:o})).json(),l=await fetch(i.url,{signal:o});if(!l.ok)throw new Error(`penzor blob GET ${l.status}: ${r}`);let h=Buffer.from(await l.arrayBuffer());if(Vs(h)!==i.hash)throw new Error(`penzor hash mismatch: ${r}`);return h},async writeFile(r,o,a,i,l){let h=tn(l),d=new URLSearchParams({path:r,mtimeMs:String(Math.floor(a)||0)});h&&(d.set("baseSeq",String(h.baseSeq)),h.baseHash&&d.set("baseHash",h.baseHash));let u=await(await s(n(`/file?${d.toString()}`),{method:"PUT",body:new Uint8Array(o),headers:{"Content-Type":"application/octet-stream"},signal:i})).json();return{key:r,size:u.size,mtimeMs:u.mtimeMs,id:or(u)}},async rm(r,o,a){let i=tn(a),l=new URLSearchParams({path:r});i&&i.baseSeq>0&&(l.set("baseSeq",String(i.baseSeq)),i.baseHash&&l.set("baseHash",i.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 xt="forsion-diagnostics",ar=50*1024*1024,ir=new Map;async function Ys(t,e){let n=ir.get(e);if(n)return{id:n};let s=await lt(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?(ir.set(e,r),{id:r}):{error:"penzor-auth-unverified"}}var nn=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function rn(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)||r===xt)return{error:"penzor-bad-vault"};let o=await Ys(n.cloudUrl,n.token);if("error"in o)return o;let a=n.token;return{remote:Tt({baseUrl:n.cloudUrl,vault:r,getToken:()=>a}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${o.id}|${r}`,maxFileBytes:ar}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{readFileSync as Gs,writeFileSync as Js,mkdirSync as Ks,chmodSync as Xs,renameSync as Zs}from"node:fs";import{join as Qs}from"node:path";function Te(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)),i=a.userId??a.sub;return typeof i!="string"&&typeof i!="number"||!String(i).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(i)}`}catch{return null}}function sn(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 cr(t,e=Date.now()){let n=sn(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function eo(t,e=Date.now()){let n=sn(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var to=36e5;function ur(t,e=Date.now()){return!!t&&cr(t,e)>=to}async function dr(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),i=typeof a?.token=="string"?a.token:"";return i&&i!==e?i:null}catch{return null}}var At=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,no=(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 fr(t){let e=()=>Qs(t.homeDir(),"auth-accounts.json"),n=(f,u)=>{Ks(t.homeDir(),{recursive:!0});let g=`${f}.tmp`;Js(g,JSON.stringify(u,null,2),{encoding:"utf8",mode:384}),Xs(g,384),Zs(g,f)},s=()=>{try{let f=JSON.parse(Gs(e(),"utf8"));return Array.isArray(f.accounts)?f.accounts.filter(u=>u&&typeof u.token=="string"&&u.id===Te(u.cloudUrl,u.token)):[]}catch{return[]}},r=(f,u)=>{let g=Te(f.cloudUrl||"",f.token||"");if(!g||!f.token||!f.cloudUrl)return;let S=s(),x=S.find(k=>k.id===g),w=sn(f.token),F={...x,id:g,cloudUrl:f.cloudUrl.replace(/\/+$/,""),token:f.token,username:u?.username||x?.username||w?.username,nickname:u?.nickname||x?.nickname};JSON.stringify(x)!==JSON.stringify(F)&&n(e(),{version:1,accounts:[...S.filter(k=>k.id!==g),F]})},o=()=>{let f=t.readCreds();r(f);let u=Te(f.cloudUrl,f.token);return s().map(({token:g,...S})=>({...S,active:S.id===u}))},a=f=>{let u=s().find(g=>g.id===f);if(!u)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:u.cloudUrl,token:u.token}},i=f=>{let u=Te(f.cloudUrl||"",f.token||"");u&&n(e(),{version:1,accounts:s().filter(g=>g.id!==u)})},l=null;return{rememberForsionAccount:r,forsionAccounts:o,savedForsionAccount:a,forgetForsionAccount:i,cancelForsionLogin:()=>{l?.abort(),l=null},forsionDeviceLogin:async(f,u,g)=>{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 S=new AbortController;l=S;let x=()=>{if(S.signal.aborted||l!==S)throw new Error("Sign-in cancelled.")};try{let w=f.replace(/\/+$/,""),F;try{F=await fetch(`${w}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([S.signal,AbortSignal.timeout(15e3)])}).then(j=>j.json())}catch(j){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${w}:${j?.message||j}`)}if(x(),!F?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let k=F.verification_uri_complete||`${F.verification_uri}?code=${F.user_code}`,A=new URL(`${w}/auth`);A.searchParams.set("logout","1"),A.searchParams.set("app","forsion-desktop"),A.searchParams.set("redirect",k);let U=A.toString();u?.({url:U,userCode:String(F.user_code||"")}),t.openExternal(U);let M=Date.now()+(F.expires_in||600)*1e3,B=(F.interval||2)*1e3;for(;Date.now()<M;){await no(B,S.signal),x();let j=null;try{j=await fetch(`${w}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:F.device_code}),signal:AbortSignal.any([S.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 K=await j.json().catch(()=>({status:"pending"}));if(x(),K.status==="approved"&&K.token){let se={cloudUrl:w,token:K.token};return await g(se,x),x(),{token:K.token,cloudUrl:w}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===S&&(l=null)}},readAccounts:s}}var hr=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],on=t=>hr.every(e=>typeof t[e]=="function");function an(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},s=fr(t),r=0,o=()=>{let i=t.readCreds();return At(i.cloudUrl,i.token)},a=null;t.handle("auth:status",async i=>{if(!t.isTrustedSender(i))return n;let l=r,h=o(),{base:d}=await t.getCloud(),f=t.readCreds().token,u=f?await lt(d,f):null,g=await t.accountBackendState(),{base:S}=await t.getCloud(),x=t.readCreds(),w=At(S,x.token)!==At(d,f),F=At(d,f);!w&&u?.status==="ok"&&u.user&&(a={key:F,user:u.user},s.rememberForsionAccount({...x,cloudUrl:d},u.user));let k=w?void 0:u?.status==="ok"?u.user:u?.status==="offline"&&a?.key===F?a.user:void 0;if(w)return{loggedIn:!!x.token,tokenValid:null,cloudUrl:S,accountId:Te(S,x.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:x.token?"tangu-login":null,backendState:g};if(u?.status==="expired"){await t.accountTransition(async()=>{if(l!==r||o()!==h)return;let U=()=>{if(l!==r||o()!==h)throw lr};try{await t.accountClear(U,()=>{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(M){if(M!==lr)throw M}});let A=t.readCreds();return{loggedIn:!!A.token,tokenValid:null,cloudUrl:A.cloudUrl||d,accountId:Te(A.cloudUrl||d,A.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:A.token?"tangu-login":null,backendState:g}}return{loggedIn:!!f,tokenValid:u&&u.status==="ok"?!0:null,cloudUrl:d,accountId:Te(d,f),username:k?.username||null,nickname:k?.nickname||null,avatar:k?.avatar||null,membershipTier:k?.membershipTier||null,tokenSource:f?"tangu-login":null,backendState:g}}),t.handle("auth:accounts",i=>t.isTrustedSender(i)?s.forsionAccounts():[]),t.handle("auth:switchAccount",async(i,l)=>{if(!t.isTrustedSender(i))return e;if(typeof l!="string")throw new Error("Invalid account.");let h=++r;return s.cancelForsionLogin(),t.accountTransition(async()=>{let d=s.savedForsionAccount(l);return await t.accountCommit(d,()=>{if(h!==r)throw new Error("Account switch cancelled.")},()=>{s.rememberForsionAccount(d),a=null}),{ok:!0,cloudUrl:d.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(i,l)=>{if(!t.isTrustedSender(i))return e;let h=++r;s.cancelForsionLogin();let{base:d}=await t.getCloud();if(h!==r)throw new Error("Sign-in cancelled.");let f=(l||d||"").trim();return{ok:!0,cloudUrl:(await s.forsionDeviceLogin(f,g=>t.broadcast("auth:device",g),(g,S)=>t.accountTransition(()=>t.accountCommit(g,()=>{if(S(),h!==r)throw new Error("Sign-in cancelled.")},()=>{s.rememberForsionAccount(g),a=null})))).cloudUrl}}),t.handle("auth:logout",async i=>t.isTrustedSender(i)?(++r,s.cancelForsionLogin(),t.accountTransition(async()=>{let{base:l}=await t.getCloud(),h=t.readCreds();return await t.accountClear(void 0,()=>{s.forgetForsionAccount(h),a=null,l&&h.token&&fetch(`${l}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${h.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:i,current:l})=>{++r,s.cancelForsionLogin(),i.token&&!l.token&&s.forgetForsionAccount(i),a=null,s.rememberForsionAccount(l)}),t.setTokenRefresher(async i=>{let l=r,h=o(),d=t.readCreds().token;if(!ur(d))return;let{base:f}=await t.getCloud(),u=await dr(f,d,i,`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()!==h||(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 lr=Symbol("stale-auth-intent");import{promises as nt}from"node:fs";import Be from"node:path";import{createHash as ro}from"node:crypto";var ln=null;function mr(t){ln=t}function pe(){if(!ln)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return ln}var ye=()=>pe().accountId();function ct(t=ye()){return t?ro("sha256").update(t).digest("hex"):"signed-out"}var xe=(t=ye())=>pe().readConfig(t),Oe=(t,e=ye())=>pe().writeConfig(t,e),Ge=(t,e=ye())=>pe().updateConfig(t,e),Fe=(t=ye())=>pe().cloudVaultDir(t),It=t=>pe().isManagedCloudVault(t);import{createHash as li}from"node:crypto";import{promises as ne,existsSync as Vr}from"node:fs";import ie from"node:path";import{EventEmitter as Do}from"node:events";import{stat as Mo}from"node:fs";import{readdir as No,stat as Oo}from"node:fs/promises";import*as Y from"node:path";import{lstat as gr,readdir as so,realpath as oo,stat as io}from"node:fs/promises";import{join as ao,resolve as lo,sep as pr}from"node:path";import{Readable as co}from"node:stream";var Se={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Je={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Se.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(Je);var Sr="READDIRP_RECURSIVE_ERROR",uo=new Set(["ENOENT","EPERM","EACCES","ELOOP",Sr]),yr=[Se.DIR_TYPE,Se.EVERYTHING_TYPE,Se.FILE_DIR_TYPE,Se.FILE_TYPE],fo=new Set([Se.DIR_TYPE,Se.EVERYTHING_TYPE,Se.FILE_DIR_TYPE]),ho=new Set([Se.EVERYTHING_TYPE,Se.FILE_DIR_TYPE,Se.FILE_TYPE]),mo=t=>uo.has(t.code),go=process.platform==="win32",wr=t=>!0,br=t=>{if(t===void 0)return wr;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 wr},cn=class extends co{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??Je.highWaterMark});let n={...Je,...e},s=n.root??Je.root,r=n.type??Je.type;this._fileFilter=br(n.fileFilter),this._directoryFilter=br(n.directoryFilter);let o=n.lstat?gr:io;go?this._stat=i=>o(i,{bigint:!0}):this._stat=o,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:Je.depth,this._wantsDir=fo.has(r),this._wantsFile=ho.has(r),this._wantsEverything=r===Se.EVERYTHING_TYPE,this._root=lo(s),this._relStart=this._root.endsWith(pr)?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)),i=this._isDirent?a:await Promise.all(a);for(let l of i){if(!l)continue;if(this.destroyed)return;let h=this._getEntryType(l);typeof h!="string"&&(h=await h),h==="directory"&&this._directoryFilter(l)?(o<=this._maxDepth&&this.parents.push({path:l.fullPath,depth:o+1}),this._wantsDir&&(this.push(l),e--)):(h==="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 so(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=ao(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){mo(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 oo(n),r=await gr(s);if(r.isFile())return"file";if(r.isDirectory()){let o=s.length;if(n.startsWith(s)&&n[o]===pr){let a=new Error(`Circular symlink detected: "${n}" points to "${s}"`);return a.code=Sr,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 vr(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Se.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!yr.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${yr.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 cn(s)}import{watch as po,unwatchFile as Er,watchFile as yo}from"node:fs";import{realpath as un,lstat as wo,open as bo,stat as _r}from"node:fs/promises";import{type as So}from"node:os";import*as Q from"node:path";var vo="data",hn="end",Cr="close",Mt=()=>{};var Nt=process.platform,mn=Nt==="win32",Eo=Nt==="darwin",ko=Nt==="linux",_o=Nt==="freebsd",Tr=So()==="OS400",te={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ae=te,Co="watch",To={lstat:wo,stat:_r},qe="listeners",Rt="errHandlers",Ke="rawEmitters",xo=[qe,Rt,Ke],Ao=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"]),Io=t=>Ao.has(Q.extname(t).slice(1).toLowerCase()),fn=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},ut=(t,e,n)=>{let s=t[e];s instanceof Set||(t[e]=s=new Set([s])),s.add(n)},Ro=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},dt=(t,e,n)=>{let s=t[e];s instanceof Set?s.delete(n):s===n&&delete t[e]},xr=t=>t instanceof Set?t.size===0:!t,Pt=new Map;function kr(t,e,n,s,r){let o=(a,i)=>{n(t),r(a,i,{watchedPath:t}),i&&t!==i&&$t(Q.resolve(t,i),qe,Q.join(t,i))};try{return po(t,{persistent:e.persistent},o)}catch(a){s(a);return}}var $t=(t,e,n,s,r)=>{let o=Pt.get(t);o&&fn(o[e],a=>{a(n,s,r)})},Po=(t,e,n,s)=>{let{listener:r,errHandler:o,rawEmitter:a}=s,i=Pt.get(e),l;if(!n.persistent)return l=kr(t,n,r,o,a),l?l.close.bind(l):void 0;if(i)ut(i,qe,r),ut(i,Rt,o),ut(i,Ke,a);else{if(l=kr(t,n,$t.bind(null,e,qe),o,$t.bind(null,e,Ke)),!l)return;l.on(Ae.ERROR,async h=>{let d=$t.bind(null,e,Rt);if(i&&(i.watcherUnusable=!0),mn&&h.code==="EPERM")try{await(await bo(t,"r")).close(),d(h)}catch{}else d(h)}),i={listeners:r,errHandlers:o,rawEmitters:a,watcher:l},Pt.set(e,i)}return()=>{dt(i,qe,r),dt(i,Rt,o),dt(i,Ke,a),xr(i.listeners)&&(i.watcher.close(),Pt.delete(e),xo.forEach(Ro(i)),i.watcher=void 0,Object.freeze(i))}},dn=new Map,$o=(t,e,n,s)=>{let{listener:r,rawEmitter:o}=s,a=dn.get(e),i=a&&a.options;return i&&(i.persistent<n.persistent||i.interval>n.interval)&&(Er(e),a=void 0),a?(ut(a,qe,r),ut(a,Ke,o)):(a={listeners:r,rawEmitters:o,options:n,watcher:yo(e,n,(l,h)=>{fn(a.rawEmitters,f=>{f(Ae.CHANGE,e,{curr:l,prev:h})});let d=l.mtimeMs;(l.size!==h.size||d>h.mtimeMs||d===0)&&fn(a.listeners,f=>f(t,l))})},dn.set(e,a)),()=>{dt(a,qe,r),dt(a,Ke,o),xr(a.listeners)&&(dn.delete(e),Er(e),a.options=a.watcher=void 0,Object.freeze(a))}},Dt=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let s=this.fsw.options,r=Q.dirname(e),o=Q.basename(e);this.fsw._getWatchedDir(r).add(o);let i=Q.resolve(e),l={persistent:s.persistent};n||(n=Mt);let h;if(s.usePolling){let d=s.interval!==s.binaryInterval;l.interval=d&&Io(o)?s.binaryInterval:s.interval,h=$o(e,i,l,{listener:n,rawEmitter:this.fsw._emitRaw})}else h=Po(e,i,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return h}_handleFile(e,n,s){if(this.fsw.closed)return;let r=Q.dirname(e),o=Q.basename(e),a=this.fsw._getWatchedDir(r),i=n;if(a.has(o))return;let l=async(d,f)=>{if(this.fsw._throttle(Co,e,5)){if(!f||f.mtimeMs===0)try{let u=await _r(e);if(this.fsw.closed)return;let g=u.atimeMs,S=u.mtimeMs;if((!g||g<=S||S!==i.mtimeMs)&&this.fsw._emit(Ae.CHANGE,e,u),(Eo||ko||_o)&&i.ino!==u.ino){this.fsw._closeFile(d),i=u;let x=this._watchWithNodeFs(e,l);x&&this.fsw._addPathCloser(d,x)}else i=u}catch{this.fsw._remove(r,o)}else if(a.has(o)){let u=f.atimeMs,g=f.mtimeMs;(!u||u<=g||g!==i.mtimeMs)&&this.fsw._emit(Ae.CHANGE,e,f),i=f}}},h=this._watchWithNodeFs(e,l);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Ae.ADD,e,0))return;this.fsw._emit(Ae.ADD,e,n)}return h}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 i;try{i=await un(s)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(o)!==i&&(this.fsw._symlinkPaths.set(o,i),this.fsw._emit(Ae.CHANGE,s,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(o,i),this.fsw._emit(Ae.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,i){e=Q.join(e,"");let l=r?`${e}:${r}`:e;if(i=this.fsw._throttle("readdir",l,1e3),!i)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(vo,async u=>{if(this.fsw.closed){f=void 0;return}let g=u.path,S=Q.join(e,g);if(d.add(g),!(u.stats.isSymbolicLink()&&await this._handleSymlink(u,e,S,g))){if(this.fsw.closed){f=void 0;return}(g===r||!r&&!h.has(g))&&(this.fsw._incrReadyCount(),S=Q.join(o,Q.relative(o,S)),this._addToNodeFs(S,n,s,a+1))}}).on(Ae.ERROR,this._boundHandleError),new Promise((u,g)=>{if(!f)return g();f.once(hn,()=>{if(this.fsw.closed){f=void 0;return}let S=i?i.clear():!1;u(void 0),h.getChildren().filter(x=>x!==e&&!d.has(x)).forEach(x=>{this.fsw._remove(e,x)}),f=void 0,S&&this._handleRead(e,!1,s,r,o,a,i)})})}async _handleDir(e,n,s,r,o,a,i){let l=this.fsw._getWatchedDir(Q.dirname(e)),h=l.has(Q.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!o&&!h&&this.fsw._emit(Ae.ADD_DIR,e,n),l.add(Q.basename(e)),this.fsw._getWatchedDir(e);let d,f,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(i)){if(!o&&(await this._handleRead(e,s,a,o,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(g,S)=>{S&&S.mtimeMs===0||this._handleRead(g,!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 i=this.fsw._getWatchHelpers(e);s&&(i.filterPath=l=>s.filterPath(l),i.filterDir=l=>s.filterDir(l));try{let l=await To[i.statMethod](i.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(i.watchPath,l))return a(),!1;let h=this.fsw.options.followSymlinks,d;if(l.isDirectory()){let f=Q.resolve(e),u=h?await un(e):e;if(this.fsw.closed||(d=await this._handleDir(i.watchPath,l,n,r,o,i,u),this.fsw.closed))return;f!==u&&u!==void 0&&this.fsw._symlinkPaths.set(f,u)}else if(l.isSymbolicLink()){let f=h?await un(e):e;if(this.fsw.closed)return;let u=Q.dirname(i.watchPath);if(this.fsw._getWatchedDir(u).add(i.watchPath),this.fsw._emit(Ae.ADD,i.watchPath,l),d=await this._handleDir(u,l,n,r,e,i,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(Q.resolve(e),f)}else d=this._handleFile(i.watchPath,l,n);return a(),d&&this.fsw._addPathCloser(e,d),!1}catch(l){if(this.fsw._handleError(l))return a(),e}}};var gn="/",Uo="//",$r=".",Fo="..",jo="string",Lo=/\\/g,Dr=/\/\//g,Ho=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,zo=/^\.[/\\]/;function Ot(t){return Array.isArray(t)?t:[t]}var pn=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function qo(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=Y.relative(t.path,e);return n?!n.startsWith("..")&&!Y.isAbsolute(n):!1}return!1}:()=>!1}function Bo(t){if(typeof t!="string")throw new Error("string expected");t=Y.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(Dr,"/"),e&&(t="/"+t),t}function Ar(t,e,n){let s=Bo(e);for(let r=0;r<t.length;r++){let o=t[r];if(o(s,n))return!0}return!1}function Wo(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let s=Ot(t).map(r=>qo(r));return e==null?(r,o)=>Ar(s,r,o):Ar(s,e)}var Ir=t=>{let e=Ot(t).flat();if(!e.every(n=>typeof n===jo))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Mr)},Rr=t=>{let e=t.replace(Lo,gn),n=!1;return e.startsWith(Uo)&&(n=!0),e=e.replace(Dr,gn),n&&(e=gn+e),e},Mr=t=>Rr(Y.normalize(Rr(t))),Pr=(t="")=>e=>typeof e=="string"?Mr(Y.isAbsolute(e)?e:Y.join(t,e)):e,Vo=(t,e)=>Y.isAbsolute(t)?t:Y.join(e,t),Yo=Object.freeze(new Set),yn=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!==$r&&e!==Fo&&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 No(s)}catch{this._removeWatcher&&this._removeWatcher(Y.dirname(s),Y.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=Mt,this.items=Yo,Object.freeze(this)}},Go="stat",Jo="lstat",wn=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,s){this.fsw=s;let r=e;this.path=e=e.replace(zo,""),this.watchPath=r,this.fullWatchPath=Y.resolve(r),this.dirParts=[],this.dirParts.forEach(o=>{o.length>1&&o.pop()}),this.followSymlinks=n,this.statMethod=n?Go:Jo}entryPath(e){return Y.join(this.watchPath,Y.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)}},Ut=class extends Do{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?Ot(e.ignored):Ot([]),awaitWriteFinish:n===!0?s:typeof n=="object"?{...s,...n}:!1};Tr&&(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 i=0;this._emitReady=()=>{i++,i>=this._readyCount&&(this._emitReady=Mt,this._readyEmitted=!0,process.nextTick(()=>this.emit(te.READY)))},this._emitRaw=(...l)=>this.emit(te.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Dt(this),Object.freeze(r)}_addIgnoredPath(e){if(pn(e)){for(let n of this._ignoredPaths)if(pn(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)pn(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=Ir(e);return r&&(o=o.map(a=>Vo(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 i=await this._nodeFsHandler._addToNodeFs(a,!s,void 0,0,n);return i&&this._emitReady(),i})).then(a=>{this.closed||a.forEach(i=>{i&&this.add(Y.dirname(i),Y.basename(n||i))})}),this}unwatch(e){if(this.closed)return this;let n=Ir(e),{cwd:s}=this.options;return n.forEach(r=>{!Y.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=Y.join(s,r)),r=Y.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?Y.relative(this.options.cwd,s):s)||$r;e[o]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==te.ERROR&&this.emit(te.ALL,e,...n)}async _emit(e,n,s){if(this.closed)return;let r=this.options;mn&&(n=Y.normalize(n)),r.cwd&&(n=Y.relative(r.cwd,n));let o=[n];s!=null&&o.push(s);let a=r.awaitWriteFinish,i;if(a&&(i=this._pendingWrites.get(n)))return i.lastChange=new Date,this;if(r.atomic){if(e===te.UNLINK)return this._pendingUnlinks.set(n,[e,...o]),setTimeout(()=>{this._pendingUnlinks.forEach((l,h)=>{this.emit(...l),this.emit(te.ALL,...l),this._pendingUnlinks.delete(h)})},typeof r.atomic=="number"?r.atomic:100),this;e===te.ADD&&this._pendingUnlinks.has(n)&&(e=te.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(e===te.ADD||e===te.CHANGE)&&this._readyEmitted){let l=(h,d)=>{h?(e=te.ERROR,o[0]=h,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===te.CHANGE&&!this._throttle(te.CHANGE,n,50))return this;if(r.alwaysStat&&s===void 0&&(e===te.ADD||e===te.ADD_DIR||e===te.CHANGE)){let l=r.cwd?Y.join(r.cwd,n):n,h;try{h=await Oo(l)}catch{}if(!h||this.closed)return;o.push(h)}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(te.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,i=()=>{let h=r.get(n),d=h?h.count:0;return r.delete(n),clearTimeout(a),h&&clearTimeout(h.timeoutObject),d};a=setTimeout(i,s);let l={timeoutObject:a,clear:i,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,i,l=e;this.options.cwd&&!Y.isAbsolute(e)&&(l=Y.join(this.options.cwd,e));let h=new Date,d=this._pendingWrites;function f(u){Mo(l,(g,S)=>{if(g||!d.has(e)){g&&g.code!=="ENOENT"&&r(g);return}let x=Number(new Date);u&&S.size!==u.size&&(d.get(e).lastChange=x);let w=d.get(e);x-w.lastChange>=n?(d.delete(e),r(void 0,S)):i=setTimeout(f,a,S)})}d.has(e)||(d.set(e,{lastChange:h,cancelWait:()=>(d.delete(e),clearTimeout(i),s)}),i=setTimeout(f,a))}_isIgnored(e,n){if(this.options.atomic&&Ho.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,o=(this.options.ignored||[]).map(Pr(s)),i=[...[...this._ignoredPaths].map(Pr(s)),...o];this._userIgnored=Wo(i,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new wn(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=Y.resolve(e);return this._watched.has(n)||this._watched.set(n,new yn(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,s){let r=Y.join(e,n),o=Y.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),h=l.has(n);l.remove(n),this._symlinkPaths.has(o)&&this._symlinkPaths.delete(o);let d=r;if(this.options.cwd&&(d=Y.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===te.ADD)return;this._watched.delete(r),this._watched.delete(o);let f=s?te.UNLINK_DIR:te.UNLINK;h&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(e){this._closeFile(e);let n=Y.dirname(e);this._getWatchedDir(n).remove(Y.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:te.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},r=vr(e,s);return this._streams.add(r),r.once(Cr,()=>{r=void 0}),r.once(hn,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ko(t,e={}){let n=new Ut(e);return n.add(t),n}var Nr={watch:Ko,FSWatcher:Ut};function Xo(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],i=n[a]||[],l=0,h=r[0];for(let d of i){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(h):r[l]=h,l=f+1,h=u,l===r.length)break}}r[l]=h}return r[r.length-1]}function Or(t,e){let n=Xo(t,e),s=[],r=t.length,o=e.length;for(let a=n;a!==null;a=a.chain){let i=r-a.buffer1index-1,l=o-a.buffer2index-1;r=a.buffer1index,o=a.buffer2index,(i||l)&&s.push({buffer1:[r+1,i],buffer1Content:t.slice(r+1,r+1+i),buffer2:[o+1,l],buffer2Content:e.slice(o+1,o+1+l)})}return s.reverse(),s}function Zo(t,e,n){let s=[];function r(l,h){s.push({ab:h,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}Or(e,t).forEach(l=>r(l,"a")),Or(e,n).forEach(l=>r(l,"b")),s.sort((l,h)=>l.oStart-h.oStart);let o=[],a=0;function i(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(),h=l.oStart,d=l.oStart+l.oLength,f=[l];for(i(h);s.length;){let u=s[0],g=u.oStart;if(g>d)break;d=Math.max(d,g+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 k=l.oStart,A=k+l.oLength,U=l.abStart,M=U+l.abLength,B=u[l.ab];B[0]=Math.min(U,B[0]),B[1]=Math.max(M,B[1]),B[2]=Math.min(k,B[2]),B[3]=Math.max(A,B[3])}let g=u.a[0]+(h-u.a[2]),S=u.a[1]+(d-u.a[3]),x=u.b[0]+(h-u.b[2]),w=u.b[1]+(d-u.b[3]),F={stable:!1,aStart:g,aLength:S-g,aContent:t.slice(g,S),oStart:h,oLength:d-h,oContent:e.slice(h,d),bStart:x,bLength:w-x,bContent:n.slice(x,w)};o.push(F)}a=d}return i(e.length),o}function Ur(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=Zo(t,e,n),i=[];function l(){i.length&&o.push({ok:i}),i=[]}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 a.forEach(d=>{d.stable?i.push(...d.bufferContent):s.excludeFalseConflicts&&h(d.aContent,d.bContent)?i.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 Ft(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,i=o>0?r.slice(o):"",l=d=>String(d).padStart(2,"0"),h=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}`;return`${s}${a} (conflict ${h})${i}`}function Qo(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 ei(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 jt(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 Fr(t,e,n){let s=Ur(t.split(`
193
+ `,ia=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function Vn(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function Yn(t){t.setPreviewHooks({sdkJs:Es,proxy:ks(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?bs(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:r}=await Ae(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:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,...r}}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 r;try{let o=ps(t.projectsRoot());if(r=ps(n.dir),r!==o&&!r.startsWith(o+na))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 s=await t.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:o,totalBytes:i}=ys(r,ia(t));if(!o.some(u=>u.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:l,json:a}=await Ae(s,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:o},3e5);return l===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:l!==200?{ok:!1,code:a?.code||"error",detail:a?.detail||`HTTP ${l}`,used:a?.used,limit:a?.limit}:(Ss(r,{slug:String(a.slug)}),{ok:!0,slug:a.slug,handle:a.handle,url:`${s.base}${a.url}`,totalBytes:i})}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 r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:s,json:o}=await Ae(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return s===401||s===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200&&s!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),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 r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:s,json:o}=await Ae(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return s===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200?{ok:!1,code:o?.code||"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0,status:o.status}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:listingWithdraw",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};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{status:s,json:o}=await Ae(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return s===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200&&s!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:r}=await Ae(e,"GET","/api/connect/store");return n!==200?{ok:!1,detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,items:Array.isArray(r.items)?r.items:[]}}catch(n){return{ok:!1,detail:n?.message||String(n)}}}),t.log("[forsion-extend] connect handlers registered")}import{createHash as aa}from"node:crypto";import{hostname as la}from"node:os";async function Tt(t,e){if(!t||!e)return{status:"offline"};let n=t.replace(/\/+$/,"");try{let r=await fetch(`${n}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(r.status===401||r.status===403)return{status:(r.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!r.ok)return{status:"offline"};let s=await r.json();if(!s)return{status:"offline"};let o=s.avatar||s.avatarUrl||s.avatar_url||void 0;return o&&/^\/(?!\/)/.test(o)&&(o=n+o),{status:"ok",user:{username:s.username||s.nickname||void 0,nickname:s.nickname||void 0,avatar:o,membershipTier:s.membershipTier||s.membership_tier||void 0}}}catch{return{status:"offline"}}}var _s=t=>`${t.seq}:${t.hash}`,ln=(t=la())=>{let e=t.replace(/\.local$/i,"").trim();return e?encodeURIComponent(e):null},ca=t=>aa("sha256").update(t).digest("hex");function Gn(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 r=e===-1?"":t.slice(e+1);return{baseSeq:n,baseHash:/^[0-9a-f]{64}$/.test(r)?r:null}}function cn(t){let e=t.baseUrl.replace(/\/+$/,""),n=o=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${o}`,r=ln(),s=async(o,i)=>{let l=t.getToken();if(!l)throw new Error("penzor-not-logged-in");let a=await fetch(o,{...i,headers:{...i.headers,Authorization:`Bearer ${l}`}});if(a.status===409){let u=await a.json().catch(()=>({}));throw new Error(`cas-conflict ${String(u.code??"")}: seq=${String(u.seq??"?")}`)}if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`penzor ${i.method??"GET"} ${a.status}: ${u.slice(0,200)}`)}return a};return{kind:"penzor",async walk(o){let i=await s(n("/manifest"),{method:"GET",signal:o}),{files:l}=await i.json();return l.map(a=>({key:a.path,size:a.size,mtimeMs:a.mtimeMs,id:_s(a),hash:a.hash}))},async readFile(o,i){let a=await(await s(n(`/file?path=${encodeURIComponent(o)}`),{method:"GET",signal:i})).json(),u=await fetch(a.url,{signal:i});if(!u.ok)throw new Error(`penzor blob GET ${u.status}: ${o}`);let d=Buffer.from(await u.arrayBuffer());if(ca(d)!==a.hash)throw new Error(`penzor hash mismatch: ${o}`);return d},async writeFile(o,i,l,a,u){let d=Gn(u),m=new URLSearchParams({path:o,mtimeMs:String(Math.floor(l)||0)});d&&(m.set("baseSeq",String(d.baseSeq)),d.baseHash&&m.set("baseHash",d.baseHash));let p=await(await s(n(`/file?${m.toString()}`),{method:"PUT",body:new Uint8Array(i),headers:{"Content-Type":"application/octet-stream",...r?{"X-Forsion-Device":r}:{}},signal:a})).json();return{key:o,size:p.size,mtimeMs:p.mtimeMs,id:_s(p)}},async rm(o,i,l){let a=Gn(l),u=new URLSearchParams({path:o});a&&a.baseSeq>0&&(u.set("baseSeq",String(a.baseSeq)),a.baseHash&&u.set("baseHash",a.baseHash)),await s(n(`/file?${u.toString()}`),{method:"DELETE",signal:i})},async check(){try{return await s(n("/manifest"),{method:"GET"}),{ok:!0}}catch(o){return{ok:!1,error:String(o?.message||o)}}}}}var un="forsion-diagnostics",xs=50*1024*1024,vs=new Map;async function ua(t,e){let n=vs.get(e);if(n)return{id:n};let r=await Tt(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let s=r.user?.username?.trim();return s?(vs.set(e,s),{id:s}):{error:"penzor-auth-unverified"}}var Jn=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function Xn(t){t.registerRemoteSyncBackend("penzor",async e=>{let n=t.readCreds();if(!n.token||!n.cloudUrl)return{error:"penzor-not-logged-in"};let r=e?.vault,s=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(s)||s===un)return{error:"penzor-bad-vault"};let o=await ua(n.cloudUrl,n.token);if("error"in o)return o;let i=n.token;return{remote:cn({baseUrl:n.cloudUrl,vault:s,getToken:()=>i}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${o.id}|${s}`,maxFileBytes:xs}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{createReadStream as da}from"node:fs";import{access as fa,link as ma,lstat as pa,mkdir as ga,open as ha,readdir as ya,rename as wa,stat as Cs,unlink as Kn}from"node:fs/promises";import{request as ba}from"node:http";import{request as Sa}from"node:https";import{homedir as ka}from"node:os";import{basename as Ts,extname as Is,isAbsolute as Ea,join as At}from"node:path";import{randomUUID as dn}from"node:crypto";var fn=50*1024*1024,_a=3,Zn=6e4,As=2e3,va=200,xa=["bytes","signed","text"];function Qn(t){if(typeof t!="string")return null;let n=(t.split(/[\\/]/).pop()??"").replace(/[\u0000-\u001f<>:"|?*]/g,"").trim().slice(0,200);return n&&n!=="."&&n!==".."?n:null}var Ca={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".svg":"image/svg+xml",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".mp4":"video/mp4",".mov":"video/quicktime",".mp3":"audio/mpeg",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"},Ta=t=>Ca[Is(t).toLowerCase()]??"application/octet-stream";function Ps(t,e,n,r){let s=n.replace(/[^\x20-\x7e]/g,"_").replace(/["\\]/g,"_")||"file",o=encodeURIComponent(n).replace(/['()*]/g,l=>`%${l.charCodeAt(0).toString(16).toUpperCase()}`),i="";for(let[l,a]of Object.entries(e))i+=`--${t}\r
194
+ Content-Disposition: form-data; name="${l}"\r
195
+ \r
196
+ ${a}\r
197
+ `;return i+=`--${t}\r
198
+ Content-Disposition: form-data; name="file"; filename="${s}"; filename*=UTF-8''${o}\r
199
+ Content-Type: ${r}\r
200
+ \r
201
+ `,{head:Buffer.from(i,"utf8"),tail:Buffer.from(`\r
202
+ --${t}--\r
203
+ `,"utf8")}}function Ds(t,e){let n=t.filter(([l])=>e-l<=3e3);if(n.length<2)return 0;let[r,s]=n[0],[o,i]=n[n.length-1];return o>r?Math.max(0,(i-s)/(o-r)*1e3):0}function Rs(t,e){let n=e??{};return t===401?"not_signed_in":n.code==="FILE_TOO_LARGE"||t===413?"too_large":typeof n.detail=="string"&&/quota exceeded/i.test(n.detail)?"quota":n.code==="STORAGE_NOT_CONFIGURED"?"storage_unavailable":`http_${t}`}function Aa(t,e,n,r,s,o,i,l){return new Promise((a,u)=>{let d=new URL(t),m=(d.protocol==="https:"?Sa:ba)(d,{method:"POST",headers:{...e,"Content-Length":String(n.length+s+o.length)}},p=>{let y=[];p.on("data",f=>y.push(f)),p.on("end",()=>{let f=null;try{f=JSON.parse(Buffer.concat(y).toString("utf8"))}catch{}a({status:p.statusCode??0,body:f})}),p.on("error",u)}),g=()=>{m.destroy(new Error("aborted"))};if(l.aborted)return g();l.addEventListener("abort",g,{once:!0}),m.setTimeout(Zn,()=>m.destroy(new Error("timeout"))),m.on("error",p=>{l.removeEventListener("abort",g),u(p)}),(async()=>{try{m.write(n);let p=0;for await(let y of da(r)){let f=y;if(p+=f.length,p>s)throw new Error("changed");m.write(f)||await new Promise(w=>m.once("drain",w)),i(p)}if(p!==s)throw new Error("changed");m.end(o)}catch(p){m.destroy(p)}})()})}function er(t,e={}){let n=e.downloadsDir??(()=>At(ka(),"Downloads")),r=e.post??Aa,s=e.now??Date.now,o=[],i=new Map,l=Promise.resolve(),a=async()=>{let h=await t.getCloud(),v=typeof t.accountId=="function"?t.accountId():null;return{...h,account:v||`${h.base}|${h.token}`}},u=h=>{let{account:v,attempt:b,relDir:A,abort:N,samples:B,dl:G,...se}=h;return{...se,speed:h.state==="active"?Ds(B,s()):0}},d=(h,v,b=null)=>{h.state=v,h.error=b,h.abort=null,h.finishedAt=s(),h.samples=[];let A=o.filter(N=>N.state==="done"||N.state==="canceled");for(let N of A.slice(0,Math.max(0,A.length-va)))o.splice(o.indexOf(N),1);m()};function m(){for(let h of["up","down"]){let v=o.filter(b=>b.kind===h&&b.state==="active").length;for(let b of o){if(v>=_a)break;if(b.kind!==h||b.state!=="queued")continue;v++,b.state="active",b.startedAt=s(),b.done=0,b.samples=[[s(),0]],b.abort=new AbortController;let A=++b.attempt,N=()=>b.attempt===A&&b.state==="active";(h==="up"?P(b,N):T(b,N)).catch(B=>{N()&&d(b,"failed",g(B))})}}}let g=h=>{let v=String(h?.message||h);return v==="changed"||v==="too_large"||v==="quota"||v==="account_changed"||v==="not_signed_in"||v.startsWith("http_")||v==="bad_response"||v==="gone"?v:"network"},p=(h,v)=>{h.done=v;let b=s(),A=h.samples[h.samples.length-1];for((!A||b-A[0]>=200)&&h.samples.push([b,v]);h.samples.length>2&&b-h.samples[0][0]>3500;)h.samples.shift()};async function y(h){let v=await a();if(v.account!==h.account)throw new Error("account_changed");if(!v.token)throw new Error("not_signed_in");return v}async function f(h,v,b,A){let N=We(h,b);if(!N)throw new Error("bad_path");let B=await fetch(N,{method:A.method??"GET",headers:{Authorization:`Bearer ${v}`,...A.body!==void 0?{"Content-Type":"application/json"}:{},...A.projectSource?{"X-Project-Source":A.projectSource}:{}},body:A.body!==void 0?JSON.stringify(A.body):void 0,signal:AbortSignal.timeout(3e4)});return{status:B.status,json:await B.json().catch(()=>null)}}function w(h,v,b){if(!h.relDir.length)return Promise.resolve(h.targetId);let A=i.get(h.batch);A||i.set(h.batch,A=new Map);let N=A,B=G=>{if(G===0)return Promise.resolve(h.targetId);let se=h.relDir.slice(0,G).join("/"),pe=N.get(se);return pe||(pe=B(G-1).then(async X=>{let de=h.relDir[G-1],Z=await f(v,b,"/files",{method:"POST",body:{type:"directory",parentId:X,name:de},projectSource:h.projectSource});if(Z.status===201&&typeof Z.json?.id=="string")return Z.json.id;if(Z.status===409){let Ee=await f(v,b,`/files${X==="ROOT"?"":`?parentId=${encodeURIComponent(X)}`}`,{projectSource:h.projectSource}),oe=Array.isArray(Ee.json)?Ee.json.find(_e=>_e?.fileType==="directory"&&_e?.name===de):null;if(oe?.id)return String(oe.id)}throw new Error(Z.status===401?"not_signed_in":`http_${Z.status}`)}),pe.catch(()=>N.delete(se)),N.set(se,pe)),pe};return B(h.relDir.length)}async function P(h,v){let{base:b,token:A}=await y(h),N=await Cs(h.localPath).catch(()=>null);if(!N?.isFile())throw new Error("gone");if(N.size>fn)throw new Error("too_large");h.size=N.size;let B=await w(h,b,A);if(!v())return;h.parentId=B;let G=We(b,"/files/upload");if(!G)throw new Error("bad_path");let se=`----penzor${dn().replace(/-/g,"")}`,{head:pe,tail:X}=Ps(se,{parentId:B,autoRename:"true"},h.name,Ta(h.name)),de=await r(G,{Authorization:`Bearer ${A}`,"Content-Type":`multipart/form-data; boundary=${se}`,...h.projectSource?{"X-Project-Source":h.projectSource}:{}},pe,h.localPath,N.size,X,Z=>{v()&&p(h,Z)},h.abort.signal);v()&&(de.status===201||de.status===200?(h.fileId=typeof de.body?.id=="string"?de.body.id:null,p(h,h.size),d(h,"done")):d(h,"failed",Rs(de.status,de.body)))}function H(h,v,b,A){let N=async()=>{let G=Is(b),se=G?b.slice(0,-G.length):b;for(let pe=0;pe<1e3;pe++){if(!A())throw new Error("aborted");let X=At(v,pe===0?b:`${se} (${pe})${G}`);try{await ma(h,X)}catch(de){let Z=de.code;if(Z==="EEXIST")continue;if(Z!=="EPERM"&&Z!=="ENOTSUP"&&Z!=="EOPNOTSUPP"&&Z!=="ENOSYS"&&Z!=="EXDEV")throw de;if(await fa(X).then(()=>!0,()=>!1))continue;await wa(h,X)}if(!A())throw await Kn(X).catch(()=>{}),new Error("aborted");return await Kn(h).catch(()=>{}),X}throw new Error("too many duplicates")},B=l.then(N,N);return l=B.catch(()=>{}),B}async function T(h,v){let b=h.dl,{base:A,token:N}=await y(h),B=We(A,b.path);if(!B)throw new Error("bad_path");let G=h.abort.signal,se=b.subdir?At(n(),b.subdir):n();await ga(se,{recursive:!0});let pe=At(se,`.${h.id}-${h.attempt}.penzor-part`),X=await ha(pe,"wx"),de=!1;try{let Z=new AbortController,Ee=setTimeout(()=>Z.abort(),Zn),oe=()=>{clearTimeout(Ee),Ee=setTimeout(()=>Z.abort(),Zn)},_e=AbortSignal.any([G,Z.signal]);try{let fe=await fetch(B,{headers:{Authorization:`Bearer ${N}`},signal:_e});if(!fe.ok)throw new Error(fe.status===401?"not_signed_in":`http_${fe.status}`);let ye=fe.body,ae=Number(fe.headers.get("content-length"))||h.size;if(b.mode!=="bytes"){let be=await fe.json().catch(()=>null);if(b.mode==="text"){if(typeof be?.content!="string")throw new Error("bad_response");let _=Buffer.from(be.content,"utf8");await X.writeFile(_),h.size=_.length,p(h,_.length),ye=null}else{if(typeof be?.url!="string"||!/^https?:\/\//i.test(be.url))throw new Error("bad_response");let _=await fetch(be.url,{signal:_e});if(!_.ok)throw new Error(`http_${_.status}`);ye=_.body,ae=Number(_.headers.get("content-length"))||h.size}}if(ye){h.size=ae;let be=0;for await(let _ of ye){oe();for(let I=0;I<_.length;){let{bytesWritten:x}=await X.write(_,I,_.length-I);if(x<=0)throw new Error("short_write");I+=x}if(be+=_.length,!v())throw new Error("aborted");p(h,be)}be>h.size&&(h.size=be)}}finally{clearTimeout(Ee)}if(await X.close(),!v()||(h.localPath=await H(pe,se,b.name,v),de=!0,!v()))return;d(h,"done")}finally{de||(await X.close().catch(()=>{}),await Kn(pe).catch(()=>{}))}}let U=(h,v)=>{let b={...h,id:dn(),attempt:0,done:0,state:v?"failed":"queued",error:v??null,abort:null,samples:[],speed:0,startedAt:null,finishedAt:v?s():null};return o.push(b),b};async function z(h){let v=[],b=async(A,N)=>{if(N.length>32)return!0;let B=await(N.length?pa(A):Cs(A)).catch(()=>null);if(!B)return!0;if(B.isFile())return v.push({path:A,size:B.size,relDir:N}),v.length<=As;if(!B.isDirectory())return!0;let G=(await ya(A).catch(()=>[])).filter(se=>!se.startsWith(".")).sort();for(let se of G)if(!await b(At(A,se),[...N,Ts(A)]))return!1;return!0};for(let A of h)if(!await b(A,[]))return"too_many";return v}return t.handle("penzor:device",h=>{if(!t.isTrustedSender(h))return{ok:!1,error:"untrusted"};let v=ln();return{ok:!0,name:v?decodeURIComponent(v):null}}),t.handle("penzor:upload",async(h,v)=>{if(!t.isTrustedSender(h))return{ok:!1,error:"untrusted"};let b=v??{},A=Array.isArray(b.paths)?b.paths.filter(oe=>typeof oe=="string"&&Ea(oe)):[],N=typeof b.parentId=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(b.parentId)?b.parentId:null,B=typeof b.projectSource=="string"&&/^[a-z0-9][a-z0-9-]{0,63}$/.test(b.projectSource)?b.projectSource:null;if(!A.length)return{ok:!1,error:"no_files"};if(!N||!B)return{ok:!1,error:"bad_target"};let{base:G,token:se,account:pe}=await a();if(!se)return{ok:!1,error:"not_signed_in"};let X=await z(A);if(X==="too_many")return{ok:!1,error:"too_many",max:As};if(!X.length)return{ok:!1,error:"no_files"};let de=X.filter(oe=>oe.size<=fn).reduce((oe,_e)=>oe+_e.size,0);try{let oe=await f(G,se,"/storage/quota",{}),_e=Number(oe.json?.used),fe=Number(oe.json?.quota);if(oe.status===200&&fe>0&&_e+de>fe)return{ok:!1,error:"quota",short:_e+de-fe}}catch{}if((await a()).account!==pe)return{ok:!1,error:"account_changed"};let Z=dn(),Ee=X.map(oe=>U({kind:"up",name:Ts(oe.path),size:oe.size,projectSource:B,parentId:oe.relDir.length?null:N,targetId:N,fileId:null,localPath:oe.path,batch:Z,account:pe,relDir:oe.relDir},oe.size>fn?"too_large":void 0).id);return m(),{ok:!0,ids:Ee,batch:Z}}),t.handle("penzor:download",async(h,v)=>{if(!t.isTrustedSender(h))return{ok:!1,error:"untrusted"};let b=v??{},A=xa.includes(b.mode)?b.mode:null,N=Qn(b.name);if(!A)return{ok:!1,error:"bad_mode"};if(!N)return{ok:!1,error:"bad_name"};let{base:B,token:G,account:se}=await a();if(typeof b.path!="string"||!We(B,b.path))return{ok:!1,error:"bad_path"};if(!G)return{ok:!1,error:"not_signed_in"};let pe=b.subdir==null?null:Qn(b.subdir),X=U({kind:"down",name:N,size:Math.max(0,Number(b.size)||0),localPath:null,batch:typeof b.batch=="string"&&b.batch.length<=64?b.batch:dn(),account:se,relDir:[],dl:{path:b.path,mode:A,name:N,subdir:pe}});return m(),{ok:!0,id:X.id}}),t.handle("penzor:transfers",h=>t.isTrustedSender(h)?{ok:!0,items:o.map(u)}:{ok:!1,error:"untrusted"}),t.handle("penzor:transfer",(h,v)=>{if(!t.isTrustedSender(h))return{ok:!1,error:"untrusted"};let b=v??{},A=o.find(B=>B.id===b.id);if(!A)return{ok:!1,error:"not_found"};let N=()=>{A.abort?.abort(),A.abort=null,A.done=0,A.samples=[]};switch(b.op){case"pause":(A.state==="active"||A.state==="queued")&&(N(),A.state="paused",m());break;case"resume":A.state==="paused"&&(A.state="queued",m());break;case"cancel":(A.state==="active"||A.state==="queued"||A.state==="paused")&&(N(),d(A,"canceled"));break;case"retry":(A.state==="failed"||A.state==="canceled")&&(A.state="queued",A.error=null,A.finishedAt=null,A.done=0,m());break;case"dismiss":A.state!=="active"&&A.state!=="queued"&&o.splice(o.indexOf(A),1);break;default:return{ok:!1,error:"bad_op"}}return{ok:!0}}),t.handle("penzor:transfers:clear",(h,v)=>{if(!t.isTrustedSender(h))return{ok:!1,error:"untrusted"};let b=v?.which==="all";for(let A of[...o])(A.state==="done"||A.state==="canceled"||b&&A.state==="failed")&&o.splice(o.indexOf(A),1);return{ok:!0}}),t.addQuitGuard?.(h=>{let v=o.filter(b=>b.state==="active"||b.state==="queued"||b.state==="paused").length;return v?h==="zh"?{message:`\u8FD8\u6709 ${v} \u4E2A\u6587\u4EF6\u6CA1\u4F20\u5B8C`,detail:"\u73B0\u5728\u9000\u51FA\u4F1A\u4E2D\u65AD\uFF0C\u4E0B\u6B21\u6253\u5F00\u8981\u91CD\u65B0\u4F20\u3002"}:{message:v===1?"1 file hasn't finished transferring":`${v} files haven't finished transferring`,detail:"Quitting now stops them. You will need to start them again next time."}:null}),{list:()=>o.map(u)}}import{readFileSync as Da,writeFileSync as Ra,mkdirSync as $a,chmodSync as Ma,renameSync as Oa}from"node:fs";import{join as Na}from"node:path";function $e(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let s=r.replace(/-/g,"+").replace(/_/g,"/"),o=Uint8Array.from(atob(s),a=>a.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(o)),l=i.userId??i.sub;return typeof l!="string"&&typeof l!="number"||!String(l).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(l)}`}catch{return null}}function tr(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Ke(Zt(e)));return n&&typeof n=="object"?n:null}catch{return null}}function nr(t,e=Date.now()){let n=tr(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function $s(t,e=Date.now()){let n=tr(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var Ia=36e5;function mn(t,e=Date.now()){return!!t&&nr(t,e)>=Ia}async function pn(t,e,n=8e3,r){if(!t||!e)return null;let s=t.replace(/\/+$/,"");try{let o=await fetch(`${s}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!o.ok)return null;let i=await o.json().catch(()=>null),l=typeof i?.token=="string"?i.token:"";return l&&l!==e?l:null}catch{return null}}var It=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,Pa=(t,e)=>new Promise((n,r)=>{let s=()=>{clearTimeout(o),r(new Error("Sign-in cancelled."))},o=setTimeout(()=>{e.removeEventListener("abort",s),n()},t);e.aborted?s():e.addEventListener("abort",s,{once:!0})});function Ms(t,e){let n=m=>e.write(JSON.stringify(m,null,2)),r=()=>{try{let m=JSON.parse(e.read()??"");return Array.isArray(m.accounts)?m.accounts.filter(g=>g&&typeof g.token=="string"&&g.id===$e(g.cloudUrl,g.token)):[]}catch{return[]}},s=(m,g)=>{let p=$e(m.cloudUrl||"",m.token||"");if(!p||!m.token||!m.cloudUrl)return;let y=r(),f=y.find(H=>H.id===p),w=tr(m.token),P={...f,id:p,cloudUrl:m.cloudUrl.replace(/\/+$/,""),token:m.token,username:g?.username||f?.username||w?.username,nickname:g?.nickname||f?.nickname};JSON.stringify(f)!==JSON.stringify(P)&&n({version:1,accounts:[...y.filter(H=>H.id!==p),P]})},o=()=>{let m=t.readCreds();s(m);let g=$e(m.cloudUrl,m.token);return r().map(({token:p,...y})=>({...y,active:y.id===g}))},i=m=>{let g=r().find(p=>p.id===m);if(!g)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:g.cloudUrl,token:g.token}},l=m=>{let g=$e(m.cloudUrl||"",m.token||"");g&&n({version:1,accounts:r().filter(p=>p.id!==g)})},a=null;return{rememberForsionAccount:s,forsionAccounts:o,savedForsionAccount:i,forgetForsionAccount:l,cancelForsionLogin:()=>{a?.abort(),a=null},forsionDeviceLogin:async(m,g,p)=>{if(a)throw new Error("A sign-in is already in progress.");if(!m)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let y=new AbortController;a=y;let f=()=>{if(y.signal.aborted||a!==y)throw new Error("Sign-in cancelled.")};try{let w=m.replace(/\/+$/,""),P;try{P=await fetch(`${w}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([y.signal,AbortSignal.timeout(15e3)])}).then(v=>v.json())}catch(v){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${w}:${v?.message||v}`)}if(f(),!P?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let H=P.verification_uri_complete||`${P.verification_uri}?code=${P.user_code}`,T=new URL(`${w}/auth`);T.searchParams.set("logout","1"),T.searchParams.set("app","forsion-desktop"),T.searchParams.set("redirect",H);let U=T.toString();g?.({url:U,userCode:String(P.user_code||"")}),t.openExternal(U);let z=Date.now()+(P.expires_in||600)*1e3,h=(P.interval||2)*1e3;for(;Date.now()<z;){await Pa(h,y.signal),f();let v=null;try{v=await fetch(`${w}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:P.device_code}),signal:AbortSignal.any([y.signal,AbortSignal.timeout(15e3)])})}catch{f();continue}if(f(),v.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let b=await v.json().catch(()=>({status:"pending"}));if(f(),b.status==="approved"&&b.token){let A={cloudUrl:w,token:b.token};return await p(A,f),f(),{token:b.token,cloudUrl:w}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{a===y&&(a=null)}},readAccounts:r}}function Ua(t){let e=()=>Na(t(),"auth-accounts.json");return{read:()=>Da(e(),"utf8"),write:n=>{$a(t(),{recursive:!0});let r=`${e()}.tmp`;Ra(r,n,{encoding:"utf8",mode:384}),Ma(r,384),Oa(r,e())}}}var Ns=t=>Ms(t,Ua(()=>t.homeDir())),Us=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],rr=t=>Us.every(e=>typeof t[e]=="function");function sr(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=Ns(t),s=0,o=()=>{let l=t.readCreds();return It(l.cloudUrl,l.token)},i=null;t.handle("auth:status",async l=>{if(!t.isTrustedSender(l))return n;let a=s,u=o(),{base:d}=await t.getCloud(),m=t.readCreds().token,g=m?await Tt(d,m):null,p=await t.accountBackendState(),{base:y}=await t.getCloud(),f=t.readCreds(),w=It(y,f.token)!==It(d,m),P=It(d,m);!w&&g?.status==="ok"&&g.user&&(i={key:P,user:g.user},r.rememberForsionAccount({...f,cloudUrl:d},g.user));let H=w?void 0:g?.status==="ok"?g.user:g?.status==="offline"&&i?.key===P?i.user:void 0;if(w)return{loggedIn:!!f.token,tokenValid:null,cloudUrl:y,accountId:$e(y,f.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:f.token?"tangu-login":null,backendState:p};if(g?.status==="expired"){await t.accountTransition(async()=>{if(a!==s||o()!==u)return;let U=()=>{if(a!==s||o()!==u)throw Os};try{await t.accountClear(U,()=>{t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++s,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),i=null})}catch(z){if(z!==Os)throw z}});let T=t.readCreds();return{loggedIn:!!T.token,tokenValid:null,cloudUrl:T.cloudUrl||d,accountId:$e(T.cloudUrl||d,T.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:T.token?"tangu-login":null,backendState:p}}return{loggedIn:!!m,tokenValid:g&&g.status==="ok"?!0:null,cloudUrl:d,accountId:$e(d,m),username:H?.username||null,nickname:H?.nickname||null,avatar:H?.avatar||null,membershipTier:H?.membershipTier||null,tokenSource:m?"tangu-login":null,backendState:p}}),t.handle("auth:accounts",l=>t.isTrustedSender(l)?r.forsionAccounts():[]),t.handle("auth:switchAccount",async(l,a)=>{if(!t.isTrustedSender(l))return e;if(typeof a!="string")throw new Error("Invalid account.");let u=++s;return r.cancelForsionLogin(),t.accountTransition(async()=>{let d=r.savedForsionAccount(a);return await t.accountCommit(d,()=>{if(u!==s)throw new Error("Account switch cancelled.")},()=>{r.rememberForsionAccount(d),i=null}),{ok:!0,cloudUrl:d.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(l,a)=>{if(!t.isTrustedSender(l))return e;let u=++s;r.cancelForsionLogin();let{base:d}=await t.getCloud();if(u!==s)throw new Error("Sign-in cancelled.");let m=(a||d||"").trim();return{ok:!0,cloudUrl:(await r.forsionDeviceLogin(m,p=>t.broadcast("auth:device",p),(p,y)=>t.accountTransition(()=>t.accountCommit(p,()=>{if(y(),u!==s)throw new Error("Sign-in cancelled.")},()=>{r.rememberForsionAccount(p),i=null})))).cloudUrl}}),t.handle("auth:logout",async l=>t.isTrustedSender(l)?(++s,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:a}=await t.getCloud(),u=t.readCreds();return await t.accountClear(void 0,()=>{r.forgetForsionAccount(u),i=null,a&&u.token&&fetch(`${a}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${u.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:l,current:a})=>{++s,r.cancelForsionLogin(),l.token&&!a.token&&r.forgetForsionAccount(l),i=null,r.rememberForsionAccount(a)}),t.setTokenRefresher(async l=>{let a=s,u=o(),d=t.readCreds().token;if(!mn(d))return;let{base:m}=await t.getCloud(),g=await pn(m,d,l,`desktop/${t.appVersion()}`);if(!g){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}a!==s||o()!==u||(r.rememberForsionAccount({cloudUrl:m,token:g}),t.writeCreds({cloudUrl:m,token:g}),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 Os=Symbol("stale-auth-intent");import{promises as ht}from"node:fs";import st from"node:path";import{execFile as ol}from"node:child_process";import il from"node:os";var or=null;function js(t){or=t}function Ie(){if(!or)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return or}var Te=()=>Ie().accountId();function Pt(t=Te()){return t?Se().sha256Hex(t):"signed-out"}var Me=(t=Te())=>Ie().readConfig(t),Ve=(t,e=Te())=>Ie().writeConfig(t,e),ft=(t,e=Te())=>Ie().updateConfig(t,e),Ze=(t=Te())=>Ie().cloudVaultDir(t),gn=t=>Ie().isManagedCloudVault(t);function ja(t,e){let n=Object.create(null);for(let o=0;o<e.length;o++){let i=e[o];n[i]?n[i].push(o):n[i]=[o]}let s=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let o=0;o<t.length;o++){let i=t[o],l=n[i]||[],a=0,u=s[0];for(let d of l){let m;for(m=a;m<s.length&&!(s[m].buffer2index<d&&(m===s.length-1||s[m+1].buffer2index>d));m++);if(m<s.length){let g={buffer1index:o,buffer2index:d,chain:s[m]};if(a===s.length?s.push(u):s[a]=u,a=m+1,u=g,a===s.length)break}}s[a]=u}return s[s.length-1]}function Fs(t,e){let n=ja(t,e),r=[],s=t.length,o=e.length;for(let i=n;i!==null;i=i.chain){let l=s-i.buffer1index-1,a=o-i.buffer2index-1;s=i.buffer1index,o=i.buffer2index,(l||a)&&r.push({buffer1:[s+1,l],buffer1Content:t.slice(s+1,s+1+l),buffer2:[o+1,a],buffer2Content:e.slice(o+1,o+1+a)})}return r.reverse(),r}function Fa(t,e,n){let r=[];function s(a,u){r.push({ab:u,oStart:a.buffer1[0],oLength:a.buffer1[1],abStart:a.buffer2[0],abLength:a.buffer2[1]})}Fs(e,t).forEach(a=>s(a,"a")),Fs(e,n).forEach(a=>s(a,"b")),r.sort((a,u)=>a.oStart-u.oStart);let o=[],i=0;function l(a){a>i&&(o.push({stable:!0,buffer:"o",bufferStart:i,bufferLength:a-i,bufferContent:e.slice(i,a)}),i=a)}for(;r.length;){let a=r.shift(),u=a.oStart,d=a.oStart+a.oLength,m=[a];for(l(u);r.length;){let g=r[0],p=g.oStart;if(p>d)break;d=Math.max(d,p+g.oLength),m.push(r.shift())}if(m.length===1){if(a.abLength>0){let g=a.ab==="a"?t:n;o.push({stable:!0,buffer:a.ab,bufferStart:a.abStart,bufferLength:a.abLength,bufferContent:g.slice(a.abStart,a.abStart+a.abLength)})}}else{let g={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;m.length;){a=m.shift();let H=a.oStart,T=H+a.oLength,U=a.abStart,z=U+a.abLength,h=g[a.ab];h[0]=Math.min(U,h[0]),h[1]=Math.max(z,h[1]),h[2]=Math.min(H,h[2]),h[3]=Math.max(T,h[3])}let p=g.a[0]+(u-g.a[2]),y=g.a[1]+(d-g.a[3]),f=g.b[0]+(u-g.b[2]),w=g.b[1]+(d-g.b[3]),P={stable:!1,aStart:p,aLength:y-p,aContent:t.slice(p,y),oStart:u,oLength:d-u,oContent:e.slice(u,d),bStart:f,bLength:w-f,bContent:n.slice(f,w)};o.push(P)}i=d}return l(e.length),o}function Ls(t,e,n,r){r=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},r),typeof t=="string"&&(t=t.split(r.stringSeparator)),typeof e=="string"&&(e=e.split(r.stringSeparator)),typeof n=="string"&&(n=n.split(r.stringSeparator));let o=[],i=Fa(t,e,n),l=[];function a(){l.length&&o.push({ok:l}),l=[]}function u(d,m){if(d.length!==m.length)return!1;for(let g=0;g<d.length;g++)if(d[g]!==m[g])return!1;return!0}return i.forEach(d=>{d.stable?l.push(...d.bufferContent):r.excludeFalseConflicts&&u(d.aContent,d.bContent)?l.push(...d.aContent):(a(),o.push({conflict:{a:d.aContent,aIndex:d.aStart,o:d.oContent,oIndex:d.oStart,b:d.bContent,bIndex:d.bStart}}))}),a(),o}function hn(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),s=n<0?t:t.slice(n+1),o=s.lastIndexOf("."),i=o>0?s.slice(0,o):s,l=o>0?s.slice(o):"",a=d=>String(d).padStart(2,"0"),u=`${e.getFullYear()}-${a(e.getMonth()+1)}-${a(e.getDate())} ${a(e.getHours())}${a(e.getMinutes())}`;return`${r}${i} (conflict ${u})${l}`}function La(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),s=r?t.slice(0,n):t,o=r?t.slice(n):"";return`${s}-${e}${o}`}function Ha(t){let e=3735928559,n=1103547991;for(let s=0;s<t.length;s++){let o=t.charCodeAt(s);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 r=4294967296*(2097151&n)+(e>>>0);return`${t.length.toString(36)}-${r.toString(36)}`}function yn(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 r=t!==e.hash,s=n.seq!==e.seq;return!r&&!s?{kind:"none"}:r?s?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function Hs(t,e,n){let r=Ls(t.split(`
194
204
  `),e.split(`
195
205
  `),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 bn(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var ti=/[\u0000-\u001f\u007f]/;function Xe(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||ti.test(e))return null;let n=e.split("/");for(let s of n)if(!s||s==="."||s==="..")return null;return n.join("/")}function Sn(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Xe(n):n.startsWith(`${e}/`)?Xe(n.slice(e.length+1)):null}function jr(t,e){return e===""?t:`${e}/${t}`}function ft(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function Pe(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var je=t=>t==="page"||t==="db";import{gzip as ni}from"node:zlib";import{promisify as ri}from"node:util";var si=ri(ni),oi=1024,fe=class extends Error{status;body;constructor(e,n,s){super(`cloud http ${e} on ${s}`),this.status=e,this.body=n}},Lr=t=>12e4+Math.ceil(t/256);function Hr(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=async(r,o,a)=>{let i={Authorization:`Bearer ${t.token}`,...a?.headers};r!=="GET"&&(i["X-Amadeus-Client"]=t.clientId);let l;a?.json!==void 0?(i["Content-Type"]="application/json",l=JSON.stringify(a.json),l.length>=oi&&(i["Content-Encoding"]="gzip",l=await si(l))):a?.form&&(l=a.form);let h=await fetch(o,{method:r,headers:i,body:l,signal:AbortSignal.timeout(a?.timeoutMs??3e4)});if(!h.ok){let d=null;try{d=await h.json()}catch{}throw new fe(h.status,d,o)}return h.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,i,l=!1){return n("PUT",`${e}/vaults/${r}/file`,{json:{path:o,content:a,baseSeq:i,...l?{force:!0}:{}}})},async deleteFile(r,o,a,i){let l={path:o};a!==void 0&&(l.baseSeq=String(a)),await n("DELETE",`${e}/vaults/${r}/file?${s(l)}`,i?.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,i){let l=new FormData;return l.set("path",o),i?.ifAbsent&&l.set("ifAbsent","true"),i?.baseSeq!==void 0&&l.set("baseSeq",String(i.baseSeq)),l.set("file",new Blob([new Uint8Array(a)]),o.split("/").pop()||"file"),n("POST",`${e}/vaults/${r}/binary`,{form:l,timeoutMs:Lr(a.length)})},async listVersions(r,o){return((await n("GET",`${e}/vaults/${r}/file/versions?${s({path:o})}`)).versions??[]).map(i=>({id:String(i.id),seq:Number(i.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,i=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 fe(l.status,null,"asset:"+o);return clearTimeout(i),i=setTimeout(()=>a.abort(),Lr(Number(l.headers.get("content-length"))||0)),Buffer.from(await l.arrayBuffer())}finally{clearTimeout(i)}},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 zr(t,e){let n=!1,s=0,r=null,o=null,a=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,i=h=>{if(n)return;e.onDown(h);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 h;try{h=await fetch(a(),{headers:{Authorization:`Bearer ${t.token}`,Accept:"text/event-stream"},signal:r.signal})}catch(w){i(w);return}if(!h.ok||!h.body){i(new Error(`sse http ${h.status}`));return}s=0,e.onOpen();let d=h.body.getReader(),f=new TextDecoder,u="",g="",S=[],x=()=>{if(!S.length&&!g)return;let w=S.join(`
198
- `),F=g||"message";g="",S=[];let k=null;try{k=w?JSON.parse(w):null}catch{return}F==="hello"?e.onHello(Number(k?.seq??0)):F==="change"?e.onChange(k):F==="reset"?e.onReset():F==="presence"?e.onPresence?.(k):F==="presence-roster"&&e.onPresenceRoster?.(k)};try{for(;;){let{done:w,value:F}=await d.read();if(w)break;for(u+=f.decode(F,{stream:!0});;){let k=u.indexOf(`
199
- `);if(k<0)break;let A=u.slice(0,k).replace(/\r$/,"");if(u=u.slice(k+1),A==="")x();else{if(A.startsWith(":"))continue;A.startsWith("event:")?g=A.slice(6).trim():A.startsWith("data:")&&S.push(A.slice(5).replace(/^ /,""))}}}}catch(w){n||i(w);return}i(new Error("sse stream ended"))};return l(),{stop:()=>{n=!0,o&&clearTimeout(o),r?.abort()}}}import{constants as ii,promises as Qe}from"node:fs";import ai from"node:path";var Ze=t=>ai.join(pe().userDataDir(),pe().isDevMode()?`${t}.dev.json`:`${t}.json`);async function vn(t){try{let e=JSON.parse(await Qe.readFile(Ze(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 qr(t){let e=null,n=null,s=Promise.resolve(),r=null,o=()=>{if(!e)return s;let a=e,i=JSON.stringify(e);return e=null,s=s.then(async()=>{try{let l=Ze(t),h=`${l}.tmp-${process.pid}-${Date.now()}-0`;await Qe.writeFile(h,i,"utf8"),await Qe.rename(h,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 Br(t){try{await Qe.unlink(Ze(t))}catch{}}async function Wr(t,e){try{await Qe.copyFile(Ze(t),Ze(e),ii.COPYFILE_EXCL)}catch(n){let s=n?.code;if(s==="EEXIST"||s==="ENOENT")return!1;throw n}return await Qe.unlink(Ze(t)).catch(()=>{}),!0}var ci=5*1024*1024,ui=5*1024*1024,di=3e4,fi=2500,hi=3e3,mi=5,gi=256*1024,pi=5,Yr=1024*1024,Gr=200,yi=6e4,wi=50,bi=".sync-trash",et=t=>li("sha256").update(t).digest("hex");function ht(t,e={localRoot:Fe(),shadowName:`amadeus-sync-${ct()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let n=c=>{let m=Sn(c,"");if(!m)return null;for(let p of e.excludePrefixes??[])if(m===p.replace(/\/$/,"")||m.startsWith(p))return null;if(e.ignoreNames?.length&&m.split("/").some(p=>e.ignoreNames.includes(p)))return null;let y=e.serverDir?`${e.serverDir}/${m}`:m;return e.inScope&&!e.inScope(y,Pe(y))?null:y},s=c=>{let m;if(e.serverDir){if(!c.startsWith(`${e.serverDir}/`))return null;m=c.slice(e.serverDir.length+1)}else{for(let y of e.excludePrefixes??[])if(c.startsWith(y))return null;m=c}return m.split("/").some(y=>ft(y)||!!e.ignoreNames?.includes(y))?null:m},r=(c,m)=>!e.inScope||e.inScope(c,m),o=e.accountId??ye(),a=!1,i=0,l=Promise.resolve(),h=new Set,d="disabled",f=null,u=null,g=null,S=null,x=null,w=null,F=0,k=new Map,A=null,U=qr(e.shadowName),M=new Map,B=!1,j=!1,K=[],se=()=>{u&&(u.pending=M.size?Object.fromEntries(M):void 0,U.save(u))},he=()=>{j=!1,K.length=0},we=()=>{if(j)return!0;let c=Date.now();for(;K.length&&c-K[0]>yi;)K.shift();return K.length>=wi?(j=!0,!0):!1},ae=[],Ee=new Set,$e=!1,_=null,C=null,b=null,v=()=>{!a||b||(b=setTimeout(()=>{b=null,t.onStatus(ze())},200))},$=(c,m)=>{d=c,m!==void 0&&(f=m),v()},E=(c,m=!1)=>{if(a){if(c.key){if(Ee.has(c.key))return;Ee.add(c.key)}m?ae.unshift(c):ae.push(c),X()}},I=new Map,N=c=>{if(!a)return;let m=(u?.files[c]?.size??0)>gi,y=(e.pushQuietMs??hi)*(m?pi:1),p=Date.now(),T=I.get(c);T&&clearTimeout(T.timer);let P=T?.since??p,O=Math.max(0,Math.min(y,P+y*mi-p)),R=setTimeout(()=>{I.delete(c),E({key:c,run:()=>de(c,!0)})},O);I.set(c,{timer:R,since:P}),v()},W=()=>{for(let{timer:c}of I.values())clearTimeout(c);I.clear()},H=c=>!(c instanceof fe)||c.status>=500||c.status===0,z=c=>c instanceof fe&&(c.status===401||c.status===403),X=async()=>{if(!$e){$e=!0;try{for(;ae.length;){(d==="idle"||d==="starting")&&$("syncing");let c=ae.shift();c.key&&Ee.delete(c.key);try{await c.run()}catch(m){if(!a)return;if(z(m)){ae.length=0,Ee.clear(),kt(),$("auth-required","login-expired");return}if(H(m)){E(c,!0),kt(),$("offline",m?.message||"network error"),J();return}let y=c.key??"(op)";k.set(y,m?.body?.code||`http ${m?.status}`),v()}}a&&d==="syncing"&&(u&&(u.lastSyncAt=Date.now(),U.save(u)),$("idle",null))}finally{$e=!1;for(let c of h)c();h.clear()}}},J=()=>{!a||_||(_=setTimeout(()=>{_=null,at()},di))},G=c=>{if(!w||!u)throw new Error("engine not bound");let m=s(c);if(m===null)throw new Error("path outside binding: "+c);let y=ie.resolve(w,jr(m,u.folder)),p=ie.relative(w,y);if(p.startsWith("..")||ie.isAbsolute(p))throw new Error("path escapes vault: "+c);return y},ee=c=>({size:c,mtimeMs:-1}),Z=async c=>{try{let m=await ne.stat(c);return m.isFile()?{size:m.size,mtimeMs:Math.floor(m.mtimeMs)}:null}catch{return null}},_e=0,He=async(c,m,y=()=>!0)=>{await ne.mkdir(ie.dirname(c),{recursive:!0});let p=`${c}.tmp-${process.pid}-${Date.now()}-${_e++}`;await ne.writeFile(p,m);let T=await Z(p)??ee(Buffer.byteLength(m));return y()?(await ne.rename(p,c),T):(await ne.rm(p,{force:!0}),null)},We=async c=>{let m;try{m=await ne.readdir(c,{withFileTypes:!0})}catch{return}for(let y of m)y.isDirectory()&&await We(ie.join(c,y.name));try{await ne.rmdir(c)}catch{}},le=async c=>{let m=G(c),y=await Z(m),p;try{p=await ne.readFile(m)}catch{return null}return{hash:je(Pe(c))?et(p.toString("utf8")):et(p),size:y?.size??p.length,mtimeMs:y?.mtimeMs??-1,buf:p}},Ie=async(c,m,y,p)=>{u&&(u.files[c]={seq:m,hash:y,size:p.size,mtimeMs:p.mtimeMs},U.save(u))},ke=c=>{u&&c in u.files&&(delete u.files[c],U.save(u))},De=async(c,m)=>{if(!g||!u||Ce(c))return;let y=oe,p=Pe(c),T,P,O;if(je(p)){let q;try{q=await g.getFile(u.vaultId,c)}catch(V){if(V instanceof fe&&V.status===404){await Yt(c);return}throw V}T=q.content,P=q.seq,O=q.hash??et(q.content)}else{let q;try{q=await g.getAsset(u.vaultId,c)}catch(V){if(V instanceof fe&&V.status===404){k.set(c,"ASSET_404"),v();return}throw V}T=q,P=m??0,O=et(q)}let R=await le(c);if(y!==oe||Ce(c))return;if(R&&R.hash===O){await Ie(c,P,O,R);return}let L=u.files[c];if(R&&L&&O===L.hash&&R.hash!==L.hash){await Ie(c,P,O,ee(L.size)),E({key:c,run:()=>de(c)});return}if(R&&(!L||R.hash!==L.hash)){if(L&&p==="page"&&typeof T=="string"&&await xs(c,L,R,T,P,O,()=>y===oe&&!Ce(c))||y!==oe||Ce(c))return;await As(c)}let D=await He(G(c),T,()=>y===oe&&!Ce(c));D&&await Ie(c,P,O,D)},xs=async(c,m,y,p,T,P,O)=>{try{if(!g||!u||y.buf.length>Yr||p.length>Yr)return!1;let L=(await g.listVersions(u.vaultId,c)).find(V=>V.seq===m.seq);if(!L)return!1;let D=await g.getVersion(u.vaultId,L.id);if(et(D)!==m.hash)return!1;let q=Fr(y.buf.toString("utf8"),D,p);return q===null?!1:(await He(G(c),q,O)&&(await Ie(c,T,P,ee(Buffer.byteLength(q))),E({key:c,run:()=>de(c)})),!0)}catch{return!1}},As=async c=>{let m=Xe(Ft(c,new Date));if(!m)return;let y=m.lastIndexOf("."),p=y>m.lastIndexOf("/"),T=p?m.slice(0,y):m,P=p?m.slice(y):"",O=m;for(let R=2;Vr(G(O));R++)O=`${T}-${R}${P}`;try{await ne.rename(G(c),G(O))}catch(R){if(R?.code==="ENOENT")return;throw R}F++,E({key:O,run:()=>de(O)}),v()},jn=async c=>{if(!w)return;let m=G(c),y=s(c)??c,p=ie.join(w,bi,new Date().toISOString().slice(0,10),...y.split("/")),T=Vr(p)?`${p}.${Date.now()}`:p;try{await ne.mkdir(ie.dirname(T),{recursive:!0}),await ne.rename(m,T)}catch(P){if(P?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${m}: ${P?.message??String(P)}`)}},Yt=async c=>{if(!u)return;let m=await le(c);if(Ce(c))return;let y=u.files[c]??null,p=jt(m?.hash??null,y,null);if(p.kind==="deleteLocal"){if(!B&&we()){M.set(c,"local"),se(),v();return}K.push(Date.now()),await jn(c),ke(c)}else p.kind==="pushCreate"?(ke(c),E({key:c,run:()=>de(c)})):ke(c)},Ln=(c,m)=>{if(u){for(let y of Object.keys(u.files))if(y===c||y.startsWith(`${c}/`)){let p=m+y.slice(c.length);u.files[p]=u.files[y],delete u.files[y]}U.save(u)}},Hn=async c=>{if(!g||!u||c.seq<=u.cursor||!await St())return;if(c.origin.client&&g.clientId===c.origin.client){u.cursor=c.seq,U.save(u);return}let m=c.type==="structure"?"folder":c.type,y=T=>s(T)!==null&&r(T,m);if(!y(c.path)&&!(c.newPath&&y(c.newPath))){u.cursor=c.seq,U.save(u);return}let p=c.path;switch(c.op){case"write":await De(p,c.fileSeq);break;case"delete":await Yt(p);break;case"move":{let T=c.newPath;if(!T)break;let P=u.files[p];if(await le(p)&&P)try{await ne.mkdir(ie.dirname(G(T)),{recursive:!0}),await ne.rename(G(p),G(T)),u.files[T]={...P,seq:c.fileSeq??P.seq},delete u.files[p],U.save(u)}catch{await De(T,c.fileSeq)}else ke(p),await De(T,c.fileSeq);break}case"mkdir":await ne.mkdir(G(p),{recursive:!0});break;case"rename-folder":case"move-folder":{let T=c.newPath;if(!T)break;try{await ne.mkdir(ie.dirname(G(T)),{recursive:!0}),await ne.rename(G(p),G(T))}catch{}Ln(p,T);break}case"delete-folder":{let T=`${p}/`;for(let P of Object.keys(u.files))(P===p||P.startsWith(T))&&await Yt(P);await We(G(p));break}}if(u.cursor=c.seq,U.save(u),c.op==="move"||c.op==="rename-folder"||c.op==="move-folder"||c.op==="delete"||c.op==="delete-folder")try{await t.onRemoteApplied?.(c)}catch{}},Is=async(c,m,y)=>{let p=Number(m?.seq??0),T=m?.content??null;if(T!==null&&et(T)===y.hash){await Ie(c,p,y.hash,y);return}if(T===null&&p===0){if(!u?.files[c]){k.set(c,m?.code||"EXISTS"),v();return}ke(c),E({key:c,run:()=>de(c)});return}await De(c,p)},wt=async(c,m)=>{if(!g||!u)return;let y=await le(c);if(!y){E({key:c,run:()=>de(c)});return}if(y.size>ci){k.set(c,"TOO_LARGE"),v();return}let p=y.buf.toString("utf8");try{let T=await g.putFile(u.vaultId,c,p,m);k.delete(c),await Ie(c,T.seq,T.hash??y.hash,y)}catch(T){if(T instanceof fe&&T.status===409){await Is(c,T.body,y);return}throw T}},bt=async(c,m)=>{if(!g||!u)return;let y=await le(c);if(!y){E({key:c,run:()=>de(c)});return}if(y.size>(A??ui)){k.set(c,"TOO_LARGE"),v();return}try{let p=await g.putBinary(u.vaultId,c,y.buf,{baseSeq:m});k.delete(c),await Ie(c,p.seq,y.hash,y)}catch(p){if(p instanceof fe&&p.status===409){let T=Number(p.body?.seq??0),P=p.body?.hash??null;if(P!==null&&P===y.hash){await Ie(c,T,y.hash,y);return}if(T===0){if(!u.files[c]){k.set(c,p.body?.code||"EXISTS"),v();return}ke(c),E({key:c,run:()=>de(c)});return}await De(c,T);return}throw p}},zn=async c=>{if(!g||!u||Ce(c))return;let m=oe,y=u.files[c];if(y){if(je(Pe(c)))try{let p=await g.getFile(u.vaultId,c);if(p.seq!==y.seq){await De(c,p.seq);return}}catch(p){if(p instanceof fe&&p.status===404){ke(c);return}throw p}if(!(m!==oe||Ce(c))){try{await g.deleteFile(u.vaultId,c,y.seq,{confirmed:B})}catch(p){if(p instanceof fe&&p.status===409){await De(c,Number(p.body?.seq??0)||null);return}if(p instanceof fe&&p.status===429&&p.body?.code==="MASS_DELETE_BLOCKED"){M.set(c,"remote"),j=!0,se(),v();return}throw p}ke(c)}}},St=async()=>w?await ne.stat(w).then(m=>m.isDirectory()).catch(()=>!1)||!e.requireRootExists&&!Object.keys(u?.files??{}).length?!0:($("error",`vault-missing: ${w}`),J(),!1):!1,oe=0,vt=new Set,Et=new Map,be=c=>JSON.stringify([c.from,c.to]),Ue=(c,m)=>c===m||c.startsWith(`${m}/`),Ce=c=>[...u?.moves??[],...vt].some(m=>Ue(c,m.from)||Ue(c,m.to)),Me=()=>!!(u?.moves?.length||vt.size),Gt=async c=>{if(!g||!u)return;let{from:m,to:y,kind:p}=c;if(s(m)===null||s(y)===null)throw new Error("Invalid queued cloud move");c.hashes??=Object.fromEntries(Object.entries(u.files).filter(([R])=>Ue(R,m)).map(([R,L])=>[R.slice(m.length),L.hash])),U.save(u),await U.flush(!0);let T,P=!1;try{if(p==="folder"){let R=ie.posix.dirname(m)==="."?"":ie.posix.dirname(m),L=ie.posix.dirname(y)==="."?"":ie.posix.dirname(y);R===L?await g.renameFolder(u.vaultId,m,ie.posix.basename(y)):await g.moveFolder(u.vaultId,m,L)}else{let R=await g.move(u.vaultId,m,y);T=Number(R.seq)}}catch(R){if(!(R instanceof fe)||R.status!==404)throw R;let L=await g.tree(u.vaultId);if(L.entries.some(V=>Ue(V.path,m))||L.folders.some(V=>Ue(V,m)))throw R;let q=L.entries.find(V=>V.path===y);if(T=q?.seq,P=!q&&!L.entries.some(V=>Ue(V.path,y))&&!L.folders.some(V=>Ue(V,y)),!P){let V=Object.entries(c.hashes);if(!(V.length>0&&V.every(([Re,Ve])=>L.entries.some(Ye=>Ye.path===y+Re&&Ye.hash===Ve))))throw new fe(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(P)for(let R of Object.keys(u.files))Ue(R,m)&&delete u.files[R];else Ln(m,y),T!==void 0&&u.files[y]&&(u.files[y].seq=T);u.moves=(u.moves??[]).filter(R=>be(R)!==be(c)),U.save(u);try{await U.flush(!0)}catch(R){throw u.moves.unshift(c),U.save(u),R}let O=Et.get(be(c));Et.delete(be(c)),O?.(),Ce(y)||(p==="folder"?await Jt():await de(y))},de=async(c,m=!1)=>{if(!u||Ce(c))return;if(!r(c,Pe(c))){ke(c);return}if(!await St())return;let y=await le(c);if(Ce(c))return;let p=u.files[c]??null,T=jt(y?.hash??null,p,p?{seq:p.seq,hash:p.hash}:null);switch(T.kind){case"push":je(Pe(c))?await wt(c,T.baseSeq):await bt(c,T.baseSeq);break;case"pushCreate":je(Pe(c))?await wt(c,0):await bt(c,0);break;case"pushDelete":if(m){Ct();break}if(!B&&(M.has(c)||we())){M.set(c,"remote"),se(),v();break}K.push(Date.now()),await zn(c);break;case"dropShadow":ke(c);break;default:y&&p&&y.hash===p.hash&&y.mtimeMs>=0&&(p.size!==y.size||p.mtimeMs!==y.mtimeMs)&&await Ie(c,p.seq,p.hash,y);break}},qn=async()=>{let c=new Map;if(!w||!u)return c;let m=w,y=null,p=async T=>{if(y)return;let P;try{P=await ne.readdir(T,{withFileTypes:!0})}catch(O){y=`${T}: ${O?.message??String(O)}`;return}for(let O of P){if(ft(O.name)||O.isDirectory()&&e.ignoreNames?.includes(O.name))continue;let R=ie.join(T,O.name);if(O.isDirectory())await p(R);else if(O.isFile()){let L=ie.relative(m,R).split(ie.sep).join("/"),D=n(L);if(!D)continue;try{let q=await ne.stat(R);if(!q.isFile())continue;c.set(D,{size:q.size,mtimeMs:Math.floor(q.mtimeMs)})}catch(q){if(q?.code==="ENOENT")continue;y=`${R}: ${q?.message??String(q)}`;return}}}};return await p(m),y?($("error",`scan-failed: ${y}`),J(),null):c},Jt=async()=>{let c=oe;if(Me()||c!==oe||!u||!await St())return;let m=await qn();if(!m||Me()||c!==oe)return;let y=!1;for(let[P,O]of[...M])(O==="remote"&&m.has(P)||O==="local"&&!m.has(P))&&(M.delete(P),y=!0);M.size||he();for(let[P,O]of m){let R=u.files[P];R&&R.size===O.size&&R.mtimeMs===O.mtimeMs||E({key:P,run:()=>de(P)})}let p=Object.keys(u.files),T=p.filter(P=>!m.has(P));if(T.length&&!B&&(j||bn(T.length,p.length,Gr))){j=!0;for(let P of T)M.set(P,"remote");se(),v();return}y&&(se(),v());for(let P of T)M.has(P)||E({key:P,run:()=>de(P)})},it=async()=>{let c=oe;if(Me()||c!==oe||!g||!u||!w||!await St())return;let m=await g.tree(u.vaultId);if(m.maxFileBytes!==void 0&&m.maxFileBytes!==A&&(A=m.maxFileBytes,v()),Me()||c!==oe)return;let y=new Map;for(let D of m.entries)s(D.path)===null||!r(D.path,D.kind)||y.set(D.path,D);let p=await qn();if(!p||Me()||c!==oe)return;let T=new Set([...y.keys(),...p.keys(),...Object.keys(u.files)]),P=Object.keys(u.files).length,O=[];for(let D of T){if(Me()||c!==oe)return;let q=u.files[D]??null,V=y.get(D)??null,me=p.get(D)??null,Re=null,Ve=ee(me?.size??0);if(me)if(q&&q.size===me.size&&q.mtimeMs===me.mtimeMs)Re=q.hash,Ve=me;else{let Ye=await le(D);Ye&&(Re=Ye.hash,Ve=Ye)}O.push({sp:D,d:jt(Re,q,V?{seq:V.seq,hash:V.hash}:null),rSeq:V?.seq??null,localHash:Re,localStat:Ve})}if(Me()||c!==oe)return;let R=O.filter(D=>D.d.kind==="deleteLocal"||D.d.kind==="pushDelete").length,L=!B&&(j||bn(R,P,Gr));L&&R&&(j=!0),M.clear();for(let{sp:D,d:q,rSeq:V,localHash:me,localStat:Re}of O){if(Me()||c!==oe)return;if(L&&(q.kind==="deleteLocal"||q.kind==="pushDelete")){M.set(D,q.kind==="deleteLocal"?"local":"remote");continue}if((q.kind==="deleteLocal"||q.kind==="pushDelete")&&((await le(D))?.hash??null)!==me){E({key:D,run:()=>de(D)});continue}if(Me()||c!==oe)return;switch(q.kind){case"adopt":await Ie(D,V,me,Re);break;case"pull":await De(D,V);break;case"push":je(Pe(D))?await wt(D,q.baseSeq):await bt(D,q.baseSeq);break;case"pushCreate":je(Pe(D))?await wt(D,0):await bt(D,0);break;case"pushDelete":await zn(D);break;case"deleteLocal":await jn(D),ke(D);break;case"conflict":await De(D,V);break;case"dropShadow":ke(D);break;case"none":break}}B&&(B=!1,K.length=0),M.size||he(),se(),L&&v();for(let D of m.folders)if(!(s(D)===null||!r(D,"folder")))try{await ne.mkdir(G(D),{recursive:!0})}catch{}u.cursor=m.seq,u.lastSyncAt=Date.now(),U.save(u)},Rs=async()=>{if(!g||!u)return;let c=u.cursor,m=await g.changes(u.vaultId,c);if(m.changes.length===0&&m.seq>c||m.changes.length>0&&m.changes[0].seq!==c+1){await it();return}for(let p of m.changes)await Hn(p)},Ne=null,Bn=[],Wn=()=>{Ne&&Bn.push(Ne.close()),Ne=null},Ps=()=>{if(!a||Ne||!w)return;Ne=Nr.watch(w,{ignoreInitial:!0,depth:12,ignored:m=>{let y=ie.basename(m);return ft(y)||!!e.ignoreNames?.includes(y)}});let c=m=>{if(!w)return;let y=ie.relative(w,m);if(!y||y.startsWith(".."))return;let p=n(y);p&&N(p)};Ne.on("change",c),Ne.on("add",c),Ne.on("unlink",()=>Ct()),Ne.on("unlinkDir",()=>Ct())},kt=()=>{S?.stop(),S=null},$s=()=>{if(!a||!g||!u||S)return;let c=x;c&&(S=zr({baseUrl:c.cloudUrl,vaultId:u.vaultId,token:c.token},{getSince:()=>u?.cursor??0,onHello:m=>{u&&m>u.cursor&&E({run:Rs})},onChange:m=>{E({run:()=>Hn(m)})},onReset:()=>{E({run:it})},onOpen:()=>{(d==="offline"||d==="starting")&&$("idle",null),E({run:Jt})},onDown:()=>{(d==="idle"||d==="syncing")&&$("offline")},onPresence:m=>t.onPresence?.(u?.vaultId??"",m),onPresenceRoster:m=>t.onPresenceRoster?.(u?.vaultId??"",m)}))},Ds=async()=>{let c=await xe(o);if(c.cloudSync?.deviceId)return c.cloudSync.deviceId;let m=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Oe({cloudSync:{...c.cloudSync??{},deviceId:m}},o),m},Ms=async c=>{kt(),Wn(),ae.length=0,Ee.clear(),M.clear(),B=!1,j=!1,K.length=0;let m=await xe(o);if(c!==i)return;let y=m.cloudSync;if(y?.enabled===!1){w=null,g=null,$("disabled",null);return}if(!o||o!==ye()){$("auth-required","not-logged-in");return}if(w=e.localRoot,e.requireRootExists){let O=await ne.stat(w).then(R=>R.isDirectory()).catch(()=>!1);if(c!==i)return;if(!O){$("error",`vault-missing: ${w}`),J();return}}if(c!==i)return;let p=t.loadCreds();if(!p.cloudUrl||!p.token){g=null,$("auth-required","not-logged-in");return}$("starting",null);let T=y?.deviceId??await Ds();if(c!==i)return;let P=e.clientIdSuffix?`${T}#${e.clientIdSuffix}`:T;x={cloudUrl:p.cloudUrl,token:p.token},g=Hr({baseUrl:p.cloudUrl,token:p.token,clientId:P});try{let O=e.vaultId==="first"?y?.vaultId:e.vaultId;if(!O){let L=await g.listVaults();if(c!==i)return;if(!L.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");O=L[0].id,await Oe({cloudSync:{...y??{},vaultId:O}},o)}if(c!==i)return;let R=await vn(e.shadowName);if(c!==i||(u=R&&R.vaultRoot===w&&R.vaultId===O&&R.folder===""?R:{vaultRoot:w,folder:"",vaultId:O,cursor:0,lastSyncAt:null,files:{}},c!==i))return;for(let[L,D]of Object.entries(u.pending??{}))M.set(L,D);if(M.size&&(j=!0),!e.requireRootExists){let L=await ne.stat(w).then(D=>D.isDirectory()).catch(()=>!1);if(c!==i)return;if(!L){if(Object.keys(u.files).length){$("error",`mirror-missing: ${w}`),J();return}if(await ne.mkdir(w,{recursive:!0}),c!==i)return}}Ps();for(let L of u.moves??[])E({key:`move:${be(L)}`,run:()=>Gt(L)});E({run:it}),E({run:async()=>{$s()}})}catch(O){if(c!==i)return;z(O)?$("auth-required","login-expired"):($("offline",O?.message||String(O)),J())}},Vn=()=>{a=!1,kt(),Wn(),ae.length=0,Ee.clear(),W();for(let c of[_,C,b])c&&clearTimeout(c);_=C=b=null},Yn=async()=>{$e&&await new Promise(c=>h.add(c)),await Promise.all(Bn.splice(0)),await U.flush(),u=null,g=null,x=null,w=null,F=0,k.clear(),A=null,M.clear(),B=!1,j=!1,K.length=0,d="disabled",f=null},Ns=()=>{Gn()},_t=null,at=()=>{_t?.(),_t=pe().onBeforeQuit(Ns);let c=++i;Vn();let m=l.catch(()=>{}).then(async()=>{await Yn(),c===i&&(a=!0,await Ms(c))});return l=m,m},Gn=()=>{_t?.(),_t=null,++i,Vn();let c=l.catch(()=>{}).then(Yn);return l=c,c},ze=()=>({enabled:d!=="disabled",state:d==="idle"&&I.size?"syncing":d,lastSyncAt:u?.lastSyncAt??null,pending:ae.length+I.size,conflicts:F,skipped:[...k].map(([c,m])=>({path:c,reason:m})),error:f,pendingDeletions:M.size,maxFileBytes:A});return{getStatus:ze,start(){at()},notifyLocal(c,m,y){if(!u||d==="disabled"||d==="auth-required")return;let p=n(c),T=y?n(y):null;if(m==="write"&&p){ft(p.split("/").pop()||"")||N(p);return}if(m==="remove"){if(!p)return;let P=`${p}/`,O=!1;for(let R of Object.keys(u.files))(R===p||R.startsWith(P))&&(O=!0,E({key:R,run:()=>de(R)}));!O&&p&&E({key:p,run:()=>de(p)})}},holdLocalMove(c,m){let y=T=>e.serverDir?`${e.serverDir}/${T.replace(/\\/g,"/").normalize("NFC")}`:T.replace(/\\/g,"/").normalize("NFC"),p={from:y(c),to:y(m)};return++oe,vt.add(p),()=>{vt.delete(p)}},async notifyLocalMove(c,m,y,p){let T=n(c),P=n(m),O=u??await vn(e.shadowName),R=Sn(c,""),L=R&&(e.serverDir?`${e.serverDir}/${R}`:R);if(!T&&P&&L&&O&&Object.keys(O.files).some(D=>D===L||D.startsWith(`${L}/`))&&(T=L),!T&&!P){y?.();return}if(T&&P){let D=u??O;if(!D){y?.();return}let q=p??(Object.keys(D.files).some(me=>me.startsWith(`${T}/`))?"folder":"file"),V={from:T,to:P,kind:q};D.moves??=[],D.moves.some(me=>be(me)===be(V))||(D.moves.push(V),++oe),y&&Et.set(be(V),y),U.save(D);try{await U.flush(!0)}catch(me){throw D.moves=D.moves.filter(Re=>be(Re)!==be(V)),Et.delete(be(V)),U.save(D),me}u===D&&a&&d!=="disabled"&&d!=="auth-required"&&E({key:`move:${be(V)}`,run:()=>Gt(V)});return}T&&this.notifyLocal(c,"remove"),P&&(E({key:P,run:()=>de(P)}),Ct()),y?.()},async setEnabled(c){let m=await xe(o);return await Oe({cloudSync:{...m.cloudSync??{},enabled:c}},o),await at(),ze()},async restart(){return await at(),ze()},async syncNow(){if(k.clear(),d==="disabled"||d==="auth-required"||!g)await at();else{for(let c of u?.moves??[])E({key:`move:${be(c)}`,run:()=>Gt(c)});E({run:it})}return ze()},confirmMassDeletions(){return M.size&&(B=!0,j=!1,M.clear(),K.length=0,se(),E({run:it})),ze()},stop:Gn};function Ct(){a&&(C&&clearTimeout(C),C=setTimeout(()=>{C=null,E({run:Jt})},fi))}}import{createHash as Si}from"node:crypto";function Jr(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 Kr(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 vi=t=>Si("sha256").update(t).digest("hex").slice(0,8),Ei=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Lt="\u4E0E\u6211\u5171\u4EAB";function En(t){let e=vi(`${t.vaultId}:${t.path}`),n=Jr(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:`${Lt}/${Ei(t.title)}-${e}`,serverDir:s,inScope:(r,o)=>Kr(n,r,o)}}function kn(){let t=pe().readCreds(),e=Te(t.cloudUrl??"",t.token??""),n=new AbortController,s=()=>{let f=pe().readCreds();if(n.signal.aborted||!e||Te(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,g)=>{let S=s();if(!S.cloudUrl||!S.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let x=await fetch(`${S.cloudUrl.replace(/\/+$/,"")}/api/amadeus${u}`,{method:f,headers:{Authorization:`Bearer ${S.token}`,...g!==void 0?{"Content-Type":"application/json"}:{}},body:g!==void 0?JSON.stringify(g):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!x.ok){let F=null;try{F=await x.json()}catch{}throw Object.assign(new Error(F?.detail||`http ${x.status}`),{status:x.status,code:F?.code})}let w=await x.json();return s(),w},a=null,i=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}},h=async()=>(await o("GET","/shared-with-me")).items.map(u=>{let g=En(u),S=u.path.split("/").pop()??u.path;return{...u,localPath:`${g.localRelDir}/${S}`}}),d=null;return{stop:()=>n.abort(),call:o,ensureOwnVault:i,myUserId:l,sharedWithMe:h,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 g=(f??"").replace(/\\/g,"/"),S,x=null,w=u.find(F=>g.startsWith(`${F.localRelDir}/`));w?(S=w.vaultId,x=w.serverDir?`${w.serverDir}/${g.slice(w.localRelDir.length+1)}`:g.slice(w.localRelDir.length+1)):(S=await i(),x=g||null),await o("POST",`/vaults/${encodeURIComponent(S)}/presence`,{page:x})}}}import{promises as Xr}from"node:fs";import ki from"node:path";var _n=".forsion-vault.md",Cn=t=>`${t}/${_n}`;var ve=t=>t.replace(/\\/g,"/").normalize("NFC");function Tn(t){let e=ve(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function tt(t,e,n){let s=ve(n);if(!s)return!1;if(t.some(r=>ve(r.path)===s))return!0;for(let r of e??[]){let o=ve(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=Tn(r);return!!o&&s.startsWith(o)})}function xn(t,e,n){let s=ve(t),r=ve(e);return s===r?ve(n):s.startsWith(`${r}/`)?ve(n)+s.slice(r.length):null}function mt(t,e,n){let s=!1,r=t.map(o=>{let a=xn(o,e,n);return a===null?o:(s=!0,a)});return{changed:s,next:r}}async function Zr(t){let e=await Xr.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[];for(let s of e)!s.isDirectory()||s.name.startsWith(".")||await Xr.access(ki.join(t,s.name,_n)).then(()=>!0,()=>!1)&&n.push(s.name);return n.sort()}var ce={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 _i}from"node:crypto";var Ht=t=>_i("sha256").update(t).digest("hex").slice(0,8);function Qr(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Le(t,e=[]){let n=[],s=[];for(let r of t){let o=ve(r.path);if(!o)continue;s.push(o);let a=Tn(r);a&&n.push(a)}return{entries:t,exclude:e,prefixes:n,paths:s}}function es(t,e){let n=Qr(ve(e));if(!n)return!1;if(tt(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 gt(t,e,n){let s=!1,r=t.map(o=>{let a=xn(o.path,e,n);return a===null?o:(s=!0,{...o,path:a})});return{changed:s,next:r}}function ts(t,e,n,s){if(e==="delete"||e==="delete-folder"){let r=ve(n),o=t.filter(a=>{let i=ve(a.path);return!(i===r||e==="delete-folder"&&i.startsWith(`${r}/`))});return{changed:o.length!==t.length,next:o}}return s?gt(t,n,s):{changed:!1,next:t}}function An(t,e){let n=Xe(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Lt?`\u300C${Lt}\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 ns=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],In=t=>ns.every(e=>typeof t[e]=="function"),Ci=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function Rn(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(ce.get,()=>e?e.get():Ci()),t.handle(ce.setEnabled,(s,r)=>n().setEnabled(r)),t.handle(ce.syncNow,()=>n().syncNow()),t.handle(ce.confirmDeletions,()=>n().confirmDeletions()),t.handle(ce.entryGet,()=>n().entryGet()),t.handle(ce.otherSideDbs,()=>n().otherSideDbs()),t.handle(ce.entryEnable,(s,r)=>n().entryEnable(r)),t.handle(ce.entryDisable,(s,r)=>n().entryDisable(r)),t.handle(ce.entryClosure,(s,r,o)=>n().entryClosure(r,o)),t.handle(ce.collabCall,(s,r,o)=>n().collabCall(r,o)),t.handle(ce.switchSide,(s,r)=>n().switchSide(s.sender.id,r)),t.setAmadeusSyncFactory(s=>{mr(s);let r=rs(s);return e=r.handlers,r.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function rs(t){let e=t.notifyAll,n=()=>t.vaultRoot(),s=0,r=!1,o=kn(),a=new Map,i=()=>{let _=Date.now();for(let[C,b]of a)_-b.at>7e4&&a.delete(C);e(ce.presence,[...a.values()])},l={loadCreds:()=>t.readCreds(),onStatus:_=>e(ce.status,{..._,pendingDeletions:K(),side:S()?"cloud":"local"}),onPresence:(_,C)=>{let b=C;b?.userId&&(a.set(b.userId,{userId:b.userId,username:String(b.username??"user"),page:b.page??null,at:Number(b.at)||Date.now()}),i())},onPresenceRoster:(_,C)=>{if(Array.isArray(C)){for(let b of C){let v=b;v?.userId&&a.set(v.userId,{userId:v.userId,username:String(v.username??"user"),page:v.page??null,at:Number(v.at)||Date.now()})}i()}}},h=()=>{let _=s;return{...l,onStatus:C=>{_===s&&l.onStatus(C)},onPresence:(C,b)=>{_===s&&l.onPresence(C,b)},onPresenceRoster:(C,b)=>{_===s&&l.onPresenceRoster(C,b)}}},d=ht(h()),f=new Map,u=[],g=async()=>{if(!r||!ye())return;let _=s,C=o,b;try{b=await C.sharedWithMe()}catch{return}if(_!==s||!r)return;let v=b.map(E=>En(E));u=v;let $=new Set(v.map(E=>E.key));for(let[E,I]of f)if(!$.has(E)){if(await I.engine.stop(),_!==s)return;f.delete(E)}for(let E of v){if(f.has(E.key))continue;let I=ht(h(),{localRoot:Be.join(Fe(),...E.localRelDir.split("/")),shadowName:`amadeus-sync-${ct()}-share-${E.key}`,vaultId:E.vaultId,serverDir:E.serverDir,inScope:E.inScope});f.set(E.key,{engine:I,plan:E}),I.start()}},S=()=>n()===Fe(),x=(_,C=_.base)=>{_.base=C;let b=[C,..._.pendingMoves];_.scope.current=Le(b.flatMap(v=>v.entries),b.flatMap(v=>v.exclude))},w=new Map,F=new Set,k=()=>{e(ce.entryChange)},A=async(_,C)=>{let b=w.get(_);if(!b)return;let v=I=>I&&I.startsWith(`${b.cloudName}/`)?I.slice(b.cloudName.length+1):null,$=v(C.path);if(!$)return;let E=!1;await Ge(I=>{if(w.get(_)!==b)return!1;let N=(I.entrySync??[]).find(J=>J.vaultRoot===_);if(!N)return!1;let W=C.op,H=v(C.newPath),z=ts(N.entries,W,$,H),X=H?mt(N.exclude??[],$,H):{changed:!1,next:N.exclude??[]};if(!z.changed&&!X.changed)return!1;E=!0,N.entries=z.next,X.changed&&(N.exclude=X.next),x(b,Le(N.entries,N.exclude??[]))}),E&&w.get(_)===b&&k()},U=_=>{let C=s;return{...h(),onStatus:b=>{C===s&&e(ce.status,{...b,pendingDeletions:K(),side:"local",binding:_})},onRemoteApplied:async b=>{C===s&&await A(_,b)}}},M=async()=>{let _=ye();if(!r||!_)return;let C=s,b=o,v=ct(_);await t.adoptLegacyCloudState(_,Wr);let $=await xe(_),E=$.entrySync??[];if(C!==s||!r||_!==ye())return;let I=new Map(E.map(N=>[N.vaultRoot,N]));for(let[N,W]of w){let H=I.get(N);if(!(H&&H.cloudName===W.cloudName)&&(await W.engine.stop(),C!==s||(w.delete(N),H&&await Br(`amadeus-sync-${v}-entry-${Ht(N)}`),C!==s)))return}for(let N of E){let W=w.get(N.vaultRoot);if(W){x(W,Le(N.entries,N.exclude??[]));continue}let H={current:Le(N.entries,N.exclude??[])},z=N.cloudName,X=ht(U(N.vaultRoot),{accountId:_,localRoot:N.vaultRoot,shadowName:`amadeus-sync-${v}-entry-${Ht(N.vaultRoot)}`,vaultId:"first",serverDir:z,clientIdSuffix:`entry-${Ht(N.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:J=>J===z?!0:J.startsWith(`${z}/`)?es(H.current,J.slice(z.length+1)):!1});w.set(N.vaultRoot,{engine:X,scope:H,cloudName:z,base:H.current,pendingMoves:new Set}),X.start()}if($.cloudSync?.enabled!==!1)for(let N of E)F.has(N.cloudName)||(async()=>{try{let W=await b.ensureOwnVault();await b.call("PUT",`/vaults/${encodeURIComponent(W)}/file`,{path:Cn(N.cloudName),content:"",baseSeq:0}),C===s&&F.add(N.cloudName)}catch(W){W?.status===409&&C===s&&F.add(N.cloudName)}})()},B=async(_,C,b,v,$)=>{let E=C.replace(/\\/g,"/").normalize("NFC"),I=b.replace(/\\/g,"/").normalize("NFC"),N=!1,W,H,z,X=$??"file";try{await Ge(async J=>{if(w.get(_)!==v)return!1;let G=(J.entrySync??[]).find(le=>le.vaultRoot===_);if(!G)return!1;let ee=gt(G.entries,E,I),Z=mt(G.exclude??[],E,I),_e=tt(G.entries,G.exclude,E);!$&&await nt.stat(Be.join(_,...I.split("/"))).then(le=>le.isDirectory(),()=>!1)&&(X="folder");let He=X==="folder"?"folder":/\.md$/i.test(I)?"page":"asset";_e&&!tt(ee.next,Z.next,I)&&(ee.next.push({path:I,kind:He}),ee.changed=!0),N=ee.changed||Z.changed;let We=G.entries.filter(le=>gt([le],E,I).changed);return _e&&!We.some(le=>le.path===E)&&We.push({path:E,kind:He}),W=Le(We,(G.exclude??[]).filter(le=>mt([le],E,I).changed)),H=v.base,v.pendingMoves.add(W),G.entries=ee.next,G.exclude=Z.next,z=Le(G.entries,G.exclude),x(v,z),N})}catch(J){throw W&&v.pendingMoves.delete(W),x(v,v.base===z&&H?H:v.base),J}try{W&&await v.engine.notifyLocalMove(E,I,()=>{v.pendingMoves.delete(W),x(v)},X)}catch(J){throw W&&v.pendingMoves.delete(W),await Ge(G=>{let ee=G.entrySync?.find(Z=>Z.vaultRoot===_);if(!ee)return!1;ee.entries=gt(ee.entries,I,E).next,ee.exclude=mt(ee.exclude??[],I,E).next,x(v,Le(ee.entries,ee.exclude))}),J}N&&w.get(_)===v&&k()},j=_=>{let C=_.replace(/\\/g,"/");for(let{engine:b,plan:v}of f.values())if(C.startsWith(`${v.localRelDir}/`))return{engine:b,rel:C.slice(v.localRelDir.length+1)};return{engine:d,rel:C}};t.setMutationHooks((_,C)=>{if(S()){let b=j(_);b.engine.notifyLocal(b.rel,C);return}w.get(n()??"")?.engine.notifyLocal(_,C)},(_,C,b)=>{if(S()){let E=j(_),I=j(C);if(E.engine===I.engine)return E.engine.notifyLocalMove(E.rel,I.rel,void 0,b);E.engine.notifyLocal(E.rel,"remove"),I.engine.notifyLocal(I.rel,"write");return}let v=n()??"",$=w.get(v);if($)return B(v,_,C,$,b)},(_,C)=>{if(S()){let b=j(_),v=j(C),$=[b.engine.holdLocalMove(b.rel,v.rel)];return b.engine!==v.engine&&$.push(v.engine.holdLocalMove(b.rel,v.rel)),()=>{for(let E of $)E()}}return w.get(n()??"")?.engine.holdLocalMove(_,C)});let K=()=>{let _=d.getStatus().pendingDeletions;for(let{engine:C}of f.values())_+=C.getStatus().pendingDeletions;for(let{engine:C}of w.values())_+=C.getStatus().pendingDeletions;return _},se=_=>({..._,pendingDeletions:K(),side:S()?"cloud":"local"}),he=()=>{if(!r)return Promise.resolve(d.getStatus());g();for(let{engine:_}of f.values())_.syncNow();for(let{engine:_}of w.values())_.syncNow();return d.syncNow()},we=async()=>{++s,r=!1,o.stop();let _=[d.stop(),...[...f.values()].map(({engine:b})=>b.stop()),...[...w.values()].map(({engine:b})=>b.stop())];f.clear(),w.clear(),u=[],F.clear(),a.clear(),i(),await Promise.all(_),await t.awaitPendingVaultWrites();let C=n();if(C&&It(C)){let b=await xe(),v=b.localVault&&!It(b.localVault)?b.localVault:Be.join(t.workspaceDir(),"Amadeus");await nt.mkdir(v,{recursive:!0}),await Oe({lastVault:v,localVault:v,lastPage:void 0}),await t.activateRoot(v,!1)}k()};return{handlers:{get:()=>se(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(),...w.values()].map(({engine:b})=>b.restart())),se(d.getStatus()))},syncNow:()=>he(),confirmDeletions:()=>{for(let{engine:_}of f.values())_.confirmMassDeletions();for(let{engine:_}of w.values())_.confirmMassDeletions();return se(d.confirmMassDeletions())},entryGet:async()=>{let _=await xe(),C=Fe();return{vaults:_.entrySync??[],activeRoot:n(),cloudRoot:C,mirrorVaults:await Zr(C)}},otherSideDbs:async()=>{let _=n();if(!_)return null;let C=Fe(),b=await xe(),v=_===C?b.localVault&&b.localVault!==C?b.localVault:null:C;if(!v)return null;let $=[],E=500,I=async(N,W)=>{if($.length>=E)return;let H;try{H=await nt.readdir(N,{withFileTypes:!0})}catch{return}for(let z of H){if($.length>=E)break;if(z.name.startsWith(".")||z.isSymbolicLink())continue;let X=W?`${W}/${z.name}`:z.name;if(z.isDirectory())await I(Be.join(N,z.name),X);else if(z.isFile()&&/\.db$/i.test(z.name))try{$.push({rel:X,source:await nt.readFile(Be.join(N,z.name),"utf8")})}catch{}}};return await I(v,""),{root:v,vaultName:v===C?"\u4E91\u7AEF":Be.basename(v),dbs:$}},entryEnable:async _=>{let C=s,b=o;if(!r||!ye())return{error:"Sign in to enable cloud sync"};let v=n();if(!v||S())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let $=await xe(),E=$.entrySync??[],I=E.find(N=>N.vaultRoot===v);if(!I){let N=(_.cloudName??Be.basename(v)).normalize("NFC").trim(),W=An(N,E.map(H=>H.cloudName));if(W)return{error:W};if(!_.merge)try{let H=await b.ensureOwnVault(),z=await b.call("GET",`/vaults/${encodeURIComponent(H)}/tree`);if((z.folders??[]).some(J=>J===N||J.startsWith(`${N}/`))||(z.entries??[]).some(J=>J.path===N||J.path.startsWith(`${N}/`)))return{conflict:N}}catch(H){return{error:H?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}I={vaultRoot:v,cloudName:N,entries:[]},E.push(I),(async()=>{try{let H=await b.ensureOwnVault();await b.call("PUT",`/vaults/${encodeURIComponent(H)}/file`,{path:Cn(I.cloudName),content:"",baseSeq:0})}catch{}})()}return C!==s||!r?{error:"Cloud account changed; retry from the current account"}:(await Ge(N=>{if(C!==s||!r)return!1;let W=N.entrySync??[],H=W.find(Z=>Z.vaultRoot===v);if(!H){let Z=An(I.cloudName,W.map(_e=>_e.cloudName));if(Z)throw new Error(Z);H={vaultRoot:v,cloudName:I.cloudName,entries:[]},W.push(H)}let z=Z=>String(Z??"").replace(/\\/g,"/").normalize("NFC"),X=new Set;for(let Z of _.entries??[]){let _e=z(Z.path);_e&&(X.add(_e),!H.entries.some(He=>He.path===_e)&&H.entries.push({path:_e,kind:Z.kind==="folder"||Z.kind==="asset"?Z.kind:"page"}))}let J=(_.exclude??[]).map(z).filter(Boolean),G=new Set([...X,...(_.include??[]).map(z).filter(Boolean)]);H.exclude=[...new Set([...(H.exclude??[]).filter(Z=>!G.has(Z)),...J])];let ee=new Set(J);H.entries=H.entries.filter(Z=>!ee.has(Z.path)),N.entrySync=W,I=H},$.cloudAccountId),C!==s?{error:"Cloud account changed; retry from the current account"}:(await M(),w.get(v)?.engine.syncNow(),k(),{ok:!0,cloudName:I.cloudName}))},entryDisable:async _=>{let C=n(),b=!1,v=s;return await Ge($=>{if(v!==s||!r)return!1;let E=($.entrySync??[]).find(W=>W.vaultRoot===C);if(!C||!E)return!1;let I=String(_??"").replace(/\\/g,"/").normalize("NFC"),N=E.entries.length;if(E.entries=E.entries.filter(W=>W.path!==I),tt(E.entries,E.exclude,I))E.exclude=[...new Set([...E.exclude??[],I])];else if(E.entries.length===N)return!1;b=!0}),!b||v!==s?{ok:!1}:(await M(),k(),{ok:!0})},entryClosure:(_,C)=>t.relatedClosure(String(_??""),C==="folder"?"folder":"page"),collabCall:async(_,C)=>{let b=o,v=async()=>b.ensureOwnVault(),$=I=>String((C??[])[I]??""),E=I=>(C??[])[I]??{};switch(_){case"listVaults":return(await b.call("GET","/vaults")).vaults;case"activeVaultId":return v();case"pageShare":return b.call("GET",`/vaults/${encodeURIComponent(await v())}/page-shares?path=${encodeURIComponent($(0))}`);case"createPageShare":return b.call("POST",`/vaults/${encodeURIComponent(await v())}/page-shares`,{path:$(0),...E(1)});case"updatePageShare":return b.call("PATCH",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}`,E(1));case"revokePageShare":return b.call("DELETE",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}`);case"setParticipantRole":return b.call("PATCH",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}/members/${encodeURIComponent($(1))}`,{role:$(2)});case"removeParticipant":return b.call("DELETE",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}/members/${encodeURIComponent($(1))}`);case"sharedWithMe":{let I=await b.sharedWithMe();return g(),I}case"leaveShare":{let I=b.myUserId();if(!I)throw new Error("\u672A\u767B\u5F55");return b.call("DELETE",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}/members/${encodeURIComponent(I)}`)}case"publishes":return b.call("GET",`/vaults/${encodeURIComponent(await v())}/shares`);case"listAllShares":{let I=(await b.call("GET","/vaults")).vaults||[],N=b.myUserId(),W=[],H=[];for(let z of I){try{let X=await b.call("GET",`/vaults/${encodeURIComponent(z.id)}/shares`);for(let J of X.shares||[])W.push({...J,vaultId:z.id,vaultName:z.name||""})}catch(X){t.log(`[connect] listAllShares publishes vault ${z.id} failed: ${X?.message}`)}try{let X=await b.call("GET",`/vaults/${encodeURIComponent(z.id)}/page-shares`),J=X?.shares||X?.pageShares||(Array.isArray(X)?X:[]);for(let G of J){let ee=G.created_by??G.createdBy;(!N||!ee||ee===N)&&H.push({...G,vaultId:z.id,vaultName:z.name||""})}}catch(X){t.log(`[connect] listAllShares pageShares vault ${z.id} failed: ${X?.message}`)}}return{publishes:W,pageShares:H,linkBase:await b.linkBase()}}case"createPublish":{let I=await b.call("POST",`/vaults/${encodeURIComponent(await v())}/shares`,{mode:$(0),path:$(1)});return{...I,url:`${await b.linkBase()}/share/${I.token}`}}case"revokePublish":return b.call("DELETE",`/vaults/${encodeURIComponent(await v())}/shares/${encodeURIComponent($(0))}`);case"revokePublishIn":return b.call("DELETE",`/vaults/${encodeURIComponent($(0))}/shares/${encodeURIComponent($(1))}`);case"revokePageShareIn":return b.call("DELETE",`/vaults/${encodeURIComponent($(0))}/page-shares/${encodeURIComponent($(1))}`);case"myUserId":return b.myUserId();case"linkBase":return b.linkBase();case"heartbeat":return b.heartbeat((C??[])[0]??null,u);default:throw new Error(`unknown collab fn: ${_}`)}},switchSide:async(_,C)=>{let b=await xe();if(C==="cloud"){if(!r||!ye())throw new Error("Sign in to open cloud notes");let E=Fe();await nt.mkdir(E,{recursive:!0}),b.lastVault&&!It(b.lastVault)&&await Oe({localVault:b.lastVault}),await Oe({lastVault:E});let I=await t.activateRoot(E,!1);return t.bindRenderer(_,E),{...I,side:"cloud"}}let v=b.localVault&&await nt.stat(b.localVault).then(E=>E.isDirectory()).catch(()=>!1)?b.localVault:null;if(!v){let E=await t.ensureDefaultVault();return t.bindRenderer(_,E.root),{...E,side:"local"}}await Oe({lastVault:v});let $=await t.activateRoot(v,!1);return t.bindRenderer(_,v),{...$,side:"local"}}},instance:{start:()=>{r=!0,d.start(),g(),M()},stopAllSync:we,restartAllSync:async()=>{await we(),o=kn(),d=ht(h()),r=!0,await Promise.all([d.restart(),g(),M()]),k(),e(ce.status,se(d.getStatus()))}}}}import{hostname as Ti}from"node:os";var xi=256*1024;function ss(t,e,n){if(n?.hasSecHeaders&&!n.gatewayStreamsSecHeaders)return!1;if(t.includes("text/event-stream"))return!0;let s=Number(e||NaN);return!Number.isFinite(s)||s>xi}var Pn=45e3,Ai=3e3,Ii=16*1024,Ri=6e4,zt=t=>`${t.replace(/\/+$/,"")}/api`,pt=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,n){return(this.deps.hubFetch??fetch)(e,n)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??Ri}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(n){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${n?.message||n}`)}}abortEnvelope(e){let n=this.inflight.get(e);return n?(this.inflight.delete(e),n.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[n,s]of[...this.inflight])e&&s.conn!==e||(this.inflight.delete(n),s.ctrl.abort())}sleep(e){return new Promise(n=>{let s=setTimeout(r,e);function r(){clearTimeout(s),n()}this.wake=()=>{this.wake=null,r()}})}async loop(e){let n=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:o,token:a}=this.deps.getCreds();if(!a)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let i=this.deps.getPairing();if(!i){if(i=await this.register(o,a,s),s.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(i),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${i.unitId}`)}let l=this.deps.getLanUrl();this.hubCaps=new Set;let h=this.deps.readIdleMs??Pn,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(`${zt(o)}/units/${i.unitId}/channel`,{headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":i.secret,...l?{"X-Unit-Lan-Url":l}:{}},signal:s.signal})}finally{d&&clearTimeout(d)}if(f.status===403||f.status===404){let u=Number(f.headers.get("content-length"))>Ii,g=setTimeout(()=>s.abort(),u?0:Ai),S=await f.json().then(x=>x?.code,()=>null);throw clearTimeout(g),S==="UNIT_NOT_FOUND"||S==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${f.status} ${S}),\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,n=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(o){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(o?.message||o),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/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,n=1e3;continue}if(await this.sleep(n),this.redialNow){this.redialNow=!1,n=1e3;continue}n=Math.min(n*2,3e4)}}async register(e,n,s){let r=this.deps.readIdleMs??Pn,o=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 a=await this.hubFetch(`${zt(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Ti(),platform:process.platform}),signal:s.signal});if(!a.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${a.status}`);let i=await a.json();if(!i.unitId||!i.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:i.unitId,secret:i.secret}}finally{o&&clearTimeout(o)}}async consume(e,n){let s=e.getReader(),r=new TextDecoder,o="",a=this.deps.readIdleMs??Pn,i=null,l=()=>{a&&(i&&clearTimeout(i),i=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(a/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),n.abort(),s.cancel().catch(()=>{})},a))};l();try{for(;;){let{done:h,value:d}=await s.read();if(h||n.signal.aborted)return;l(),o=this.parseFrames(o+r.decode(d,{stream:!0}),n)}}finally{i&&clearTimeout(i)}}parseFrames(e,n){let s=e,r;for(;(r=s.indexOf(`
206
+ `),{excludeFalseConflicts:!0}),s=[];for(let o of r){if(o.conflict)return null;o.ok&&s.push(...o.ok)}return s.join(`
207
+ `)}function ir(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var za=/[\u0000-\u001f\u007f]/;function mt(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||za.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function ar(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?mt(n):n.startsWith(`${e}/`)?mt(n.slice(e.length+1)):null}function zs(t,e){return e===""?t:`${e}/${t}`}function Dt(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function Le(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var Qe=t=>t==="page"||t==="db";var qa=1024,xe=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},qs=t=>12e4+Math.ceil(t/256);function Bs(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=async(s,o,i)=>{let l={Authorization:`Bearer ${t.token}`,...i?.headers};s!=="GET"&&(l["X-Amadeus-Client"]=t.clientId);let a;i?.json!==void 0?(l["Content-Type"]="application/json",a=JSON.stringify(i.json),a.length>=qa&&(l["Content-Encoding"]="gzip",a=await Lr(a))):i?.form&&(a=i.form);let u=await fetch(o,{method:s,headers:l,body:a,signal:AbortSignal.timeout(i?.timeoutMs??3e4)});if(!u.ok){let d=null;try{d=await u.json()}catch{}throw new xe(u.status,d,o)}return u.json()},r=s=>new URLSearchParams(s).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(s){let o=await n("GET",`${e}/vaults/${s}/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(i=>({path:String(i.path),kind:i.kind,seq:Number(i.seq??0),hash:i.hash??null,size:Number(i.size??0)}))}},async getFile(s,o){let i=await n("GET",`${e}/vaults/${s}/file?${r({path:o})}`);return{content:String(i.content??""),seq:Number(i.seq??0),hash:i.hash??null}},putFile(s,o,i,l,a=!1){return n("PUT",`${e}/vaults/${s}/file`,{json:{path:o,content:i,baseSeq:l,...a?{force:!0}:{}}})},async deleteFile(s,o,i,l){let a={path:o};i!==void 0&&(a.baseSeq=String(i)),await n("DELETE",`${e}/vaults/${s}/file?${r(a)}`,l?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(s,o,i){return n("POST",`${e}/vaults/${s}/move`,{json:{from:o,to:i}})},renameFolder(s,o,i){return n("POST",`${e}/vaults/${s}/folders/rename`,{json:{path:o,newName:i}})},moveFolder(s,o,i){return n("POST",`${e}/vaults/${s}/folders/move`,{json:{path:o,dest:i}})},async deleteFolder(s,o){await n("DELETE",`${e}/vaults/${s}/folders?${r({path:o})}`)},putBinary(s,o,i,l){let a=new FormData;return a.set("path",o),l?.ifAbsent&&a.set("ifAbsent","true"),l?.baseSeq!==void 0&&a.set("baseSeq",String(l.baseSeq)),a.set("file",new Blob([new Uint8Array(i)]),o.split("/").pop()||"file"),n("POST",`${e}/vaults/${s}/binary`,{form:a,timeoutMs:qs(i.length)})},async listVersions(s,o){return((await n("GET",`${e}/vaults/${s}/file/versions?${r({path:o})}`)).versions??[]).map(l=>({id:String(l.id),seq:Number(l.seq??0)}))},async getVersion(s,o){let i=await n("GET",`${e}/vaults/${s}/file/versions/${o}`);return String(i.content??"")},async getAsset(s,o){let i=new AbortController,l=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/vaults/${s}/asset?${r({ref:o})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:i.signal});if(!a.ok)throw new xe(a.redirected&&(a.status===401||a.status===403)?502:a.status,null,"asset:"+o);return clearTimeout(l),l=setTimeout(()=>i.abort(),qs(Number(a.headers.get("content-length"))||0)),new Uint8Array(await a.arrayBuffer())}finally{clearTimeout(l)}},async changes(s,o){let i=await n("GET",`${e}/vaults/${s}/changes?${r({since:String(o)})}`);return{changes:i.changes??[],seq:Number(i.seq??0)}}}}function Ws(t,e){let n=!1,r=0,s=null,o=null,i=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,l=u=>{if(n)return;e.onDown(u);let d=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,o=setTimeout(()=>void a(),d)},a=async()=>{if(n)return;s=new AbortController;let u;try{u=await fetch(i(),{headers:{Authorization:`Bearer ${t.token}`,Accept:"text/event-stream"},signal:s.signal})}catch(w){l(w);return}if(!u.ok||!u.body){l(new Error(`sse http ${u.status}`));return}r=0,e.onOpen();let d=u.body.getReader(),m=new TextDecoder,g="",p="",y=[],f=()=>{if(!y.length&&!p)return;let w=y.join(`
208
+ `),P=p||"message";p="",y=[];let H=null;try{H=w?JSON.parse(w):null}catch{return}P==="hello"?e.onHello(Number(H?.seq??0)):P==="change"?e.onChange(H):P==="reset"?e.onReset():P==="presence"?e.onPresence?.(H):P==="presence-roster"&&e.onPresenceRoster?.(H)};try{for(;;){let{done:w,value:P}=await d.read();if(w)break;for(g+=m.decode(P,{stream:!0});;){let H=g.indexOf(`
209
+ `);if(H<0)break;let T=g.slice(0,H).replace(/\r$/,"");if(g=g.slice(H+1),T==="")f();else{if(T.startsWith(":"))continue;T.startsWith("event:")?p=T.slice(6).trim():T.startsWith("data:")&&y.push(T.slice(5).replace(/^ /,""))}}}}catch(w){n||l(w);return}l(new Error("sse stream ended"))};return a(),{stop:()=>{n=!0,o&&clearTimeout(o),s?.abort()}}}var Rt=t=>Se().path.join(Ie().userDataDir(),Ie().isDevMode()?`${t}.dev.json`:`${t}.json`),lr=Rt;async function cr(t){try{let e=JSON.parse(await Se().fs.readFile(lr(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 Vs(t){let e=null,n=null,r=Promise.resolve(),s=null,o=()=>{if(!e)return r;let i=e,l=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let a=lr(t),u=`${a}.tmp-${Se().tmpTag()}-${Date.now()}-0`;await Se().fs.writeFile(u,l,"utf8"),await Se().fs.rename(u,a),s=null}catch(a){e??=i,s=a}}),r};return{save(i){e=i,!n&&(n=setTimeout(()=>{n=null,o()},500))},async flush(i=!1){if(n&&(clearTimeout(n),n=null),await o(),i&&s)throw s}}}async function Ys(t){try{await Se().fs.unlink(lr(t))}catch{}}var Ba=5*1024*1024,Wa=5*1024*1024,Va=3e4,Ya=2500,Ga=3e3,Ja=5,Xa=256*1024,Ka=5,Gs=1024*1024,Js=200,Za=6e4,Qa=50,el=".sync-trash",pt=t=>Se().sha256Hex(t);function $t(t,e={localRoot:Ze(),shadowName:`amadeus-sync-${Pt()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let n=c=>{let S=ar(c,"");if(!S)return null;for(let k of e.excludePrefixes??[])if(S===k.replace(/\/$/,"")||S.startsWith(k))return null;if(e.ignoreNames?.length&&S.split("/").some(k=>e.ignoreNames.includes(k)))return null;let E=e.serverDir?`${e.serverDir}/${S}`:S;return e.inScope&&!e.inScope(E,Le(E))?null:E},r=c=>{let S;if(e.serverDir){if(!c.startsWith(`${e.serverDir}/`))return null;S=c.slice(e.serverDir.length+1)}else{for(let E of e.excludePrefixes??[])if(c.startsWith(E))return null;S=c}return S.split("/").some(E=>Dt(E)||!!e.ignoreNames?.includes(E))?null:S},s=(c,S)=>!e.inScope||e.inScope(c,S),o=e.accountId??Te(),{fs:i,path:l}=Se(),a=c=>i.access(c).then(()=>!0,()=>!1),u=!1,d=0,m=Promise.resolve(),g=new Set,p="disabled",y=null,f=null,w=null,P=null,H=null,T=null,U=0,z=new Map,h=null,v=Vs(e.shadowName),b=new Map,A=!1,N=!1,B=[],G=()=>{f&&(f.pending=b.size?Object.fromEntries(b):void 0,v.save(f))},se=()=>{N=!1,B.length=0},pe=()=>{if(N)return!0;let c=Date.now();for(;B.length&&c-B[0]>Za;)B.shift();return B.length>=Qa?(N=!0,!0):!1},X=[],de=new Set,Z=!1,Ee=null,oe=null,_e=null,fe=()=>{!u||_e||(_e=setTimeout(()=>{_e=null,t.onStatus(nt())},200))},ye=(c,S)=>{p=c,S!==void 0&&(y=S),fe()},ae=(c,S=!1)=>{if(u){if(c.key){if(de.has(c.key))return;de.add(c.key)}S?X.unshift(c):X.push(c),L()}},be=new Map,_=c=>{if(!u)return;let S=(f?.files[c]?.size??0)>Xa,E=(e.pushQuietMs??Ga)*(S?Ka:1),k=Date.now(),D=be.get(c);D&&clearTimeout(D.timer);let F=D?.since??k,q=Math.max(0,Math.min(E,F+E*Ja-k)),j=setTimeout(()=>{be.delete(c),ae({key:c,run:()=>ve(c,!0)})},q);be.set(c,{timer:j,since:F}),fe()},I=()=>{for(let{timer:c}of be.values())clearTimeout(c);be.clear()},x=c=>!(c instanceof xe)||c.status>=500||c.status===0,C=c=>c instanceof xe&&(c.status===401||c.status===403),L=async()=>{if(!Z){Z=!0;try{for(;X.length;){(p==="idle"||p==="starting")&&ye("syncing");let c=X.shift();c.key&&de.delete(c.key);try{await c.run()}catch(S){if(!u)return;if(C(S)){X.length=0,de.clear(),Jt(),ye("auth-required","login-expired");return}if(x(S)){ae(c,!0),Jt(),ye("offline",S?.message||"network error"),R();return}let E=c.key??"(op)";z.set(E,S?.body?.code||`http ${S?.status}`),fe()}}u&&p==="syncing"&&(f&&(f.lastSyncAt=Date.now(),v.save(f)),ye("idle",null))}finally{Z=!1;for(let c of g)c();g.clear()}}},R=()=>{!u||Ee||(Ee=setTimeout(()=>{Ee=null,_t()},Va))},$=c=>{if(!T||!f)throw new Error("engine not bound");let S=r(c);if(S===null)throw new Error("path outside binding: "+c);let E=l.resolve(T,zs(S,f.folder)),k=l.relative(T,E);if(k.startsWith("..")||l.isAbsolute(k))throw new Error("path escapes vault: "+c);return E},M=c=>({size:c,mtimeMs:-1}),Y=async c=>{try{let S=await i.stat(c);return S.isFile()?{size:S.size,mtimeMs:Math.floor(S.mtimeMs)}:null}catch{return null}},W=0,J=async(c,S,E=()=>!0)=>{await i.mkdir(l.dirname(c),{recursive:!0});let k=`${c}.tmp-${Se().tmpTag()}-${Date.now()}-${W++}`;await i.writeFile(k,S);let D=await Y(k)??M(Rn(S));return E()?(await i.rename(k,c),D):(await i.rm(k,{force:!0}),null)},le=async c=>{let S;try{S=await i.readdir(c,{withFileTypes:!0})}catch{return}for(let E of S)E.isDirectory()&&await le(l.join(c,E.name));try{await i.rmdir(c)}catch{}},ie=async c=>{let S=$(c),E=await Y(S),k;try{k=await i.readFile(S)}catch{return null}return{hash:Qe(Le(c))?pt(Ke(k)):pt(k),size:E?.size??k.length,mtimeMs:E?.mtimeMs??-1,buf:k}},me=async(c,S,E,k)=>{f&&(f.files[c]={seq:S,hash:E,size:k.size,mtimeMs:k.mtimeMs},v.save(f))},ce=c=>{f&&c in f.files&&(delete f.files[c],v.save(f))},ue=async(c,S)=>{if(!w||!f||Ne(c))return;let E=we,k=Le(c),D,F,q;if(Qe(k)){let K;try{K=await w.getFile(f.vaultId,c)}catch(te){if(te instanceof xe&&te.status===404){await Pe(c);return}throw te}D=K.content,F=K.seq,q=K.hash??pt(K.content)}else{let K;try{K=await w.getAsset(f.vaultId,c)}catch(te){if(te instanceof xe&&te.status===404){z.set(c,"ASSET_404"),fe();return}throw te}D=K,F=S??0,q=pt(K)}let j=await ie(c);if(E!==we||Ne(c))return;if(j&&j.hash===q){await me(c,F,q,j);return}let V=f.files[c];if(j&&V&&q===V.hash&&j.hash!==V.hash){await me(c,F,q,M(V.size)),ae({key:c,run:()=>ve(c)});return}if(j&&(!V||j.hash!==V.hash)&&(V&&k==="page"&&typeof D=="string"&&await Ue(c,V,j,D,F,q,()=>E===we&&!Ne(c))||E!==we||Ne(c)||!await it(c,()=>E===we&&!Ne(c))))return;let O=await J($(c),D,()=>E===we&&!Ne(c));O&&await me(c,F,q,O)},Ue=async(c,S,E,k,D,F,q)=>{try{if(!w||!f||E.buf.length>Gs||k.length>Gs)return!1;let V=(await w.listVersions(f.vaultId,c)).find(te=>te.seq===S.seq);if(!V)return!1;let O=await w.getVersion(f.vaultId,V.id);if(pt(O)!==S.hash)return!1;let K=Hs(Ke(E.buf),O,k);return K===null?!1:(await J($(c),K,q)&&(await me(c,D,F,M(Rn(K))),ae({key:c,run:()=>ve(c)})),!0)}catch{return!1}},it=async(c,S)=>{let E=mt(hn(c,new Date));if(!E)return!0;let k=E.lastIndexOf("."),D=k>E.lastIndexOf("/"),F=D?E.slice(0,k):E,q=D?E.slice(k):"",j=E,V=Se().existsSync;if(V)for(let O=2;V($(j));O++)j=`${F}-${O}${q}`;else for(let O=2;await a($(j));O++)j=`${F}-${O}${q}`;if(!S())return!1;try{await i.rename($(c),$(j))}catch(O){if(O?.code==="ENOENT")return!0;throw O}return U++,ae({key:j,run:()=>ve(j)}),fe(),!0},at=async c=>{if(!T)return;let S=$(c),E=r(c)??c,k=l.join(T,el,new Date().toISOString().slice(0,10),...E.split("/")),D=await a(k)?`${k}.${Date.now()}`:k;try{await i.mkdir(l.dirname(D),{recursive:!0}),await i.rename(S,D)}catch(F){if(F?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${S}: ${F?.message??String(F)}`)}},Pe=async c=>{if(!f)return;let S=await ie(c);if(Ne(c))return;let E=f.files[c]??null,k=yn(S?.hash??null,E,null);if(k.kind==="deleteLocal"){if(!A&&pe()){b.set(c,"local"),G(),fe();return}B.push(Date.now()),await at(c),ce(c)}else k.kind==="pushCreate"?(ce(c),ae({key:c,run:()=>ve(c)})):ce(c)},Ar=(c,S)=>{if(f){for(let E of Object.keys(f.files))if(E===c||E.startsWith(`${c}/`)){let k=S+E.slice(c.length);f.files[k]=f.files[E],delete f.files[E]}v.save(f)}},Ir=async c=>{if(!w||!f||c.seq<=f.cursor||!await Vt())return;if(c.origin.client&&w.clientId===c.origin.client){f.cursor=c.seq,v.save(f);return}let S=c.type==="structure"?"folder":c.type,E=D=>r(D)!==null&&s(D,S);if(!E(c.path)&&!(c.newPath&&E(c.newPath))){f.cursor=c.seq,v.save(f);return}let k=c.path;switch(c.op){case"write":await ue(k,c.fileSeq);break;case"delete":await Pe(k);break;case"move":{let D=c.newPath;if(!D)break;let F=f.files[k];if(await ie(k)&&F)try{await i.mkdir(l.dirname($(D)),{recursive:!0}),await i.rename($(k),$(D)),f.files[D]={...F,seq:c.fileSeq??F.seq},delete f.files[k],v.save(f)}catch{await ue(D,c.fileSeq)}else ce(k),await ue(D,c.fileSeq);break}case"mkdir":await i.mkdir($(k),{recursive:!0});break;case"rename-folder":case"move-folder":{let D=c.newPath;if(!D)break;try{await i.mkdir(l.dirname($(D)),{recursive:!0}),await i.rename($(k),$(D))}catch{}Ar(k,D);break}case"delete-folder":{let D=`${k}/`;for(let F of Object.keys(f.files))(F===k||F.startsWith(D))&&await Pe(F);await le($(k));break}}if(f.cursor=c.seq,v.save(f),c.op==="move"||c.op==="rename-folder"||c.op==="move-folder"||c.op==="delete"||c.op==="delete-folder")try{await t.onRemoteApplied?.(c)}catch{}},Bo=async(c,S,E)=>{let k=Number(S?.seq??0),D=S?.content??null;if(D!==null&&pt(D)===E.hash){await me(c,k,E.hash,E);return}if(D===null&&k===0){if(!f?.files[c]){z.set(c,S?.code||"EXISTS"),fe();return}ce(c),ae({key:c,run:()=>ve(c)});return}await ue(c,k)},Bt=async(c,S)=>{if(!w||!f)return;let E=await ie(c);if(!E){ae({key:c,run:()=>ve(c)});return}if(E.size>Ba){z.set(c,"TOO_LARGE"),fe();return}let k=Ke(E.buf);try{let D=await w.putFile(f.vaultId,c,k,S);z.delete(c),await me(c,D.seq,D.hash??E.hash,E)}catch(D){if(D instanceof xe&&D.status===409){await Bo(c,D.body,E);return}throw D}},Wt=async(c,S)=>{if(!w||!f)return;let E=await ie(c);if(!E){ae({key:c,run:()=>ve(c)});return}if(E.size>(h??Wa)){z.set(c,"TOO_LARGE"),fe();return}try{let k=await w.putBinary(f.vaultId,c,E.buf,{baseSeq:S});z.delete(c),await me(c,k.seq,E.hash,E)}catch(k){if(k instanceof xe&&k.status===409){let D=Number(k.body?.seq??0),F=k.body?.hash??null;if(F!==null&&F===E.hash){await me(c,D,E.hash,E);return}if(D===0){if(!f.files[c]){z.set(c,k.body?.code||"EXISTS"),fe();return}ce(c),ae({key:c,run:()=>ve(c)});return}await ue(c,D);return}throw k}},Pr=async c=>{if(!w||!f||Ne(c))return;let S=we,E=f.files[c];if(E){if(Qe(Le(c)))try{let k=await w.getFile(f.vaultId,c);if(k.seq!==E.seq){await ue(c,k.seq);return}}catch(k){if(k instanceof xe&&k.status===404){ce(c);return}throw k}if(!(S!==we||Ne(c))){try{await w.deleteFile(f.vaultId,c,E.seq,{confirmed:A})}catch(k){if(k instanceof xe&&k.status===409){await ue(c,Number(k.body?.seq??0)||null);return}if(k instanceof xe&&k.status===429&&k.body?.code==="MASS_DELETE_BLOCKED"){b.set(c,"remote"),N=!0,G(),fe();return}throw k}ce(c)}}},Vt=async()=>T?await i.stat(T).then(S=>S.isDirectory()).catch(()=>!1)||!e.requireRootExists&&!Object.keys(f?.files??{}).length?!0:(ye("error",`vault-missing: ${T}`),R(),!1):!1,we=0,Yt=new Set,Gt=new Map,De=c=>JSON.stringify([c.from,c.to]),Xe=(c,S)=>c===S||c.startsWith(`${S}/`),Ne=c=>[...f?.moves??[],...Yt].some(S=>Xe(c,S.from)||Xe(c,S.to)),Be=()=>!!(f?.moves?.length||Yt.size),In=async c=>{if(!w||!f)return;let{from:S,to:E,kind:k}=c;if(r(S)===null||r(E)===null)throw new Error("Invalid queued cloud move");c.hashes??=Object.fromEntries(Object.entries(f.files).filter(([j])=>Xe(j,S)).map(([j,V])=>[j.slice(S.length),V.hash])),v.save(f),await v.flush(!0);let D,F=!1;try{if(k==="folder"){let j=l.posix.dirname(S)==="."?"":l.posix.dirname(S),V=l.posix.dirname(E)==="."?"":l.posix.dirname(E);j===V?await w.renameFolder(f.vaultId,S,l.posix.basename(E)):await w.moveFolder(f.vaultId,S,V)}else{let j=await w.move(f.vaultId,S,E);D=Number(j.seq)}}catch(j){if(!(j instanceof xe)||j.status!==404)throw j;let V=await w.tree(f.vaultId);if(V.entries.some(te=>Xe(te.path,S))||V.folders.some(te=>Xe(te,S)))throw j;let K=V.entries.find(te=>te.path===E);if(D=K?.seq,F=!K&&!V.entries.some(te=>Xe(te.path,E))&&!V.folders.some(te=>Xe(te,E)),!F){let te=Object.entries(c.hashes);if(!(te.length>0&&te.every(([Fe,lt])=>V.entries.some(ct=>ct.path===E+Fe&&ct.hash===lt))))throw new xe(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(F)for(let j of Object.keys(f.files))Xe(j,S)&&delete f.files[j];else Ar(S,E),D!==void 0&&f.files[E]&&(f.files[E].seq=D);f.moves=(f.moves??[]).filter(j=>De(j)!==De(c)),v.save(f);try{await v.flush(!0)}catch(j){throw f.moves.unshift(c),v.save(f),j}let q=Gt.get(De(c));Gt.delete(De(c)),q?.(),Ne(E)||(k==="folder"?await Pn():await ve(E))},ve=async(c,S=!1)=>{if(!f||Ne(c))return;if(!s(c,Le(c))){ce(c);return}if(!await Vt())return;let E=await ie(c);if(Ne(c))return;let k=f.files[c]??null,D=yn(E?.hash??null,k,k?{seq:k.seq,hash:k.hash}:null);switch(D.kind){case"push":Qe(Le(c))?await Bt(c,D.baseSeq):await Wt(c,D.baseSeq);break;case"pushCreate":Qe(Le(c))?await Bt(c,0):await Wt(c,0);break;case"pushDelete":if(S){Kt();break}if(!A&&(b.has(c)||pe())){b.set(c,"remote"),G(),fe();break}B.push(Date.now()),await Pr(c);break;case"dropShadow":ce(c);break;default:E&&k&&E.hash===k.hash&&E.mtimeMs>=0&&(k.size!==E.size||k.mtimeMs!==E.mtimeMs)&&await me(c,k.seq,k.hash,E);break}},Dr=async()=>{let c=new Map;if(!T||!f)return c;let S=T,E=null,k=async D=>{if(E)return;let F;try{F=await i.readdir(D,{withFileTypes:!0})}catch(q){E=`${D}: ${q?.message??String(q)}`;return}for(let q of F){if(Dt(q.name)||q.isDirectory()&&e.ignoreNames?.includes(q.name))continue;let j=l.join(D,q.name);if(q.isDirectory())await k(j);else if(q.isFile()){let V=l.relative(S,j).split(l.sep).join("/"),O=n(V);if(!O)continue;try{let K=await i.stat(j);if(!K.isFile())continue;c.set(O,{size:K.size,mtimeMs:Math.floor(K.mtimeMs)})}catch(K){if(K?.code==="ENOENT")continue;E=`${j}: ${K?.message??String(K)}`;return}}}};return await k(S),E?(ye("error",`scan-failed: ${E}`),R(),null):c},Pn=async()=>{let c=we;if(Be()||c!==we||!f||!await Vt())return;let S=await Dr();if(!S||Be()||c!==we)return;let E=!1;for(let[F,q]of[...b])(q==="remote"&&S.has(F)||q==="local"&&!S.has(F))&&(b.delete(F),E=!0);b.size||se();for(let[F,q]of S){let j=f.files[F];j&&j.size===q.size&&j.mtimeMs===q.mtimeMs||ae({key:F,run:()=>ve(F)})}let k=Object.keys(f.files),D=k.filter(F=>!S.has(F));if(D.length&&!A&&(N||ir(D.length,k.length,Js))){N=!0;for(let F of D)b.set(F,"remote");G(),fe();return}E&&(G(),fe());for(let F of D)b.has(F)||ae({key:F,run:()=>ve(F)})},kt=async()=>{let c=we;if(Be()||c!==we||!w||!f||!T||!await Vt())return;let S=await w.tree(f.vaultId);if(S.maxFileBytes!==void 0&&S.maxFileBytes!==h&&(h=S.maxFileBytes,fe()),Be()||c!==we)return;let E=new Map;for(let O of S.entries)r(O.path)===null||!s(O.path,O.kind)||E.set(O.path,O);let k=await Dr();if(!k||Be()||c!==we)return;let D=new Set([...E.keys(),...k.keys(),...Object.keys(f.files)]),F=Object.keys(f.files).length,q=[];for(let O of D){if(Be()||c!==we)return;let K=f.files[O]??null,te=E.get(O)??null,Ce=k.get(O)??null,Fe=null,lt=M(Ce?.size??0);if(Ce)if(K&&K.size===Ce.size&&K.mtimeMs===Ce.mtimeMs)Fe=K.hash,lt=Ce;else{let ct=await ie(O);ct&&(Fe=ct.hash,lt=ct)}q.push({sp:O,d:yn(Fe,K,te?{seq:te.seq,hash:te.hash}:null),rSeq:te?.seq??null,localHash:Fe,localStat:lt})}if(Be()||c!==we)return;let j=q.filter(O=>O.d.kind==="deleteLocal"||O.d.kind==="pushDelete").length,V=!A&&(N||ir(j,F,Js));V&&j&&(N=!0),b.clear();for(let{sp:O,d:K,rSeq:te,localHash:Ce,localStat:Fe}of q){if(Be()||c!==we)return;if(V&&(K.kind==="deleteLocal"||K.kind==="pushDelete")){b.set(O,K.kind==="deleteLocal"?"local":"remote");continue}if((K.kind==="deleteLocal"||K.kind==="pushDelete")&&((await ie(O))?.hash??null)!==Ce){ae({key:O,run:()=>ve(O)});continue}if(Be()||c!==we)return;switch(K.kind){case"adopt":await me(O,te,Ce,Fe);break;case"pull":await ue(O,te);break;case"push":Qe(Le(O))?await Bt(O,K.baseSeq):await Wt(O,K.baseSeq);break;case"pushCreate":Qe(Le(O))?await Bt(O,0):await Wt(O,0);break;case"pushDelete":await Pr(O);break;case"deleteLocal":await at(O),ce(O);break;case"conflict":await ue(O,te);break;case"dropShadow":ce(O);break;case"none":break}}A&&(A=!1,B.length=0),b.size||se(),G(),V&&fe();for(let O of S.folders)if(!(r(O)===null||!s(O,"folder")))try{await i.mkdir($(O),{recursive:!0})}catch{}f.cursor=S.seq,f.lastSyncAt=Date.now(),v.save(f)},Wo=async()=>{if(!w||!f)return;let c=f.cursor,S=await w.changes(f.vaultId,c);if(S.changes.length===0&&S.seq>c||S.changes.length>0&&S.changes[0].seq!==c+1){await kt();return}for(let k of S.changes)await Ir(k)},Et=null,Rr=[],$r=()=>{Et&&Rr.push(Et.close()),Et=null},Vo=()=>{if(!u||Et||!T)return;let c=Se();if(!c.watch)return;let S=E=>{if(!T)return;let k=l.relative(T,E);if(!k||k.startsWith(".."))return;let D=n(k);D&&_(D)};Et=c.watch(T,{depth:12,ignored:E=>{let k=l.basename(E);return Dt(k)||!!e.ignoreNames?.includes(k)}},{change:S,add:S,unlink:()=>Kt(),unlinkDir:()=>Kt()})},Jt=()=>{P?.stop(),P=null},Yo=()=>{if(!u||!w||!f||P)return;let c=H;c&&(P=Ws({baseUrl:c.cloudUrl,vaultId:f.vaultId,token:c.token},{getSince:()=>f?.cursor??0,onHello:S=>{f&&S>f.cursor&&ae({run:Wo})},onChange:S=>{ae({run:()=>Ir(S)})},onReset:()=>{ae({run:kt})},onOpen:()=>{(p==="offline"||p==="starting")&&ye("idle",null),ae({run:Pn})},onDown:()=>{(p==="idle"||p==="syncing")&&ye("offline")},onPresence:S=>t.onPresence?.(f?.vaultId??"",S),onPresenceRoster:S=>t.onPresenceRoster?.(f?.vaultId??"",S)}))},Go=async()=>{let c=await Me(o);if(c.cloudSync?.deviceId)return c.cloudSync.deviceId;let S=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Ve({cloudSync:{...c.cloudSync??{},deviceId:S}},o),S},Jo=async c=>{Jt(),$r(),X.length=0,de.clear(),b.clear(),A=!1,N=!1,B.length=0;let S=await Me(o);if(c!==d)return;let E=S.cloudSync;if(E?.enabled===!1){T=null,w=null,ye("disabled",null);return}if(!o||o!==Te()){ye("auth-required","not-logged-in");return}if(T=e.localRoot,e.requireRootExists){let q=await i.stat(T).then(j=>j.isDirectory()).catch(()=>!1);if(c!==d)return;if(!q){ye("error",`vault-missing: ${T}`),R();return}}if(c!==d)return;let k=t.loadCreds();if(!k.cloudUrl||!k.token){w=null,ye("auth-required","not-logged-in");return}ye("starting",null);let D=E?.deviceId??await Go();if(c!==d)return;let F=e.clientIdSuffix?`${D}#${e.clientIdSuffix}`:D;H={cloudUrl:k.cloudUrl,token:k.token},w=Bs({baseUrl:k.cloudUrl,token:k.token,clientId:F});try{let q=e.vaultId==="first"?E?.vaultId:e.vaultId;if(!q){let V=await w.listVaults();if(c!==d)return;if(!V.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");q=V[0].id,await Ve({cloudSync:{...E??{},vaultId:q}},o)}if(c!==d)return;let j=await cr(e.shadowName);if(c!==d||(f=j&&j.vaultRoot===T&&j.vaultId===q&&j.folder===""?j:{vaultRoot:T,folder:"",vaultId:q,cursor:0,lastSyncAt:null,files:{}},c!==d))return;for(let[V,O]of Object.entries(f.pending??{}))b.set(V,O);if(b.size&&(N=!0),!e.requireRootExists){let V=await i.stat(T).then(O=>O.isDirectory()).catch(()=>!1);if(c!==d)return;if(!V){if(Object.keys(f.files).length){ye("error",`mirror-missing: ${T}`),R();return}if(await i.mkdir(T,{recursive:!0}),c!==d)return}}Vo();for(let V of f.moves??[])ae({key:`move:${De(V)}`,run:()=>In(V)});ae({run:kt}),ae({run:async()=>{Yo()}})}catch(q){if(c!==d)return;C(q)?ye("auth-required","login-expired"):(ye("offline",q?.message||String(q)),R())}},Mr=()=>{u=!1,Jt(),$r(),X.length=0,de.clear(),I();for(let c of[Ee,oe,_e])c&&clearTimeout(c);Ee=oe=_e=null},Or=async()=>{Z&&await new Promise(c=>g.add(c)),await Promise.all(Rr.splice(0)),await v.flush(),f=null,w=null,H=null,T=null,U=0,z.clear(),h=null,b.clear(),A=!1,N=!1,B.length=0,p="disabled",y=null},Xo=()=>{Nr()},Xt=null,_t=()=>{Xt?.(),Xt=Ie().onBeforeQuit(Xo);let c=++d;Mr();let S=m.catch(()=>{}).then(async()=>{await Or(),c===d&&(u=!0,await Jo(c))});return m=S,S},Nr=()=>{Xt?.(),Xt=null,++d,Mr();let c=m.catch(()=>{}).then(Or);return m=c,c},nt=()=>({enabled:p!=="disabled",state:p==="idle"&&be.size?"syncing":p,lastSyncAt:f?.lastSyncAt??null,pending:X.length+be.size,conflicts:U,skipped:[...z].map(([c,S])=>({path:c,reason:S})),error:y,pendingDeletions:b.size,maxFileBytes:h});return{getStatus:nt,start(){_t()},notifyLocal(c,S,E){if(!f||p==="disabled"||p==="auth-required")return;let k=n(c),D=E?n(E):null;if(S==="write"&&k){Dt(k.split("/").pop()||"")||_(k);return}if(S==="remove"){if(!k)return;let F=`${k}/`,q=!1;for(let j of Object.keys(f.files))(j===k||j.startsWith(F))&&(q=!0,ae({key:j,run:()=>ve(j)}));!q&&k&&ae({key:k,run:()=>ve(k)})}},holdLocalMove(c,S){let E=D=>e.serverDir?`${e.serverDir}/${D.replace(/\\/g,"/").normalize("NFC")}`:D.replace(/\\/g,"/").normalize("NFC"),k={from:E(c),to:E(S)};return++we,Yt.add(k),()=>{Yt.delete(k)}},async notifyLocalMove(c,S,E,k){let D=n(c),F=n(S),q=f??await cr(e.shadowName),j=ar(c,""),V=j&&(e.serverDir?`${e.serverDir}/${j}`:j);if(!D&&F&&V&&q&&Object.keys(q.files).some(O=>O===V||O.startsWith(`${V}/`))&&(D=V),!D&&!F){E?.();return}if(D&&F){let O=f??q;if(!O){E?.();return}let K=k??(Object.keys(O.files).some(Ce=>Ce.startsWith(`${D}/`))?"folder":"file"),te={from:D,to:F,kind:K};O.moves??=[],O.moves.some(Ce=>De(Ce)===De(te))||(O.moves.push(te),++we),E&&Gt.set(De(te),E),v.save(O);try{await v.flush(!0)}catch(Ce){throw O.moves=O.moves.filter(Fe=>De(Fe)!==De(te)),Gt.delete(De(te)),v.save(O),Ce}f===O&&u&&p!=="disabled"&&p!=="auth-required"&&ae({key:`move:${De(te)}`,run:()=>In(te)});return}D&&this.notifyLocal(c,"remove"),F&&(ae({key:F,run:()=>ve(F)}),Kt()),E?.()},async setEnabled(c){let S=await Me(o);return await Ve({cloudSync:{...S.cloudSync??{},enabled:c}},o),await _t(),nt()},async restart(){return await _t(),nt()},async syncNow(){if(z.clear(),p==="disabled"||p==="auth-required"||!w)await _t();else{for(let c of f?.moves??[])ae({key:`move:${De(c)}`,run:()=>In(c)});ae({run:kt})}return nt()},confirmMassDeletions(){return b.size&&(A=!0,N=!1,b.clear(),B.length=0,G(),ae({run:kt})),nt()},stop:Nr};function Kt(){u&&(oe&&clearTimeout(oe),oe=setTimeout(()=>{oe=null,ae({run:Pn})},Ya))}}function Xs(t){let e=t.replace(/\.md$/i,""),n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n);return{root:t,fdPrefix:`${e}.fd/`,assetPrefix:r?`${r}/.amadeus/`:".amadeus/"}}function Ks(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 tl=t=>Se().sha256Hex(t).slice(0,8),nl=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",wn="\u4E0E\u6211\u5171\u4EAB";function ur(t){let e=tl(`${t.vaultId}:${t.path}`),n=Xs(t.path),r=t.path.includes("/")?t.path.slice(0,t.path.lastIndexOf("/")):"";return{key:e,vaultId:t.vaultId,rootPath:t.path,title:t.title,localRelDir:`${wn}/${nl(t.title)}-${e}`,serverDir:r,inScope:(s,o)=>Ks(n,s,o)}}function dr(){let t=Ie().readCreds(),e=$e(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let m=Ie().readCreds();if(n.signal.aborted||!e||$e(m.cloudUrl??"",m.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return m},s=()=>{let m=r();if(!m.cloudUrl||!m.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return m.cloudUrl.replace(/\/+$/,"")},o=async(m,g,p)=>{let y=r();if(!y.cloudUrl||!y.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let f=await fetch(`${y.cloudUrl.replace(/\/+$/,"")}/api/amadeus${g}`,{method:m,headers:{Authorization:`Bearer ${y.token}`,...p!==void 0?{"Content-Type":"application/json"}:{}},body:p!==void 0?JSON.stringify(p):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!f.ok){let P=null;try{P=await f.json()}catch{}throw Object.assign(new Error(P?.detail||`http ${f.status}`),{status:f.status,code:P?.code})}let w=await f.json();return r(),w},i=null,l=async()=>(r(),i||(i=(await o("GET","/vaults")).vaults[0]?.id??"default",i)),a=()=>{try{let m=(r().token??"").split(".")[1],g=JSON.parse(Ke(Zt(m)));return typeof g.userId=="string"?g.userId:null}catch{return null}},u=async()=>(await o("GET","/shared-with-me")).items.map(g=>{let p=ur(g),y=g.path.split("/").pop()??g.path;return{...g,localPath:`${p.localRelDir}/${y}`}}),d=null;return{stop:()=>n.abort(),call:o,ensureOwnVault:l,myUserId:a,sharedWithMe:u,linkBase:async()=>{if(r(),d)return d;try{d=((await o("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||s()}catch{d=s()}return d},async heartbeat(m,g){let p=(m??"").replace(/\\/g,"/"),y,f=null,w=g.find(P=>p.startsWith(`${P.localRelDir}/`));w?(y=w.vaultId,f=w.serverDir?`${w.serverDir}/${p.slice(w.localRelDir.length+1)}`:p.slice(w.localRelDir.length+1)):(y=await l(),f=p||null),await o("POST",`/vaults/${encodeURIComponent(y)}/presence`,{page:f})}}}import{promises as eo}from"node:fs";import rl from"node:path";var fr=".forsion-vault.md",Zs=t=>`${t}/${fr}`;function bn(t){let e=/^devices:\s*(\[.*\])\s*$/m.exec(t??"");if(!e)return null;try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(r=>!!r&&typeof r.id=="string"&&typeof r.name=="string").map(r=>({id:r.id,name:r.name,...typeof r.since=="string"?{since:r.since}:{}})):null}catch{return null}}var Qs=t=>`---
210
+ devices: ${JSON.stringify(t.map(e=>({id:e.id,name:e.name,...e.since?{since:e.since}:{}})))}
211
+ ---
212
+ `;var Oe=t=>t.replace(/\\/g,"/").normalize("NFC");function mr(t){let e=Oe(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function gt(t,e,n){let r=Oe(n);if(!r)return!1;if(t.some(s=>Oe(s.path)===r))return!0;for(let s of e??[]){let o=Oe(s);if(!o)continue;let i=`${o.replace(/\.md$/i,"")}.fd`;if(r===o||r.startsWith(`${o}/`)||r===i||r.startsWith(`${i}/`))return!1}return t.some(s=>{let o=mr(s);return!!o&&r.startsWith(o)})}function pr(t,e,n){let r=Oe(t),s=Oe(e);return r===s?Oe(n):r.startsWith(`${s}/`)?Oe(n)+r.slice(s.length):null}function Mt(t,e,n){let r=!1,s=t.map(o=>{let i=pr(o,e,n);return i===null?o:(r=!0,i)});return{changed:r,next:s}}async function to(t){let e=await eo.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[],r=Object.create(null);for(let s of e){if(!s.isDirectory()||s.name.startsWith("."))continue;let o=await eo.readFile(rl.join(t,s.name,fr),"utf8").catch(()=>null);if(o===null)continue;n.push(s.name);let i=bn(o);i?.length&&(r[s.name]=i)}return{names:n.sort(),devices:r}}var ke={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",entryMark:"amadeus:entry-sync:mark",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};var Sn=t=>Se().sha256Hex(t).slice(0,8);function no(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function et(t,e=[]){let n=[],r=[];for(let s of t){let o=Oe(s.path);if(!o)continue;r.push(o);let i=mr(s);i&&n.push(i)}return{entries:t,exclude:e,prefixes:n,paths:r}}function ro(t,e){let n=no(Oe(e));if(!n)return!1;if(gt(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let s of t.paths)if(s.startsWith(r))return!0;for(let s of t.prefixes)if(s.startsWith(r))return!0;return!1}function Ot(t,e,n){let r=!1,s=t.map(o=>{let i=pr(o.path,e,n);return i===null?o:(r=!0,{...o,path:i})});return{changed:r,next:s}}function so(t,e,n,r){if(e==="delete"||e==="delete-folder"){let s=Oe(n),o=t.filter(i=>{let l=Oe(i.path);return!(l===s||e==="delete-folder"&&l.startsWith(`${s}/`))});return{changed:o.length!==t.length,next:o}}return r?Ot(t,n,r):{changed:!1,next:t}}function gr(t,e){let n=mt(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===wn?`\u300C${wn}\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}import{constants as sl,promises as oo}from"node:fs";async function io(t,e){try{await oo.copyFile(Rt(t),Rt(e),sl.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await oo.unlink(Rt(t)).catch(()=>{}),!0}var ao=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],hr=t=>ao.every(e=>typeof t[e]=="function"),al=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function yr(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(ke.get,()=>e?e.get():al()),t.handle(ke.setEnabled,(r,s)=>n().setEnabled(s)),t.handle(ke.syncNow,()=>n().syncNow()),t.handle(ke.confirmDeletions,()=>n().confirmDeletions()),t.handle(ke.entryGet,()=>n().entryGet()),t.handle(ke.otherSideDbs,()=>n().otherSideDbs()),t.handle(ke.entryEnable,(r,s)=>n().entryEnable(s)),t.handle(ke.entryDisable,(r,s)=>n().entryDisable(s)),t.handle(ke.entryMark,(r,s,o)=>n().entryMark(s,o)),t.handle(ke.entryClosure,(r,s,o)=>n().entryClosure(s,o)),t.handle(ke.collabCall,(r,s,o)=>n().collabCall(s,o)),t.handle(ke.switchSide,(r,s)=>n().switchSide(r.sender.id,s)),t.setAmadeusSyncFactory(r=>{js(r);let s=lo(r);return e=s.handlers,s.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function lo(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,s=!1,o=dr(),i=new Map,l=()=>{let _=Date.now();for(let[I,x]of i)_-x.at>7e4&&i.delete(I);e(ke.presence,[...i.values()])},a={loadCreds:()=>t.readCreds(),onStatus:_=>e(ke.status,{..._,pendingDeletions:Ee(),side:y()?"cloud":"local"}),onPresence:(_,I)=>{let x=I;x?.userId&&(i.set(x.userId,{userId:x.userId,username:String(x.username??"user"),page:x.page??null,at:Number(x.at)||Date.now()}),l())},onPresenceRoster:(_,I)=>{if(Array.isArray(I)){for(let x of I){let C=x;C?.userId&&i.set(C.userId,{userId:C.userId,username:String(C.username??"user"),page:C.page??null,at:Number(C.at)||Date.now()})}l()}}},u=()=>{let _=r;return{...a,onStatus:I=>{_===r&&a.onStatus(I)},onPresence:(I,x)=>{_===r&&a.onPresence(I,x)},onPresenceRoster:(I,x)=>{_===r&&a.onPresenceRoster(I,x)}}},d=$t(u()),m=new Map,g=[],p=async()=>{if(!s||!Te())return;let _=r,I=o,x;try{x=await I.sharedWithMe()}catch{return}if(_!==r||!s)return;let C=x.map(R=>ur(R));g=C;let L=new Set(C.map(R=>R.key));for(let[R,$]of m)if(!L.has(R)){if(await $.engine.stop(),_!==r)return;m.delete(R)}for(let R of C){if(m.has(R.key))continue;let $=$t(u(),{localRoot:st.join(Ze(),...R.localRelDir.split("/")),shadowName:`amadeus-sync-${Pt()}-share-${R.key}`,vaultId:R.vaultId,serverDir:R.serverDir,inScope:R.inScope});m.set(R.key,{engine:$,plan:R}),$.start()}},y=()=>n()===Ze(),f=(_,I=_.base)=>{_.base=I;let x=[I,..._.pendingMoves];_.scope.current=et(x.flatMap(C=>C.entries),x.flatMap(C=>C.exclude))},w=new Map,P=new Set,H=new Set,T=null,U=()=>T??=new Promise(_=>{let I=()=>il.hostname().replace(/\.(local|lan|home)$/i,"")||"Desktop";if(process.platform!=="darwin")return _(I());ol("scutil",["--get","ComputerName"],{timeout:1500},(x,C)=>_(!x&&String(C).trim()||I()))}),z=async()=>{let _=(await Me()).cloudSync?.deviceId;return _?{id:_,name:await U()}:null},h=new Map,v=(_,I,x)=>{let C=r,L=(h.get(_)??Promise.resolve()).catch(()=>{}).then(async()=>{C!==r||x&&!await x()||C!==r||await b(_,I,C)});return h.set(_,L),L.finally(()=>{h.get(_)===L&&h.delete(_)}).catch(()=>{}),L},b=async(_,I,x)=>{let C=o,L=encodeURIComponent(await C.ensureOwnVault()),R=Zs(_);for(let $=0;$<3;$++){let M=null;try{M=await C.call("GET",`/vaults/${L}/file?path=${encodeURIComponent(R)}`)}catch(W){if(W?.status!==404)throw W}let Y=I(!!M,M?bn(M.content):null);if(Y===void 0||x!==r)return;try{if(Y===null){M&&await C.call("DELETE",`/vaults/${L}/file?path=${encodeURIComponent(R)}&baseSeq=${M.seq}`);return}await C.call("PUT",`/vaults/${L}/file`,{path:R,content:Qs(Y),baseSeq:M?.seq??0});return}catch(W){if(W?.status!==409)throw W}}throw Object.assign(new Error("marker write kept conflicting"),{status:409})},A=async _=>!!(await Me()).entrySync?.some(I=>I.cloudName===_&&I.entries.length>0),N=(_,I)=>v(_,(x,C)=>{let L=C?.find($=>$.id===I.id);if(L&&L.name===I.name)return;let R=L?.since??new Date().toISOString().slice(0,10);return[...(C??[]).filter($=>$.id!==I.id),{...I,since:R}]},()=>A(_)),B=(_,I)=>v(_,(x,C)=>{if(!x||!C?.some(R=>R.id===I))return;let L=C.filter(R=>R.id!==I);return L.length?L:null},async()=>!await A(_)),G=()=>{e(ke.entryChange)},se=async(_,I)=>{let x=w.get(_);if(!x)return;let C=$=>$&&$.startsWith(`${x.cloudName}/`)?$.slice(x.cloudName.length+1):null,L=C(I.path);if(!L)return;let R=!1;await ft($=>{if(w.get(_)!==x)return!1;let M=($.entrySync??[]).find(ie=>ie.vaultRoot===_);if(!M)return!1;let Y=I.op,W=C(I.newPath),J=so(M.entries,Y,L,W),le=W?Mt(M.exclude??[],L,W):{changed:!1,next:M.exclude??[]};if(!J.changed&&!le.changed)return!1;R=!0,M.entries=J.next,le.changed&&(M.exclude=le.next),f(x,et(M.entries,M.exclude??[]))}),R&&w.get(_)===x&&G()},pe=_=>{let I=r;return{...u(),onStatus:x=>{I===r&&e(ke.status,{...x,pendingDeletions:Ee(),side:"local",binding:_})},onRemoteApplied:async x=>{I===r&&await se(_,x)}}},X=async()=>{let _=Te();if(!s||!_)return;let I=r,x=o,C=Pt(_);await t.adoptLegacyCloudState(_,io);let L=await Me(_),R=L.entrySync??[];if(I!==r||!s||_!==Te())return;let $=new Map(R.map(M=>[M.vaultRoot,M]));for(let[M,Y]of w){let W=$.get(M);if(!(W&&W.cloudName===Y.cloudName)&&(await Y.engine.stop(),I!==r||(w.delete(M),W&&await Ys(`amadeus-sync-${C}-entry-${Sn(M)}`),I!==r)))return}for(let M of R){let Y=w.get(M.vaultRoot);if(Y){f(Y,et(M.entries,M.exclude??[]));continue}let W={current:et(M.entries,M.exclude??[])},J=M.cloudName,le=$t(pe(M.vaultRoot),{accountId:_,localRoot:M.vaultRoot,shadowName:`amadeus-sync-${C}-entry-${Sn(M.vaultRoot)}`,vaultId:"first",serverDir:J,clientIdSuffix:`entry-${Sn(M.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:ie=>ie===J?!0:ie.startsWith(`${J}/`)?ro(W.current,ie.slice(J.length+1)):!1});w.set(M.vaultRoot,{engine:le,scope:W,cloudName:J,base:W.current,pendingMoves:new Set}),le.start()}if(L.cloudSync?.enabled!==!1)for(let M of R){let Y=M.entries.length>0,W=Y?P:H;W.has(M.cloudName)||((Y?H:P).delete(M.cloudName),(async()=>{try{let J=await z();if(!J||I!==r||(await(Y?N(M.cloudName,J):B(M.cloudName,J.id)),I!==r))return;W.add(M.cloudName),(Y?H:P).delete(M.cloudName)}catch{}})())}},de=async(_,I,x,C,L)=>{let R=I.replace(/\\/g,"/").normalize("NFC"),$=x.replace(/\\/g,"/").normalize("NFC"),M=!1,Y,W,J,le=L??"file";try{await ft(async ie=>{if(w.get(_)!==C)return!1;let me=(ie.entrySync??[]).find(Pe=>Pe.vaultRoot===_);if(!me)return!1;let ce=Ot(me.entries,R,$),ue=Mt(me.exclude??[],R,$),Ue=gt(me.entries,me.exclude,R);!L&&await ht.stat(st.join(_,...$.split("/"))).then(Pe=>Pe.isDirectory(),()=>!1)&&(le="folder");let it=le==="folder"?"folder":/\.md$/i.test($)?"page":"asset";Ue&&!gt(ce.next,ue.next,$)&&(ce.next.push({path:$,kind:it}),ce.changed=!0),M=ce.changed||ue.changed;let at=me.entries.filter(Pe=>Ot([Pe],R,$).changed);return Ue&&!at.some(Pe=>Pe.path===R)&&at.push({path:R,kind:it}),Y=et(at,(me.exclude??[]).filter(Pe=>Mt([Pe],R,$).changed)),W=C.base,C.pendingMoves.add(Y),me.entries=ce.next,me.exclude=ue.next,J=et(me.entries,me.exclude),f(C,J),M})}catch(ie){throw Y&&C.pendingMoves.delete(Y),f(C,C.base===J&&W?W:C.base),ie}try{Y&&await C.engine.notifyLocalMove(R,$,()=>{C.pendingMoves.delete(Y),f(C)},le)}catch(ie){throw Y&&C.pendingMoves.delete(Y),await ft(me=>{let ce=me.entrySync?.find(ue=>ue.vaultRoot===_);if(!ce)return!1;ce.entries=Ot(ce.entries,$,R).next,ce.exclude=Mt(ce.exclude??[],$,R).next,f(C,et(ce.entries,ce.exclude))}),ie}M&&w.get(_)===C&&G()},Z=_=>{let I=_.replace(/\\/g,"/");for(let{engine:x,plan:C}of m.values())if(I.startsWith(`${C.localRelDir}/`))return{engine:x,rel:I.slice(C.localRelDir.length+1)};return{engine:d,rel:I}};t.setMutationHooks((_,I)=>{if(y()){let x=Z(_);x.engine.notifyLocal(x.rel,I);return}w.get(n()??"")?.engine.notifyLocal(_,I)},(_,I,x)=>{if(y()){let R=Z(_),$=Z(I);if(R.engine===$.engine)return R.engine.notifyLocalMove(R.rel,$.rel,void 0,x);R.engine.notifyLocal(R.rel,"remove"),$.engine.notifyLocal($.rel,"write");return}let C=n()??"",L=w.get(C);if(L)return de(C,_,I,L,x)},(_,I)=>{if(y()){let x=Z(_),C=Z(I),L=[x.engine.holdLocalMove(x.rel,C.rel)];return x.engine!==C.engine&&L.push(C.engine.holdLocalMove(x.rel,C.rel)),()=>{for(let R of L)R()}}return w.get(n()??"")?.engine.holdLocalMove(_,I)});let Ee=()=>{let _=d.getStatus().pendingDeletions;for(let{engine:I}of m.values())_+=I.getStatus().pendingDeletions;for(let{engine:I}of w.values())_+=I.getStatus().pendingDeletions;return _},oe=_=>({..._,pendingDeletions:Ee(),side:y()?"cloud":"local"}),_e=()=>{if(!s)return Promise.resolve(d.getStatus());p();for(let{engine:_}of m.values())_.syncNow();for(let{engine:_}of w.values())_.syncNow();return d.syncNow()},fe=async()=>{++r,s=!1,o.stop();let _=[d.stop(),...[...m.values()].map(({engine:x})=>x.stop()),...[...w.values()].map(({engine:x})=>x.stop())];m.clear(),w.clear(),g=[],P.clear(),H.clear(),i.clear(),l(),await Promise.all(_),await t.awaitPendingVaultWrites();let I=n();if(I&&gn(I)){let x=await Me(),C=x.localVault&&!gn(x.localVault)?x.localVault:st.join(t.workspaceDir(),"Amadeus");await ht.mkdir(C,{recursive:!0}),await Ve({lastVault:C,localVault:C,lastPage:void 0}),await t.activateRoot(C,!1)}G()};return{handlers:{get:()=>oe(d.getStatus()),setEnabled:async _=>{if(!s)throw new Error("Cloud account is changing");let I=r;return await d.setEnabled(_),I!==r?d.getStatus():(await Promise.all([...m.values(),...w.values()].map(({engine:x})=>x.restart())),oe(d.getStatus()))},syncNow:()=>_e(),confirmDeletions:()=>{for(let{engine:_}of m.values())_.confirmMassDeletions();for(let{engine:_}of w.values())_.confirmMassDeletions();return oe(d.confirmMassDeletions())},entryGet:async()=>{let _=await Me(),I=Ze(),x=await to(I);return{vaults:_.entrySync??[],activeRoot:n(),cloudRoot:I,mirrorVaults:x.names,mirrorVaultDevices:x.devices,deviceId:_.cloudSync?.deviceId??null}},otherSideDbs:async()=>{let _=n();if(!_)return null;let I=Ze(),x=await Me(),C=_===I?x.localVault&&x.localVault!==I?x.localVault:null:I;if(!C)return null;let L=[],R=500,$=async(M,Y)=>{if(L.length>=R)return;let W;try{W=await ht.readdir(M,{withFileTypes:!0})}catch{return}for(let J of W){if(L.length>=R)break;if(J.name.startsWith(".")||J.isSymbolicLink())continue;let le=Y?`${Y}/${J.name}`:J.name;if(J.isDirectory())await $(st.join(M,J.name),le);else if(J.isFile()&&/\.db$/i.test(J.name))try{L.push({rel:le,source:await ht.readFile(st.join(M,J.name),"utf8")})}catch{}}};return await $(C,""),{root:C,vaultName:C===I?"\u4E91\u7AEF":st.basename(C),dbs:L}},entryEnable:async _=>{let I=r,x=o;if(!s||!Te())return{error:"Sign in to enable cloud sync"};let C=n();if(!C||y())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let L=await Me(),R=L.entrySync??[],$=R.find(M=>M.vaultRoot===C);if(!$){let M=(_.cloudName??st.basename(C)).normalize("NFC").trim(),Y=gr(M,R.map(W=>W.cloudName));if(Y)return{error:Y};if(!_.merge)try{let W=await x.ensureOwnVault(),J=await x.call("GET",`/vaults/${encodeURIComponent(W)}/tree`);if((J.folders??[]).some(ie=>ie===M||ie.startsWith(`${M}/`))||(J.entries??[]).some(ie=>ie.path===M||ie.path.startsWith(`${M}/`)))return{conflict:M}}catch(W){return{error:W?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}$={vaultRoot:C,cloudName:M,entries:[]},R.push($)}return I!==r||!s?{error:"Cloud account changed; retry from the current account"}:(await ft(M=>{if(I!==r||!s)return!1;let Y=M.entrySync??[],W=Y.find(ue=>ue.vaultRoot===C);if(!W){let ue=gr($.cloudName,Y.map(Ue=>Ue.cloudName));if(ue)throw new Error(ue);W={vaultRoot:C,cloudName:$.cloudName,entries:[]},Y.push(W)}let J=ue=>String(ue??"").replace(/\\/g,"/").normalize("NFC"),le=new Set;for(let ue of _.entries??[]){let Ue=J(ue.path);Ue&&(le.add(Ue),!W.entries.some(it=>it.path===Ue)&&W.entries.push({path:Ue,kind:ue.kind==="folder"||ue.kind==="asset"?ue.kind:"page"}))}let ie=(_.exclude??[]).map(J).filter(Boolean),me=new Set([...le,...(_.include??[]).map(J).filter(Boolean)]);W.exclude=[...new Set([...(W.exclude??[]).filter(ue=>!me.has(ue)),...ie])];let ce=new Set(ie);W.entries=W.entries.filter(ue=>!ce.has(ue.path)),M.entrySync=Y,$=W},L.cloudAccountId),I!==r?{error:"Cloud account changed; retry from the current account"}:(await X(),w.get(C)?.engine.syncNow(),G(),{ok:!0,cloudName:$.cloudName}))},entryDisable:async _=>{let I=n(),x=!1,C=r;return await ft(L=>{if(C!==r||!s)return!1;let R=(L.entrySync??[]).find(Y=>Y.vaultRoot===I);if(!I||!R)return!1;let $=String(_??"").replace(/\\/g,"/").normalize("NFC"),M=R.entries.length;if(R.entries=R.entries.filter(Y=>Y.path!==$),gt(R.entries,R.exclude,$))R.exclude=[...new Set([...R.exclude??[],$])];else if(R.entries.length===M)return!1;x=!0}),!x||C!==r?{ok:!1}:(await X(),G(),{ok:!0})},entryMark:async(_,I)=>{let x=String(_??"").normalize("NFC");if(!x||x.includes("/")||x.startsWith("."))return{error:"invalid name"};if(!s||!Te())return{error:"Sign in first"};try{await v(x,C=>I?C?void 0:[]:C?null:void 0)}catch(C){return{error:C?.message||String(C)}}return d.syncNow(),{ok:!0}},entryClosure:(_,I)=>t.relatedClosure(String(_??""),I==="folder"?"folder":"page"),collabCall:async(_,I)=>{let x=o,C=async()=>x.ensureOwnVault(),L=$=>String((I??[])[$]??""),R=$=>(I??[])[$]??{};switch(_){case"listVaults":return(await x.call("GET","/vaults")).vaults;case"activeVaultId":return C();case"pageShare":return x.call("GET",`/vaults/${encodeURIComponent(await C())}/page-shares?path=${encodeURIComponent(L(0))}`);case"createPageShare":return x.call("POST",`/vaults/${encodeURIComponent(await C())}/page-shares`,{path:L(0),...R(1)});case"updatePageShare":return x.call("PATCH",`/vaults/${encodeURIComponent(await C())}/page-shares/${encodeURIComponent(L(0))}`,R(1));case"revokePageShare":return x.call("DELETE",`/vaults/${encodeURIComponent(await C())}/page-shares/${encodeURIComponent(L(0))}`);case"setParticipantRole":return x.call("PATCH",`/vaults/${encodeURIComponent(await C())}/page-shares/${encodeURIComponent(L(0))}/members/${encodeURIComponent(L(1))}`,{role:L(2)});case"removeParticipant":return x.call("DELETE",`/vaults/${encodeURIComponent(await C())}/page-shares/${encodeURIComponent(L(0))}/members/${encodeURIComponent(L(1))}`);case"sharedWithMe":{let $=await x.sharedWithMe();return p(),$}case"leaveShare":{let $=x.myUserId();if(!$)throw new Error("\u672A\u767B\u5F55");return x.call("DELETE",`/vaults/${encodeURIComponent(await C())}/page-shares/${encodeURIComponent(L(0))}/members/${encodeURIComponent($)}`)}case"publishes":return x.call("GET",`/vaults/${encodeURIComponent(await C())}/shares`);case"listAllShares":{let $=(await x.call("GET","/vaults")).vaults||[],M=x.myUserId(),Y=[],W=[];for(let J of $){try{let le=await x.call("GET",`/vaults/${encodeURIComponent(J.id)}/shares`);for(let ie of le.shares||[])Y.push({...ie,vaultId:J.id,vaultName:J.name||""})}catch(le){t.log(`[connect] listAllShares publishes vault ${J.id} failed: ${le?.message}`)}try{let le=await x.call("GET",`/vaults/${encodeURIComponent(J.id)}/page-shares`),ie=le?.shares||le?.pageShares||(Array.isArray(le)?le:[]);for(let me of ie){let ce=me.created_by??me.createdBy;(!M||!ce||ce===M)&&W.push({...me,vaultId:J.id,vaultName:J.name||""})}}catch(le){t.log(`[connect] listAllShares pageShares vault ${J.id} failed: ${le?.message}`)}}return{publishes:Y,pageShares:W,linkBase:await x.linkBase()}}case"createPublish":{let $=await x.call("POST",`/vaults/${encodeURIComponent(await C())}/shares`,{mode:L(0),path:L(1)});return{...$,url:`${await x.linkBase()}/share/${$.token}`}}case"revokePublish":return x.call("DELETE",`/vaults/${encodeURIComponent(await C())}/shares/${encodeURIComponent(L(0))}`);case"revokePublishIn":return x.call("DELETE",`/vaults/${encodeURIComponent(L(0))}/shares/${encodeURIComponent(L(1))}`);case"revokePageShareIn":return x.call("DELETE",`/vaults/${encodeURIComponent(L(0))}/page-shares/${encodeURIComponent(L(1))}`);case"myUserId":return x.myUserId();case"linkBase":return x.linkBase();case"heartbeat":return x.heartbeat((I??[])[0]??null,g);default:throw new Error(`unknown collab fn: ${_}`)}},switchSide:async(_,I)=>{let x=await Me();if(I==="cloud"){if(!s||!Te())throw new Error("Sign in to open cloud notes");let R=Ze();await ht.mkdir(R,{recursive:!0}),x.lastVault&&!gn(x.lastVault)&&await Ve({localVault:x.lastVault}),await Ve({lastVault:R});let $=await t.activateRoot(R,!1);return t.bindRenderer(_,R),{...$,side:"cloud"}}let C=x.localVault&&await ht.stat(x.localVault).then(R=>R.isDirectory()).catch(()=>!1)?x.localVault:null;if(!C){let R=await t.ensureDefaultVault();return t.bindRenderer(_,R.root),{...R,side:"local"}}await Ve({lastVault:C});let L=await t.activateRoot(C,!1);return t.bindRenderer(_,C),{...L,side:"local"}}},instance:{start:()=>{s=!0,d.start(),p(),X()},stopAllSync:fe,restartAllSync:async()=>{await fe(),o=dr(),d=$t(u()),s=!0,await Promise.all([d.restart(),p(),X()]),G(),e(ke.status,oe(d.getStatus()))}}}}import{hostname as ll}from"node:os";var cl=256*1024;function co(t,e,n){if(n?.hasSecHeaders&&!n.gatewayStreamsSecHeaders)return!1;if(t.includes("text/event-stream"))return!0;let r=Number(e||NaN);return!Number.isFinite(r)||r>cl}var wr=45e3,ul=3e3,dl=16*1024,fl=6e4,kn=t=>`${t.replace(/\/+$/,"")}/api`,Nt=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,n){return(this.deps.hubFetch??fetch)(e,n)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??fl}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(n){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${n?.message||n}`)}}abortEnvelope(e){let n=this.inflight.get(e);return n?(this.inflight.delete(e),n.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[n,r]of[...this.inflight])e&&r.conn!==e||(this.inflight.delete(n),r.ctrl.abort())}sleep(e){return new Promise(n=>{let r=setTimeout(s,e);function s(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,s()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,s=()=>r.abort();e.signal.addEventListener("abort",s,{once:!0}),this.conn=r;try{let{cloudUrl:o,token:i}=this.deps.getCreds();if(!i)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let l=this.deps.getPairing();if(!l){if(l=await this.register(o,i,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(l),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${l.unitId}`)}let a=this.deps.getLanUrl();this.hubCaps=new Set;let u=this.deps.readIdleMs??wr,d=u?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(u/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},u):null,m;try{m=await this.hubFetch(`${kn(o)}/units/${l.unitId}/channel`,{headers:{Authorization:`Bearer ${i}`,"X-Unit-Secret":l.secret,...a?{"X-Unit-Lan-Url":a}:{}},signal:r.signal})}finally{d&&clearTimeout(d)}if(m.status===403||m.status===404){let g=Number(m.headers.get("content-length"))>dl,p=setTimeout(()=>r.abort(),g?0:ul),y=await m.json().then(f=>f?.code,()=>null);throw clearTimeout(p),y==="UNIT_NOT_FOUND"||y==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${m.status} ${y}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${m.status} (not a hub verdict; keeping pairing and retrying)`)}if(!m.ok||!m.body)throw new Error(`channel HTTP ${m.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(m.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(o){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(o?.message||o),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",s),this.conn===r&&(this.conn=null),r.abort(),this.abortEnvelopes(r)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,n=1e3;continue}if(await this.sleep(n),this.redialNow){this.redialNow=!1,n=1e3;continue}n=Math.min(n*2,3e4)}}async register(e,n,r){let s=this.deps.readIdleMs??wr,o=s?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(s/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},s):null;try{let i=await this.hubFetch(`${kn(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:ll(),platform:process.platform}),signal:r.signal});if(!i.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${i.status}`);let l=await i.json();if(!l.unitId||!l.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:l.unitId,secret:l.secret}}finally{o&&clearTimeout(o)}}async consume(e,n){let r=e.getReader(),s=new TextDecoder,o="",i=this.deps.readIdleMs??wr,l=null,a=()=>{i&&(l&&clearTimeout(l),l=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(i/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),n.abort(),r.cancel().catch(()=>{})},i))};a();try{for(;;){let{done:u,value:d}=await r.read();if(u||n.signal.aborted)return;a(),o=this.parseFrames(o+s.decode(d,{stream:!0}),n)}}finally{l&&clearTimeout(l)}}parseFrames(e,n){let r=e,s;for(;(s=r.indexOf(`
200
213
 
201
- `))>=0;){let o=s.slice(0,r);if(s=s.slice(r+2),o.includes("event: ready")){let i=o.split(`
202
- `).find(l=>l.startsWith("data: "))?.slice(6);try{let l=JSON.parse(i||"{}").caps;this.hubCaps=new Set(Array.isArray(l)?l.map(String):[])}catch{this.hubCaps=new Set}n.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!o.includes("event: dispatch"))continue;let a=o.split(`
203
- `).find(i=>i.startsWith("data: "))?.slice(6);if(a)try{let i=JSON.parse(a);this.dispatch(i,n).catch(l=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${l?.message||l}`))}catch{}}return s}async dispatch(e,n){let s=new AbortController;if(n.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let r={ctrl:s,conn:n};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,n){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,n.signal);return}let r={"x-unit-internal":s.internalSecret};e.ct&&(r["Content-Type"]=e.ct),e.accept&&(r.Accept=e.accept);let o;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})),o=await fetch(d,{method:e.method,headers:r,body:e.body??void 0,signal:n.signal})}catch(d){if(n.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,n.signal);return}let a=o.headers.get("content-type")||"",i={};for(let d of["content-security-policy","x-content-type-options"]){let f=o.headers.get(d);f&&(i[d]=f)}let l=a||"application/octet-stream";o.body&&ss(a,o.headers.get("content-length"),{hasSecHeaders:Object.keys(i).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,o,n,l,i):await this.respond(e.id,o.status,l,Buffer.from(await o.arrayBuffer()),i,n.signal)}async respond(e,n,s,r,o,a){if(a?.aborted)return;let{cloudUrl:i,token:l}=this.deps.getCreds(),h=this.deps.getPairing();if(!h)return;let d=this.requestTimeoutMs*2,f=[...d?[AbortSignal.timeout(d)]:[],...a?[a]:[]],u=f.length>1?AbortSignal.any(f):f[0];await this.hubFetch(`${zt(i)}/units/${h.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"X-Unit-Secret":h.secret,"Content-Type":"application/json"},body:JSON.stringify({status:n,headers:{"content-type":s,...o},bodyB64:r.toString("base64")}),...u?{signal:u}:{}}).then(g=>{g.body?.cancel().catch(()=>{})}).catch(g=>{a?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${g?.name==="TimeoutError"?`${Math.round(d/1e3)}s \u672A\u5B8C\u6210`:g?.message||g}`)})}async streamBack(e,n,s,r,o){let{cloudUrl:a,token:i}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let h=o?.["content-security-policy"],d=o?.["x-content-type-options"],f=`${zt(a)}/units/${l.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(r)}`+(h?`&csp=${encodeURIComponent(h)}`:"")+(d?`&xcto=${encodeURIComponent(d)}`:""),u=n.body;if(!u)return;let g=u.getReader(),S=0,x=this.requestTimeoutMs,w=x?setTimeout(()=>{S>=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,F=new ReadableStream({async pull(k){++S===2&&w&&clearTimeout(w);let{done:A,value:U}=await g.read();A?k.close():k.enqueue(U)},cancel(k){return g.cancel(k)}},{highWaterMark:0});try{await this.hubFetch(f,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Unit-Secret":l.secret,"Content-Type":"application/octet-stream"},body:F,signal:s.signal,duplex:"half"})}catch(k){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${k?.message||k}`);try{await g.cancel()}catch{}}finally{w&&clearTimeout(w)}}};var yt=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(i){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${i?.message||i}`);return}if(e===this.lastSent)return;let n=this.d.getPairing(),s;try{s=this.d.getCreds()}catch{return}if(!n||!s.token||!s.cloudUrl)return;let r=this.gen;this.inflight=!0;let o=new AbortController,a=setTimeout(()=>o.abort(),this.d.timeoutMs??1e4);try{let i=`${s.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(n.unitId)}/caps`,l=await(this.d.hubFetch??fetch)(i,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"X-Unit-Secret":n.secret,"Content-Type":"application/json"},body:JSON.stringify({engine:e,tools:[]}),signal:o.signal});try{await l.text()}catch{}if(r!==this.gen)return;l.ok?(this.lastSent=e,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}`)):l.status===404||l.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${l.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):l.status===400||l.status===401||l.status===403?this.warned.has(l.status)||(this.warned.add(l.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${l.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${l.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(i){r===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${o.signal.aborted?"\u8D85\u65F6":i?.message||i}`)}finally{clearTimeout(a),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var os=["setUnitHubFactory"],$n=t=>os.every(e=>typeof t[e]=="function");function is(t){let e=new yt({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),log:s=>t.log(s)}),n=new pt({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:s=>t.callerHeaders(s),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:s=>t.savePairing(s),clearPairing:()=>t.clearPairing(),log:s=>t.log(s)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:s=>n.reconnect(s),status:()=>n.status(),engineChanged:()=>e.engineChanged()}}function Dn(t){let e=async(n,s,r)=>{let{base:o,token:a}=await t.getCloud();if(!a)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let i=await fetch(`${o}/api${s}`,{method:n,headers:{Authorization:`Bearer ${a}`,...r!==void 0?{"Content-Type":"application/json"}:{}},body:r!==void 0?JSON.stringify(r):void 0});return{status:i.status,json:await i.json().catch(()=>null)}}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}};t.handle("units:list",()=>e("GET","/units")),t.handle("units:update",(n,s,r)=>e("PATCH",`/units/${encodeURIComponent(String(s))}`,{name:r?.name,icon:r?.icon})),t.handle("units:remove",(n,s)=>e("DELETE",`/units/${encodeURIComponent(String(s))}`)),t.handle("units:openInBrowser",async(n,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:o}=await t.getCloud();await t.openExternal(`${r}/api/units/${s}/open${o?`#token=${encodeURIComponent(o)}`:""}`)}),t.setUnitHubFactory(is),t.log("[forsion-extend] unit hub registered")}import{createHash as Pi}from"node:crypto";import{mkdirSync as $i,readFileSync as Di,renameSync as Mi,writeFileSync as Ni}from"node:fs";import{lstat as Vt,open as Oi,readFile as Ui,readdir as ps}from"node:fs/promises";import{homedir as as,hostname as ys,release as Fi}from"node:os";import{basename as ji,join as ue}from"node:path";var ws=14,Un=60*6e4,Li=24*Un,Hi=2*6e4,zi=12e4,qi=10*6e4,ls=Un,Bi=15e3,cs=1792*1024,Wi=7,Vi=4*1024*1024,Yi=256*1024,ot=t=>t.toISOString().slice(0,10),Bt=t=>Date.parse(ot(t))-(Wi-1)*Li,us=["user","teamwork","discussion","delegate"],Gi=/^(?:New remarks in the team chat:|You are activated now \()/,bs={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Ji=["homeDir","readCreds","accountId","appVersion"],Ss=t=>Ji.every(e=>typeof t[e]=="function"),ds=as().length>3?as():null;function Mn(t){return typeof t=="string"?(ds?t.split(ds).join("~"):t).replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\b(sk-[a-zA-Z0-9_-]{12,})\b/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|LTAI[0-9A-Za-z]{12,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})/g,"[redacted]").replace(/-{5}BEGIN [A-Z ]*PRIVATE KEY-{5}[\s\S]*?(?:-{5}END [A-Z ]*PRIVATE KEY-{5}|$)/g,"[redacted]").replace(/\b[a-fA-F0-9]{32,}\b/g,e=>`[hex:${e.length}]`).replace(/((?:["']?)(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|cookie)(?:["']?)\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\[[^\]\n]*\]|[^\s,"';&}]+)/gi,"$1[redacted]"):Array.isArray(t)?t.map(Mn):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,/^(?:token|.*api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie|set-cookie)$/i.test(e)?"[redacted]":Mn(n)])):t}var Ki=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,re=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,Xi=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function rt(t,e=0){if(typeof t=="boolean"||typeof t=="number"||t===null||t===void 0)return t??null;if(typeof t=="string")return`[string:${t.length}]`;if(Array.isArray(t))return`[array:${t.length}]`;if(typeof t!="object"||e>=4)return"[object]";let n={};for(let[s,[r,o]]of Object.entries(t).slice(0,100).entries())n[Xi(r,s)]=Ki.test(r)&&re(o,80)!==void 0?o:rt(o,e+1);return n}var Zi=/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,Qi=/^(?:apps|enabled_skill_ids)$/;function ea(t){let e=[],n=t.split(/\r?\n/);for(let s=0;s<n.length;s++){let r=n[s].trim();if(/^\[\[?[\w.-]{1,80}\]\]?$/.test(r)){e.push(r);continue}let o=/^([\w.-]+)\s*=\s*(.*)$/.exec(r);if(!o)continue;let[,a,i]=o,l=/^('''|""")/.exec(i)?.[1],h=i.length;if(l&&!i.slice(3).includes(l))for(;++s<n.length&&!n[s].includes(l);)h+=n[s].length+1;let d=/^(?:true|false|[+-]?\d[\d._]*)$/.test(i)||Zi.test(a)&&h<=120&&/^(?:"[^"]*"|'[^']*'|\d{4}-\d{2}-\d{2}[\dT:.+Z -]*)$/.test(i)||Qi.test(a)&&h<=2e3&&/^\[[^\[\]{}]*\]$/.test(i);e.push(d?`${a} = ${i}`:`${a} = "[text:${h}]"`)}return e.join(`
204
- `)}var vs=async t=>{try{return(await Vt(t)).isFile()?await Ui(t,"utf8"):null}catch{return null}},ta=t=>Vt(t).then(e=>e.isDirectory(),()=>!1),Fn=async t=>{try{return JSON.parse(await vs(t)??"null")}catch{return null}},st=async(t,e=200)=>{try{return(await ps(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function na(t,e){if(!(await Vt(t)).isFile())return"";let n=await Oi(t,"r");try{let{size:s}=await n.stat(),r=Math.max(0,s-e),o=Buffer.alloc(s-r);await n.read(o,0,o.length,r);let a=o.toString("utf8");return r>0?a.slice(a.indexOf(`
205
- `)+1):a}finally{await n.close()}}function ra(t){if(!t||typeof t!="object")return{};let e=n=>n&&typeof n=="object"?Object.entries(n).slice(0,100):[];return{defaultModel:re(t.cloud?.defaultModel)??null,models:rt(t.models),tts:rt(t.tts),asr:rt(t.asr),specialAgents:rt(t.specialAgents),pluginSettings:rt(t.plugins?.global),providers:(Array.isArray(t.providers)?t.providers:[]).slice(0,50).map(n=>({providerId:re(n?.providerId)??null,models:(Array.isArray(n?.modelIds)?n.modelIds:[]).filter(s=>re(s)!==void 0).slice(0,100)})),mcpServers:e(t.mcp?.mcpServers).map(([n,s])=>({name:re(n,64)??"[name]",enabled:s?.enabled!==!1})),channels:e(t.channels).map(([n,s])=>({name:re(n,64)??"[name]",enabled:s?.enabled===!0}))}}var sa=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function fs(t){let e=[];for(let n of await st(t,100)){let s=ue(t,n);if(!await ta(s))continue;let r=await vs(ue(s,"config.toml"));e.push({id:n,config:r===null?null:ea(r).slice(0,4096),files:(await st(s,400)).filter(o=>sa.has(o))})}return e}async function hs(t){let e=[];for(let n of await st(t,300)){let s=await Fn(ue(t,n,"manifest.json"));s&&e.push({id:re(s.id)??n,version:re(s.version,40)??null,name:re(s.nameEn)??re(s.name)??null})}return e}var Nn=t=>String(t?.code||t?.message||t).slice(0,120);async function oa(t,e,n,s=Yi){let r=u=>String(u).padStart(2,"0"),o=u=>{let g=new Date(u);return`${g.getFullYear()}${r(g.getMonth()+1)}${r(g.getDate())}${r(g.getHours())}${r(g.getMinutes())}`},a=u=>`${u.slice(0,4)}-${u.slice(4,6)}-${u.slice(6,8)}.log`,i=o(n),l=o(e.getTime()),h=[],d=s,f=!1;try{let u=(await ps(t)).filter(g=>/^\d{4}-\d{2}-\d{2}\.log$/.test(g)&&g>=a(i)&&g<=a(l)).sort().reverse();for(let g of u){if(f)break;let x=(await na(ue(t,g),Vi).catch(F=>{if(F?.code==="ENOENT")return"";throw F})).split(`
206
- `).filter(F=>/^\d{12} /.test(F)&&F.slice(0,12)>=i&&F.slice(0,12)<l),w=x.length;for(;w>0&&Buffer.byteLength(x[w-1])+1<=d;)d-=Buffer.byteLength(x[--w])+1;w>0&&(f=!0),w<x.length&&h.push({date:g.slice(0,10),log:x.slice(w).join(`
207
- `)})}}catch(u){return u?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:Nn(u)}}return{activity:h.reverse(),...f?{activityTruncated:!0}:{}}}var qt=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},ms=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},gs=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function ia(t,e,n=bs,s=Bt(e)){let r=ue(t,"tangu","state.db"),o=await Vt(r).then(i=>i.isFile(),i=>i?.code==="ENOENT"?!1:Nn(i));if(o!==!0)return o===!1?{sessions:[]}:{sessions:[],sessionsError:o};let a;try{let{DatabaseSync:i}=await import("node:sqlite");a=new i(r,{readOnly:!0}),a.exec("PRAGMA busy_timeout = 1500");let h="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",d=[gs(s),gs(e.getTime()),Bt(e)],f=a.prepare(`SELECT s.id, s.kind, s.parent_session_id, s.app_id, s.title, s.model_id, s.project_name, s.archived, s.created_at, s.updated_at, MAX(m.updated_at) AS changed_at
214
+ `))>=0;){let o=r.slice(0,s);if(r=r.slice(s+2),o.includes("event: ready")){let l=o.split(`
215
+ `).find(a=>a.startsWith("data: "))?.slice(6);try{let a=JSON.parse(l||"{}").caps;this.hubCaps=new Set(Array.isArray(a)?a.map(String):[])}catch{this.hubCaps=new Set}n.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!o.includes("event: dispatch"))continue;let i=o.split(`
216
+ `).find(l=>l.startsWith("data: "))?.slice(6);if(i)try{let l=JSON.parse(i);this.dispatch(l,n).catch(a=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${a?.message||a}`))}catch{}}return r}async dispatch(e,n){let r=new AbortController;if(n.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let s={ctrl:r,conn:n};this.inflight.set(e.id,s);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===s&&this.inflight.delete(e.id)}}async handle(e,n){let r=this.deps.getUnitWeb();if(!r.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,n.signal);return}let s={"x-unit-internal":r.internalSecret};e.ct&&(s["Content-Type"]=e.ct),e.accept&&(s.Accept=e.accept);let o;try{let d=new URL(`${r.url}${e.path}`);Object.assign(s,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:d,proxyCaller:e.proxyCaller})),o=await fetch(d,{method:e.method,headers:s,body:e.body??void 0,signal:n.signal})}catch(d){if(n.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,n.signal);return}let i=o.headers.get("content-type")||"",l={};for(let d of["content-security-policy","x-content-type-options"]){let m=o.headers.get(d);m&&(l[d]=m)}let a=i||"application/octet-stream";o.body&&co(i,o.headers.get("content-length"),{hasSecHeaders:Object.keys(l).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,o,n,a,l):await this.respond(e.id,o.status,a,Buffer.from(await o.arrayBuffer()),l,n.signal)}async respond(e,n,r,s,o,i){if(i?.aborted)return;let{cloudUrl:l,token:a}=this.deps.getCreds(),u=this.deps.getPairing();if(!u)return;let d=this.requestTimeoutMs*2,m=[...d?[AbortSignal.timeout(d)]:[],...i?[i]:[]],g=m.length>1?AbortSignal.any(m):m[0];await this.hubFetch(`${kn(l)}/units/${u.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":u.secret,"Content-Type":"application/json"},body:JSON.stringify({status:n,headers:{"content-type":r,...o},bodyB64:s.toString("base64")}),...g?{signal:g}:{}}).then(p=>{p.body?.cancel().catch(()=>{})}).catch(p=>{i?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${p?.name==="TimeoutError"?`${Math.round(d/1e3)}s \u672A\u5B8C\u6210`:p?.message||p}`)})}async streamBack(e,n,r,s,o){let{cloudUrl:i,token:l}=this.deps.getCreds(),a=this.deps.getPairing();if(!a)return;let u=o?.["content-security-policy"],d=o?.["x-content-type-options"],m=`${kn(i)}/units/${a.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(s)}`+(u?`&csp=${encodeURIComponent(u)}`:"")+(d?`&xcto=${encodeURIComponent(d)}`:""),g=n.body;if(!g)return;let p=g.getReader(),y=0,f=this.requestTimeoutMs,w=f?setTimeout(()=>{y>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(f/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),r.abort())},f):null,P=new ReadableStream({async pull(H){++y===2&&w&&clearTimeout(w);let{done:T,value:U}=await p.read();T?H.close():H.enqueue(U)},cancel(H){return p.cancel(H)}},{highWaterMark:0});try{await this.hubFetch(m,{method:"POST",headers:{Authorization:`Bearer ${l}`,"X-Unit-Secret":a.secret,"Content-Type":"application/octet-stream"},body:P,signal:r.signal,duplex:"half"})}catch(H){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${H?.message||H}`);try{await p.cancel()}catch{}}finally{w&&clearTimeout(w)}}};var Ut=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(l){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${l?.message||l}`);return}if(e===this.lastSent)return;let n=this.d.getPairing(),r;try{r=this.d.getCreds()}catch{return}if(!n||!r.token||!r.cloudUrl)return;let s=this.gen;this.inflight=!0;let o=new AbortController,i=setTimeout(()=>o.abort(),this.d.timeoutMs??1e4);try{let l=`${r.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(n.unitId)}/caps`,a=await(this.d.hubFetch??fetch)(l,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"X-Unit-Secret":n.secret,"Content-Type":"application/json"},body:JSON.stringify({engine:e,tools:[]}),signal:o.signal});try{await a.text()}catch{}if(s!==this.gen)return;a.ok?(this.lastSent=e,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}`)):a.status===404||a.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${a.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):a.status===400||a.status===401||a.status===403?this.warned.has(a.status)||(this.warned.add(a.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${a.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${a.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(l){s===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${o.signal.aborted?"\u8D85\u65F6":l?.message||l}`)}finally{clearTimeout(i),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var uo=["setUnitHubFactory"],br=t=>uo.every(e=>typeof t[e]=="function");function fo(t){let e=new Ut({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),log:r=>t.log(r)}),n=new Nt({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:r=>t.callerHeaders(r),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:r=>t.savePairing(r),clearPairing:()=>t.clearPairing(),log:r=>t.log(r)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:r=>n.reconnect(r),status:()=>n.status(),engineChanged:()=>e.engineChanged()}}function Sr(t){let e=async(n,r,s)=>{let{base:o,token:i}=await t.getCloud();if(!i)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let l=await fetch(`${o}/api${r}`,{method:n,headers:{Authorization:`Bearer ${i}`,...s!==void 0?{"Content-Type":"application/json"}:{}},body:s!==void 0?JSON.stringify(s):void 0});return{status:l.status,json:await l.json().catch(()=>null)}}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}};t.handle("units:list",()=>e("GET","/units")),t.handle("units:update",(n,r,s)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:s?.name,icon:s?.icon})),t.handle("units:remove",(n,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),t.handle("units:openInBrowser",async(n,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:s,token:o}=await t.getCloud();await t.openExternal(`${s}/api/units/${r}/open${o?`#token=${encodeURIComponent(o)}`:""}`)}),t.setUnitHubFactory(fo),t.log("[forsion-extend] unit hub registered")}import{createHash as xl}from"node:crypto";import{constants as So,mkdirSync as Cl,readFileSync as Tl,renameSync as Al,writeFileSync as Il}from"node:fs";import{lstat as Je,open as $o,readFile as Pl,readdir as Mo,statfs as Dl}from"node:fs/promises";import{cpus as Rl,freemem as $l,homedir as ko,hostname as Oo,release as Ml,totalmem as Ol}from"node:os";import{basename as No,join as ne}from"node:path";var ml=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,jt=class t extends Date{#t=!1;#n=!1;#e=null;constructor(e){let n=!0,r=!0,s="Z";if(typeof e=="string"){let o=e.match(ml);o?(o[1]||(n=!1,e=`0000-01-01T${e}`),r=!!o[2],r&&e[10]===" "&&(e=e.replace(" ","T")),o[2]&&+o[2]>23?e="":(s=o[3]||null,e=e.toUpperCase(),!s&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=s)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let r=new t(e);return r.#e=n,r}static wrapAsLocalDateTime(e){let n=new t(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new t(e);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new t(e);return n.#t=!1,n.#e=null,n}};function pl(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function gl(t,e,n){let r=t.split(/\r\n|\n|\r/g),s="",o=(Math.log10(e+1)|0)+1;for(let i=e-1;i<=e+1;i++){let l=r[i-1];l&&(s+=i.toString().padEnd(o," "),s+=": ",s+=l,s+=`
217
+ `,i===e&&(s+=" ".repeat(o+n+2),s+=`^
218
+ `))}return s}var Q=class extends Error{line;column;codeblock;constructor(e,n){let[r,s]=pl(n.toml,n.ptr),o=gl(n.toml,r,s);super(`Invalid TOML document: ${e}
219
+
220
+ ${o}`,n),this.line=r,this.column=s,this.codeblock=o}};var hl=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,yl=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,wl=/^[+-]?0[0-9_]/;function En(t,e){let n=t[e++],r=n,s=n==="'",o=n===t[e]&&n===t[e+1];o&&(t[e+=2]===`
221
+ `?e++:t[e]==="\r"&&t[e+1]===`
222
+ `&&(e+=2));let i="",l=e,a=0;for(let u=e;u<t.length;u++)if(n=t[u],o&&(n===`
223
+ `||n==="\r"&&t[u+1]===`
224
+ `))a=a&&3;else{if(n<" "&&n!==" "||n==="\x7F")throw new Q("control characters are not allowed in strings",{toml:t,ptr:u});if((!a||a===3)&&n===r&&(!o||t[u+1]===r&&t[u+2]===r))return o&&(t[u+3]===r&&u++,t[u+3]===r&&u++),[a?i:i+t.slice(l,u),u+(o?3:1)];if(!a)!s&&n==="\\"&&(i+=t.slice(l,l=u),a=1);else if(a===1)if(n==="x"||n==="u"||n==="U"){let d=0,m=n==="x"?2:n==="u"?4:8;for(let g=0;g<m;g++,u++){let p=t.charCodeAt(u+1),y=p>=48&&p<=57?p-48:p>=65&&p<=70?p-65+10:p>=97&&p<=102?p-97+10:-1;if(y<0)throw new Q("invalid non-hex character in unicode escape",{toml:t,ptr:u+1});d=d<<4|y}if(d<0||d>1114111||d>=55296&&d<=57343)throw new Q("invalid unicode escape",{toml:t,ptr:u});i+=String.fromCodePoint(d),l=u+1,a=0}else if(n===" "||n===" ")a=2;else{if(n==="b")i+="\b";else if(n==="t")i+=" ";else if(n==="n")i+=`
225
+ `;else if(n==="f")i+="\f";else if(n==="r")i+="\r";else if(n==="e")i+="\x1B";else if(n==='"')i+='"';else if(n==="\\")i+="\\";else throw new Q("unrecognized escape sequence",{toml:t,ptr:u});l=u+1,a=0}else if(n!==" "&&n!==" "){if(a===2)throw new Q("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:l});a=!s&&n==="\\"?1:0,l=u}}throw new Q("unfinished string",{toml:t,ptr:e})}function mo(t,e,n,r){if(t==="true")return!0;if(t==="false")return!1;if(t==="-inf")return-1/0;if(t==="inf"||t==="+inf")return 1/0;if(t==="nan"||t==="+nan"||t==="-nan")return NaN;if(t==="-0")return r?0n:0;let s=hl.test(t);if(s||yl.test(t)){if(wl.test(t))throw new Q("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let i=+t;if(isNaN(i))throw new Q("invalid number",{toml:e,ptr:n});if(s){if((s=!Number.isSafeInteger(i))&&!r)throw new Q("integer value cannot be represented losslessly",{toml:e,ptr:n});(s||r===!0)&&(i=BigInt(t))}return i}let o=new jt(t);if(!o.isValid())throw new Q("invalid value",{toml:e,ptr:n});return o}function _n(t,e=0,n=t.length){let r=t.indexOf(`
226
+ `,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function yt(t,e){for(let n=e;n<t.length;n++){let r=t[n];if(r===`
227
+ `)return n;if(r==="\r"&&t[n+1]===`
228
+ `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new Q("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function He(t,e,n,r){let s;for(;;){for(;(s=t[e])===" "||s===" "||!n&&(s===`
229
+ `||s==="\r"&&t[e+1]===`
230
+ `);)e++;if(r||s!=="#")break;e=yt(t,e)}return e}function po(t,e,n,r,s=!1){if(!r)return e=_n(t,e),e<0?t.length:e;for(let o=e;o<t.length;o++){let i=t[o];if(i==="#")o=_n(t,o);else{if(i===n)return o+1;if(i===r||s&&(i===`
231
+ `||i==="\r"&&t[o+1]===`
232
+ `))return o}}throw new Q("cannot find end of structure",{toml:t,ptr:e})}function bl(t,e,n){let r=t.slice(e,n),s=r.indexOf("#");return s>-1&&(yt(t,s),r=r.slice(0,s)),[r.trimEnd(),s]}function Ft(t,e,n,r,s){if(r===0)throw new Q("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let o=t[e];if(o==="["||o==="{"){let[a,u]=o==="["?ho(t,e,r,s):go(t,e,r,s);if(n){if(u=He(t,u),t[u]===",")u++;else if(t[u]!==n)throw new Q("expected comma or end of structure",{toml:t,ptr:u})}return[a,u]}if(o==='"'||o==="'"){let[a,u]=En(t,e);if(n){if(u=He(t,u),t[u]&&t[u]!==","&&t[u]!==n&&t[u]!==`
233
+ `&&t[u]!=="\r")throw new Q("unexpected character encountered",{toml:t,ptr:u});t[u]===","&&u++}return[a,u]}let i=po(t,e,",",n),l=bl(t,e,i-(t[i-1]===","?1:0));if(!l[0])throw new Q("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return n&&l[1]>-1&&(i=He(t,e+l[1]),t[i]===","&&i++),[mo(l[0],t,e,s),i]}var Sl=/^[a-zA-Z0-9-_]+[ \t]*$/;function vn(t,e,n="="){let r=e-1,s=[],o=t.indexOf(n,e);if(o<0)throw new Q("incomplete key-value: cannot find end of key",{toml:t,ptr:e});do{let i=t[e=++r];if(i!==" "&&i!==" ")if(i==='"'||i==="'"){if(i===t[e+1]&&i===t[e+2])throw new Q("multiline strings are not allowed in keys",{toml:t,ptr:e});let[l,a]=En(t,e);r=t.indexOf(".",a);let u=t.slice(a,r<0||r>o?o:r),d=_n(u);if(d>-1)throw new Q("newlines are not allowed in keys",{toml:t,ptr:e+r+d});if(u.trimStart())throw new Q("found extra tokens after the string part",{toml:t,ptr:a});if(o<a&&(o=t.indexOf(n,a),o<0))throw new Q("incomplete key-value: cannot find end of key",{toml:t,ptr:e});s.push(l)}else{r=t.indexOf(".",e);let l=t.slice(e,r<0||r>o?o:r);if(!Sl.test(l))throw new Q("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});s.push(l.trimEnd())}}while(r+1&&r<o);return[s,He(t,o+1,!0,!0)]}function go(t,e,n,r){let s={},o=new Set,i;for(e++;(i=t[e++])!=="}"&&i;){if(i===",")throw new Q("expected value, found comma",{toml:t,ptr:e-1});if(i==="#")e=yt(t,e);else if(i!==" "&&i!==" "&&i!==`
234
+ `&&i!=="\r"){let l,a=s,u=!1,[d,m]=vn(t,e-1);for(let y=0;y<d.length;y++){if(y&&(a=u?a[l]:a[l]={}),l=d[y],(u=Object.hasOwn(a,l))&&(typeof a[l]!="object"||o.has(a[l])))throw new Q("trying to redefine an already defined value",{toml:t,ptr:e});!u&&l==="__proto__"&&Object.defineProperty(a,l,{enumerable:!0,configurable:!0,writable:!0})}if(u)throw new Q("trying to redefine an already defined value",{toml:t,ptr:e});let[g,p]=Ft(t,m,"}",n-1,r);o.add(g),a[l]=g,e=p}}if(!i)throw new Q("unfinished table encountered",{toml:t,ptr:e});return[s,e]}function ho(t,e,n,r){let s=[],o;for(e++;(o=t[e++])!=="]"&&o;){if(o===",")throw new Q("expected value, found comma",{toml:t,ptr:e-1});if(o==="#")e=yt(t,e);else if(o!==" "&&o!==" "&&o!==`
235
+ `&&o!=="\r"){let i=Ft(t,e-1,"]",n-1,r);s.push(i[0]),e=i[1]}}if(!o)throw new Q("unfinished array encountered",{toml:t,ptr:e});return[s,e]}function yo(t,e,n,r){let s=e,o=n,i,l=!1,a;for(let u=0;u<t.length;u++){if(u){if(s=l?s[i]:s[i]={},o=(a=o[i]).c,r===0&&(a.t===1||a.t===2))return null;if(a.t===2){let d=s.length-1;s=s[d],o=o[d].c}}if(i=t[u],(l=Object.hasOwn(s,i))&&o[i]?.t===0&&o[i]?.d)return null;l||(i==="__proto__"&&(Object.defineProperty(s,i,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,i,{enumerable:!0,configurable:!0,writable:!0})),o[i]={t:u<t.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(a=o[i],a.t!==r&&!(r===1&&a.t===3)||(r===2&&(a.d||(a.d=!0,s[i]=[]),s[i].push(s={}),a.c[a.i++]=a={t:1,d:!1,i:0,c:{}}),a.d))return null;if(a.d=!0,r===1)s=l?s[i]:s[i]={};else if(r===0&&l)return null;return[i,s,a.c]}function xn(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},s={},o=r,i=s;for(let l=He(t,0);l<t.length;){if(t[l]==="["){let a=t[++l]==="[",u=vn(t,l+=+a,"]");if(a){if(t[u[1]-1]!=="]")throw new Q("expected end of table declaration",{toml:t,ptr:u[1]-1});u[1]++}let d=yo(u[0],r,s,a?2:1);if(!d)throw new Q("trying to redefine an already defined table or value",{toml:t,ptr:l});i=d[2],o=d[1],l=u[1]}else{let a=vn(t,l),u=yo(a[0],o,i,0);if(!u)throw new Q("trying to redefine an already defined table or value",{toml:t,ptr:l});let d=Ft(t,a[1],void 0,e,n);u[1][u[0]]=d[0],l=d[1]}if(l=He(t,l,!0),t[l]&&t[l]!==`
236
+ `&&t[l]!=="\r")throw new Q("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:l});l=He(t,l)}return r}var Tn=14,kl=1440*6e4,El=12e4,_l=15e3,kr=1792*1024,vl=7,Ye=t=>t.toISOString().slice(0,10),ze=t=>Date.parse(Ye(t))-(vl-1)*kl,wo=["sessions","activity"],Cn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Er(t,e,n){let r=t?.day===Ye(n)?t:void 0;return Object.fromEntries(wo.map(s=>[s,Cn(r?.[s])??Math.min(Math.max(Cn(e[s])??0,ze(n)),n.getTime())]))}function _r(t,e,n,r,s,o){let i=e?.day===Ye(r)?e:void 0,l={sent:{...t},file:{day:Ye(r)}};for(let a of wo){let u=a in s&&!o.includes(a)&&!(`${a}Error`in s),d=Cn(i?.[a]);u?(l.file[a]=n[a],l.sent[a]=r.getTime()):d!==void 0&&(l.sent[a]=Math.min(Cn(t[a])??d,d))}return l}function bo(t,e=[]){let n={...t},r=vt(JSON.stringify(n));for(let s of["activity","sessions","memory","runs","engine"]){if(r.length<=kr)break;s in n&&(delete n[s],e.push(s),r=vt(JSON.stringify({...n,truncated:e})))}return r.length>kr?null:r}async function vr(t,e,n,r=new Date){let s=AbortSignal.timeout(El);await t.writeFile(`${e}/${Ye(r)}.json`,n,r.getTime(),s);try{let o=Ye(new Date(r.getTime()-Tn*24*60*6e4));for(let i of await t.walk(s)){let l=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(i.key);l&&l[1]===e&&l[2]<o&&await t.rm(i.key,s)}}catch{}}var xr={mode:"scheduled",intervalHours:24,requestedAt:0};function Lt(t){let e=t&&typeof t=="object"?t:{},n=Number(e.intervalHours),r=Number(e.requestedAt);return{mode:e.mode==="manual"?"manual":"scheduled",intervalHours:Number.isInteger(n)&&n>=1&&n<=720?n:xr.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function Cr(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(_l)});return e.status===404?{...xr}:e.ok?Lt(await e.json()):null}catch{return null}}var Nl=(t,e=[])=>{let n=bo(t,e);return n&&Buffer.from(n.buffer,n.byteOffset,n.byteLength)},Uo=60*6e4,Ul=2*6e4,jl=10*6e4,Eo=Uo,Fl=4*1024*1024,Ll=256*1024,_o=["user","teamwork","discussion","delegate"],Hl=/^(?:New remarks in the team chat:|You are activated now \()/,jo={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},zl=t=>t.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i.test(e)?e:"[path]"),qt=4e3,An=(t,e)=>typeof t=="string"&&t?Ge(zl(tt(t.slice(0,qt))),e):void 0,ql={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},Bl=64*1024,Tr=500,Wl={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},Vl=256*1024,vo=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],Yl=["description","developer_instructions"],Gl=["memory","harness","project_memory","human","dream","log_appended"],Jl=["homeDir","readCreds","accountId","appVersion"],Fo=t=>Jl.every(e=>typeof t[e]=="function"),xo=ko().length>3?ko():null;function tt(t){return typeof t=="string"?(xo?t.split(xo).join("~"):t).replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\b(sk-[a-zA-Z0-9_-]{12,})\b/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|LTAI[0-9A-Za-z]{12,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})/g,"[redacted]").replace(/-{5}BEGIN [A-Z ]*PRIVATE KEY-{5}[\s\S]*?(?:-{5}END [A-Z ]*PRIVATE KEY-{5}|$)/g,"[redacted]").replace(/\b[a-fA-F0-9]{32,}\b/g,(e,n,r)=>/^[a-f0-9]{48}$/.test(e)&&/(?:^|[^\w-])pr-$/.test(r.slice(Math.max(0,n-4),n))?e:`[hex:${e.length}]`).replace(/((?:["']?)(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|cookie)(?:["']?)\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\[[^\]\n]*\]|[^\s,"';&}]+)/gi,"$1[redacted]"):Array.isArray(t)?t.map(tt):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,/^(?:token|.*api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie|set-cookie)$/i.test(e)?"[redacted]":tt(n)])):t}var Xl=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,ee=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,Kl=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function wt(t,e=0){if(typeof t=="boolean"||typeof t=="number"||t===null||t===void 0)return t??null;if(typeof t=="string")return`[string:${t.length}]`;if(Array.isArray(t))return`[array:${t.length}]`;if(typeof t!="object"||e>=4)return"[object]";let n={};for(let[r,[s,o]]of Object.entries(t).slice(0,100).entries())n[Kl(s,r)]=Xl.test(s)&&ee(o,80)!==void 0?o:wt(o,e+1);return n}var Zl={"":/^(?:name|version|description|model|model_reasoning_effort|approval_mode|max_iterations|tools|enabled_skill_ids|enabled_mcp_servers|library_order|apps|avatar|share_default_memory|cloud_sync|activity_access|tools_strict|tools_mode|tools_list|created_by|created_at|developer_instructions|compaction|lead|slug|members|mode|max_rounds)$/,compaction:/^(?:enabled|reserveTokens|thresholdPercent|keepRecentTokens|summaryMaxTokens|thinking|model|instructions|prompt)$/,members:/^(?:slug|role)$/},Co={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},Ql=/^(?:apps|enabled_skill_ids)$/,To=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function ec(t){try{let e=xn(t),n=[],r=[],s=8192,o=(a,u)=>s<=0?!1:(s-=u.length+1,a.push(u),!0),i=(a,u,d)=>{let m=Zl[a].test(u)?u:`[key:${u.length}]`,g=Co[a].test(u),p;return typeof d=="boolean"||typeof d=="number"?p=String(d):g&&typeof d=="string"&&!/[\r\n]/.test(d)&&JSON.stringify(d).length<=120?p=JSON.stringify(d):g&&d instanceof Date?p=d.toISOString():a===""&&Ql.test(u)&&Array.isArray(d)&&d.every(y=>typeof y=="string"&&!/[\r\n]/.test(y))&&JSON.stringify(d).length<=2e3&&(p=`[${d.map(y=>JSON.stringify(y)).join(", ")}]`),`${m} = ${p??`"[text:${typeof d=="string"?d.length:JSON.stringify(d).length}]"`}`},l=(a,u,d)=>{if(o(r,u)){for(let[m,g]of Object.entries(d))if(!o(r,i(a,m,g)))return}};for(let[a,u]of Object.entries(e)){let d=a!==""&&Object.hasOwn(Co,a);if(d&&To(u))l(a,`[${a}]`,u);else if(d&&Array.isArray(u)&&u.length>0&&u.every(To))for(let m of u)l(a,`[[${a}]]`,m);else o(n,i("",a,u));if(s<=0)break}return[...n,...r].join(`
237
+ `)}catch{return`[unparsed:${t.length}]`}}var Lo=async t=>{try{return(await Je(t)).isFile()?await Pl(t,"utf8"):null}catch{return null}},zt=t=>Je(t).then(e=>e.isDirectory(),()=>!1),bt=async t=>{try{return JSON.parse(await Lo(t)??"null")}catch{return null}},qe=async(t,e=200)=>{try{return(await Mo(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function tc(t,e){if(!(await Je(t)).isFile())return"";let n=await $o(t,"r");try{let{size:r}=await n.stat(),s=Math.max(0,r-e),o=Buffer.alloc(r-s);await n.read(o,0,o.length,s);let i=o.toString("utf8");return s>0?i.slice(i.indexOf(`
238
+ `)+1):i}finally{await n.close()}}function nc(t){if(!t||typeof t!="object")return{};let e=n=>n&&typeof n=="object"?Object.entries(n).slice(0,100):[];return{defaultModel:ee(t.cloud?.defaultModel)??null,models:wt(t.models),tts:wt(t.tts),asr:wt(t.asr),specialAgents:wt(t.specialAgents),pluginSettings:wt(t.plugins?.global),providers:(Array.isArray(t.providers)?t.providers:[]).slice(0,50).map(n=>({providerId:ee(n?.providerId)??null,models:(Array.isArray(n?.modelIds)?n.modelIds:[]).filter(r=>ee(r)!==void 0).slice(0,100)})),mcpServers:e(t.mcp?.mcpServers).map(([n,r])=>({name:ee(n,64)??"[name]",enabled:r?.enabled!==!1})),channels:e(t.channels).map(([n,r])=>({name:ee(n,64)??"[name]",enabled:r?.enabled===!0}))}}var rc=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function Ao(t){let e=[];for(let n of await qe(t,100)){let r=ne(t,n);if(!await zt(r))continue;let s=await Lo(ne(r,"config.toml"));e.push({id:n,config:s===null?null:ec(s).slice(0,4096),files:(await qe(r,400)).filter(o=>rc.has(o))})}return e}async function Io(t){let e=[];for(let n of await qe(t,300)){let r=await bt(ne(t,n,"manifest.json"));r&&e.push({id:ee(r.id)??n,version:ee(r.version,40)??null,name:ee(r.nameEn)??ee(r.name)??null})}return e}var ot=t=>String(t?.code||t?.message||t).slice(0,120);async function sc(t,e,n,r=Ll){let s=g=>String(g).padStart(2,"0"),o=g=>{let p=new Date(g);return`${p.getFullYear()}${s(p.getMonth()+1)}${s(p.getDate())}${s(p.getHours())}${s(p.getMinutes())}`},i=g=>`${g.slice(0,4)}-${g.slice(4,6)}-${g.slice(6,8)}.log`,l=o(n),a=o(e.getTime()),u=[],d=r,m=!1;try{let g=(await Mo(t)).filter(p=>/^\d{4}-\d{2}-\d{2}\.log$/.test(p)&&p>=i(l)&&p<=i(a)).sort().reverse();for(let p of g){if(m)break;let f=(await tc(ne(t,p),Fl).catch(P=>{if(P?.code==="ENOENT")return"";throw P})).split(`
239
+ `).filter(P=>/^\d{12} /.test(P)&&P.slice(0,12)>=l&&P.slice(0,12)<a),w=f.length;for(;w>0&&Buffer.byteLength(f[w-1])+1<=d;)d-=Buffer.byteLength(f[--w])+1;w>0&&(m=!0),w<f.length&&u.push({date:p.slice(0,10),log:f.slice(w).join(`
240
+ `)})}}catch(g){return g?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:ot(g)}}return{activity:u.reverse(),...m?{activityTruncated:!0}:{}}}var Ge=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},Po=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},St=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function oc(t,e,n=jo,r=ze(e)){let s=ne(t,"tangu","state.db"),o=await Je(s).then(l=>l.isFile(),l=>l?.code==="ENOENT"?!1:ot(l));if(o!==!0)return o===!1?{sessions:[]}:{sessions:[],sessionsError:o};let i;try{let{DatabaseSync:l}=await import("node:sqlite");i=new l(s,{readOnly:!0}),i.exec("PRAGMA busy_timeout = 1500");let u="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",d=[St(r),St(e.getTime()),ze(e)],m=i.prepare(`SELECT s.id, s.kind, s.parent_session_id, s.app_id, s.title, s.model_id, s.project_name, s.archived, s.created_at, s.updated_at, MAX(m.updated_at) AS changed_at
208
241
  FROM chat_messages m JOIN chat_sessions s ON s.id = m.session_id
209
- WHERE s.kind IN (${us.map(()=>"?").join(", ")}) AND ${h} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...us,...d,n.sessions+1),u=a.prepare(`SELECT m.role, m.content, m.reasoning, m.timestamp, m.model_id, m.is_error, m.tool_calls, length(m.tool_results) AS tool_result_chars, m.attachments, m.agent_slug
210
- FROM chat_messages m WHERE m.session_id = ? AND ${h} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),g=[],S=0,x=f.length>n.sessions;for(let w of f.slice(0,n.sessions)){let F=u.all(w.id,...d,n.messages+1),k=F.length>n.messages,A=[],U=0;for(let j of F.slice(0,n.messages)){let K=ms(j.tool_calls),se=w.kind==="teamwork"&&j.role==="user"&&Gi.test(String(j.content??"")),he={role:re(j.role,16)??null,at:Number(j.timestamp)||null,agent:re(j.agent_slug,64),model:re(j.model_id,128),error:j.is_error?!0:void 0,text:se?void 0:qt(j.content,n.textChars),relayChars:se?String(j.content??"").length:void 0,reasoning:qt(j.reasoning,n.textChars),tools:K.length?K.map(ae=>re(ae?.function?.name??ae?.name,80)??"?"):void 0,toolArgChars:K.length?K.reduce((ae,Ee)=>ae+String(Ee?.function?.arguments??"").length,0):void 0,toolResultChars:Number(j.tool_result_chars)||void 0,attachments:ms(j.attachments).length||void 0},we=Buffer.byteLength(JSON.stringify(he));if(U+we>n.sessionBytes){k=!0;break}U+=we,A.push(he)}let M={id:re(w.id,64)??null,kind:re(w.kind,16)??null,parent:re(w.parent_session_id,64),app:re(w.app_id,50)??null,title:qt(w.title,200)??null,model:re(w.model_id,128)??null,project:qt(w.project_name,120),archived:w.archived?!0:void 0,createdAt:re(w.created_at,40)??null,updatedAt:re(w.updated_at,40)??null,messages:A.reverse(),...k?{olderMessagesDropped:!0}:{}},B=Buffer.byteLength(JSON.stringify(M));if(S+B>n.totalBytes){x=!0;break}S+=B,g.push(M)}return{sessions:g,...x?{sessionsTruncated:!0}:{}}}catch(i){return{sessions:[],sessionsError:Nn(i)}}finally{try{a?.close()}catch{}}}async function Es(t){let e=(await Fn(ue(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${Pi("sha256").update(ys()).digest("hex").slice(0,8)}`}var ks=["sessions","activity"],Wt=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function aa(t,e,n){let s=t?.day===ot(n)?t:void 0;return Object.fromEntries(ks.map(r=>[r,Wt(s?.[r])??Math.min(Math.max(Wt(e[r])??0,Bt(n)),n.getTime())]))}function la(t,e,n,s,r,o){let a=e?.day===ot(s)?e:void 0,i={sent:{...t},file:{day:ot(s)}};for(let l of ks){let h=l in r&&!o.includes(l)&&!(`${l}Error`in r),d=Wt(a?.[l]);h?(i.file[l]=n[l],i.sent[l]=s.getTime()):d!==void 0&&(i.sent[l]=Math.min(Wt(t[l])??d,d))}return i}async function ca(t){let{home:e}=t,n=ue(e,"tangu"),s=t.now??new Date,r=o=>t.since?.[o]??Bt(s);return Mn({schema:2,collectedAt:s.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:Fi(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:ji(e),cloudUrl:t.cloudUrl},device:{id:await Es(e),name:ys()},config:ra(await Fn(ue(e,"config.json"))),agents:await fs(ue(n,"agents")),teams:await fs(ue(n,"teams")),plugins:{desktop:await hs(ue(e,"plugins")),engine:await hs(ue(n,"plugins"))},inventory:{skills:await st(ue(n,"skills")),spaces:await st(ue(e,"spaces")),themes:await st(ue(e,"themes"))},...t.activity?{...await oa(ue(e,"activity"),s,r("activity")),activitySince:new Date(r("activity")).toISOString()}:{},...t.sessions?{...await ia(e,s,bs,r("sessions")),sessionsSince:new Date(r("sessions")).toISOString()}:{}})}function ua(t,e=[]){let n={...t},s=Buffer.from(JSON.stringify(n),"utf8");for(let r of["activity","sessions"]){if(s.length<=cs)break;r in n&&(delete n[r],e.push(r),s=Buffer.from(JSON.stringify({...n,truncated:e}),"utf8"))}return s.length>cs?null:s}async function da(t,e,n,s=new Date){let r=AbortSignal.timeout(zi);await t.writeFile(`${e}/${ot(s)}.json`,n,s.getTime(),r);try{let o=ot(new Date(s.getTime()-ws*24*60*6e4));for(let a of await t.walk(r)){let i=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(a.key);i&&i[1]===e&&i[2]<o&&await t.rm(a.key,r)}}catch{}}var _s={mode:"scheduled",intervalHours:24,requestedAt:0};function On(t){let e=t&&typeof t=="object"?t:{},n=Number(e.intervalHours),s=Number(e.requestedAt);return{mode:e.mode==="manual"?"manual":"scheduled",intervalHours:Number.isInteger(n)&&n>=1&&n<=720?n:_s.intervalHours,requestedAt:Number.isFinite(s)&&s>0?s:0}}async function fa(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(Bi)});return e.status===404?{..._s}:e.ok?On(await e.json()):null}catch{return null}}function Cs(t,e={}){let n=e.now??(()=>new Date),s=e.remoteFor??(k=>Tt({baseUrl:k.cloudUrl,vault:xt,getToken:()=>k.token})),r=e.policyFor??fa,o=()=>ue(t.homeDir(),"extend-diagnostics.json"),a=()=>{let k=A=>A&&typeof A=="object"?A:{};try{let A=JSON.parse(Di(o(),"utf8"));return{accounts:k(A?.accounts),sent:k(A?.sent)}}catch{return{accounts:{},sent:{}}}},i=()=>a().accounts,l=(k,A,U)=>{let M=a();M.accounts[k]={...M.accounts[k],...A},Object.assign(M.sent,U),$i(t.homeDir(),{recursive:!0});let B=`${o()}.${process.pid}.tmp`;Ni(B,JSON.stringify(M,null,2),{encoding:"utf8",mode:384}),Mi(B,o())},h=()=>{let k=t.readCreds();return k.token&&k.cloudUrl?t.accountId():null},d=()=>{let k=h(),A=k?i()[k]??{}:{},U=On(A.policy);return{signedIn:!!k,enabled:A.enabled===!0,activity:A.activity!==!1,sessions:A.sessions??A.enabled!==!0,lastUploadAt:A.lastUploadAt??null,lastError:A.lastError??null,retainDays:ws,mode:U.mode,intervalHours:U.intervalHours}},f=null,u=new Map,g=async()=>{let k=h();if(!k)return!1;if(f)return f.id===k?f.done:(await f.done,g());let A={...t.readCreds()},U=n(),M=a(),B=M.accounts[k],j=A.cloudUrl.replace(/\/+$/,""),K=aa(B?.file,M.sent[j]??{},U),se=(async()=>{try{let he=await ca({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:A.cloudUrl,activity:B?.activity!==!1,sessions:B?.sessions===!0,now:U,since:K}),we=await Es(t.homeDir()),ae=i()[k];if(h()!==k||ae?.enabled!==!0)return!1;if(ae.activity===!1)for(let C of["activity","activityTruncated","activityError","activitySince"])delete he[C];if(ae.sessions!==!0)for(let C of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete he[C];let Ee=[],$e=ua(he,Ee);if(!$e)throw new Error("snapshot too large");await da(s(A),we,$e,U),u.delete(k);let _=la(a().sent[j]??{},B?.file,K,U,he,Ee);return l(k,{lastUploadAt:n().getTime(),lastError:void 0,file:_.file},{[j]:_.sent}),t.log(`[forsion-extend] diagnostics uploaded (${$e.length} bytes)`),!0}catch(he){u.set(k,n().getTime());let we=String(he?.message||he).slice(0,300);try{l(k,{lastError:we})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${we}`),!1}finally{f=null}})();return f={id:k,done:se},se},S=async()=>{try{let k=h();if(!k||i()[k]?.enabled!==!0)return;let A=await r({...t.readCreds()}),U=h()===k?i()[k]:void 0;if(U?.enabled!==!0)return;A&&(A.mode!==U.policy?.mode||A.intervalHours!==U.policy?.intervalHours)&&l(k,{policy:{mode:A.mode,intervalHours:A.intervalHours}}),A&&U.requestSeen===void 0&&l(k,{requestSeen:A.requestedAt});let M=A??{...On(U.policy),requestedAt:0},B=M.requestedAt>(U.requestSeen??M.requestedAt),j=U.lastUploadAt??0,K=!j||M.mode==="scheduled"&&n().getTime()-j>=M.intervalHours*Un;if(!B&&!K||n().getTime()-(u.get(k)??-ls)<ls)return;await g()&&B&&l(k,{requestSeen:M.requestedAt})}catch(k){t.log(`[forsion-extend] diagnostics tick failed: ${String(k?.message||k)}`)}},x={ok:!1,error:"untrusted"};t.handle("diagnostics:get",k=>t.isTrustedSender(k)?d():x),t.handle("diagnostics:set",(k,A)=>{if(!t.isTrustedSender(k))return x;let U=h();if(!U)return d();let M={};typeof A?.enabled=="boolean"&&(M.enabled=A.enabled),M.enabled&&(M.requestSeen=void 0),typeof A?.activity=="boolean"&&(M.activity=A.activity),typeof A?.sessions=="boolean"&&(M.sessions=A.sessions);let B=i()[U];return M.sessions===void 0&&B?.sessions===void 0&&(B?.enabled===!0?M.sessions=!1:M.enabled&&(M.sessions=!0)),l(U,M),M.enabled&&(u.delete(U),S()),d()}),t.handle("diagnostics:uploadNow",async k=>t.isTrustedSender(k)?(d().enabled&&await g(),d()):x);let w=setTimeout(()=>void S(),Hi),F=setInterval(()=>void S(),qi);return w.unref?.(),F.unref?.(),t.log("[forsion-extend] diagnostics registered"),Object.assign(()=>{clearTimeout(w),clearInterval(F)},{tick:S})}async function Ts(t,e){if(!e)return"";try{let n=await ge({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 ha=["membership","credits","storefront"],ma=["monthly","quarterly","yearly"],ga=/^[A-Za-z0-9_-]{1,64}$/;function pc(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:i}=await t.getCloud();if(!a)return{ok:!1};let l=o&&/^[a-z0-9-]+$/i.test(o)?`#${o}`:"",h=await Ts(a,i),d=`${a}/account${h?`?${h}`:""}${l}`;return await t.openExternal(d),{ok:!0}}),t.handle("auth:openPayCenter",async(r,o,a,i)=>{if(!t.isTrustedSender(r))return n;if(o!==void 0&&!ha.includes(o))return{ok:!1,error:"invalid_tab"};if(a!==void 0&&(typeof a!="string"||!ga.test(a)))return{ok:!1,error:"invalid_plan"};if(i!==void 0&&!ma.includes(i))return{ok:!1,error:"invalid_period"};let l=(o??"membership")==="membership"&&a?`&plan=${encodeURIComponent(a)}${i?`&period=${i}`:""}`:"",{base:h,token:d}=await t.getCloud();if(!h)return{ok:!1};let f=await Ts(h,d),u=`${h}/pay?tab=${o??"membership"}${l}${f?`&${f}`:""}&redirect=${encodeURIComponent(`${h}/account`)}`;return await t.openExternal(u),{ok:!0}}),t.handle("profile:publicOrigin",async r=>{if(!t.isTrustedSender(r))return n;let{base:o}=await t.getCloud();if(!o)return{ok:!1};try{let a=await fetch(`${o}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});a.body?.cancel().catch(()=>{});let i=a.status>=300&&a.status<400?a.headers.get("location"):null;return i&&/^https?:\/\//i.test(i)?{ok:!0,origin:new URL(i).origin}:{ok:!1}}catch{return{ok:!1}}});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 ge(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 i=o??"both";try{return await ge(a,"POST","/api/token-quota/reset-card/use",{type:i},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 ge(a,"POST","/api/token-quota/background/convert",{percent:o},15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),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 ge(a,"POST","/api/token-quota/background/auto-main",{enabled:o},15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),t.handle("feedback:submit",async(r,o)=>{if(!t.isTrustedSender(r))return n;let{base:a,token:i}=await t.getCloud();if(!a||!i)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 h=[],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"};h.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 ${i}`},body:JSON.stringify({description:l,attachments:h}),signal:AbortSignal.timeout(2e4)});if(!f.ok){let g=`HTTP ${f.status}`;try{g=(await f.json())?.detail||g}catch{}return{ok:!1,error:g}}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??{},i=typeof a.path=="string"?a.path:"",l=Math.min(12e4,Math.max(1e3,Number(a.timeoutMs)||15e3)),h=typeof a.method=="string"?a.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(h))return{status:0,error:"bad_method"};if(!i.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=Jn(d,i);if(!u)return{status:0,error:"bad_path"};if(!f)return{status:401,error:"not_signed_in"};let g=a.body!==void 0&&h!=="GET"&&h!=="DELETE",S=new AbortController,x=setTimeout(()=>S.abort(),l);try{let w=await fetch(u,{method:h,headers:{Authorization:`Bearer ${f}`,...g?{"Content-Type":"application/json"}:{}},body:g?JSON.stringify(a.body):void 0,signal:S.signal});return{status:w.status,json:await w.json().catch(()=>null)}}catch(w){return{status:0,error:String(w?.message||w)}}finally{clearTimeout(x)}}),t.log("[forsion-extend] cloud account handlers registered"),Qt(t)?en(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),nn(t)?rn(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),on(t)?an(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),In(t)?Rn(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),$n(t)?Dn(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Ss(t)?Cs(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off")}export{hr as ACCOUNT_SEAM,ns as AMADEUS_SEAM,Xt as CONNECT_MAX_FILES,Xn as CONNECT_MAX_FILE_BYTES,Zn as CONNECT_MAX_TOTAL_BYTES,xt as DIAGNOSTICS_VAULT,sr as FORSION_CONNECT_LOCAL_SDK,ma as PAY_PERIODS,ha as PAY_TABS,ar as PENZOR_MAX_FILE,ce as SYNC_IPC,os as UNIT_SEAM,yt as UnitCapsReporter,pt as UnitHost,ge as cloudJson,Qn as collectProjectFiles,Ft as conflictCopyPath,Qo as conflictCopyVariant,fr as createAccountCloud,rs as createAmadeusCloud,Tt as createPenzorRemote,is as createUnitHub,tn as expectedPartsOf,Te as forsionAccountId,dr as forsionRefreshToken,lt as forsionWhoami,on as hasAccountHost,In as hasAmadeusHost,Qt as hasConnectHost,nn as hasRemoteSyncHost,$n as hasUnitHost,rr as makePreviewProxy,tr as readConnectMeta,an as registerAccount,Rn as registerAmadeus,pc as registerCloud,en as registerConnect,rn as registerPenzor,Dn as registerUnit,ur as shouldRefreshToken,ss as streamWorthy,Qr as stripConflictSuffix,ei as textFingerprint,cr as tokenAgeMs,eo as tokenRemainingMs,nr as writeConnectMeta};
242
+ WHERE s.kind IN (${_o.map(()=>"?").join(", ")}) AND ${u} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(..._o,...d,n.sessions+1),g=i.prepare(`SELECT m.role, m.content, m.reasoning, m.timestamp, m.model_id, m.is_error, m.tool_calls, length(m.tool_results) AS tool_result_chars, m.attachments, m.agent_slug
243
+ FROM chat_messages m WHERE m.session_id = ? AND ${u} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),p=[],y=0,f=m.length>n.sessions;for(let w of m.slice(0,n.sessions)){let P=g.all(w.id,...d,n.messages+1),H=P.length>n.messages,T=[],U=0;for(let v of P.slice(0,n.messages)){let b=Po(v.tool_calls),A=w.kind==="teamwork"&&v.role==="user"&&Hl.test(String(v.content??"")),N={role:ee(v.role,16)??null,at:Number(v.timestamp)||null,agent:ee(v.agent_slug,64),model:ee(v.model_id,128),error:v.is_error?!0:void 0,text:A?void 0:Ge(v.content,n.textChars),relayChars:A?String(v.content??"").length:void 0,reasoning:Ge(v.reasoning,n.textChars),tools:b.length?b.map(G=>ee(G?.function?.name??G?.name,80)??"?"):void 0,toolArgChars:b.length?b.reduce((G,se)=>G+String(se?.function?.arguments??"").length,0):void 0,toolResultChars:Number(v.tool_result_chars)||void 0,attachments:Po(v.attachments).length||void 0},B=Buffer.byteLength(JSON.stringify(N));if(U+B>n.sessionBytes){H=!0;break}U+=B,T.push(N)}let z={id:ee(w.id,64)??null,kind:ee(w.kind,16)??null,parent:ee(w.parent_session_id,64),app:ee(w.app_id,50)??null,title:Ge(w.title,200)??null,model:ee(w.model_id,128)??null,project:Ge(w.project_name,120),archived:w.archived?!0:void 0,createdAt:ee(w.created_at,40)??null,updatedAt:ee(w.updated_at,40)??null,messages:T.reverse(),...H?{olderMessagesDropped:!0}:{}},h=Buffer.byteLength(JSON.stringify(z));if(y+h>n.totalBytes){f=!0;break}y+=h,p.push(z)}return{sessions:p,...f?{sessionsTruncated:!0}:{}}}catch(l){return{sessions:[],sessionsError:ot(l)}}finally{try{i?.close()}catch{}}}async function ic(t,e,n=ql){let r=ne(t,"tangu","state.db"),s=await Je(r).then(i=>i.isFile(),i=>i?.code==="ENOENT"?!1:ot(i));if(s!==!0)return s===!1?{runs:[]}:{runs:[],runsError:s};let o;try{let{DatabaseSync:i}=await import("node:sqlite");o=new i(r,{readOnly:!0}),o.exec("PRAGMA busy_timeout = 1500");let a=o.prepare(`SELECT r.id, r.session_id, r.app_id, r.status, r.current_step, r.model_id, substr(r.error, 1, ${qt}) AS error, r.tokens_total, r.created_at, r.updated_at, s.kind
244
+ FROM agent_runs r LEFT JOIN chat_sessions s ON s.id = r.session_id
245
+ WHERE r.updated_at >= ? AND r.updated_at < ? ORDER BY r.updated_at DESC, r.id LIMIT ?`).all(St(ze(e)),St(e.getTime()),n.runs+1),u=o.prepare(`SELECT e.type, json_extract(e.payload, '$.name') AS name, json_extract(e.payload, '$.isError') AS failed, json_extract(e.payload, '$.elapsedMs') AS ms,
246
+ json_extract(e.payload, '$.prompt') AS prompt, json_extract(e.payload, '$.completion') AS completion, json_extract(e.payload, '$.cached') AS cached,
247
+ json_extract(e.payload, '$.reasoningTokens') AS reasoning, json_extract(e.payload, '$.llmMs') AS llm_ms, json_extract(e.payload, '$.ttftMs') AS ttft_ms,
248
+ json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${qt}) AS error
249
+ FROM agent_run_events e WHERE e.run_id = ? AND e.type IN ('usage', 'tool_result', 'error', 'status') AND json_valid(e.payload) ORDER BY e.seq LIMIT ?`),d=f=>typeof f=="number"&&Number.isFinite(f)&&f>0?f:0,m=f=>f||void 0,g=[],p=0,y=a.length>n.runs;for(let f of a.slice(0,n.runs)){let w={llmCalls:0,prompt:0,completion:0,cached:0,reasoning:0,llmMs:0,ttftMaxMs:0,requestMaxBytes:0},P=new Map,H=[],T=0,U=u.all(f.id,n.events+1),z=U.length>n.events;for(let b of U.slice(0,n.events))if(b.type==="usage")w.llmCalls++,w.prompt+=d(b.prompt),w.completion+=d(b.completion),w.cached+=d(b.cached),w.reasoning+=d(b.reasoning),w.llmMs+=d(b.llm_ms),w.ttftMaxMs=Math.max(w.ttftMaxMs,d(b.ttft_ms)),w.requestMaxBytes=Math.max(w.requestMaxBytes,d(b.request_bytes));else if(b.type==="tool_result"){let A=ee(b.name,80)??"?",N=P.get(A)??(P.size<n.tools?{name:A,n:0,ms:0,maxMs:0}:void 0);if(!N){z=!0;continue}P.set(A,N),N.n++,b.failed&&(N.errors=(N.errors??0)+1),N.ms+=d(b.ms),N.maxMs=Math.max(N.maxMs,d(b.ms))}else if(b.type==="error"){let A=An(b.error,n.errorChars);A&&!H.includes(A)&&H.length<3&&H.push(A)}else b.phase==="llm_retry"&&T++;let h={id:ee(f.id,64)??null,session:ee(f.session_id,64)??null,kind:ee(f.kind,16),app:ee(f.app_id,50),model:ee(f.model_id,128),status:ee(f.status,16)??null,error:An(f.error,n.errorChars),createdAt:ee(f.created_at,40)??null,updatedAt:ee(f.updated_at,40)??null,steps:m(d(f.current_step)),tokens:m(d(f.tokens_total)),retries:m(T),...Object.fromEntries(Object.entries(w).map(([b,A])=>[b,m(A)])),errors:H.length?H:void 0,tools:P.size?[...P.values()]:void 0,partial:z||void 0},v=Buffer.byteLength(JSON.stringify(h));if(p+v>n.totalBytes){y=!0;break}p+=v,g.push(h)}return{runs:g,...y?{runsTruncated:!0}:{}}}catch(i){return{runs:[],runsError:ot(i)}}finally{try{o?.close()}catch{}}}async function ac(t){let e=s=>Math.round(s/1048576),n=s=>Je(s).then(o=>o.isFile()?o.size:0,()=>0),r=ne(t,"tangu","state.db");return{cpus:Rl().length,memTotalMB:e(Ol()),memFreeMB:e($l()),diskFreeMB:await Dl(t).then(s=>e(s.bavail*s.bsize),()=>null),stateDbMB:e(await n(r)+await n(`${r}-wal`)),uptimeMin:Math.round(process.uptime()/60)}}var Do=t=>typeof t.diagnosticLogs=="function";function lc(t,e=Bl){let n=t?.engine;if(!n||typeof n!="object")return null;let r=(Array.isArray(n.lines)?n.lines:[]).filter(a=>typeof a=="string"&&!!a),s=r.map(a=>An(a,Tr)??""),o=s.some((a,u)=>a.length>Tr||r[u].length>qt),i=s.length,l=e;for(;i>0&&Buffer.byteLength(s[i-1])+1<=l;)l-=Buffer.byteLength(s[--i])+1;return i>0&&(o=!0),{state:ee(n.state,32)??null,lastError:An(n.lastError,Tr)??null,log:s.slice(i).join(`
250
+ `),...o?{logTruncated:!0}:{}}}function cc(t,e=Yl){let n;try{n=xn(t)}catch{return{}}return Object.fromEntries(e.flatMap(r=>typeof n[r]=="string"&&n[r]?[[r,n[r]]]:[]))}async function Ho(t,e=Vl){try{if(!(await Je(t)).isFile())return null;let n=await $o(t,So.O_RDONLY|(So.O_NOFOLLOW??0));try{let r=await n.stat();if(!r.isFile())return null;let s=Buffer.alloc(Math.min(e,r.size)),{bytesRead:o}=await n.read(s,0,s.length,0);return s.subarray(0,o).toString("utf8")}finally{await n.close()}}catch{return null}}var Ht=async(t,e)=>{let n=await Ho(t);return n?Ge(tt(n),e):void 0};async function uc(t,e){let n=await Ho(ne(t,"config.toml")),r=Object.entries(n?cc(n):{}).map(([s,o])=>[s,Ge(tt(o),e)??""]);return r.length?Object.fromEntries(r):void 0}async function Ro(t){let e=await bt(ne(t,".memory-state.json"));if(!e||typeof e!="object")return;let n=r=>Array.isArray(r)?r.length:0;return{entries:n(e.entries),tombstones:n(e.tombstones),revisions:n(e.revisions),processedCandidates:n(e.processedCandidateIds),updatedAt:typeof e.updatedAt=="number"?e.updatedAt:null,projectionPending:e.projectionPending===!0?!0:void 0}}async function dc(t,e,n=Wl){let r=ne(t,"tangu"),s=p=>Je(p).then(y=>y.isFile()?y.mtimeMs:0,()=>0),o=Ye(new Date(ze(e))),i={agents:[],teams:[],projects:[],activity:[]},l=n.totalBytes,a=(p,y)=>{let f=Buffer.byteLength(JSON.stringify(y))+1;return f>l?(i.truncated=!0,!1):(l-=f,p.push(y),!0)},u=await Ht(ne(r,"USER.md"),n.fileChars);u&&a([],u)&&(i.user=u);let d=ne(r,"state.db"),m=await Je(d).then(p=>p.isFile(),p=>p?.code==="ENOENT"?!1:ot(p));if(typeof m=="string")i.activityError=m;else if(m){let p;try{let{DatabaseSync:y}=await import("node:sqlite");p=new y(d,{readOnly:!0}),p.exec("PRAGMA busy_timeout = 1500");let w=p.prepare(`SELECT agent, action, substr(detail, 1, ${qt}) AS detail, session_ref, created_at FROM special_agent_log
251
+ WHERE created_at >= ? AND created_at < ? AND (${Gl.map(P=>`action GLOB '${P}*'`).join(" OR ")})
252
+ ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(St(ze(e)),St(e.getTime()),n.activity+1);w.length>n.activity&&(i.truncated=!0);for(let P of w.slice(0,n.activity))if(!a(i.activity,{at:ee(P.created_at,40)??null,agent:ee(P.agent,64)??null,action:ee(P.action,64)??null,detail:typeof P.detail=="string"&&P.detail?Ge(tt(P.detail),n.detailChars):void 0,session:ee(P.session_ref,64)}))break}catch(y){i.activityError=ot(y)}finally{try{p?.close()}catch{}}}for(let p of await qe(ne(r,"project-memory"),100)){let y=ne(r,"project-memory",p);if(!await zt(y))continue;let f=await Ht(ne(y,"MEMORY.md"),n.fileChars),w=await Ro(y);if(!f&&!w)continue;let P=(await bt(ne(y,"PROJECT.json")))?.project;if(!a(i.projects,{id:ee(p,64)??null,name:typeof P=="string"?ee(No(P.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:w,memory:f}))break}for(let p of await qe(ne(r,"teams"),100)){if(!await zt(ne(r,"teams",p)))continue;let y=await Ht(ne(r,"teams",p,"TEAM.md"),n.fileChars);if(y&&!a(i.teams,{id:p,files:{"TEAM.md":y}}))break}let g=[];for(let p of await qe(ne(r,"agents"),100)){let y=ne(r,"agents",p);await zt(y)&&g.push({id:p,dir:y,at:Math.max(0,...await Promise.all([...vo,".memory-state.json"].map(f=>s(ne(y,f)))))})}for(let{id:p,dir:y,at:f}of g.sort((w,P)=>P.at-w.at||w.id.localeCompare(P.id))){let w={};for(let z of vo){let h=await Ht(ne(y,z),n.fileChars);h&&(w[z]=h)}let P=[];if(await zt(ne(y,"LOG")))for(let z of(await qe(ne(y,"LOG"),400)).filter(h=>/^\d{4}-\d{2}-\d{2}\.md$/.test(h)&&h.slice(0,10)>=o&&h.slice(0,10)<=Ye(e))){let h=await Ht(ne(y,"LOG",z),n.logChars);h&&P.push({date:z.slice(0,10),text:h})}let H=(await bt(ne(y,".memory-dream.json")))?.last,T=await Ro(y),U=await uc(y,n.fileChars);!Object.keys(w).length&&!P.length&&!T&&!U||a(i.agents,{id:p,updatedAt:f?new Date(f).toISOString():null,config:U,state:T,dream:H&&typeof H=="object"?{state:ee(H.state,32),startedAt:ee(H.startedAt,40),finishedAt:ee(H.finishedAt,40),calls:typeof H.calls=="number"?H.calls:void 0,detail:typeof H.detail=="string"?Ge(tt(H.detail),n.detailChars):void 0}:void 0,files:Object.keys(w).length?w:void 0,log:P.length?P:void 0})}return i}async function zo(t){let e=(await bt(ne(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${xl("sha256").update(Oo()).digest("hex").slice(0,8)}`}async function fc(t){let{home:e}=t,n=ne(e,"tangu"),r=t.now??new Date,s=i=>t.since?.[i]??ze(r),o=lc(t.engineLogs);return tt({schema:3,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:Ml(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:No(e),cloudUrl:t.cloudUrl},device:{id:await zo(e),name:Oo()},system:await ac(e),config:nc(await bt(ne(e,"config.json"))),agents:await Ao(ne(n,"agents")),teams:await Ao(ne(n,"teams")),plugins:{desktop:await Io(ne(e,"plugins")),engine:await Io(ne(n,"plugins"))},inventory:{skills:await qe(ne(n,"skills")),spaces:await qe(ne(e,"spaces")),themes:await qe(ne(e,"themes"))},...t.activity?{...await sc(ne(e,"activity"),r,s("activity")),activitySince:new Date(s("activity")).toISOString()}:{},...t.sessions?{...await oc(e,r,jo,s("sessions")),sessionsSince:new Date(s("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await dc(e,r)}:{},...await ic(e,r),runsSince:new Date(ze(r)).toISOString(),...o?{engine:o}:{}})}function qo(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(T=>cn({baseUrl:T.cloudUrl,vault:un,getToken:()=>T.token})),s=e.policyFor??Cr,o=()=>ne(t.homeDir(),"extend-diagnostics.json"),i=()=>{let T=U=>U&&typeof U=="object"?U:{};try{let U=JSON.parse(Tl(o(),"utf8"));return{accounts:T(U?.accounts),sent:T(U?.sent)}}catch{return{accounts:{},sent:{}}}},l=()=>i().accounts,a=(T,U,z)=>{let h=i();h.accounts[T]={...h.accounts[T],...U},Object.assign(h.sent,z),Cl(t.homeDir(),{recursive:!0});let v=`${o()}.${process.pid}.tmp`;Il(v,JSON.stringify(h,null,2),{encoding:"utf8",mode:384}),Al(v,o())},u=()=>{let T=t.readCreds();return T.token&&T.cloudUrl?t.accountId():null},d=()=>{let T=u(),U=T?l()[T]??{}:{},z=Lt(U.policy);return{signedIn:!!T,enabled:U.enabled===!0,activity:U.activity!==!1,sessions:U.sessions??U.enabled!==!0,memory:U.memory??U.enabled!==!0,lastUploadAt:U.lastUploadAt??null,lastError:U.lastError??null,retainDays:Tn,mode:z.mode,intervalHours:z.intervalHours}},m=()=>{try{return Do(t)?t.diagnosticLogs():null}catch{return null}},g=null,p=new Map,y=async()=>{let T=u();if(!T)return!1;if(g)return g.id===T?g.done:(await g.done,y());let U={...t.readCreds()},z=n(),h=i(),v=h.accounts[T],b=U.cloudUrl.replace(/\/+$/,""),A=Er(v?.file,h.sent[b]??{},z),N=(async()=>{try{let B=await fc({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:U.cloudUrl,activity:v?.activity!==!1,sessions:v?.sessions===!0,now:z,since:A,engineLogs:m(),memory:()=>{let Z=u()===T?l()[T]:void 0;return Z?.enabled===!0&&Z.memory===!0}}),G=await zo(t.homeDir()),se=l()[T];if(u()!==T||se?.enabled!==!0)return!1;if(se.activity===!1)for(let Z of["activity","activityTruncated","activityError","activitySince"])delete B[Z];if(se.sessions!==!0)for(let Z of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete B[Z];se.memory!==!0&&delete B.memory;let pe=[],X=Nl(B,pe);if(!X)throw new Error("snapshot too large");await vr(r(U),G,X,z),p.delete(T);let de=_r(i().sent[b]??{},v?.file,A,z,B,pe);return a(T,{lastUploadAt:n().getTime(),lastError:void 0,file:de.file},{[b]:de.sent}),t.log(`[forsion-extend] diagnostics uploaded (${X.length} bytes)`),!0}catch(B){p.set(T,n().getTime());let G=String(B?.message||B).slice(0,300);try{a(T,{lastError:G})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${G}`),!1}finally{g=null}})();return g={id:T,done:N},N},f=async()=>{try{let T=u();if(!T||l()[T]?.enabled!==!0)return;let U=await s({...t.readCreds()}),z=u()===T?l()[T]:void 0;if(z?.enabled!==!0)return;U&&(U.mode!==z.policy?.mode||U.intervalHours!==z.policy?.intervalHours)&&a(T,{policy:{mode:U.mode,intervalHours:U.intervalHours}}),U&&z.requestSeen===void 0&&a(T,{requestSeen:U.requestedAt});let h=U??{...Lt(z.policy),requestedAt:0},v=h.requestedAt>(z.requestSeen??h.requestedAt),b=z.lastUploadAt??0,A=!b||h.mode==="scheduled"&&n().getTime()-b>=h.intervalHours*Uo;if(!v&&!A||n().getTime()-(p.get(T)??-Eo)<Eo)return;await y()&&v&&a(T,{requestSeen:h.requestedAt})}catch(T){t.log(`[forsion-extend] diagnostics tick failed: ${String(T?.message||T)}`)}},w={ok:!1,error:"untrusted"};t.handle("diagnostics:get",T=>t.isTrustedSender(T)?d():w),t.handle("diagnostics:set",(T,U)=>{if(!t.isTrustedSender(T))return w;let z=u();if(!z)return d();let h={};typeof U?.enabled=="boolean"&&(h.enabled=U.enabled),h.enabled&&(h.requestSeen=void 0),typeof U?.activity=="boolean"&&(h.activity=U.activity),typeof U?.sessions=="boolean"&&(h.sessions=U.sessions),typeof U?.memory=="boolean"&&(h.memory=U.memory);let v=l()[z];for(let b of["sessions","memory"])h[b]!==void 0||v?.[b]!==void 0||(v?.enabled===!0?h[b]=!1:h.enabled&&(h[b]=!0));return a(z,h),h.enabled&&(p.delete(z),f()),d()}),t.handle("diagnostics:uploadNow",async T=>t.isTrustedSender(T)?(d().enabled&&await y(),d()):w);let P=setTimeout(()=>void f(),Ul),H=setInterval(()=>void f(),jl);return P.unref?.(),H.unref?.(),t.log(`[forsion-extend] diagnostics registered${Do(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(P),clearInterval(H)},{tick:f})}Ur(ms);function Cf(t){Wr(t),er(t),t.log("[forsion-extend] cloud account handlers registered"),Vn(t)?Yn(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),Jn(t)?Xn(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),rr(t)?sr(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),hr(t)?yr(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),br(t)?Sr(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Fo(t)?qo(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off")}export{Us as ACCOUNT_SEAM,ao as AMADEUS_SEAM,Bn as CONNECT_MAX_FILES,gs as CONNECT_MAX_FILE_BYTES,hs as CONNECT_MAX_TOTAL_BYTES,un as DIAGNOSTICS_VAULT,Es as FORSION_CONNECT_LOCAL_SDK,Br as PAY_PERIODS,qr as PAY_TABS,xs as PENZOR_MAX_FILE,ke as SYNC_IPC,uo as UNIT_SEAM,fn as UPLOAD_MAX_FILE,Ut as UnitCapsReporter,Nt as UnitHost,Ae as cloudJson,ys as collectProjectFiles,hn as conflictCopyPath,La as conflictCopyVariant,Ns as createAccountCloud,lo as createAmadeusCloud,cn as createPenzorRemote,fo as createUnitHub,ln as deviceHeader,Gn as expectedPartsOf,$e as forsionAccountId,pn as forsionRefreshToken,Tt as forsionWhoami,rr as hasAccountHost,hr as hasAmadeusHost,Vn as hasConnectHost,Jn as hasRemoteSyncHost,br as hasUnitHost,ks as makePreviewProxy,Ps as multipartFrame,bs as readConnectMeta,sr as registerAccount,yr as registerAmadeus,Cf as registerCloud,Yn as registerConnect,Xn as registerPenzor,er as registerPenzorTransfers,Sr as registerUnit,Qn as safeDownloadName,mn as shouldRefreshToken,Ds as speedOf,co as streamWorthy,no as stripConflictSuffix,Ha as textFingerprint,nr as tokenAgeMs,$s as tokenRemainingMs,Rs as uploadError,Ss as writeConnectMeta};
211
253
  /*! Bundled license information:
212
254
 
213
255
  chokidar/index.js:
214
256
  (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
257
+
258
+ smol-toml/dist/date.js:
259
+ smol-toml/dist/error.js:
260
+ smol-toml/dist/primitive.js:
261
+ smol-toml/dist/util.js:
262
+ smol-toml/dist/extract.js:
263
+ smol-toml/dist/struct.js:
264
+ smol-toml/dist/parse.js:
265
+ smol-toml/dist/stringify.js:
266
+ smol-toml/dist/index.js:
267
+ (*!
268
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
269
+ * SPDX-License-Identifier: BSD-3-Clause
270
+ *
271
+ * Redistribution and use in source and binary forms, with or without
272
+ * modification, are permitted provided that the following conditions are met:
273
+ *
274
+ * 1. Redistributions of source code must retain the above copyright notice, this
275
+ * list of conditions and the following disclaimer.
276
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
277
+ * this list of conditions and the following disclaimer in the
278
+ * documentation and/or other materials provided with the distribution.
279
+ * 3. Neither the name of the copyright holder nor the names of its contributors
280
+ * may be used to endorse or promote products derived from this software without
281
+ * specific prior written permission.
282
+ *
283
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
284
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
285
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
286
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
287
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
288
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
289
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
290
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
292
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
293
+ *)
215
294
  */