sliccy 6.131.0 → 6.131.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/ui/.vite/manifest.json +121 -121
  2. package/dist/ui/assets/{account-store-DsMvFZgS.js → account-store-B2fM_hVm.js} +1 -1
  3. package/dist/ui/assets/{account-store-naVgJKHe.js → account-store-CnTVyV3B.js} +1 -1
  4. package/dist/ui/assets/{adobe-BhZB46bT.js → adobe-Cwc5x2uv.js} +1 -1
  5. package/dist/ui/assets/{adobe-sRIQnDEl.js → adobe-DDIBiAPC.js} +1 -1
  6. package/dist/ui/assets/{agent-bridge-DVqU5-sn.js → agent-bridge-BNzVNteR.js} +1 -1
  7. package/dist/ui/assets/{apply-layout-dNkV0TEv.js → apply-layout-CaZC02vG.js} +1 -1
  8. package/dist/ui/assets/{apps-tzFQ7_KO.js → apps-BKCcSwUS.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-B9ZeZZ0T.js → azure-openai-BbS3zNfN.js} +1 -1
  10. package/dist/ui/assets/{azure-openai-DsmgiFlX.js → azure-openai-DS9LetAu.js} +1 -1
  11. package/dist/ui/assets/{cerebras-CsdnfQnc.js → cerebras-Bl6JS-Zz.js} +1 -1
  12. package/dist/ui/assets/{cerebras-Mux-1Uqj.js → cerebras-CXTvGhJy.js} +1 -1
  13. package/dist/ui/assets/{connect-surface-DgrjdeR5.js → connect-surface-Cga7yA1x.js} +1 -1
  14. package/dist/ui/assets/{directed-approval-BDO2wdC5.js → directed-approval-D5JxaPCg.js} +1 -1
  15. package/dist/ui/assets/{fs-CDaCMxrL.js → fs-B5l0OgHF.js} +1 -1
  16. package/dist/ui/assets/{fs-CBaQR8Xc.js → fs-WglxnM0m.js} +2 -2
  17. package/dist/ui/assets/{github-B7uOq9Q1.js → github-CipnBUW0.js} +1 -1
  18. package/dist/ui/assets/{github-copilot-BeWJoZwD.js → github-copilot-ByPeJOvj.js} +1 -1
  19. package/dist/ui/assets/{github-copilot-DwKSI23j.js → github-copilot-CPGYy73b.js} +1 -1
  20. package/dist/ui/assets/{github-install-DE7dF6r8.js → github-install-B7uGR7D1.js} +1 -1
  21. package/dist/ui/assets/{github-qhOhjD2Q.js → github-rNEu9Il2.js} +2 -2
  22. package/dist/ui/assets/{github-zip-CuwUOO-U.js → github-zip-CXwGYOT2.js} +1 -1
  23. package/dist/ui/assets/{help-D66VHlYj.js → help-aOXHqJ8Q.js} +1 -1
  24. package/dist/ui/assets/{js-realm-worker-Bsb6rmK5.js → js-realm-worker-BNIyA4hZ.js} +1 -1
  25. package/dist/ui/assets/{kernel-worker-CkZd8Enf.js → kernel-worker-_zyksCUm.js} +30 -30
  26. package/dist/ui/assets/{local-llm-B-qS5oNT.js → local-llm-DZNM8DQQ.js} +1 -1
  27. package/dist/ui/assets/{local-llm-COCS88AU.js → local-llm-mXBzcfos.js} +1 -1
  28. package/dist/ui/assets/{main-CAXbdHY8.js → main-B-nfOo4q.js} +3 -3
  29. package/dist/ui/assets/{mount-BbUBqN71.js → mount-B4KSGLVw.js} +1 -1
  30. package/dist/ui/assets/{mount-ysOnJBjr.js → mount-Ch4xd9rB.js} +3 -3
  31. package/dist/ui/assets/{mount-recovery-OxgGejDC.js → mount-recovery-Di7nIeaF.js} +1 -1
  32. package/dist/ui/assets/{new-session-JIL4tJ1I.js → new-session-ClnfXCAZ.js} +2 -2
  33. package/dist/ui/assets/{oauth-bootstrap-DP5y5Dy8.js → oauth-bootstrap-DESksVSP.js} +2 -2
  34. package/dist/ui/assets/{openai-codex-DlFMWNVB.js → openai-codex-ByROFNSi.js} +1 -1
  35. package/dist/ui/assets/{openai-codex-BZDYkVh6.js → openai-codex-nfIOpXSu.js} +1 -1
  36. package/dist/ui/assets/{openrouter-BrS9XpJS.js → openrouter-BfHAZQmK.js} +1 -1
  37. package/dist/ui/assets/{openrouter-Dn_iX45f.js → openrouter-CqAv3VZj.js} +1 -1
  38. package/dist/ui/assets/{openrouter-oauth-CioQlp0x.js → openrouter-oauth-BoC1y3uz.js} +1 -1
  39. package/dist/ui/assets/{openrouter-oauth-D9gZVt7e.js → openrouter-oauth-DQITUCdi.js} +1 -1
  40. package/dist/ui/assets/{panel-rpc-handlers-DUN0E_f8.js → panel-rpc-handlers-B6r8KSY4.js} +2 -2
  41. package/dist/ui/assets/{provider-BfGyOQHs.js → provider-CuvQQp10.js} +2 -2
  42. package/dist/ui/assets/{provider-DnIZJQjl.js → provider-NGK7XrJs.js} +1 -1
  43. package/dist/ui/assets/{provider-settings-DrWv51sQ.js → provider-settings-C_7ia6Wg.js} +1 -1
  44. package/dist/ui/assets/provider-settings-s-43s4y0.js +1 -0
  45. package/dist/ui/assets/provider-store-access-BLtf32eE.js +1 -0
  46. package/dist/ui/assets/{provider-store-access-BqErJhmB.js → provider-store-access-CMt1lgF6.js} +2 -2
  47. package/dist/ui/assets/{providers-CqZKx9qW.js → providers-Cc4NoSCd.js} +2 -2
  48. package/dist/ui/assets/{providers-CF2FF0H2.js → providers-CtPlPUAl.js} +1 -1
  49. package/dist/ui/assets/{quick-llm-B9NubAhJ.js → quick-llm-By0alwjq.js} +1 -1
  50. package/dist/ui/assets/{recovery-screen-cHPORxsj.js → recovery-screen-Cr55gwtB.js} +1 -1
  51. package/dist/ui/assets/{run-DZh-18uA.js → run-Bf9B4QDH.js} +2 -2
  52. package/dist/ui/assets/{run-BOu4zIOZ.js → run-Bub_JJ9Q.js} +1 -1
  53. package/dist/ui/assets/{run-D5Va_gO8.js → run-mzRo2_pR.js} +1 -1
  54. package/dist/ui/assets/{session-freezer-Bltt6zUt.js → session-freezer-FCAjtzB9.js} +3 -3
  55. package/dist/ui/assets/{setup-feature-flags-remote-BkP-HRZt.js → setup-feature-flags-remote-AO0av6y4.js} +1 -1
  56. package/dist/ui/assets/{setup-standalone-prelude-C2tPUGcI.js → setup-standalone-prelude-C-gDZsJ6.js} +1 -1
  57. package/dist/ui/assets/{setup-sudo-BSw__xoN.js → setup-sudo-CyDP6flA.js} +2 -2
  58. package/dist/ui/assets/{skills-wzno5Tj5.js → skills-CoT8PzSA.js} +1 -1
  59. package/dist/ui/assets/slicc-version-C11usX8a.js +1 -0
  60. package/dist/ui/assets/{snapshot-Bi6QabWh.js → snapshot-C26Hnrzl.js} +1 -1
  61. package/dist/ui/assets/{snapshot-features-BEPdcWF6.js → snapshot-features-DMqvwv22.js} +1 -1
  62. package/dist/ui/assets/{state-DIwkpIaB.js → state-DihPwc0x.js} +1 -1
  63. package/dist/ui/assets/{store-i7XHN1Er.js → store-BFQaIUNf.js} +1 -1
  64. package/dist/ui/assets/{store-CFx1fIZL.js → store-jCHEXPsn.js} +1 -1
  65. package/dist/ui/assets/{sudo-r7OrTMGT.js → sudo-DV79W8d_.js} +1 -1
  66. package/dist/ui/assets/{upgrade-detection-Cz0eOMYf.js → upgrade-detection-DS0TnOrq.js} +1 -1
  67. package/dist/ui/assets/{wc-extension-CJ6cvLnw.js → wc-extension-NZBjLMIl.js} +2 -2
  68. package/dist/ui/assets/{wc-follower-CkrdiOKN.js → wc-follower-BdUaqkeK.js} +3 -3
  69. package/dist/ui/assets/{wc-live-CxoqWHpR.js → wc-live-Doom1Cuk.js} +3 -3
  70. package/dist/ui/assets/{wc-nav-Bnd_bEYw.js → wc-nav-DX0vhaA2.js} +2 -2
  71. package/dist/ui/assets/{wc-onboarding-FeHr2fj5.js → wc-onboarding-DWR8Cofn.js} +2 -2
  72. package/dist/ui/assets/{wc-placeholder-C79lmtig.js → wc-placeholder-EhKkP8p0.js} +2 -2
  73. package/dist/ui/assets/{wc-settings-DdAeaZhQ.js → wc-settings-D_ym_qw0.js} +2 -2
  74. package/dist/ui/assets/{wc-shell-BP3biEU1.js → wc-shell-p7cHxhJQ.js} +2 -2
  75. package/dist/ui/assets/{wc-sprinkles-ChlcnDD2.js → wc-sprinkles-Bm5U1hNI.js} +2 -2
  76. package/dist/ui/assets/{wc-tray-BfoqEbBg.js → wc-tray-DL-rVcIK.js} +4 -4
  77. package/dist/ui/assets/{xai-grok-3L0LL1R8.js → xai-grok-DbCJs1Ps.js} +1 -1
  78. package/dist/ui/assets/{xai-grok-CKevFY8L.js → xai-grok-QZxyqlOs.js} +1 -1
  79. package/dist/ui/index.html +6 -6
  80. package/dist/ui/packages/webapp/index.html +6 -6
  81. package/package.json +1 -1
  82. package/dist/ui/assets/provider-settings-C6uIHjd4.js +0 -1
  83. package/dist/ui/assets/provider-store-access-BuQzycZu.js +0 -1
  84. package/dist/ui/assets/slicc-version-HwuyIZfW.js +0 -1
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{n as s,t as c}from"./types-Dgm4REV3.js";import{i as l,r as u,t as d}from"./mount-index-D9w_zMSm.js";import{a as f,i as p,n as m,t as h}from"./mount-table-store-DrF_Ifaz.js";import{n as g,t as _}from"./virtual-device-paths-CS5o4QVz.js";import{i as v,r as y,t as b}from"./sidecar-repair-CIHuOk7H.js";function x(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function S(e,t){try{return await e(t)}catch{return t}}async function*C(e,t,n,r=0){let a=i(t);if(x(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await S(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*w(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*w(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*T(e,n,r,i);return}yield*C(e,n,r,i)}async function*T(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*C(e,t,n,r))}catch{}}const E=t(`fs-watcher`);let D=0;function O(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var k=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++D}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),E.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),E.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>O(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){E.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),E.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const A=new TextEncoder,j=new TextDecoder(`utf-8`,{fatal:!1});var M=class{entries=new Map;static handles(e){return g(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?A.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?j.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return j.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new c(`ENOENT`,`no such file or directory`,t);return n}};const N={[_]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},P=[`/tmp/`];var F=class{ephemeralFds=new M;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,a={}){this.vfs=e;let o=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(o),this.readOnlyPrefixes=n.map(o),this.writeEnforcement=r,this.includeMounts=a.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...P]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...P].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return M.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=N[i(e)];if(n)return n.read(t);if(M.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(N[i(e)]||M.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=i(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=N[i(e)];if(t)return t.stat();if(M.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=N[i(e)];return t?t.stat():M.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=N[i(e)];return t?t.stat():M.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(M.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new c(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(N[i(e)])return!0;if(M.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=N[i(e)];if(t)return t.readText();if(M.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=N[i(e)];if(r){r.write(t);return}if(M.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(M.handles(e))throw new c(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(M.handles(e)){if(!this.ephemeralFds.remove(e))throw new c(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(M.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(M.handles(t)){if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=N[i(e)];if(t)return t.stat();if(M.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function I(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const L=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function R(e,t){if(e instanceof c)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new c(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(L.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function z(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function B(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function V(e){let t=e?.mode;return typeof t==`number`?t:void 0}function H(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=z(V(r));o!==z(V(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function U(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}async function W(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=R(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function G(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw R(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function K(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await W(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await G(e,o,i)}}async function q(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await K(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function J(e,t,n){return t(n)?n:q(e,t,n)}function Y(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function X(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function Z(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var Q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new d;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await e.seedOpfsMetadataSidecarIfMissing(i);let[a,{WebAccess:o}]=await Promise.all([import(`./dist-CBELmDjr.js`).then(e=>e.t),import(`./dist-iMxkf8fm.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-CBELmDjr.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Y(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await h().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=y(e,r,i))}let o=JSON.stringify(v(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=H(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=b(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await b(n)(a),s=z(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=B(o,s),d=B(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-CBELmDjr.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push(a===`symlink`?{name:i,type:a}:{name:i,type:a,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??u(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=Z(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await f(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await p(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await m(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return l.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-BxfjZHzO.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-BbUBqN71.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r(e.profile)})}case`da`:{let{DaMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-BbUBqN71.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}case`aem`:{let{AemMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-BbUBqN71.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}getMountBackend(e){let t=i(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,u(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){I(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw R(e,n)}}async readFileRange(e,t,n){let r=i(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new c(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let a=this.findMount(r),o=a?.backend.readFileRange;if(a&&o){if(a.relParts.length===0)throw new c(`EISDIR`,`is a directory`,r);try{return await o.call(a.backend,a.relParts.join(`/`),t,n)}catch(e){I(e,r)}}let s=await this.readFile(r,{encoding:`binary`});return new Uint8Array(s.subarray(t,Math.min(n,s.byteLength)))}async getNativeFile(e){let t=i(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r=this.opfsHandle;if(!r)return null;try{return await U(r,await this.resolveSymlinks(t))}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){I(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw R(e,a)}}else throw R(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw R(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e,t){let n=i(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){I(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,X(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw R(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw R(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){I(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw R(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.ctime??t.mtime,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){I(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*C({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw R(e,r)}}else throw R(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw R(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async realpath(e){return q(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return J(this.lfs,e=>this.findMount(e)!==null,e)}},$=e({FsError:()=>c,FsWatcher:()=>k,MountIndex:()=>d,RestrictedFS:()=>F,VirtualFS:()=>Q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>Y,splitPath:()=>n,statsFromDirEntry:()=>s});export{k as i,Q as n,F as r,$ as t};
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{n as s,t as c}from"./types-Dgm4REV3.js";import{i as l,r as u,t as d}from"./mount-index-D9w_zMSm.js";import{a as f,i as p,n as m,t as h}from"./mount-table-store-DrF_Ifaz.js";import{n as g,t as _}from"./virtual-device-paths-CS5o4QVz.js";import{i as v,r as y,t as b}from"./sidecar-repair-CIHuOk7H.js";function x(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function S(e,t){try{return await e(t)}catch{return t}}async function*C(e,t,n,r=0){let a=i(t);if(x(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await S(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*w(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*w(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*T(e,n,r,i);return}yield*C(e,n,r,i)}async function*T(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*C(e,t,n,r))}catch{}}const E=t(`fs-watcher`);let D=0;function O(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var k=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++D}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),E.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),E.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>O(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){E.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),E.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const A=new TextEncoder,j=new TextDecoder(`utf-8`,{fatal:!1});var M=class{entries=new Map;static handles(e){return g(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?A.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?j.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return j.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new c(`ENOENT`,`no such file or directory`,t);return n}};const N={[_]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},P=[`/tmp/`];var F=class{ephemeralFds=new M;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,a={}){this.vfs=e;let o=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(o),this.readOnlyPrefixes=n.map(o),this.writeEnforcement=r,this.includeMounts=a.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...P]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...P].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return M.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=N[i(e)];if(n)return n.read(t);if(M.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(N[i(e)]||M.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=i(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=N[i(e)];if(t)return t.stat();if(M.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=N[i(e)];return t?t.stat():M.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=N[i(e)];return t?t.stat():M.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(M.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new c(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(N[i(e)])return!0;if(M.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=N[i(e)];if(t)return t.readText();if(M.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=N[i(e)];if(r){r.write(t);return}if(M.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(M.handles(e))throw new c(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(M.handles(e)){if(!this.ephemeralFds.remove(e))throw new c(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(M.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(M.handles(t)){if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=N[i(e)];if(t)return t.stat();if(M.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function I(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const L=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function R(e,t){if(e instanceof c)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new c(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(L.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function z(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function B(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function V(e){let t=e?.mode;return typeof t==`number`?t:void 0}function H(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=z(V(r));o!==z(V(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function U(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}async function W(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=R(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function G(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw R(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function K(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await W(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await G(e,o,i)}}async function q(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await K(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function J(e,t,n){return t(n)?n:q(e,t,n)}function Y(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function X(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function Z(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var Q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new d;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await e.seedOpfsMetadataSidecarIfMissing(i);let[a,{WebAccess:o}]=await Promise.all([import(`./dist-CBELmDjr.js`).then(e=>e.t),import(`./dist-iMxkf8fm.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-CBELmDjr.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Y(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await h().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=y(e,r,i))}let o=JSON.stringify(v(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=H(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=b(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await b(n)(a),s=z(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=B(o,s),d=B(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-CBELmDjr.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push(a===`symlink`?{name:i,type:a}:{name:i,type:a,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??u(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=Z(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await f(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await p(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await m(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return l.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-BxfjZHzO.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-B4KSGLVw.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r(e.profile)})}case`da`:{let{DaMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-B4KSGLVw.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}case`aem`:{let{AemMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-B4KSGLVw.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}getMountBackend(e){let t=i(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,u(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){I(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw R(e,n)}}async readFileRange(e,t,n){let r=i(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new c(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let a=this.findMount(r),o=a?.backend.readFileRange;if(a&&o){if(a.relParts.length===0)throw new c(`EISDIR`,`is a directory`,r);try{return await o.call(a.backend,a.relParts.join(`/`),t,n)}catch(e){I(e,r)}}let s=await this.readFile(r,{encoding:`binary`});return new Uint8Array(s.subarray(t,Math.min(n,s.byteLength)))}async getNativeFile(e){let t=i(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r=this.opfsHandle;if(!r)return null;try{return await U(r,await this.resolveSymlinks(t))}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){I(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw R(e,a)}}else throw R(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw R(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e,t){let n=i(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){I(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,X(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw R(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw R(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){I(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw R(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.ctime??t.mtime,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){I(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*C({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw R(e,r)}}else throw R(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw R(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async realpath(e){return q(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return J(this.lfs,e=>this.findMount(e)!==null,e)}},$=e({FsError:()=>c,FsWatcher:()=>k,MountIndex:()=>d,RestrictedFS:()=>F,VirtualFS:()=>Q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>Y,splitPath:()=>n,statsFromDirEntry:()=>s});export{k as i,Q as n,F as r,$ as t};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-BKQr3WRb.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/safe-buffer-iah92gQe.js","assets/dist-DHO9E-gl.js","assets/sidecar-repair-431vRT2V.js","assets/backend-hostfs-BH8uwRZG.js","assets/api-endpoint-DGxXvrur.js","assets/runtime-env-Dlaokqg1.js","assets/types-Dgm4REV3.js","assets/remote-cache-3KNT1gsp.js","assets/mount-ysOnJBjr.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-D0xZwlMO.js","assets/base64-DJRlyqZu.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{r as s,t as c}from"./bounded-walk-BjxKWNqp.js";import{n as l,t as u}from"./types-Dgm4REV3.js";import{n as d,t as f}from"./virtual-device-paths-D45tpPP6.js";import{a as p,i as m,n as h,t as g}from"./mount-table-store-dY2IfQ5S.js";import{i as _,r as v,t as y}from"./sidecar-repair-431vRT2V.js";var b=t(`fs-watcher`),x=0;function ee(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var S=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++x}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),b.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),b.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>ee(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){b.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),b.debug(`All watchers disposed`)}get size(){return this.registrations.size}},C=t(`mount-index`),w=400,T=2e6,E=`SLICC_MOUNT_INDEX_MAX_DEPTH`,D=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,O=256,k=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function te(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>O?t.slice(0,O):t;return`${t.length}\u0001${n.join(``)}`}async function ne(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function re(e,t){return e instanceof Map?e.get(t):e[t]}function A(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function j(e,t,n){let r=re(e,t);if(r===void 0||r.trim()===``)return n;let i=A(r);return i===void 0?(C.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function M(e){return{maxDepth:j(e,E,w),maxEntries:j(e,D,T),skipNoiseDirs:!0}}var N=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=M({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,childrenByDirectory:new Map,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),n.childrenByDirectory.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=n.childrenByDirectory.get(t);if(r)return[...r].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`||this.isSkippedNoisePath(t,e,n,`file`))return;n.files.add(e),this.addPathToChildIndex(n,e,`file`);let r=this.parentPath(e);for(;(r===t||r.startsWith(`${t}/`))&&(n.directories.add(r),this.ensureDirectoryChildren(n,r),r!==t);)this.addPathToChildIndex(n,r,`directory`),r=this.parentPath(r)}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`||this.isSkippedNoisePath(t,e,n,`unknown`))return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e);this.removePathFromChildIndex(n,e);for(let t of n.childrenByDirectory.keys())(t===e||t.startsWith(r))&&n.childrenByDirectory.delete(t)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status!==`ready`)return;let i=r.files.has(e)?`file`:r.directories.has(e)?`directory`:`unknown`;if(i===`unknown`||this.isSkippedNoisePath(n,e,r,i))return;if(this.isSkippedNoisePath(n,t,r,i)){this.notifyDelete(e);return}if(i===`file`){r.files.delete(e),r.files.add(t),this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`file`);return}r.directories.delete(e),r.directories.add(t);let a=e+`/`,o=t+`/`;for(let e of[...r.files])e.startsWith(a)&&(r.files.delete(e),r.files.add(o+e.slice(a.length)));for(let e of[...r.directories])e.startsWith(a)&&(r.directories.delete(e),r.directories.add(o+e.slice(a.length)));this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`directory`);let s=[...r.childrenByDirectory.entries()].filter(([t])=>t===e||t.startsWith(a));for(let[e]of s)r.childrenByDirectory.delete(e);for(let[n,i]of s){let s=n===e?t:o+n.slice(a.length);r.childrenByDirectory.set(s,i)}}ensureDirectoryChildren(e,t){let n=e.childrenByDirectory.get(t);return n||(n=new Map,e.childrenByDirectory.set(t,n)),n}addPathToChildIndex(e,t,n){let r=t.slice(t.lastIndexOf(`/`)+1);r&&(this.ensureDirectoryChildren(e,this.parentPath(t)).set(r,n),n===`directory`&&this.ensureDirectoryChildren(e,t))}removePathFromChildIndex(e,t){let n=t.slice(t.lastIndexOf(`/`)+1);e.childrenByDirectory.get(this.parentPath(t))?.delete(n)}parentPath(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}isSkippedNoisePath(e,t,n,r){if(!n.limits.skipNoiseDirs||!t.startsWith(`${e}/`))return!1;let i=t.slice(e.length+1).split(`/`),a=r===`unknown`?n.files.has(t)?`file`:n.directories.has(t)?`directory`:`unknown`:r;for(let e=0;e<i.length;e++){let t=e===i.length-1;if(!(t&&a===`file`)&&!(t&&a===`unknown`&&!c(i[e]))&&c(i[e]))return!0}return!1}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,C.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof k?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},C.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e),this.ensureDirectoryChildren(n,e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new k(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new k(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new k(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=te(n),a=r.get(i);if(a){for(let n of a)if(await ne(n.handle,t))throw new k(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;if(s.kind===`file`)n.files.add(t),this.addPathToChildIndex(n,t,`file`),n.state.indexed++;else if(s.kind===`directory`){if(n.limits.skipNoiseDirs&&c(o))continue;this.addPathToChildIndex(n,t,`directory`),await this.walkHandle(t,s,n,r,i+1,a)}n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},P=new TextEncoder,F=new TextDecoder(`utf-8`,{fatal:!1}),I=class{entries=new Map;static handles(e){return d(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?P.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?F.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return F.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new u(`ENOENT`,`no such file or directory`,t);return n}},L={[f]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},R=[`/tmp/`],z=class{ephemeralFds=new I;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,a={}){this.vfs=e;let o=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(o),this.readOnlyPrefixes=n.map(o),this.writeEnforcement=r,this.includeMounts=a.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...R]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...R].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return I.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new u(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new u(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof u?t:new u(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new u(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=L[i(e)];if(n)return n.read(t);if(I.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(L[i(e)]||I.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=i(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=L[i(e)];if(t)return t.stat();if(I.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=L[i(e)];return t?t.stat():I.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=L[i(e)];return t?t.stat():I.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(I.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new u(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(L[i(e)])return!0;if(I.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=L[i(e)];if(t)return t.readText();if(I.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=L[i(e)];if(r){r.write(t);return}if(I.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(I.handles(e))throw new u(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(I.handles(e)){if(!this.ephemeralFds.remove(e))throw new u(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(I.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(I.handles(t)){if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new u(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=L[i(e)];if(t)return t.stat();if(I.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new u(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new u(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new u(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new u(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function B(e,t){if(e instanceof u){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new u(e.code,r,t)}throw e}var V=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function H(e,t){if(e instanceof u)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new u(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(V.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new u(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new u(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new u(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new u(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new u(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new u(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new u(`ELOOP`,`too many levels of symbolic links`,t):new u(`EINVAL`,r,t)}var U=61440,W=16384;function G(e){return e===void 0?`absent`:(e&U)===W?`directory`:`file`}function K(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function q(e){let t=e?.mode;return typeof t==`number`?t:void 0}function J(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=G(q(r));o!==G(q(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var Y=512,X=class e{kind=`local`;listingStatsMatchStat=!0;source=void 0;profile=void 0;mountId;handle;dirCacheMax;dirCache=new Map;closed=!1;constructor(e,t){this.handle=e,this.mountId=t.mountId,this.dirCacheMax=t.dirCacheMax??Y}static fromHandle(t,n){return new e(t,n)}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new u(`EBADF`,`mount closed`,e)}splitPath(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(e=>e.length>0)}cacheGet(e){let t=this.dirCache.get(e);if(t!==void 0)return this.dirCache.delete(e),this.dirCache.set(e,t),t}cacheSet(e,t){for(this.dirCache.has(e)&&this.dirCache.delete(e),this.dirCache.set(e,t);this.dirCache.size>this.dirCacheMax;){let e=this.dirCache.keys().next();if(e.done)break;this.dirCache.delete(e.value)}}invalidate(e){if(e===``){this.dirCache.clear();return}let t=`${e}/`;for(let n of[...this.dirCache.keys()])(n===e||n.startsWith(t))&&this.dirCache.delete(n)}getDirCacheSize(){return this.dirCache.size}async resolveDirFrom(e,t,n,r=!0){let i=this.handle,a=``,o=0;if(r)for(let t=e.length;t>0;t--){let n=e.slice(0,t).join(`/`),r=this.cacheGet(n);if(r){i=r,a=n,o=t;break}}let s=a;for(;o<e.length;o++){let r=e[o];try{i=await i.getDirectoryHandle(r,{create:n})}catch(r){if(n&&s!==``)return this.invalidate(s),this.resolveDirFrom(e,t,n,!1);throw this.toFsError(r,t)}a=a===``?r:`${a}/${r}`,this.cacheSet(a,i)}return i}async resolveDir(e,t=!1){return this.resolveDirFrom(this.splitPath(e),e,t)}async resolveParent(e,t){let n=this.splitPath(e);if(n.length===0)throw new u(`EISDIR`,`is a directory`,e);let r=n.pop();return{parent:await this.resolveDirFrom(n,e,t),name:r}}async resolveFile(e,t=!1){let{parent:n,name:r}=await this.resolveParent(e,t);try{return await n.getFileHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}}toFsError(e,t){if(e instanceof u)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new u(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}return new u(`EINVAL`,e instanceof Error?e.message:String(e),t)}async readDir(e,t){this.assertOpen(e);let n=await this.resolveDir(e),r=[];for await(let[e,i]of n){if(i.kind!==`file`){r.push({name:e,kind:`directory`});continue}if(!t?.includeStats){r.push({name:e,kind:`file`});continue}let n=await i.getFile();r.push({name:e,kind:`file`,size:n.size,lastModified:n.lastModified})}return r}async readFile(e){this.assertOpen(e);let t=await(await this.resolveFile(e)).getFile();return new Uint8Array(await t.arrayBuffer())}async getNativeFile(e){this.assertOpen(e);try{return await(await this.resolveFile(e)).getFile()}catch{return null}}async writeFile(e,t){this.assertOpen(e);let n=await(await this.resolveFile(e,!0)).createWritable();await n.write(t),await n.close()}async stat(e){this.assertOpen(e);let t=this.splitPath(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};let n=t.pop(),r=await this.resolveDirFrom(t,e,!1);try{let e=await(await r.getFileHandle(n)).getFile();return{kind:`file`,size:e.size,mtime:e.lastModified}}catch(t){let n=this.toFsError(t,e);if(n.code!==`ENOENT`&&n.code!==`ENOTDIR`)throw n}try{let e=await r.getDirectoryHandle(n);this.cacheSet(t.length===0?n:`${t.join(`/`)}/${n}`,e)}catch(t){throw this.toFsError(t,e)}return{kind:`directory`,size:0,mtime:0}}async mkdir(e){this.assertOpen(e),await this.resolveDir(e,!0)}async remove(e,t){this.assertOpen(e);let n=this.splitPath(e);if(n.length===0)throw new u(`EINVAL`,`cannot remove mount root`,e);let r=n.pop(),i=await this.resolveDirFrom(n,e,!1);try{await i.removeEntry(r,{recursive:t?.recursive??!1})}catch(t){throw this.toFsError(t,e)}this.invalidate(n.length===0?r:`${n.join(`/`)}/${r}`)}async refresh(){return this.assertOpen(`/`),this.dirCache.clear(),{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:this.handle.name}}async close(){this.closed=!0,this.dirCache.clear()}};async function ie(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}async function ae(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=H(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function Z(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw H(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function oe(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await ae(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new u(`ELOOP`,`too many symbolic links encountered`,i);o=await Z(e,o,i)}}async function Q(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await oe(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function se(e,t,n){return t(n)?n:Q(e,t,n)}function $(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function ce(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function le(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var ue=class t{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new N;static writeChains=new Map;onRepairProgress;constructor(e,n,r,i,a){if(this.dbName=e,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?t.initOpfsBackend(this,i,n===!0):t.initMemoryBackend(this,e,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${e}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(n,r,i){let a=r??await t.acquireOpfsHandle(n.dbName,i);await t.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2])),e(()=>import(`./dist-DHO9E-gl.js`),__vite__mapDeps([3,0,1,2]))]);await t.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=t.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}t.opfsBackends.delete(n.dbName),l=void 0}if(!l){let r=()=>o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:i,repairOpfsMetadataSidecar:u}=await e(async()=>{let{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}=await import(`./sidecar-repair-431vRT2V.js`).then(e=>e.n);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},__vite__mapDeps([4,1]));try{let e=await n.withWriteLock(()=>u(a,n.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let d=await i(r,()=>n.withWriteLock(()=>u(a,n.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{o.mount(c,d)}catch{}l={backendFs:d,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},t.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]));await t.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=t.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}t.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},t.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(e){return t.rootMountReady===null&&(t.rootMountReady=(async()=>{await e.configureSingle({backend:e.InMemory,label:`__vfs_root__`})})()),t.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new u(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(e){return new t(e)}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=e?.backend??$(),a=new t(n,r,i,void 0,e?.onRepairProgress);return await a._ready,r&&await g().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,n=this.opfsHandle;if(!e||!n)return;let r=e.index.toJSON(),i=t.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=v(e,r,i))}let o=JSON.stringify(_(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=J(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=y(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(e,r=`path`){if(this.backend!==`opfs`)return;let a=t.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(e);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await y(n)(a),s=G(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=K(o,s),d=K(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new u(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?t.opfsBackends:t.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push(a===`symlink`?{name:i,type:a}:{name:i,type:a,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new u(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new u(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new u(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof u)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??M(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=le(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await p(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await m(t)}catch{}}async reconstructBackendFromDescriptor(t,n){switch(t.kind){case`local`:{let e=await h(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return X.fromHandle(e,{mountId:t.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await e(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-BH8uwRZG.js`);return{HostFsMountBackend:e}},__vite__mapDeps([5,6,7,8,9]));return new r({targetPath:n,hostPath:t.hostPath,mountId:t.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await e(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-ysOnJBjr.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([10,11,12,13,8,14,1,9])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i(t.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-ysOnJBjr.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([10,11,12,13,8,14,1,9])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-ysOnJBjr.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([10,11,12,13,8,14,1,9])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}getMountBackend(e){let t=i(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new u(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new u(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new u(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,M(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){B(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw H(e,n)}}async readFileRange(e,t,n){let r=i(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new u(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let a=this.findMount(r),o=a?.backend.readFileRange;if(a&&o){if(a.relParts.length===0)throw new u(`EISDIR`,`is a directory`,r);try{return await o.call(a.backend,a.relParts.join(`/`),t,n)}catch(e){B(e,r)}}let s=await this.readFile(r,{encoding:`binary`});return new Uint8Array(s.subarray(t,Math.min(n,s.byteLength)))}async getNativeFile(e){let t=i(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r=this.opfsHandle;if(!r)return null;try{return await ie(r,await this.resolveSymlinks(t))}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new u(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){B(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let c=!1;try{await this.lfs.stat(s),c=!0}catch{}let{dir:l}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),l!==`/`&&await this.mkdirRecursiveUnlocked(l);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(l!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(l);try{await this.lfs.writeFile(s,t)}catch(e){throw H(e,a)}}else throw H(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw H(e,a)}}),this.watcher?.notify([{type:c?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e,t){let n=i(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){B(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,ce(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw H(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(e){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=t.writeChains.get(n)??Promise.resolve();t.writeChains.set(n,i),await a;try{let t=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof t?.request!=`function`?await e():await t.request(`slicc-vfs:${n}`,()=>e())}finally{r(),t.writeChains.get(n)===i&&t.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw H(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new u(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof u&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){B(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw H(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){B(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw H(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.ctime??t.mtime,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){B(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw H(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){B(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw H(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*s({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new u(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new u(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw H(e,r)}}else throw H(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw H(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw H(e,t)}}async realpath(e){return Q(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return se(this.lfs,e=>this.findMount(e)!==null,e)}};export{u as FsError,S as FsWatcher,N as MountIndex,z as RestrictedFS,ue as VirtualFS,o as joinPath,i as normalizePath,r as pathSegments,$ as resolveVfsBackendFromEnv,n as splitPath,l as statsFromDirEntry,X as t};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-BKQr3WRb.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/safe-buffer-iah92gQe.js","assets/dist-DHO9E-gl.js","assets/sidecar-repair-431vRT2V.js","assets/backend-hostfs-BH8uwRZG.js","assets/api-endpoint-DGxXvrur.js","assets/runtime-env-Dlaokqg1.js","assets/types-Dgm4REV3.js","assets/remote-cache-3KNT1gsp.js","assets/mount-Ch4xd9rB.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-D0xZwlMO.js","assets/base64-DJRlyqZu.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{r as s,t as c}from"./bounded-walk-BjxKWNqp.js";import{n as l,t as u}from"./types-Dgm4REV3.js";import{n as d,t as f}from"./virtual-device-paths-D45tpPP6.js";import{a as p,i as m,n as h,t as g}from"./mount-table-store-dY2IfQ5S.js";import{i as _,r as v,t as y}from"./sidecar-repair-431vRT2V.js";var b=t(`fs-watcher`),x=0;function ee(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var S=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++x}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),b.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),b.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>ee(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){b.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),b.debug(`All watchers disposed`)}get size(){return this.registrations.size}},C=t(`mount-index`),w=400,T=2e6,E=`SLICC_MOUNT_INDEX_MAX_DEPTH`,D=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,O=256,k=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function te(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>O?t.slice(0,O):t;return`${t.length}\u0001${n.join(``)}`}async function ne(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function re(e,t){return e instanceof Map?e.get(t):e[t]}function A(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function j(e,t,n){let r=re(e,t);if(r===void 0||r.trim()===``)return n;let i=A(r);return i===void 0?(C.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function M(e){return{maxDepth:j(e,E,w),maxEntries:j(e,D,T),skipNoiseDirs:!0}}var N=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=M({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,childrenByDirectory:new Map,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),n.childrenByDirectory.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=n.childrenByDirectory.get(t);if(r)return[...r].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`||this.isSkippedNoisePath(t,e,n,`file`))return;n.files.add(e),this.addPathToChildIndex(n,e,`file`);let r=this.parentPath(e);for(;(r===t||r.startsWith(`${t}/`))&&(n.directories.add(r),this.ensureDirectoryChildren(n,r),r!==t);)this.addPathToChildIndex(n,r,`directory`),r=this.parentPath(r)}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`||this.isSkippedNoisePath(t,e,n,`unknown`))return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e);this.removePathFromChildIndex(n,e);for(let t of n.childrenByDirectory.keys())(t===e||t.startsWith(r))&&n.childrenByDirectory.delete(t)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status!==`ready`)return;let i=r.files.has(e)?`file`:r.directories.has(e)?`directory`:`unknown`;if(i===`unknown`||this.isSkippedNoisePath(n,e,r,i))return;if(this.isSkippedNoisePath(n,t,r,i)){this.notifyDelete(e);return}if(i===`file`){r.files.delete(e),r.files.add(t),this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`file`);return}r.directories.delete(e),r.directories.add(t);let a=e+`/`,o=t+`/`;for(let e of[...r.files])e.startsWith(a)&&(r.files.delete(e),r.files.add(o+e.slice(a.length)));for(let e of[...r.directories])e.startsWith(a)&&(r.directories.delete(e),r.directories.add(o+e.slice(a.length)));this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`directory`);let s=[...r.childrenByDirectory.entries()].filter(([t])=>t===e||t.startsWith(a));for(let[e]of s)r.childrenByDirectory.delete(e);for(let[n,i]of s){let s=n===e?t:o+n.slice(a.length);r.childrenByDirectory.set(s,i)}}ensureDirectoryChildren(e,t){let n=e.childrenByDirectory.get(t);return n||(n=new Map,e.childrenByDirectory.set(t,n)),n}addPathToChildIndex(e,t,n){let r=t.slice(t.lastIndexOf(`/`)+1);r&&(this.ensureDirectoryChildren(e,this.parentPath(t)).set(r,n),n===`directory`&&this.ensureDirectoryChildren(e,t))}removePathFromChildIndex(e,t){let n=t.slice(t.lastIndexOf(`/`)+1);e.childrenByDirectory.get(this.parentPath(t))?.delete(n)}parentPath(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}isSkippedNoisePath(e,t,n,r){if(!n.limits.skipNoiseDirs||!t.startsWith(`${e}/`))return!1;let i=t.slice(e.length+1).split(`/`),a=r===`unknown`?n.files.has(t)?`file`:n.directories.has(t)?`directory`:`unknown`:r;for(let e=0;e<i.length;e++){let t=e===i.length-1;if(!(t&&a===`file`)&&!(t&&a===`unknown`&&!c(i[e]))&&c(i[e]))return!0}return!1}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,C.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof k?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},C.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e),this.ensureDirectoryChildren(n,e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new k(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new k(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new k(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=te(n),a=r.get(i);if(a){for(let n of a)if(await ne(n.handle,t))throw new k(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;if(s.kind===`file`)n.files.add(t),this.addPathToChildIndex(n,t,`file`),n.state.indexed++;else if(s.kind===`directory`){if(n.limits.skipNoiseDirs&&c(o))continue;this.addPathToChildIndex(n,t,`directory`),await this.walkHandle(t,s,n,r,i+1,a)}n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},P=new TextEncoder,F=new TextDecoder(`utf-8`,{fatal:!1}),I=class{entries=new Map;static handles(e){return d(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?P.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?F.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return F.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new u(`ENOENT`,`no such file or directory`,t);return n}},L={[f]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},R=[`/tmp/`],z=class{ephemeralFds=new I;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,a={}){this.vfs=e;let o=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(o),this.readOnlyPrefixes=n.map(o),this.writeEnforcement=r,this.includeMounts=a.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...R]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...R].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return I.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new u(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new u(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof u?t:new u(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new u(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=L[i(e)];if(n)return n.read(t);if(I.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(L[i(e)]||I.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=i(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=L[i(e)];if(t)return t.stat();if(I.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=L[i(e)];return t?t.stat():I.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=L[i(e)];return t?t.stat():I.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(I.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new u(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(L[i(e)])return!0;if(I.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=L[i(e)];if(t)return t.readText();if(I.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=L[i(e)];if(r){r.write(t);return}if(I.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(I.handles(e))throw new u(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(I.handles(e)){if(!this.ephemeralFds.remove(e))throw new u(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(I.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(I.handles(t)){if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new u(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=L[i(e)];if(t)return t.stat();if(I.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new u(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new u(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new u(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new u(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function B(e,t){if(e instanceof u){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new u(e.code,r,t)}throw e}var V=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function H(e,t){if(e instanceof u)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new u(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(V.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new u(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new u(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new u(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new u(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new u(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new u(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new u(`ELOOP`,`too many levels of symbolic links`,t):new u(`EINVAL`,r,t)}var U=61440,W=16384;function G(e){return e===void 0?`absent`:(e&U)===W?`directory`:`file`}function K(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function q(e){let t=e?.mode;return typeof t==`number`?t:void 0}function J(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=G(q(r));o!==G(q(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var Y=512,X=class e{kind=`local`;listingStatsMatchStat=!0;source=void 0;profile=void 0;mountId;handle;dirCacheMax;dirCache=new Map;closed=!1;constructor(e,t){this.handle=e,this.mountId=t.mountId,this.dirCacheMax=t.dirCacheMax??Y}static fromHandle(t,n){return new e(t,n)}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new u(`EBADF`,`mount closed`,e)}splitPath(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(e=>e.length>0)}cacheGet(e){let t=this.dirCache.get(e);if(t!==void 0)return this.dirCache.delete(e),this.dirCache.set(e,t),t}cacheSet(e,t){for(this.dirCache.has(e)&&this.dirCache.delete(e),this.dirCache.set(e,t);this.dirCache.size>this.dirCacheMax;){let e=this.dirCache.keys().next();if(e.done)break;this.dirCache.delete(e.value)}}invalidate(e){if(e===``){this.dirCache.clear();return}let t=`${e}/`;for(let n of[...this.dirCache.keys()])(n===e||n.startsWith(t))&&this.dirCache.delete(n)}getDirCacheSize(){return this.dirCache.size}async resolveDirFrom(e,t,n,r=!0){let i=this.handle,a=``,o=0;if(r)for(let t=e.length;t>0;t--){let n=e.slice(0,t).join(`/`),r=this.cacheGet(n);if(r){i=r,a=n,o=t;break}}let s=a;for(;o<e.length;o++){let r=e[o];try{i=await i.getDirectoryHandle(r,{create:n})}catch(r){if(n&&s!==``)return this.invalidate(s),this.resolveDirFrom(e,t,n,!1);throw this.toFsError(r,t)}a=a===``?r:`${a}/${r}`,this.cacheSet(a,i)}return i}async resolveDir(e,t=!1){return this.resolveDirFrom(this.splitPath(e),e,t)}async resolveParent(e,t){let n=this.splitPath(e);if(n.length===0)throw new u(`EISDIR`,`is a directory`,e);let r=n.pop();return{parent:await this.resolveDirFrom(n,e,t),name:r}}async resolveFile(e,t=!1){let{parent:n,name:r}=await this.resolveParent(e,t);try{return await n.getFileHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}}toFsError(e,t){if(e instanceof u)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new u(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}return new u(`EINVAL`,e instanceof Error?e.message:String(e),t)}async readDir(e,t){this.assertOpen(e);let n=await this.resolveDir(e),r=[];for await(let[e,i]of n){if(i.kind!==`file`){r.push({name:e,kind:`directory`});continue}if(!t?.includeStats){r.push({name:e,kind:`file`});continue}let n=await i.getFile();r.push({name:e,kind:`file`,size:n.size,lastModified:n.lastModified})}return r}async readFile(e){this.assertOpen(e);let t=await(await this.resolveFile(e)).getFile();return new Uint8Array(await t.arrayBuffer())}async getNativeFile(e){this.assertOpen(e);try{return await(await this.resolveFile(e)).getFile()}catch{return null}}async writeFile(e,t){this.assertOpen(e);let n=await(await this.resolveFile(e,!0)).createWritable();await n.write(t),await n.close()}async stat(e){this.assertOpen(e);let t=this.splitPath(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};let n=t.pop(),r=await this.resolveDirFrom(t,e,!1);try{let e=await(await r.getFileHandle(n)).getFile();return{kind:`file`,size:e.size,mtime:e.lastModified}}catch(t){let n=this.toFsError(t,e);if(n.code!==`ENOENT`&&n.code!==`ENOTDIR`)throw n}try{let e=await r.getDirectoryHandle(n);this.cacheSet(t.length===0?n:`${t.join(`/`)}/${n}`,e)}catch(t){throw this.toFsError(t,e)}return{kind:`directory`,size:0,mtime:0}}async mkdir(e){this.assertOpen(e),await this.resolveDir(e,!0)}async remove(e,t){this.assertOpen(e);let n=this.splitPath(e);if(n.length===0)throw new u(`EINVAL`,`cannot remove mount root`,e);let r=n.pop(),i=await this.resolveDirFrom(n,e,!1);try{await i.removeEntry(r,{recursive:t?.recursive??!1})}catch(t){throw this.toFsError(t,e)}this.invalidate(n.length===0?r:`${n.join(`/`)}/${r}`)}async refresh(){return this.assertOpen(`/`),this.dirCache.clear(),{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:this.handle.name}}async close(){this.closed=!0,this.dirCache.clear()}};async function ie(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}async function ae(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=H(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function Z(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw H(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function oe(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await ae(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new u(`ELOOP`,`too many symbolic links encountered`,i);o=await Z(e,o,i)}}async function Q(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await oe(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function se(e,t,n){return t(n)?n:Q(e,t,n)}function $(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function ce(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function le(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var ue=class t{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new N;static writeChains=new Map;onRepairProgress;constructor(e,n,r,i,a){if(this.dbName=e,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?t.initOpfsBackend(this,i,n===!0):t.initMemoryBackend(this,e,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${e}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(n,r,i){let a=r??await t.acquireOpfsHandle(n.dbName,i);await t.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2])),e(()=>import(`./dist-DHO9E-gl.js`),__vite__mapDeps([3,0,1,2]))]);await t.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=t.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}t.opfsBackends.delete(n.dbName),l=void 0}if(!l){let r=()=>o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:i,repairOpfsMetadataSidecar:u}=await e(async()=>{let{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}=await import(`./sidecar-repair-431vRT2V.js`).then(e=>e.n);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},__vite__mapDeps([4,1]));try{let e=await n.withWriteLock(()=>u(a,n.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let d=await i(r,()=>n.withWriteLock(()=>u(a,n.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{o.mount(c,d)}catch{}l={backendFs:d,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},t.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]));await t.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=t.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}t.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},t.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(e){return t.rootMountReady===null&&(t.rootMountReady=(async()=>{await e.configureSingle({backend:e.InMemory,label:`__vfs_root__`})})()),t.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new u(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(e){return new t(e)}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=e?.backend??$(),a=new t(n,r,i,void 0,e?.onRepairProgress);return await a._ready,r&&await g().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,n=this.opfsHandle;if(!e||!n)return;let r=e.index.toJSON(),i=t.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=v(e,r,i))}let o=JSON.stringify(_(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=J(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=y(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(e,r=`path`){if(this.backend!==`opfs`)return;let a=t.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(e);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await y(n)(a),s=G(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=K(o,s),d=K(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new u(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?t.opfsBackends:t.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push(a===`symlink`?{name:i,type:a}:{name:i,type:a,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new u(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new u(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new u(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof u)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??M(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=le(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await p(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await m(t)}catch{}}async reconstructBackendFromDescriptor(t,n){switch(t.kind){case`local`:{let e=await h(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return X.fromHandle(e,{mountId:t.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await e(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-BH8uwRZG.js`);return{HostFsMountBackend:e}},__vite__mapDeps([5,6,7,8,9]));return new r({targetPath:n,hostPath:t.hostPath,mountId:t.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await e(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-Ch4xd9rB.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([10,11,12,13,8,14,1,9])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i(t.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-Ch4xd9rB.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([10,11,12,13,8,14,1,9])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-Ch4xd9rB.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([10,11,12,13,8,14,1,9])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}getMountBackend(e){let t=i(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new u(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new u(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new u(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,M(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){B(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw H(e,n)}}async readFileRange(e,t,n){let r=i(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new u(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let a=this.findMount(r),o=a?.backend.readFileRange;if(a&&o){if(a.relParts.length===0)throw new u(`EISDIR`,`is a directory`,r);try{return await o.call(a.backend,a.relParts.join(`/`),t,n)}catch(e){B(e,r)}}let s=await this.readFile(r,{encoding:`binary`});return new Uint8Array(s.subarray(t,Math.min(n,s.byteLength)))}async getNativeFile(e){let t=i(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r=this.opfsHandle;if(!r)return null;try{return await ie(r,await this.resolveSymlinks(t))}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new u(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){B(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let c=!1;try{await this.lfs.stat(s),c=!0}catch{}let{dir:l}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),l!==`/`&&await this.mkdirRecursiveUnlocked(l);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(l!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(l);try{await this.lfs.writeFile(s,t)}catch(e){throw H(e,a)}}else throw H(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw H(e,a)}}),this.watcher?.notify([{type:c?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e,t){let n=i(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){B(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,ce(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw H(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(e){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=t.writeChains.get(n)??Promise.resolve();t.writeChains.set(n,i),await a;try{let t=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof t?.request!=`function`?await e():await t.request(`slicc-vfs:${n}`,()=>e())}finally{r(),t.writeChains.get(n)===i&&t.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw H(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new u(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof u&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){B(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw H(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){B(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw H(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.ctime??t.mtime,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){B(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw H(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){B(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw H(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*s({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new u(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new u(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw H(e,r)}}else throw H(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw H(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw H(e,t)}}async realpath(e){return Q(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return se(this.lfs,e=>this.findMount(e)!==null,e)}};export{u as FsError,S as FsWatcher,N as MountIndex,z as RestrictedFS,ue as VirtualFS,o as joinPath,i as normalizePath,r as pathSegments,$ as resolveVfsBackendFromEnv,n as splitPath,l as statsFromDirEntry,X as t};
@@ -1 +1 @@
1
- import{c as e,g as t,n}from"./account-store-naVgJKHe.js";import"./proxied-fetch-DUC7X0GS.js";import{i as r}from"./api-endpoint-Lx_FU5cP.js";import{n as i}from"./tray-storage-keys-DbThbnIh.js";import{t as a}from"./tray-runtime-config-C3Ti4Pik.js";import{t as o}from"./global-db-DJXlpNui.js";import{r as s,t as c}from"./silent-renew-backoff-DIMz5UqB.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-Bconf2Pz.js";import"./provider-settings-C6uIHjd4.js";var d={clientId:``,scopes:`repo,read:user,user:email`};function f(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}function p(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function m(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return p(t)}async function h(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function g(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function _(e){let t=`${f()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}const v=Object.assign({"/packages/webapp/providers/github-config.json":d})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let y=null,b=null;function x(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function S(){if(y)return y;if(C){try{let e=await fetch(`${f()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}catch{}return v.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,t.trayWorkerBaseUrl&&(b=t.trayWorkerBaseUrl),y;if(t.trayWorkerBaseUrl){b=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}}}catch{}return v.clientId}const C=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function w(){return n().find(e=>e.providerId===`github`)}function T(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function E(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function D(e,t){return`${e}+${t}@users.noreply.github.com`}async function O(e){try{let{VirtualFS:t}=await import(`./fs-CDaCMxrL.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function k(){try{let{VirtualFS:e}=await import(`./fs-CDaCMxrL.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function A(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-CDaCMxrL.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-Bdgu8kD2.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=D(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const j=c();async function M(){try{let n=w();if(!n?.refreshToken)return null;let r=await g({provider:`github`,refreshToken:n.refreshToken});await t({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:n.userName,userAvatar:n.userAvatar,scopes:r.scope??n.scopes});let i=e(`github`)?.maskedValue;return i?await O(i):await k(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function N(){let e=w()?.accessToken;if(!e)return{status:`unknown`,detail:`no stored token`};try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`},signal:AbortSignal.timeout(1e4)});if(t.ok){let e=await t.json().catch(()=>({}));return{status:`accepted`,userName:e.name||e.login}}return P(t)}catch(e){return{status:`unknown`,detail:e instanceof Error?e.message:String(e)}}}function P(e){let t=`HTTP ${e.status}${e.statusText?` ${e.statusText}`:``}`;return e.status===401?{status:`rejected`,detail:t}:e.status===403&&F(e)?{status:`unknown`,detail:`${t} (rate limited)`}:{status:`unknown`,detail:t}}function F(e){return e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.has(`retry-after`)}async function I(){let t=e(`github`)?.maskedValue;t&&await O(t)}async function L(){let e=w();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return await I(),e.accessToken;let t=await j.run(()=>M());if(t)return t;let n=w();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return await I(),n.accessToken;throw Error(`GitHub session expired — please log in again`)}const R={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,i,a)=>{let o=await S();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??v.scopes,c=C?null:await l(),d=!C&&await u(),p=crypto.randomUUID(),m=C?chrome.runtime.id:``,{redirectUri:g,state:_}=x({isExtension:C,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:f(),runtimeWorkerBaseUrl:b,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:r(),delegated:d,extensionId:m,nonce:p}),y=btoa(JSON.stringify(_)),w=p,D=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});y&&D.set(`state`,y);let j=await n(`https://github.com/login/oauth/authorize?${D}`);if(!j)return;if(w)try{if(new URL(j).searchParams.get(`nonce`)!==w){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=T(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await h({provider:`github`,code:M,redirectUri:g}),P=await E(N.access_token);await t({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=e(`github`)?.maskedValue;F?await O(F):await k(),await A(P),i()},onSilentRenew:M,onValidateToken:N,getValidAccessToken:L,onOAuthLogout:async()=>{let e=w();e?.accessToken&&await _({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await k(),await t({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{D as buildNoreplyEmail,R as config,T as extractCodeFromUrl,L as getValidAccessToken,x as resolveGithubOAuthRedirect,A as syncGitIdentityFromGitHub};
1
+ import{c as e,g as t,n}from"./account-store-CnTVyV3B.js";import"./proxied-fetch-DUC7X0GS.js";import{i as r}from"./api-endpoint-Lx_FU5cP.js";import{n as i}from"./tray-storage-keys-DbThbnIh.js";import{t as a}from"./tray-runtime-config-C3Ti4Pik.js";import{t as o}from"./global-db-DJXlpNui.js";import{r as s,t as c}from"./silent-renew-backoff-DIMz5UqB.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-Bconf2Pz.js";import"./provider-settings-s-43s4y0.js";var d={clientId:``,scopes:`repo,read:user,user:email`};function f(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}function p(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function m(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return p(t)}async function h(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function g(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function _(e){let t=`${f()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}const v=Object.assign({"/packages/webapp/providers/github-config.json":d})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let y=null,b=null;function x(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function S(){if(y)return y;if(C){try{let e=await fetch(`${f()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}catch{}return v.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,t.trayWorkerBaseUrl&&(b=t.trayWorkerBaseUrl),y;if(t.trayWorkerBaseUrl){b=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}}}catch{}return v.clientId}const C=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function w(){return n().find(e=>e.providerId===`github`)}function T(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function E(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function D(e,t){return`${e}+${t}@users.noreply.github.com`}async function O(e){try{let{VirtualFS:t}=await import(`./fs-B5l0OgHF.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function k(){try{let{VirtualFS:e}=await import(`./fs-B5l0OgHF.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function A(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-B5l0OgHF.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-Bdgu8kD2.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=D(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const j=c();async function M(){try{let n=w();if(!n?.refreshToken)return null;let r=await g({provider:`github`,refreshToken:n.refreshToken});await t({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:n.userName,userAvatar:n.userAvatar,scopes:r.scope??n.scopes});let i=e(`github`)?.maskedValue;return i?await O(i):await k(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function N(){let e=w()?.accessToken;if(!e)return{status:`unknown`,detail:`no stored token`};try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`},signal:AbortSignal.timeout(1e4)});if(t.ok){let e=await t.json().catch(()=>({}));return{status:`accepted`,userName:e.name||e.login}}return P(t)}catch(e){return{status:`unknown`,detail:e instanceof Error?e.message:String(e)}}}function P(e){let t=`HTTP ${e.status}${e.statusText?` ${e.statusText}`:``}`;return e.status===401?{status:`rejected`,detail:t}:e.status===403&&F(e)?{status:`unknown`,detail:`${t} (rate limited)`}:{status:`unknown`,detail:t}}function F(e){return e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.has(`retry-after`)}async function I(){let t=e(`github`)?.maskedValue;t&&await O(t)}async function L(){let e=w();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return await I(),e.accessToken;let t=await j.run(()=>M());if(t)return t;let n=w();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return await I(),n.accessToken;throw Error(`GitHub session expired — please log in again`)}const R={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,i,a)=>{let o=await S();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??v.scopes,c=C?null:await l(),d=!C&&await u(),p=crypto.randomUUID(),m=C?chrome.runtime.id:``,{redirectUri:g,state:_}=x({isExtension:C,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:f(),runtimeWorkerBaseUrl:b,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:r(),delegated:d,extensionId:m,nonce:p}),y=btoa(JSON.stringify(_)),w=p,D=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});y&&D.set(`state`,y);let j=await n(`https://github.com/login/oauth/authorize?${D}`);if(!j)return;if(w)try{if(new URL(j).searchParams.get(`nonce`)!==w){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=T(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await h({provider:`github`,code:M,redirectUri:g}),P=await E(N.access_token);await t({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=e(`github`)?.maskedValue;F?await O(F):await k(),await A(P),i()},onSilentRenew:M,onValidateToken:N,getValidAccessToken:L,onOAuthLogout:async()=>{let e=w();e?.accessToken&&await _({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await k(),await t({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{D as buildNoreplyEmail,R as config,T as extractCodeFromUrl,L as getValidAccessToken,x as resolveGithubOAuthRedirect,A as syncGitIdentityFromGitHub};
@@ -1 +1 @@
1
- import{g as e,n as t}from"./account-store-naVgJKHe.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{a as r,n as i,r as a}from"./compat-uEPf6-XW.js";import{a as o,c as s,i as c,r as l,s as u,t as d}from"./legacy-api-aliases-jKEvBgOL.js";import"./provider-settings-C6uIHjd4.js";const f=`github-copilot`,p=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),m={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},h={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`};function g(){return t().find(e=>e.providerId===f)}async function _(){let e=await fetch(`https://github.com/login/device/code`,{method:`POST`,headers:h,body:new URLSearchParams({client_id:p,scope:`read:user`})});if(!e.ok)throw Error(`GitHub device-code request failed: ${e.status} ${e.statusText} — ${await e.text().catch(()=>``)}`);let t=await e.json();if(typeof t.device_code!=`string`||typeof t.user_code!=`string`||typeof t.verification_uri!=`string`||typeof t.expires_in!=`number`||typeof t.interval!=`number`)throw Error(`GitHub device-code response had an unexpected shape`);return t}async function v(e,t){let n=Date.now()+e.expires_in*1e3,r=Math.max(1e3,Math.floor(e.interval*1e3)),i=1.2;for(;Date.now()<n;){if(t.aborted)throw Error(`Copilot login cancelled`);await y(Math.ceil(r*i),t);let n=await fetch(`https://github.com/login/oauth/access_token`,{method:`POST`,headers:h,body:new URLSearchParams({client_id:p,device_code:e.device_code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`})});if(!n.ok)throw Error(`GitHub token poll failed: ${n.status} ${n.statusText} — ${await n.text().catch(()=>``)}`);let a=await n.json();if(typeof a.access_token==`string`&&a.access_token.length>0)return a.access_token;if(a.error!==`authorization_pending`){if(a.error===`slow_down`){r=typeof a.interval==`number`?a.interval*1e3:r+5e3,i=1.4;continue}if(a.error){let e=a.error_description?`: ${a.error_description}`:``;throw Error(`Device flow failed (${a.error})${e}`)}}}throw Error(`Copilot device flow timed out (device code expired)`)}function y(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`Copilot login cancelled`));return}let i=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Copilot login cancelled`))},{once:!0})})}function b(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function x(e){let t=await fetch(`https://api.github.com/copilot_internal/v2/token`,{headers:{...m,Authorization:`Bearer ${e}`}});if(!t.ok){let e=await t.text().catch(()=>``);throw Error(`Copilot token exchange failed: ${t.status} ${t.statusText} — ${e.slice(0,300)}`)}let n=await t.json();if(typeof n.token!=`string`||typeof n.expires_at!=`number`)throw Error(`Copilot token exchange returned an unexpected payload`);if(n.chat_enabled===!1)throw Error(`GitHub Copilot Chat is disabled for this account (no chat features granted)`);return{copilotToken:n.token,expiresAtMs:n.expires_at*1e3-3e5,apiBaseUrl:b(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}const S=`github-copilot.models.v1`;function C(e){let t=e.supported_endpoints??[],n=(e.vendor??``).toLowerCase(),r=e.id;return n===`anthropic`&&t.includes(`/v1/messages`)?`anthropic-messages`:n===`openai`&&(/^gpt-5/i.test(r)||/codex/i.test(r)||/^o\d/i.test(r))?`openai-responses`:`openai-completions`}function w(e){if(!e||typeof e!=`object`)return[];let t=e.data;if(!Array.isArray(t))return[];let n=[];for(let e of t)e.capabilities?.type&&e.capabilities.type!==`chat`||e.model_picker_enabled!==!1&&e.id&&n.push({id:e.id,name:e.name??e.id,vendor:e.vendor??``,api:C(e),contextWindow:e.capabilities?.limits?.max_context_window_tokens??e.capabilities?.limits?.max_prompt_tokens??128e3,maxTokens:e.capabilities?.limits?.max_output_tokens??8192,supportsTools:e.capabilities?.supports?.tool_calls===!0,supportsStreaming:e.capabilities?.supports?.streaming!==!1,supportsVision:e.capabilities?.supports?.vision===!0,supportsReasoning:e.capabilities?.supports?.adaptive_thinking===!0||Array.isArray(e.capabilities?.supports?.reasoning_effort),policyState:e.policy?.state??`enabled`});return n}async function T(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...m,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return w(await t.json())}function E(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(S);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function D(e){if(!(typeof localStorage>`u`))try{localStorage.setItem(S,JSON.stringify(e))}catch{}}function O(e){return E().find(t=>t.id===e)??null}async function k(e){let t;try{t=await T(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}D(t),await Promise.all(t.filter(e=>e.policyState===`disabled`).map(async t=>{let n=`${e.apiBaseUrl}/models/${encodeURIComponent(t.id)}/policy`;try{let r=await fetch(n,{method:`POST`,headers:{...m,"Content-Type":`application/json`,Authorization:`Bearer ${e.copilotToken}`,"openai-intent":`chat-policy`,"x-interaction-type":`chat-policy`},body:JSON.stringify({state:`enabled`})});r.ok?t.policyState=`enabled`:r.status!==404&&r.status!==400&&console.warn(`[github-copilot] enable policy for ${t.id} returned ${r.status} ${r.statusText}`)}catch(e){console.warn(`[github-copilot] enable policy for ${t.id} failed:`,e instanceof Error?e.message:String(e))}})),D(t)}async function A(t,n){await e({providerId:f,accessToken:t.copilotToken,refreshToken:t.githubAccessToken,tokenExpiresAt:t.expiresAtMs,baseUrl:t.apiBaseUrl,userName:n})}async function j(){let e=g();if(!e?.accessToken||!e.refreshToken)throw Error(`Not logged in to GitHub Copilot — click "Login" in the provider settings`);let t=e.tokenExpiresAt??0;if(Date.now()<t-6e4)return e.accessToken;let n=await x(e.refreshToken);return await A(n,e.userName),n.copilotToken}const M=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function N(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!M.some(e=>t.some(t=>t.includes(e)))}function P(){if(!g()?.accessToken)return[];let e=E();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>N(e)).map(e=>({id:e.id,name:e.name,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.supportsReasoning,input:e.supportsVision?[`text`,`image`]:[`text`]}));let t;try{t=a(`github-copilot`)}catch{return[]}return t.filter(e=>N({id:e.id,name:e.name})).map(e=>({id:e.id,name:e.name??e.id,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.reasoning,input:e.input}))}function F(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:f,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const I={"User-Agent":`GitHubCopilotChat/0.35.0`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`};function L(e){let t=g(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=O(e);if(r)return{api:r.api,baseUrl:n,headers:{...I}};try{let n=i(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...I}}}catch{return null}}function R(e,t){let n=E(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},D(n))}function z(e,t){return`GitHub Copilot rejected "${e}" with model_not_supported. This usually means the model isn't included in your Copilot plan (Opus and other premium models require Copilot Pro / Pro+ / Business / Enterprise). Try Claude Sonnet 4.6 or another model that appears in the picker after a fresh login. Original error: ${t}`}function B(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.type!==`error`)return null;if(t.error&&typeof t.error==`object`){let e=t.error.errorMessage;if(typeof e==`string`)return e}return typeof t.errorMessage==`string`?t.errorMessage:null}function V(e,t){return e===`anthropic-messages`?t?o:d:e===`openai-responses`?t?s:c:t?u:l}function H(e,t,n){let r=B(n);if(r&&/model_not_supported/i.test(r)){R(t.id,`model_not_supported`);let n=z(t.id,r);return console.error(`[github-copilot] Plan-gated model rejection:`,n),e.push(F(t,Error(n))),e.end(),!0}return e.push(n),!1}function U(e,t,n){let r=n instanceof Error?n.message:String(n),i=n;/model_not_supported/i.test(r)&&(R(t.id,`model_not_supported`),i=Error(z(t.id,r))),console.error(`[github-copilot] Stream error:`,i instanceof Error?i.message:String(i)),e.push(F(t,i)),e.end()}async function W(e,t,n,r,i){try{let a=await j(),o=L(t.id);if(!o)throw Error(`GitHub Copilot does not recognize "${t.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let s={...t,api:o.api,baseUrl:o.baseUrl,headers:o.headers,provider:`github-copilot`},c={...r,apiKey:a},l=V(o.api,i)(s,n,c);for await(let n of l)if(H(e,t,n))return;e.end()}catch(n){U(e,t,n)}}function G(e){return(t,r,i={})=>{let a=n();return W(a,t,r,i,e),a}}const K=G(!1),q=G(!0),J=({userCode:e,verificationUrl:t})=>typeof document>`u`?(console.info(`[github-copilot] Device verification code: ${e} — open ${t} in a browser to authorize.`),Promise.resolve(`continue`)):new Promise(t=>{let n=document.createElement(`div`);n.setAttribute(`data-slicc-overlay`,`github-copilot-device`),n.style.cssText=[`position:fixed`,`top:24px`,`right:24px`,`z-index:2147483647`,`background:#0d1117`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:10px`,`padding:16px 18px`,`box-shadow:0 8px 32px rgba(0,0,0,0.45)`,`font:13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,`min-width:260px`,`max-width:340px`].join(`;`);let r=document.createElement(`div`);r.textContent=`GitHub Copilot — verification code`,r.style.cssText=`font-weight:600;margin-bottom:8px;color:#7ee787`;let i=document.createElement(`div`);i.textContent=e,i.style.cssText=[`font:600 22px ui-monospace, SFMono-Regular, Menlo, monospace`,`letter-spacing:2px`,`background:#161b22`,`border:1px solid #30363d`,`border-radius:6px`,`padding:10px 12px`,`text-align:center`,`margin-bottom:10px`,`user-select:all`,`cursor:text`].join(`;`);let a=document.createElement(`div`);a.style.cssText=`color:#8b949e;font-size:12px;line-height:1.5`,a.textContent=`Copy the code, then click Continue to open the GitHub authorization page in a new tab.`;let o=document.createElement(`div`);o.style.cssText=`display:flex;gap:8px;margin-top:12px;justify-content:flex-end`;let s=document.createElement(`button`);s.type=`button`,s.textContent=`Cancel`,s.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let c=document.createElement(`button`);c.type=`button`,c.textContent=`Copy & Continue`,c.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=()=>{try{n.remove()}catch{}};s.addEventListener(`click`,()=>{l(),t(`cancel`)}),c.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:t}=await import(`./clipboard-CknViQHB.js`).then(e=>e.t);await t(e)}catch{}l(),t(`continue`)})()}),o.appendChild(s),o.appendChild(c),n.appendChild(r),n.appendChild(i),n.appendChild(a),n.appendChild(o),document.body.appendChild(n)}),Y={id:f,name:`GitHub Copilot`,description:`Use your GitHub Copilot subscription to access Claude, GPT-5, Codex, Gemini, and Grok models. Sign in with the GitHub device-code flow.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`claude-sonnet-4.6`,oauthTokenDomains:[`*.githubcopilot.com`,`api.individual.githubcopilot.com`,`api.business.githubcopilot.com`,`api.enterprise.githubcopilot.com`],getModelIds:P,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await _(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??J)({userCode:r.user_code,verificationUrl:i.toString(),expiresInSeconds:r.expires_in})===`cancel`)throw Error(`GitHub Copilot login cancelled`);let a=new AbortController,o=e({authorizeUrl:i.toString(),redirectUriPattern:`https://github.com/login/device/success*`,onCapture:`close`,timeoutMs:r.expires_in*1e3}).catch(e=>(console.warn(`[github-copilot] Launcher failed:`,e instanceof Error?e.message:String(e)),null)),s;try{s=await v(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await x(s),l;try{let e=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${s}`,Accept:`application/json`}});if(e.ok){let t=await e.json();l=t.name||t.login}}catch{}await A(c,l),await k(c),t()},onOAuthLogout:async()=>{await e({providerId:f,accessToken:``})},onSilentRenew:async()=>{let e=g();if(!e?.refreshToken)return null;try{let t=await x(e.refreshToken);return await A(t,e.userName),await k(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function X(){r({api:`github-copilot-anthropic`,stream:K,streamSimple:q}),r({api:`github-copilot-openai`,stream:K,streamSimple:q})}export{Y as config,N as isCopilotConeCompatible,X as register};
1
+ import{g as e,n as t}from"./account-store-CnTVyV3B.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{a as r,n as i,r as a}from"./compat-uEPf6-XW.js";import{a as o,c as s,i as c,r as l,s as u,t as d}from"./legacy-api-aliases-jKEvBgOL.js";import"./provider-settings-s-43s4y0.js";const f=`github-copilot`,p=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),m={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},h={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`};function g(){return t().find(e=>e.providerId===f)}async function _(){let e=await fetch(`https://github.com/login/device/code`,{method:`POST`,headers:h,body:new URLSearchParams({client_id:p,scope:`read:user`})});if(!e.ok)throw Error(`GitHub device-code request failed: ${e.status} ${e.statusText} — ${await e.text().catch(()=>``)}`);let t=await e.json();if(typeof t.device_code!=`string`||typeof t.user_code!=`string`||typeof t.verification_uri!=`string`||typeof t.expires_in!=`number`||typeof t.interval!=`number`)throw Error(`GitHub device-code response had an unexpected shape`);return t}async function v(e,t){let n=Date.now()+e.expires_in*1e3,r=Math.max(1e3,Math.floor(e.interval*1e3)),i=1.2;for(;Date.now()<n;){if(t.aborted)throw Error(`Copilot login cancelled`);await y(Math.ceil(r*i),t);let n=await fetch(`https://github.com/login/oauth/access_token`,{method:`POST`,headers:h,body:new URLSearchParams({client_id:p,device_code:e.device_code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`})});if(!n.ok)throw Error(`GitHub token poll failed: ${n.status} ${n.statusText} — ${await n.text().catch(()=>``)}`);let a=await n.json();if(typeof a.access_token==`string`&&a.access_token.length>0)return a.access_token;if(a.error!==`authorization_pending`){if(a.error===`slow_down`){r=typeof a.interval==`number`?a.interval*1e3:r+5e3,i=1.4;continue}if(a.error){let e=a.error_description?`: ${a.error_description}`:``;throw Error(`Device flow failed (${a.error})${e}`)}}}throw Error(`Copilot device flow timed out (device code expired)`)}function y(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`Copilot login cancelled`));return}let i=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Copilot login cancelled`))},{once:!0})})}function b(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function x(e){let t=await fetch(`https://api.github.com/copilot_internal/v2/token`,{headers:{...m,Authorization:`Bearer ${e}`}});if(!t.ok){let e=await t.text().catch(()=>``);throw Error(`Copilot token exchange failed: ${t.status} ${t.statusText} — ${e.slice(0,300)}`)}let n=await t.json();if(typeof n.token!=`string`||typeof n.expires_at!=`number`)throw Error(`Copilot token exchange returned an unexpected payload`);if(n.chat_enabled===!1)throw Error(`GitHub Copilot Chat is disabled for this account (no chat features granted)`);return{copilotToken:n.token,expiresAtMs:n.expires_at*1e3-3e5,apiBaseUrl:b(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}const S=`github-copilot.models.v1`;function C(e){let t=e.supported_endpoints??[],n=(e.vendor??``).toLowerCase(),r=e.id;return n===`anthropic`&&t.includes(`/v1/messages`)?`anthropic-messages`:n===`openai`&&(/^gpt-5/i.test(r)||/codex/i.test(r)||/^o\d/i.test(r))?`openai-responses`:`openai-completions`}function w(e){if(!e||typeof e!=`object`)return[];let t=e.data;if(!Array.isArray(t))return[];let n=[];for(let e of t)e.capabilities?.type&&e.capabilities.type!==`chat`||e.model_picker_enabled!==!1&&e.id&&n.push({id:e.id,name:e.name??e.id,vendor:e.vendor??``,api:C(e),contextWindow:e.capabilities?.limits?.max_context_window_tokens??e.capabilities?.limits?.max_prompt_tokens??128e3,maxTokens:e.capabilities?.limits?.max_output_tokens??8192,supportsTools:e.capabilities?.supports?.tool_calls===!0,supportsStreaming:e.capabilities?.supports?.streaming!==!1,supportsVision:e.capabilities?.supports?.vision===!0,supportsReasoning:e.capabilities?.supports?.adaptive_thinking===!0||Array.isArray(e.capabilities?.supports?.reasoning_effort),policyState:e.policy?.state??`enabled`});return n}async function T(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...m,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return w(await t.json())}function E(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(S);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function D(e){if(!(typeof localStorage>`u`))try{localStorage.setItem(S,JSON.stringify(e))}catch{}}function O(e){return E().find(t=>t.id===e)??null}async function k(e){let t;try{t=await T(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}D(t),await Promise.all(t.filter(e=>e.policyState===`disabled`).map(async t=>{let n=`${e.apiBaseUrl}/models/${encodeURIComponent(t.id)}/policy`;try{let r=await fetch(n,{method:`POST`,headers:{...m,"Content-Type":`application/json`,Authorization:`Bearer ${e.copilotToken}`,"openai-intent":`chat-policy`,"x-interaction-type":`chat-policy`},body:JSON.stringify({state:`enabled`})});r.ok?t.policyState=`enabled`:r.status!==404&&r.status!==400&&console.warn(`[github-copilot] enable policy for ${t.id} returned ${r.status} ${r.statusText}`)}catch(e){console.warn(`[github-copilot] enable policy for ${t.id} failed:`,e instanceof Error?e.message:String(e))}})),D(t)}async function A(t,n){await e({providerId:f,accessToken:t.copilotToken,refreshToken:t.githubAccessToken,tokenExpiresAt:t.expiresAtMs,baseUrl:t.apiBaseUrl,userName:n})}async function j(){let e=g();if(!e?.accessToken||!e.refreshToken)throw Error(`Not logged in to GitHub Copilot — click "Login" in the provider settings`);let t=e.tokenExpiresAt??0;if(Date.now()<t-6e4)return e.accessToken;let n=await x(e.refreshToken);return await A(n,e.userName),n.copilotToken}const M=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function N(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!M.some(e=>t.some(t=>t.includes(e)))}function P(){if(!g()?.accessToken)return[];let e=E();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>N(e)).map(e=>({id:e.id,name:e.name,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.supportsReasoning,input:e.supportsVision?[`text`,`image`]:[`text`]}));let t;try{t=a(`github-copilot`)}catch{return[]}return t.filter(e=>N({id:e.id,name:e.name})).map(e=>({id:e.id,name:e.name??e.id,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.reasoning,input:e.input}))}function F(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:f,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const I={"User-Agent":`GitHubCopilotChat/0.35.0`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`};function L(e){let t=g(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=O(e);if(r)return{api:r.api,baseUrl:n,headers:{...I}};try{let n=i(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...I}}}catch{return null}}function R(e,t){let n=E(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},D(n))}function z(e,t){return`GitHub Copilot rejected "${e}" with model_not_supported. This usually means the model isn't included in your Copilot plan (Opus and other premium models require Copilot Pro / Pro+ / Business / Enterprise). Try Claude Sonnet 4.6 or another model that appears in the picker after a fresh login. Original error: ${t}`}function B(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.type!==`error`)return null;if(t.error&&typeof t.error==`object`){let e=t.error.errorMessage;if(typeof e==`string`)return e}return typeof t.errorMessage==`string`?t.errorMessage:null}function V(e,t){return e===`anthropic-messages`?t?o:d:e===`openai-responses`?t?s:c:t?u:l}function H(e,t,n){let r=B(n);if(r&&/model_not_supported/i.test(r)){R(t.id,`model_not_supported`);let n=z(t.id,r);return console.error(`[github-copilot] Plan-gated model rejection:`,n),e.push(F(t,Error(n))),e.end(),!0}return e.push(n),!1}function U(e,t,n){let r=n instanceof Error?n.message:String(n),i=n;/model_not_supported/i.test(r)&&(R(t.id,`model_not_supported`),i=Error(z(t.id,r))),console.error(`[github-copilot] Stream error:`,i instanceof Error?i.message:String(i)),e.push(F(t,i)),e.end()}async function W(e,t,n,r,i){try{let a=await j(),o=L(t.id);if(!o)throw Error(`GitHub Copilot does not recognize "${t.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let s={...t,api:o.api,baseUrl:o.baseUrl,headers:o.headers,provider:`github-copilot`},c={...r,apiKey:a},l=V(o.api,i)(s,n,c);for await(let n of l)if(H(e,t,n))return;e.end()}catch(n){U(e,t,n)}}function G(e){return(t,r,i={})=>{let a=n();return W(a,t,r,i,e),a}}const K=G(!1),q=G(!0),J=({userCode:e,verificationUrl:t})=>typeof document>`u`?(console.info(`[github-copilot] Device verification code: ${e} — open ${t} in a browser to authorize.`),Promise.resolve(`continue`)):new Promise(t=>{let n=document.createElement(`div`);n.setAttribute(`data-slicc-overlay`,`github-copilot-device`),n.style.cssText=[`position:fixed`,`top:24px`,`right:24px`,`z-index:2147483647`,`background:#0d1117`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:10px`,`padding:16px 18px`,`box-shadow:0 8px 32px rgba(0,0,0,0.45)`,`font:13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,`min-width:260px`,`max-width:340px`].join(`;`);let r=document.createElement(`div`);r.textContent=`GitHub Copilot — verification code`,r.style.cssText=`font-weight:600;margin-bottom:8px;color:#7ee787`;let i=document.createElement(`div`);i.textContent=e,i.style.cssText=[`font:600 22px ui-monospace, SFMono-Regular, Menlo, monospace`,`letter-spacing:2px`,`background:#161b22`,`border:1px solid #30363d`,`border-radius:6px`,`padding:10px 12px`,`text-align:center`,`margin-bottom:10px`,`user-select:all`,`cursor:text`].join(`;`);let a=document.createElement(`div`);a.style.cssText=`color:#8b949e;font-size:12px;line-height:1.5`,a.textContent=`Copy the code, then click Continue to open the GitHub authorization page in a new tab.`;let o=document.createElement(`div`);o.style.cssText=`display:flex;gap:8px;margin-top:12px;justify-content:flex-end`;let s=document.createElement(`button`);s.type=`button`,s.textContent=`Cancel`,s.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let c=document.createElement(`button`);c.type=`button`,c.textContent=`Copy & Continue`,c.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=()=>{try{n.remove()}catch{}};s.addEventListener(`click`,()=>{l(),t(`cancel`)}),c.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:t}=await import(`./clipboard-CknViQHB.js`).then(e=>e.t);await t(e)}catch{}l(),t(`continue`)})()}),o.appendChild(s),o.appendChild(c),n.appendChild(r),n.appendChild(i),n.appendChild(a),n.appendChild(o),document.body.appendChild(n)}),Y={id:f,name:`GitHub Copilot`,description:`Use your GitHub Copilot subscription to access Claude, GPT-5, Codex, Gemini, and Grok models. Sign in with the GitHub device-code flow.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`claude-sonnet-4.6`,oauthTokenDomains:[`*.githubcopilot.com`,`api.individual.githubcopilot.com`,`api.business.githubcopilot.com`,`api.enterprise.githubcopilot.com`],getModelIds:P,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await _(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??J)({userCode:r.user_code,verificationUrl:i.toString(),expiresInSeconds:r.expires_in})===`cancel`)throw Error(`GitHub Copilot login cancelled`);let a=new AbortController,o=e({authorizeUrl:i.toString(),redirectUriPattern:`https://github.com/login/device/success*`,onCapture:`close`,timeoutMs:r.expires_in*1e3}).catch(e=>(console.warn(`[github-copilot] Launcher failed:`,e instanceof Error?e.message:String(e)),null)),s;try{s=await v(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await x(s),l;try{let e=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${s}`,Accept:`application/json`}});if(e.ok){let t=await e.json();l=t.name||t.login}}catch{}await A(c,l),await k(c),t()},onOAuthLogout:async()=>{await e({providerId:f,accessToken:``})},onSilentRenew:async()=>{let e=g();if(!e?.refreshToken)return null;try{let t=await x(e.refreshToken);return await A(t,e.userName),await k(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function X(){r({api:`github-copilot-anthropic`,stream:K,streamSimple:q}),r({api:`github-copilot-openai`,stream:K,streamSimple:q})}export{Y as config,N as isCopilotConeCompatible,X as register};