@legit-sdk/core 0.4.5 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,13 +1,18 @@
1
1
  // legit-sdk server bundle (Node.js)
2
2
 
3
- var _e=Object.defineProperty;var Et=(m,s,e)=>s in m?_e(m,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):m[s]=e;var n=(m,s)=>_e(m,"name",{value:s,configurable:!0});var y=(m,s,e)=>Et(m,typeof s!="symbol"?s+"":s,e);var Fe=class Fe{constructor(s,e){y(this,"entries",[]);y(this,"currentIndex",0);y(this,"closed",!1);y(this,"compositFs");y(this,"dirPath");y(this,"initialized",!1);this.compositFs=s,this.dirPath=e}async initialize(){if(this.initialized)return;let s=new Set;for(let e of[...this.compositFs.filterLayers].reverse())if(e.readDirFiltering)s=new Set(await e.readDirFiltering(this.dirPath,Array.from(s)));else{let r=await e.readdir(this.dirPath);for(let t of r)s.add(t)}this.initialized=!0}async*[Symbol.asyncIterator](){for(await this.initialize();this.currentIndex<this.entries.length&&!this.closed;){let s=this.entries[this.currentIndex++];try{let e=await this.compositFs.stat(s.path);yield{name:s.name,isFile:n(()=>e.isFile(),"isFile"),isDirectory:n(()=>e.isDirectory(),"isDirectory"),isBlockDevice:n(()=>e.isBlockDevice(),"isBlockDevice"),isCharacterDevice:n(()=>e.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:n(()=>e.isSymbolicLink(),"isSymbolicLink"),isFIFO:n(()=>e.isFIFO(),"isFIFO"),isSocket:n(()=>e.isSocket(),"isSocket")}}catch(e){console.debug(`Failed to stat ${s.path}:`,e)}}}async read(){if(this.closed)throw new Error("Directory handle is closed");if(await this.initialize(),this.currentIndex>=this.entries.length)return null;let s=this.entries[this.currentIndex++];try{let e=await this.compositFs.stat(s.path);return{name:s.name,isFile:n(()=>e.isFile(),"isFile"),isDirectory:n(()=>e.isDirectory(),"isDirectory"),isBlockDevice:n(()=>e.isBlockDevice(),"isBlockDevice"),isCharacterDevice:n(()=>e.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:n(()=>e.isSymbolicLink(),"isSymbolicLink"),isFIFO:n(()=>e.isFIFO(),"isFIFO"),isSocket:n(()=>e.isSocket(),"isSocket")}}catch{return this.read()}}async close(){this.closed=!0,this.entries=[]}get path(){return this.dirPath}};n(Fe,"CompositeFsDir");var W=Fe;function At(m){let s=m.split("/").filter(Boolean),e=[],r=[],t=!1,i;for(let o of s)if(o.startsWith("[[")&&o.endsWith("]]")){let a=o.slice(2,-2).replace(/^\.\.\./,"");if(e.push(a),o.startsWith("[[..."))t=!0,r.push("(/.*)*"),i=a;else throw new Error("Optional single-segment parameters [[param]] are not supported. Use [[...param]] for catch-all or [param] for required single segment.")}else if(o.startsWith("[")&&o.endsWith("]")){if(o.startsWith("[..."))throw new Error("Required catch-all parameters [...param] are not supported. Use [[...param]] instead.");{let a=o.slice(1,-1);e.push(a),r.push("/([^\\/]+)")}}else o==="."?t=!0:r.push("/"+o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return{regexStr:r.join("")+"$",paramNames:e,folderRoute:t,pathParameter:i}}n(At,"compilePattern");function ge(m){if(m===".")return 1;let s=m.split("/").filter(Boolean),e=Math.pow(2,s.length);for(let r=0;r<s.length;r++){let t=s[r],i;t.startsWith("[[...")?i=10:t.startsWith("[[")?i=50:t.startsWith("[")?i=100:i=1e3+t.length;let o=Math.pow(.9,r);e+=i*o}return e}n(ge,"calculatePriority");function Lt(m){if(typeof m.name!="string")return"folder";let s=m;return s.fsType==="folder"?"folder":s.fsType==="file"?"file":"readdir"in s&&typeof s.readdir=="function"?"folder":"file"}n(Lt,"getNodeType");function Ht(m){let s=[];function e(r,t){if(typeof r.name=="string"){s.push({pattern:t||".",handler:r,priority:ge(t||"."),staticBaseChildren:[]});return}let i=r,o=[],a=Object.keys(i).filter(l=>l.startsWith("[[")||l===".");if(a.length>1)throw new Error(`Expected exactly one folder handler for ${t||"/"} expected but multuple found: ${a.join(", ")}`);if(a.length===0)throw new Error(`No folder handler for ${t||"/"} founds`);for(let[l,c]of Object.entries(i)){let d=t?`${t}/${l}`:l;if(l==="."){if(typeof c.name!="string")throw new Error(`Folder root '.' at path '${t}' must be a handler, not a folder`);if(c.fsType!=="folder"&&c.fsType!=="fs")throw new Error(`Folder root handler '.' at path '${t}' must be of type 'folder' or 'fs'`);s.push({pattern:t+"/.",handler:c,priority:ge(t),staticBaseChildren:o})}else if(l.startsWith("[["))if(l.startsWith("[[..."))if(typeof c.name=="string"){if(s.push({pattern:d,handler:c,priority:ge(d),staticBaseChildren:o}),c.fsType!=="folder"&&c.fsType!=="fs")throw new Error(`Folder root handler '.' at path '${t}' must be of type 'folder' or 'fs'`)}else e(c,d);else e(c,d);else if(l.startsWith("[")){if(l.startsWith("[..."))throw new Error(`Required catch-all '${l}' is not supported. Use '[[...${l.slice(5,-1)}]]' instead`);e(c,d)}else o.push({segment:l,type:Lt(c)}),e(c,d)}}return n(e,"walk"),e(m,""),s}n(Ht,"flattenRoutes");var ye=class ye{constructor(s,e){this.routes=s;this.rootPath=e;y(this,"compiledRoutes");let r=Ht(s);this.compiledRoutes=r.map(t=>{let{regexStr:i,paramNames:o,folderRoute:a,pathParameter:l}=At(t.pattern);return{regex:new RegExp(i),paramNames:o,staticBaseChildren:t.staticBaseChildren,handler:t.handler,priority:t.priority,pattern:t.pattern,folderRoute:a,pathParameter:l}})}match(s){let e=s;e.startsWith(this.rootPath+"/")?e=e.slice(this.rootPath.length+1):e.startsWith(this.rootPath)&&(e=e.slice(this.rootPath.length)),e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1));let r,t={},i=-1,o=this.compiledRoutes,a=[];for(let c of o){let d=e.match(c.regex);if(d)a.push(c);else continue;if(!(!d||c.priority<=i)){t={};for(let h=0;h<c.paramNames.length;h++){let u=d[h+1]||"";u.startsWith("/")&&(u=u.slice(1)),t[c.paramNames[h]]=decodeURIComponent(u)}i=c.priority,r=c}}if(!r||r.handler===void 0)return;let l=[];return r.folderRoute&&(r.pathParameter?t[r.pathParameter]===""&&(l=r.staticBaseChildren.map(c=>({segment:c.segment,type:c.type}))):l=r.staticBaseChildren.map(c=>({segment:c.segment,type:c.type}))),{handler:r.handler,matchingPattern:r.pattern,params:t,staticSiblings:l}}};n(ye,"PathRouter");var ae=ye;function B(m){return typeof m=="string"?m:Buffer.isBuffer(m)?m.toString():String(m)}n(B,"pathToString");var we=class we{constructor({name:s,rootPath:e}){y(this,"compositeFs");y(this,"context");y(this,"newContext");y(this,"fsType","fs");y(this,"rootInstanceId");y(this,"name");y(this,"rootPath");this.name=s,this.rootPath=e,this.rootInstanceId=`${s}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}attach(s){this.compositeFs=s}withContext(s){let e=Object.create(Object.getPrototypeOf(this));return Object.assign(e,this),e.context=s,e}async open(s,e,r){throw new Error(`open not implemented for: ${B(s)}`)}async access(s,e){throw new Error(`access not implemented for: ${B(s)}`)}async stat(s,e){throw new Error(`lstat not implemented for: ${B(s)}`)}async lstat(s,e){throw new Error(`lstat not implemented for: ${B(s)}`)}async opendir(s,e){throw new Error(`opendir not implemented for: ${B(s)}`)}async link(s,e){throw new Error(`link not implemented for: ${B(s)}`)}async mkdir(s,e){throw new Error(`mkdir not implemented for: ${B(s)}`)}async readdir(s,e){throw new Error(`readdir not implemented for: ${B(s)}`)}async readlink(s,...e){throw new Error(`readlink not implemented for: ${B(s)}`)}async unlink(s){throw new Error(`unlink not implemented for: ${B(s)}`)}async rename(s,e){throw new Error(`rename not implemented for: ${B(s)}`)}async rmdir(s,...e){throw new Error(`rmdir not implemented for: ${B(s)}`)}async symlink(s,e,r){throw new Error(`symlink not implemented for: ${B(e)}`)}async lookup(s){throw new Error(`lookup not implemented for: ${B(s)}`)}resolvePath(s){throw new Error(`resolvePath not implemented for fd: ${s}`)}async close(s){this.compositeFs.close(s)}async dataSync(s){throw new Error(`dataSync not implemented for: ${s.subFsFileDescriptor}`)}async read(s,e,r,t,i){throw new Error(`read not implemented for: ${s.subFsFileDescriptor}`)}async appendFile(s,e,r){throw new Error(`appendFile not implemented for: ${s.subFsFileDescriptor}`)}async fchmod(s,e){throw new Error(`fchmod not implemented for: ${s.subFsFileDescriptor}`)}async fchown(s,e,r){throw new Error(`fchown not implemented for: ${s.subFsFileDescriptor}`)}async ftruncate(s,e){throw new Error(`ftruncate not implemented for: ${s.subFsFileDescriptor}`)}async fstat(s,e){throw new Error(`fstat not implemented for: ${s.subFsFileDescriptor}`)}async futimes(s,e,r){throw new Error(`futimes not implemented for: ${s.subFsFileDescriptor}`)}async write(s,e,r,t,i){throw new Error(`write not implemented for: ${s.subFsFileDescriptor}`)}async writev(s,e,r){throw new Error(`writev not implemented for: ${s.subFsFileDescriptor}`)}async readv(s,e,r){throw new Error(`readv not implemented for: ${s.subFsFileDescriptor}`)}async readFile(s,e){throw new Error(`readFile not implemented for: ${s}`)}async writeFile(s,e,r){throw new Error(`writeFile not implemented for: ${s}`)}};n(we,"BaseCompositeSubFs");var A=we;var be=class be{constructor({name:s,filterLayers:e,routes:r,rootPath:t}){y(this,"promises");y(this,"filterLayers",[]);y(this,"router");y(this,"parentFs");y(this,"name");y(this,"rootPath");y(this,"pathToFileDescriptors",new Map);y(this,"openFileHandles",new Map);y(this,"logOperation");this.name=s,this.rootPath=t;for(let i of e)this.filterLayers.push(i),i.attach(this);this.router=new ae(r,this.rootPath),this.promises={access:this.access.bind(this),opendir:this.opendir.bind(this),mkdir:this.mkdir.bind(this),readdir:this.readdir.bind(this),open:this.open.bind(this),stat:this.stat.bind(this),lstat:this.lstat.bind(this),link:this.link.bind(this),readlink:this.readlink.bind(this),unlink:this.unlink.bind(this),rename:this.rename.bind(this),rmdir:this.rmdir.bind(this),symlink:this.symlink.bind(this),readFile:this.readFile.bind(this),writeFile:this.writeFile.bind(this),getFilehandle:this.getFilehandle.bind(this)}}getNextFileDescriptor(){let s=Array.from(this.openFileHandles.keys());return s.length===0?1:Math.max(...s)+1}setLoggger(s){this.logOperation=s}async logOperationOnFileDescsriptor(s,e,r){if(!this.logOperation)return;let t=[];for(let[i,o]of this.pathToFileDescriptors.entries())o.includes(s.fd)&&t.push(i);if(t.length!==0)return this.logOperation?.({fsName:s.delegate.name,fd:s,path:t[0],operation:e,operationArgs:r})}getFilehandle(s){return this.openFileHandles.get(s)}async getResponsibleFs(s){let e=s.toString();for(let i of this.filterLayers)if(await i.responsible(e)){if(i.withContext!==void 0)return i.withContext({fullPath:e,params:{},staticSiblings:[]});throw new Error(`Filter layer filesystem ${i.name} is not a BaseCompositeSubFs`)}let r=this.router.match(e);if(!r)throw new Error(`No route match for: ${e}`);let t=r.handler;return t.attach(this),t.withContext({fullPath:e,params:r.params,staticSiblings:r.staticSiblings})}async access(s,e){let r=await this.getResponsibleFs(s);return await this.logOperation?.({fsName:r.name,path:s,operation:"access",operationArgs:{mode:e}}),r.access(s,e)}async stat(s,e){let r=s.toString(),t=await this.getResponsibleFs(s);return await this.logOperation?.({fsName:t.name,path:r,operation:"stat",operationArgs:{opts:e}}),t.stat(s)}async lstat(s,e){let r=await this.getResponsibleFs(s);return await this.logOperation?.({fsName:r.name,path:s.toString(),operation:"lstat",operationArgs:{opts:e}}),r.lstat(s,e)}async unlink(s){let e=await this.getResponsibleFs(s);return await this.logOperation?.({fsName:e.name,path:s.toString(),operation:"unlink",operationArgs:{}}),e.unlink(s)}async mkdir(s,e){let r=await this.getResponsibleFs(s);return await this.logOperation?.({fsName:r.name,path:s.toString(),operation:"mkdir",operationArgs:{options:e}}),r.mkdir(s,e)}async rmdir(s,e){let r=await this.getResponsibleFs(s);return await this.logOperation?.({fsName:r.name,path:s.toString(),operation:"rmdir",operationArgs:{dirPath:s,options:e}}),r.rmdir(s,e)}async opendir(s,e){await this.logOperation?.({fsName:this.name,path:s.toString(),operation:"opendir",operationArgs:{options:e}});let r=s.toString();return new W(this,r)}async readdir(s,e){await this.logOperation?.({fsName:this.name,path:s.toString(),operation:"readdir",operationArgs:{options:e}});let r=new Set,t=this.router.match(s.toString());if(t?.handler instanceof A){let i=t?.handler.withContext({fullPath:s.toString(),params:t.params,staticSiblings:t.staticSiblings});i.attach(this),r=new Set(await i.readdir(s,e))}for(let i of[...this.filterLayers].reverse())if(i.readDirFiltering)r=new Set(await i.readDirFiltering(s,Array.from(r)));else{let o=await i.readdir(s,e);for(let a of o)r.add(a)}return Array.from(r)}async open(s,e,r){let t=await this.getResponsibleFs(s);await this.logOperation?.({fsName:t.name,path:s,operation:"open",operationArgs:{flags:e,mode:r}});let i=await t.open(s,e,r),o=this.getNextFileDescriptor();return i.realize(o),this.openFileHandles.set(o,i),this.pathToFileDescriptors.get(s)||this.pathToFileDescriptors.set(s,[]),this.pathToFileDescriptors.get(s).push(o),i}async close(s){try{await s.delegate.close(s)}catch(e){throw e}finally{for(let[e,r]of this.pathToFileDescriptors.entries()){let t=r.indexOf(s.fd);if(t!==-1){r.splice(t,1),r.length===0&&this.pathToFileDescriptors.delete(e);break}}this.openFileHandles.delete(s.fd)}}async link(s,e){throw new Error("not implemented")}async readlink(s,e){throw new Error("not implemented")}async rename(s,e){let r=await this.getResponsibleFs(s),t=await this.getResponsibleFs(e);if(r.rootInstanceId===t.rootInstanceId)return await this.logOperation?.({fsName:r.name,path:s.toString(),operation:"rename",operationArgs:{oldPath:s,newPath:e}}),r.newContext=t.context,r.rename(s,e);let i=await r.open(s.toString(),"r");try{let o=await r.fstat(i),a=Buffer.alloc(o.size);await r.read(i,a,0,o.size,0),await r.close(i),await t.writeFile(e.toString(),a,"utf8"),await r.unlink(s)}catch(o){try{await r.close(i)}catch{}throw o}}async symlink(s,e,r){throw new Error("not implemented")}async readFile(s,e){await this.logOperation?.({fsName:this.name,path:s.toString(),operation:"readFile",operationArgs:{path:s,options:e}});let r=!0,t;if(typeof s=="number"){r=!1;let i=this.getFilehandle(s);if(!i)throw new Error("Invalid file descriptor");t=i}else if(typeof s=="string")t=await this.open(s,"r");else throw new Error("only filehandle and path are supported atm");try{let o=(await t.stat()).size;if(typeof o=="bigint"){if(o>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("File too large to read into buffer");o=Number(o)}let a=Buffer.alloc(o),{bytesRead:l}=await t.read(a,0,o,0);if(e&&typeof e.encoding=="string")return a.slice(0,l).toString(e.encoding);if(typeof e=="string"){if(e==="utf8"||e==="utf-8")return a.slice(0,l).toString(e);throw new Error("Unsupported encoding: "+e)}return a.slice(0,l)}finally{t&&r&&await t.close()}}async writeFile(s,e,r){await this.logOperation?.({fsName:this.name,path:s.toString(),operation:"writeFile",operationArgs:{data:e,options:r}});let t=typeof s!="number",i,o,a,l="w";if(typeof r=="string"?o=r:r&&typeof r=="object"&&(o=r.encoding,a=r.mode,l=r.flag||"w"),typeof s=="number"){let c=this.getFilehandle(s);if(!c)throw new Error("Invalid file descriptor");i=c}else if(typeof s=="string")i=await this.open(s,l,a);else throw new Error("only filehandle and path are supported atm");try{let c;if(typeof e=="string")c=Buffer.from(e,o||"utf8");else if(e instanceof Buffer)c=e;else if(e instanceof Uint8Array)c=Buffer.from(e);else throw new Error("Invalid data type for writeFile");let d=0;for(;d<c.length;){let{bytesWritten:h}=await i.write(c,d,c.length-d,d);d+=h}}finally{i&&t&&await i.close()}}};n(be,"CompositeFs");var Z=be;import It from"ignore";var Pe=class Pe extends A{constructor({name:e,hiddenFiles:r,rootPath:t}){super({name:e,rootPath:t});y(this,"ig");this.ig=It(),this.ig.add(r)}async responsible(e){let r=e.replace(/\\/g,"/"),t=r;if(this.rootPath){let i=this.rootPath;r.startsWith(i+"/")?t=r.slice(i.length+1):r.startsWith(i)&&(t=r.slice(i.length))}return t=t.startsWith("./")?t.slice(2):t,t=t.startsWith("/")?t.slice(1):t,t===""||t==="."?!1:this.ig.ignores(t)}fileType(){return 255}error(e){return new Error(`Access to hidden file is not allowed: ${B(e)}`)}async open(e,r,t){throw this.error(e)}async access(e){throw this.error(e)}async stat(e){throw this.error(e)}async lstat(e){throw this.error(e)}async opendir(e){throw this.error(e)}async link(e){throw this.error(e)}async mkdir(e){throw this.error(e)}async readDirFiltering(e,r){let t=[];for(let i of r){let o=B(e)!=="/"?B(e)+"/"+i:"/"+i;await this.responsible(o)||t.push(i)}return t}async readdir(e){throw this.error(e)}async readlink(e){throw this.error(e)}async unlink(e){throw this.error(e)}async rename(e){throw this.error(e)}async rmdir(e){throw this.error(e)}async symlink(e,r){throw this.error(r)}async lookup(e){throw this.error(e)}resolvePath(e){throw new Error(`Access to hidden file is not allowed: resolvePath(${e})`)}async close(e){throw new Error("Access to hidden file is not allowed: close: "+e.subFsFileDescriptor)}async dataSync(e){throw new Error("Access to hidden file is not allowed: dataSync: "+e.subFsFileDescriptor)}async read(e,r,t,i,o){throw new Error("Access to hidden file is not allowed: readFileHandle: "+e.subFsFileDescriptor)}};n(Pe,"HiddenFileSubFs");var le=Pe;var ve=class ve{constructor(s){y(this,"delegate");y(this,"compositeFs");y(this,"_subFsFileDescriptor");y(this,"handleType","file");y(this,"_compositFsFileDescriptor",-1);this.delegate=s.fs,this._subFsFileDescriptor=s.subFsFileDescriptor,this._compositFsFileDescriptor=-1,this.compositeFs=s.compositeFs;let e=this._subFsFileDescriptor}get fsType(){return this.delegate.fileType()}get subFsFileDescriptor(){return this._subFsFileDescriptor}get fd(){return this._compositFsFileDescriptor}realize(s){if(this._compositFsFileDescriptor!==-1)throw new Error("was already realized");this._compositFsFileDescriptor=s}readableWebStream(s){throw new Error("Method not implemented.")}async appendFile(s,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"appendFile",{data:s,options:e}),await this.delegate.appendFile(this,s,e)}async chmod(s){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chmod",{mode:s}),this.delegate.fchmod(this,s)}async chown(s,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chown",{uid:s,gid:e}),this.delegate.fchown(this,s,e)}async close(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"close",{}),this.compositeFs.close(this)}async datasync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"datasync",{}),this.delegate.dataSync(this)}async read(s,e,r,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"read",{targetBufferLength:s.length,offset:e,length:r,position:t}),await this.delegate.read(this,s,e,r,t)}async readv(s,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"readv",{buffers:s,position:e}),this.delegate.readv(this,s,e)}async stat(s){return await this.compositeFs.logOperationOnFileDescsriptor(this,"stat",{options:s}),this.delegate.fstat(this,s)}async truncate(s){return await this.compositeFs.logOperationOnFileDescsriptor(this,"truncate",{len:s}),this.delegate.ftruncate(this,s)}async utimes(s,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"utimes",{atime:s,mtime:e}),this.delegate.futimes(this,s,e)}async write(s,e,r,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"write",{buffer:s,offset:e,length:r,position:t}),this.delegate.write(this,s,e,r,t)}async writev(s,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"writev",{buffers:s,position:e}),this.delegate.writev(this,s,e)}async sync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"sync",{}),this.delegate.dataSync(this)}};n(ve,"CompositFsFileHandle");var H=ve;import*as ce from"path";import{createFsFromVolume as Nt,Volume as xt}from"memfs";import Rt from"ignore";var ke=class ke extends A{constructor({name:e,rootPath:r,ephemeralPatterns:t}){super({name:e,rootPath:r});y(this,"openFh",new Map);y(this,"memFs",Nt(new xt));y(this,"ig");y(this,"patterns");this.ig=Rt(),this.ig.add(t),this.patterns=t}normalizePath(e){let r=typeof e=="string"?e:e.toString();return r.startsWith("/")?r:"/"+r}async responsible(e){let r=e.replace(/\\/g,"/"),t=r;return this.rootPath&&(r.startsWith(this.rootPath+"/")?t=r.slice(this.rootPath.length+1):r.startsWith(this.rootPath)&&(t=r.slice(this.rootPath.length))),t=t.startsWith("./")?t.slice(2):t,t=t.startsWith("/")?t.slice(1):t,t===""||t==="."?!1:this.ig.ignores(t)}fileType(){return 5}async open(e,r,t){let i=this.normalizePath(e),o=ce.dirname(i);o&&o!=="/"&&o!=="."&&await this.memFs.promises.mkdir(o,{recursive:!0});let a=await this.memFs.promises.open(i,r,t);return this.openFh.set(a.fd,a),new H({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:a.fd,parentFsFileDescriptors:[a.fd]})}async access(e,r){let t=this.normalizePath(e);return await this.memFs.promises.access(t,r)}async stat(e,r){let t=this.normalizePath(e);return this.memFs.promises.stat(t,{bigint:!1})}async lstat(e,r){let t=this.normalizePath(e);return this.memFs.promises.lstat(t,{bigint:!1})}async opendir(e,r){let t=this.normalizePath(e);return await this.memFs.promises.opendir(t,r)}async link(e,r){let t=this.normalizePath(e),i=this.normalizePath(r);return await this.memFs.promises.link(t,i)}async mkdir(e,r){let t=this.normalizePath(e);if(!(typeof r=="object"&&r&&"recursive"in r&&r.recursive)){let o=ce.dirname(t);if(o&&o!=="/"&&o!==".")try{await this.memFs.promises.stat(o)}catch{await this.memFs.promises.mkdir(o,{recursive:!0})}}await this.memFs.promises.mkdir(t,r)}async readdir(e,...r){let t=this.normalizePath(e),i=await this.memFs.promises.readdir(t,...r);return console.log("EPHEMERAL: READDIR: ",i),i}async readlink(e){throw new Error("readlink is not implemented for EphemeralFileSubFs")}async unlink(e){let r=this.normalizePath(e);return await this.memFs.promises.unlink(r)}async rename(e,r){let t=this.normalizePath(e),i=this.normalizePath(r);return await this.memFs.promises.rename(t,i)}async rmdir(e,r){let t=this.normalizePath(e);return await this.memFs.promises.rmdir(t,r)}async symlink(e,r,t){let i=this.normalizePath(e),o=this.normalizePath(r);return await this.memFs.promises.symlink(i,o,t)}async lookup(e){throw new Error(`lookup is not implemented for: ${B(e)}`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(await r.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.datasync()}async read(e,r,t,i,o){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.read(r,t,i,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.chmod(r)}async fchown(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(r,t)}async write(e,r,t,i,o){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.write(r,t,i,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.truncate(r)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(r,t)}async writev(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(r,t??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.readv(r,t??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){if(typeof e=="string"||Buffer.isBuffer(e)){let t=this.normalizePath(e);return this.memFs.promises.readFile(t,r)}return super.readFile(e,r)}async writeFile(e,r,t){let i=this.normalizePath(e),o=ce.dirname(i);return o&&o!=="/"&&o!=="."&&await this.memFs.promises.mkdir(o,{recursive:!0}),this.memFs.promises.writeFile(i,r,t)}};n(ke,"EphemeralSubFs");var Ge=ke;import*as _ from"path";import $t from"ignore";var Se=class Se extends A{constructor({name:e,sourceFs:r,copyToFs:t,copyToRootPath:i,rootPath:o,patterns:a}){super({rootPath:o,name:e});y(this,"openFh",new Map);y(this,"sourceFs");y(this,"copyToFs");y(this,"copyPath");y(this,"ig");y(this,"patterns");this.sourceFs=r,this.copyToFs=t,this.copyPath=i,this.patterns=a,this.ig=$t(),this.ig.add(a)}normalizeCopyPath(e){let r=typeof e=="string"?e:e.toString(),t=r.startsWith("/")?r:"/"+r;return _.join(this.copyPath,t)}normalizePath(e){let r=typeof e=="string"?e:e.toString();return r.startsWith("/")?r:"/"+r}async responsible(e){let r=e.replace(/\\/g,"/"),t=r;if(this.compositeFs.rootPath){let i=this.compositeFs.rootPath;r.startsWith(i+"/")?t=r.slice(i.length+1):r.startsWith(i)&&(t=r.slice(i.length))}return t=t.startsWith("./")?t.slice(2):t,t=t.startsWith("/")?t.slice(1):t,t===""||t==="."?!1:this.ig.ignores(t)}fileType(){return 6}async isCopied(e){let r=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.access(r),!0}catch{return!1}}async copyFromSource(e){let r=this.normalizeCopyPath(e),t=this.normalizePath(e),i=_.dirname(r);i&&i!=="/"&&i!=="."&&await this.copyToFs.promises.mkdir(i,{recursive:!0});try{let o=await this.sourceFs.promises.readFile(t);await this.copyToFs.promises.writeFile(r,o)}catch(o){if(o.code!=="ENOENT")throw o}}async open(e,r,t){let i=this.normalizePath(e),o=this.normalizeCopyPath(e);if(r.includes("w")||r.includes("a")||r.includes("+")){let l=_.dirname(o);if(l&&l!=="/"&&l!=="."&&await this.copyToFs.promises.mkdir(l,{recursive:!0}),!await this.isCopied(e))try{await this.sourceFs.promises.access(i),await this.copyFromSource(e)}catch{}let d=await this.copyToFs.promises.open(o,r,t);return this.openFh.set(d.fd,d),new H({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:d.fd,parentFsFileDescriptors:[d.fd]})}else{let l=await this.isCopied(e),c=l?this.copyToFs:this.sourceFs,d=l?o:i,h=await c.promises.open(d,r,t);return this.openFh.set(h.fd,h),new H({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:h.fd,parentFsFileDescriptors:[h.fd]})}}async access(e,r){let t=this.normalizePath(e),i=this.normalizeCopyPath(e);try{await this.copyToFs.promises.access(i,r);return}catch{return await this.sourceFs.promises.access(t,r)}}async stat(e,r){let t=this.normalizePath(e),i=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.stat(i,{bigint:r?.bigint??!1})}catch{return this.sourceFs.promises.stat(t,{bigint:r?.bigint??!1})}}async lstat(e,r){let t=this.normalizePath(e),i=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.lstat(i,{bigint:r?.bigint??!1})}catch{return this.sourceFs.promises.lstat(t,{bigint:r?.bigint??!1})}}async opendir(e,r){let t=this.normalizePath(e);return new W(this.compositeFs,t)}async link(e,r){let t=this.normalizeCopyPath(e),i=this.normalizeCopyPath(r);return await this.copyToFs.promises.link(t,i)}async mkdir(e,r){let t=this.normalizeCopyPath(e);if(!(typeof r=="object"&&r&&"recursive"in r&&r.recursive)){let o=_.dirname(t);if(o&&o!=="/"&&o!==".")try{await this.copyToFs.promises.stat(o)}catch{await this.copyToFs.promises.mkdir(o,{recursive:!0})}}await this.copyToFs.promises.mkdir(t,r)}async readdir(e,...r){let t=this.normalizePath(e),i=this.normalizeCopyPath(e),o=new Set,a=new Set;try{let c=await this.sourceFs.promises.readdir(t,...r);Array.isArray(c)&&c.forEach(d=>o.add(typeof d=="string"?d:d.name))}catch(c){if(c.code!=="ENOENT")throw c}try{let c=await this.copyToFs.promises.readdir(i,...r);Array.isArray(c)&&c.forEach(d=>a.add(typeof d=="string"?d:d.name))}catch(c){if(c.code!=="ENOENT")throw c}return Array.from(new Set([...o,...a]))}async readlink(e){throw new Error("readlink is not implemented for CopyOnWriteSubFs")}async unlink(e){let r=this.normalizeCopyPath(e);return await this.copyToFs.promises.unlink(r)}async rename(e,r){let t=this.normalizeCopyPath(e),i=this.normalizeCopyPath(r);return await this.copyToFs.promises.rename(t,i)}async rmdir(e,r){let t=this.normalizeCopyPath(e);return await this.copyToFs.promises.rmdir(t,r)}async symlink(e,r,t){let i=this.normalizeCopyPath(e),o=this.normalizeCopyPath(r);return await this.copyToFs.promises.symlink(i,o,t)}async lookup(e){throw new Error(`lookup is not implemented for: ${B(e)}`)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(await r.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.datasync()}async read(e,r,t,i,o){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.read(r,t,i,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.chmod(r)}async fchown(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(r,t)}async write(e,r,t,i,o){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.write(r,t,i,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.truncate(r)}async fstat(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(r,t)}async writev(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(r,t??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.readv(r,t??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){if(typeof e!="string"&&!Buffer.isBuffer(e))return super.readFile(e,r);let t=this.normalizePath(e),i=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.readFile(i,r)}catch{return this.sourceFs.promises.readFile(t,r)}}async writeFile(e,r,t){let i=this.normalizeCopyPath(e);await this.isCopied(e)||await this.copyFromSource(e);let a=_.dirname(i);a&&a!=="/"&&a!=="."&&await this.copyToFs.promises.mkdir(a,{recursive:!0}),await this.copyToFs.promises.writeFile(i,r,t)}};n(Se,"CopyOnWriteSubFs");var ee=Se;import*as Ke from"path";import{createFsFromVolume as Mt,Volume as zt}from"memfs";var De=class De extends A{constructor({name:e,parentFs:r,rootPath:t}){super({name:e,rootPath:t});y(this,"openFh",new Map);y(this,"memFs",Mt(new zt));y(this,"targetFs");if(this.compositeFs=r,this.compositeFs.parentFs===void 0)throw new Error("PassThroughSubFs not allowed in root fs");this.targetFs=this.compositeFs.parentFs}async responsible(e){return!0}fileType(){return 4}async open(e,r,t){let i=Ke.dirname(e),o=await this.targetFs.promises.open(e,r,t);return this.openFh.set(o.fd,o),new H({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:o.fd,parentFsFileDescriptors:[o.fd]})}async access(e,r){return await this.targetFs.promises.access(e,r)}async stat(e,r){return this.targetFs.promises.stat(e,{bigint:!1})}async lstat(e,r){return this.targetFs.promises.lstat(e,{bigint:!1})}async opendir(e,r){return await this.targetFs.promises.opendir(e,r)}async link(e,r){return await this.targetFs.promises.link(e,r)}async mkdir(e,r){let t=typeof e=="string"?e:e.toString();return await this.targetFs.promises.mkdir(t,r)}async readdir(e,...r){return this.targetFs.promises.readdir(e,...r)}async readlink(e,...r){throw new Error("not implemented")}async unlink(e){return await this.targetFs.promises.unlink(e)}async rename(e,r){return await this.targetFs.promises.rename(e,r)}async rmdir(e,r){return await this.targetFs.promises.rmdir(e,r)}async symlink(e,r,t){return await this.targetFs.promises.symlink(e,r,t)}async lookup(e){throw new Error(`lookup is not implemented for: ${B(e)}`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(await r.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.sync()}async read(e,r,t,i,o){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.read(r,t,i,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.chmod(r)}async fchown(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(r,t)}async write(e,r,t,i,o){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.write(r,t,i,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.truncate(r)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(r,t)}async writev(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(r,t??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.readv(r,t??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){return typeof e=="string"||Buffer.isBuffer(e)?this.targetFs.readFile(e.toString(),r):super.readFile(e,r)}async writeFile(e,r,t){let i=typeof t=="object"&&t.flag?t.flag:"w",o=await this.targetFs.open(e,i);try{let a;if(typeof r=="string"){let l=typeof t=="object"&&t.encoding?t.encoding:"utf8";a=Buffer.from(r,l)}else Buffer.isBuffer(r)?a=r:a=Buffer.from(r);await o.write(a,0,a.length,0)}finally{await this.targetFs.close(o)}}};n(De,"PassThroughSubFs");var Je=De;import Xe from"@legit-sdk/isomorphic-git";import*as Ce from"path";import{createFsFromVolume as Vt,Volume as Wt}from"memfs";import z from"@legit-sdk/isomorphic-git";function R(m){return m.replace(/\./g,"%2E").replace(/\//g,".")}n(R,"encodeBranchNameForVfs");function O(m){return m.replace(/\./g,"/").replace(/%2E/g,".")}n(O,"decodeBranchNameFromVfs");async function P(m,s,e,r){try{return await z.resolveRef({fs:m,dir:s,ref:`refs/heads/${O(e)}`})}catch{return}}n(P,"tryResolveRef");async function V({dir:m,fs:s,treeOid:e,deletePathParts:r,addPathParts:t,addObj:i,addKeepIfEmpty:o,deleteKeepIfNotEmpty:a,keepFilename:l=".keep",gitCache:c}){let[d,...h]=t??[],[u,...f]=r??[],p=[];if(e){let{tree:w}=await z.readTree({fs:s,dir:m,oid:e,cache:c||{}});p=[...w]}if(d===u){let w=d;if(w===void 0)throw new Error("illegal arguement - called with out a path part");if(h.length===0)throw new Error("can not move into it self");if(f.length===0)throw new Error("can not move from it self");let F=p.findIndex(D=>D.path===w),b=(F!==-1?p[F]:void 0)?.oid,k=await V({dir:m,fs:s,treeOid:b,addPathParts:h,deletePathParts:f,addObj:i,addKeepIfEmpty:o,deleteKeepIfNotEmpty:a});if(k===void 0)throw new Error("on the same path we expect an update - respectivly a newly created subTreeOid");let T=!1;if(k!==b){T=!0;let D={mode:"040000",path:w,oid:k,type:"tree"};F!==-1?p[F]=D:p.push(D)}if(e==null&&!T)throw new Error("Illegal state - if the currentOid is undefined - a new tree should have been created (an update should have happened)");if(T)return await z.writeTree({fs:s,dir:m,tree:p});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}else{let w=!1,F;if(u){let g=p.findIndex(k=>k.path===u),b=g!==-1?p[g]:void 0;if(b===void 0)throw new Error("Element doesnt exist in tree");if(f.length>0){if(b&&b.type!=="tree")throw new Error("SubPart of the path for the obj to delete is not a tree");let k=await V({dir:m,fs:s,treeOid:b.oid,addPathParts:void 0,deletePathParts:f,addObj:i,addKeepIfEmpty:o,deleteKeepIfNotEmpty:a});if(k===b.oid)throw new Error("in case of a delete we expect a different subtree oid");w=!0,k===void 0?p.splice(g,1):p[g]={mode:"040000",path:u,oid:k,type:"tree"}}else if(w=!0,p.splice(g,1),p.length===0&&o){let k=new Uint8Array(0),T=await z.writeBlob({fs:s,dir:m,blob:k});p.push({mode:"100644",oid:T,path:l,type:"blob"})}F=b}if(d){let g=p.findIndex(k=>k.path===d),b=g!==-1?p[g]:void 0;if(h.length>0){if(b&&b.type!=="tree")throw new Error("SubPart of the path for the obj to add is not a tree");let k=await V({dir:m,fs:s,treeOid:b?.oid,addPathParts:h,deletePathParts:void 0,addObj:i,addKeepIfEmpty:o,deleteKeepIfNotEmpty:a});if(k===void 0)throw new Error("in case we add, we expect an update - respectivly a newly created subTreeOid");if(k!==b?.oid){w=!0;let T={mode:"040000",path:d,oid:k,type:"tree"};if(g!==-1)p[g]=T;else if(p.push(T),a&&p.length>1){let D=p.findIndex(N=>N.path===l);D!==-1&&p.splice(D,1)}}}else{if(w=!0,i){let k={mode:i.type==="tree"?"040000":"100644",path:d,oid:i.oid,type:i.type};if(g!==-1)p[g]=k;else{if(a&&p.length>0){let T=p.findIndex(D=>D.path===l);T!==-1&&p.splice(T,1)}p.push(k)}}if(o&&p.length===0){let k=new Uint8Array(0),T=await z.writeBlob({fs:s,dir:m,blob:k});p.push({mode:"100644",oid:T,path:l,type:"blob"})}}}if(p.length===0)return;if(w)return await z.writeTree({fs:s,dir:m,tree:p});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}}n(V,"buildUpdatedTree");async function qe(m,s,e,r,t=0,i={}){let{tree:o}=await z.readTree({fs:m,dir:s,oid:e,cache:i});if(r.length===t)return{type:"tree",entries:o.map(c=>$({parent:r.join("/"),name:c.path,isDir:c.type==="tree"})),oid:e};let a=r[t],l=o.find(c=>c.path===a);if(l){if(r.length===t+1){if(l.type==="blob")return{type:"blob",oid:l.oid};if(l.type==="tree"){let c=await z.readTree({fs:m,dir:s,oid:l.oid,cache:i});return{type:"tree",entries:c.tree.map(d=>$({parent:r.join("/"),name:d.path,isDir:d.type==="tree"})),oid:c.oid}}}else if(l.type==="tree")return await qe(m,s,l.oid,r,t+1,i)}}n(qe,"findGitObjectAtPath");async function G({filePath:m,gitRoot:s,nodeFs:e,commitSha:r,pathParams:t,gitCache:i}){let o=i||{};if(!t.filePath){let c=await z.readTree({fs:e,dir:s,oid:r,cache:o});return{type:"tree",entries:c.tree.map(h=>$({parent:m,name:h.path,isDir:h.type==="tree"})),oid:c.oid}}let a=t.filePath?t.filePath.split("/"):[];return await qe(e,s,r,a,0,o)}n(G,"resolveGitObjAtPath");function $(m){return{name:m.name,isFile:n(()=>!m.isDir,"isFile"),isDirectory:n(()=>m.isDir,"isDirectory"),isBlockDevice:n(()=>!0,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isFIFO:n(()=>!1,"isFIFO"),isSocket:n(()=>!1,"isSocket"),parentPath:m.parent,path:m.parent}}n($,"toDirEntry");var Te=class Te extends A{constructor({name:e,gitStorageFs:r,gitRoot:t,handler:i,rootPath:o}){super({name:e,rootPath:o});y(this,"memFs");y(this,"openFh",{});y(this,"storageFs");y(this,"gitRoot");y(this,"handler");this.handler=i,this.gitRoot=t,this.storageFs=r,this.memFs=Vt(new Wt)}async getAuthor(){let e=await Xe.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.name"}),r=await Xe.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.email"}),t=Math.floor(Date.now()/1e3),i=new Date().getTimezoneOffset();return{name:e,email:r,date:t,timezoneOffset:i}}async responsible(e){return!0}getRouteParams(){return this.context?.params||{}}getStaticSiblings(){return this.context?.staticSiblings||[]}async open(e,r,t){if(!(this.handler.writeFile!==void 0)&&(r.includes("w")||r.includes("a")))throw new Error(`Write operations not allowed for ${this.handler.type}`);if(r.includes("x")&&this.handler.type!=="gitBranchFileVirtualFile"&&this.handler.type!=="claudeVirtualSessionFileVirtualFile")throw new Error(`Exclusive operations not allowed for ${this.handler.type}`);let o=await this.getAuthor(),a=this.getRouteParams(),l=await this.handler.getFile({cacheFs:this.memFs,filePath:e,userSpaceFs:this.compositeFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:a,author:o}),c=!1;for(let p of Object.values(this.openFh))p.path===e&&(c=!0);if((l||c)&&r.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!l&&!c&&!(r.includes("w")||r.includes("a")))throw Object.assign(new Error(`ENOENT: no such file or directory, open '${e}'`),{code:"ENOENT",errno:-2,syscall:"open",path:e});let d=Ce.dirname(e);if(await this.memFs.promises.mkdir(d,{recursive:!0}),l===void 0&&!r.includes("x")||l&&l.type==="file")try{let p=await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let h=await this.memFs.promises.open(e,r,t),u=h.fd,f=new H({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:u,parentFsFileDescriptors:[]});return this.openFh[u]={path:e,mode:r,fh:h,openSha:l?.oid,readSha:void 0,unflushed:[]},(r.includes("x")||r.includes("w"))&&this.openFh[u].unflushed.push({length:0,start:0}),f}async mkdir(e,r){let t=e.toString(),i=this.getRouteParams(),o=r?{options:r}:{};try{let a=await this.getAuthor();await this.handler.mkdir({cacheFs:this.memFs,filePath:e.toString(),userSpaceFs:this.compositeFs,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:i,...o,author:a});let l=typeof r=="object"?{...r,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,l);let c=t.split("/"),d="";for(let h=1;h<=c.length;h++){d=c.slice(0,h).join("/");try{if((await this.memFs.promises.stat(d)).isDirectory()){let f=await this.memFs.promises.open(d,"r");this.openFh[f.fd]={path:d,mode:"r",fh:f,openSha:void 0,readSha:void 0,unflushed:[]}}}catch{}}}catch(a){throw a}}async access(e,r){await this.stat(e)}async futimes(e,r,t){let i=this.openFh[e.subFsFileDescriptor];if(!i)throw new Error("Invalid file handle");return await i.fh.utimes(r,t)}async fstat(e,r){let t=this.openFh[e.subFsFileDescriptor];if(!t)throw new Error("Invalid file handle");return this.stat(t.path,r)}async ftruncate(e,r){let t=this.openFh[e.subFsFileDescriptor];if(!t)throw new Error("Invalid file handle");return t.unflushed.push({length:0,start:0}),await t.fh.truncate(r)}async stat(e,r){let t=e.toString(),i=Object.values(this.openFh).find(c=>c.path===t&&c.unflushed.length>0);if(i&&i.unflushed.length>0)return await i.fh.stat(r);let o=this.getRouteParams(),a=await this.getAuthor();return await this.handler.getStats({cacheFs:this.memFs,filePath:t,userSpaceFs:this.compositeFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:o,author:a})}async lstat(e,r){return this.stat(e,r)}async readdir(e,r){let t=e.toString(),i=this.getRouteParams(),o=this.getStaticSiblings(),a=await this.getAuthor(),l=await this.handler.getFile({cacheFs:this.memFs,filePath:t,userSpaceFs:this.compositeFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:i,author:a});if(l){if(l.type!=="directory")throw new Error("not a folder");let c=Array.from(new Set([...l.content,...o.map(d=>$({name:d.segment,parent:t,isDir:d.type==="folder"}))])).sort((d,h)=>d.name.localeCompare(h.name,void 0,{numeric:!0,sensitivity:"base"}));return r?.withFileTypes?c:c.map(d=>d.name)}return[]}async read(e,r,t,i,o){let a=e.subFsFileDescriptor,l=this.openFh[a];if(!l)throw new Error("Invalid file handle");if(l.unflushed.length===0){let c=this.getRouteParams(),d=await this.getAuthor(),h=await this.handler.getFile({cacheFs:this.memFs,filePath:l.path,userSpaceFs:this.compositeFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:c,author:d});if(!h?.content)throw new Error("couldnt access content");if(h.type!=="file")throw new Error("not a file");let u=typeof h.content=="string"?Buffer.from(h.content):h.content,f=typeof o=="number"?o:0,p=Math.min(f+i,u.length),w=Math.max(0,p-f);return u.copy(r,t,f,f+w),{bytesRead:w,buffer:r}}return await l.fh.read(r,t,i,o)}async write(e,r,t,i,o){let a=this.openFh[e.subFsFileDescriptor];if(!a)throw new Error("Invalid file handle");let l=a.mode;if(!l.includes("w")&&!l.includes("a")&&!l.includes("+"))throw Object.assign(new Error("EBADF: bad file descriptor, write"),{code:"EBADF",errno:-9,syscall:"write"});if(a.unflushed.length===0){let u=this.getRouteParams(),f=await this.getAuthor(),p=await this.handler.getFile({cacheFs:this.memFs,filePath:a.path,userSpaceFs:this.compositeFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:u,author:f});p&&p.oid&&(await this.memFs.promises.writeFile(a.path,p.content),a.readSha=p.oid)}let c=await a.fh.write(r,t,i,o),d=t??0,h=o??0;return a.unflushed.push({start:h,length:i||r.byteLength-d+h}),c}async close(e){let r=e.subFsFileDescriptor,t=this.openFh[r];if(!t)throw new Error("Invalid file handle");try{await this.dataSync(e),await t.fh.close()}finally{delete this.openFh[r]}}async dataSync(e){let r=e.subFsFileDescriptor,t=this.openFh[r];if(!t)throw new Error("Invalid file handle");if(t.unflushed.length>0){if(this.handler.writeFile){let i=await this.memFs.promises.readFile(t.path),o=this.getRouteParams(),a=await this.getAuthor();await this.handler.writeFile({cacheFs:this.memFs,filePath:t.path,userSpaceFs:this.compositeFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,content:i,pathParams:o,author:a})}t.unflushed=[]}}async readFile(e,r){let t=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),i=null;typeof r=="string"?i=r:r&&typeof r=="object"&&r.encoding&&(i=r.encoding);let o=await this.open(t,"r");try{let l=(await this.fstat(o)).size,c=Buffer.alloc(l);return await this.read(o,c,0,l,0),await this.close(o),i?c.toString(i):c}catch(a){try{await this.close(o)}catch{}throw a}}async writeFile(e,r,t){let i="w",o="utf8",a;typeof t=="string"?o=t:t&&typeof t=="object"&&(t.flag&&(i=String(t.flag)),t.encoding&&(o=t.encoding),t.mode&&(a=typeof t.mode=="string"?parseInt(t.mode,8):t.mode));let l=await this.open(e,i,a);try{let c;typeof r=="string"?c=Buffer.from(r,o):Buffer.isBuffer(r)?c=r:r instanceof Uint8Array?c=Buffer.from(r):ArrayBuffer.isView(r)?c=Buffer.from(r.buffer,r.byteOffset,r.byteLength):c=Buffer.from(r),await this.write(l,c,0,c.length,0)}finally{await this.close(l)}}async rename(e,r){let t=e.toString(),i=r.toString();if(!this.handler.rename)throw new Error(`Rename not supported for ${this.handler.type} files`);let o=await this.memFs.promises.access(i).then(()=>!0).catch(()=>!1),a=await this.stat(i).then(()=>!0).catch(()=>!1),l=await this.stat(t).then(()=>!0).catch(()=>!1);if(await this.memFs.promises.access(t).then(()=>!0).catch(()=>!1)){let u=Ce.dirname(i);try{await this.memFs.promises.access(u)}catch{await this.memFs.promises.mkdir(u,{recursive:!0})}await this.memFs.promises.rename(e,r)}let d=this.getRouteParams(),h=await this.getAuthor();await this.handler.rename({cacheFs:this.memFs,filePath:t,userSpaceFs:this.compositeFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,newPath:i,pathParams:d,newPathParams:this.newContext?.params||{},author:h})}async fchmod(e,r){}async unlink(e){let r=e.toString();if(!this.handler.unlink)throw new Error(`Cannot unlink ${this.handler.type} files`);try{let t=this.getRouteParams(),i=await this.getAuthor();await this.handler.unlink({cacheFs:this.memFs,filePath:r,userSpaceFs:this.compositeFs,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:t,author:i})}catch(t){let i=!1;for(let[o,a]of Object.entries(this.openFh))a.path===r&&a.unflushed.length>0&&(i=!0);if(!i)throw t}finally{let t=!1;for(let[i,o]of Object.entries(this.openFh))o.path===r&&(t=!0,await o.fh.close(),delete this.openFh[Number(i)]);t&&await this.memFs.promises.unlink(r)}}async rmdir(e,...r){let t=e.toString();if(!this.handler.rmdir)throw new Error(`Cannot rmdir ${this.handler.type} directories`);let i=this.getRouteParams(),o=await this.getAuthor();await this.handler.rmdir({cacheFs:this.memFs,filePath:t,userSpaceFs:this.compositeFs,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:i,author:o});let a=!1;for(let[l,c]of Object.entries(this.openFh))c.path===t&&(a=!0,await c.fh.close(),delete this.openFh[Number(l)]);a&&await this.memFs.promises.rmdir(t,{recursive:!0})}fileType(){return 10}};n(Te,"CompositeSubFsAdapter");var C=Te;import q from"@legit-sdk/isomorphic-git";import jt from"@legit-sdk/isomorphic-git";var Be="-operation";async function x(m,s,e){let t=(await jt.listBranches({fs:m,dir:s})).filter(i=>i.endsWith(O(e)+Be))[0];return t?R(t):void 0}n(x,"resolveOperationBranchName");import Oe from"@legit-sdk/isomorphic-git";async function v(m,s){try{let e=await Oe.getConfig({fs:s,dir:m,path:"user.legit-current-branch"});if(e)return R(e)}catch{}try{let e=await Oe.getConfig({fs:s,dir:m,path:"init.defaultBranch"});return R(e)||"main"}catch{return"main"}}n(v,"getCurrentBranch");async function Qe(m,s,e){await Oe.setConfig({fs:s,dir:m,path:"user.legit-current-branch",value:O(e)})}n(Qe,"setCurrentBranch");function Ye({gitStorageFs:m,gitRoot:s,rootPath:e}){let r={type:"gitBranchOperationsVirtualFile",rootType:"file",getStats:n(async i=>{let{gitRoot:o,nodeFs:a,pathParams:l}=i;l.branchName===void 0&&(l.branchName=await v(o,a));let c=await x(a,o,l.branchName),d,h=!1;if(c)try{d=await q.resolveRef({fs:a,dir:o,ref:c}),h=!0}catch{try{d=await q.resolveRef({fs:a,dir:o,ref:`refs/heads/${c}`}),h=!0}catch{throw new Error(`Base Branch ${l.branchName} for operations does not exis`)}}else try{d=await q.resolveRef({fs:a,dir:o,ref:`refs/heads/${l.branchName}`})}catch{throw new Error(`Base Branch ${l.branchName} for operations does not exis`)}let u=await q.readCommit({fs:a,dir:o,oid:d}),{commit:f}=u,p=f.committer.timestamp*1e3;try{return{mode:420,size:(h?await t.handler.getFile(i):void 0)?.content?.length??0,atimeMs:p,mtimeMs:p,ctimeMs:p,birthtimeMs:p,atime:new Date(p),mtime:new Date(p),ctime:new Date(p),birthtime:new Date(p),isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:n(async i=>{let{gitRoot:o,nodeFs:a,pathParams:l}=i;l.branchName===void 0&&(l.branchName=await v(o,a));let c=await x(a,o,l.branchName),d=[];if(c){let f=await q.resolveRef({fs:a,dir:o,ref:`refs/heads/${c}`}),p=!1,w=f;for(;w&&!p;){let F=await q.readCommit({fs:a,dir:o,oid:w});d.push({oid:F.oid,parentOids:F.commit.parent,message:F.commit.message,originBranchOid:"unset"}),w=F.commit.parent&&F.commit.parent.length>0?F.commit.parent[0]:null,F.commit.parent.length===2&&F.commit.parent[0]===F.commit.parent[1]&&(p=!0)}}let h;for(let f=d.length-1;f>=0;f--){let p=d[f];if(h===void 0){if(p.parentOids.length!==2&&p.parentOids[0]!==p.parentOids[1])throw new Error(`Operation commit ${p.oid} does not have two parents as expected`);h=p.parentOids[1]}p.parentOids.length===2&&(h=p.parentOids[1]),p.originBranchOid=h}let u=Buffer.from(JSON.stringify(d,null,2),"utf-8");return{type:"file",content:u,mode:420,size:u.length}},"getFile"),rename:n(async function(i){throw new Error("not implemented")},"rename"),mkdir:n(async function(i){throw new Error("not implemented")},"mkdir")},t=new C({name:"branch-operations",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:r});return t}n(Ye,"createBranchOperationsAdapter");import I from"@legit-sdk/isomorphic-git";import Ee from"@legit-sdk/isomorphic-git/http/node";var j="legit",Ze=n(({fs:m,gitRepoPath:s,serverUrl:e="https://hub.legitcontrol.com",auth:r,anonymousBranch:t,authHeaderPrefix:i="Bearer "})=>{let o=!1;async function a(F){let g=await r.getMaxAccessTokenForBranch(F);if(!g)throw new Error(`No access token for branch ${F}`);await I.fetch({fs:m,http:Ee,dir:s,singleBranch:!0,ref:`${F}`,remote:j,url:e,headers:{Authorization:`${i}${g}`}});let b=await I.resolveRef({fs:m,dir:s,ref:`${j}/${F}`});await I.writeRef({fs:m,dir:s,ref:`refs/heads/${F}`,value:b})}n(a,"loadBranch");let l=[];async function c(){let F=await r.getMaxAccessTokenForBranch("todo");await I.fetch({fs:m,http:Ee,dir:s,remote:j,url:e,headers:{Authorization:`${i}${F}`}});let g=await I.listBranches({fs:m,dir:s});for(let b of g){if(b===t)continue;let k=`${j}/${b}`,T,D;try{T=await I.resolveRef({fs:m,dir:s,ref:b})}catch(N){console.log(`Could not resolve local ref ${b}:`,N)}try{D=await I.resolveRef({fs:m,dir:s,ref:k})}catch{D=void 0}if(T&&D){if(T!==D){let N=await I.findMergeBase({fs:m,dir:s,oids:[T,D]});if(N[0]!==T&&N[0]!==D){let re=await I.merge({fs:m,dir:s,ours:T,theirs:D,fastForwardOnly:!1,abortOnConflict:!1,author:{name:"Your Name",email:"your.email@example.com"},mergeDriver:n(async({branches:ie,contents:se,path:ze})=>{let[Ve,oe,Q]=se;return console.log(`Merging ${ie[0]} with ${ie[1]}...`),console.log("merged:"),console.log(se),{cleanMerge:!0,mergedText:Q===void 0?oe:Q}},"mergeDriver")});await I.writeRef({fs:m,dir:s,ref:`refs/heads/${b}`,value:re.oid,force:!0})}N[0]===T?(console.log(`branch ${b} differs - remote ahaed, not behind`),await I.writeRef({fs:m,dir:s,ref:`refs/heads/${b}`,value:D,force:!0})):N[0]===D?(console.log(`branch ${b} differs - local ahead, not behind`),l.push(b)):(console.log(`branch ${b} differs - both changed`),l.push(b))}}else T&&!D&&l.push(b)}}n(c,"pull");async function d(F){if((await r.getUser()).type!=="local")for(let g of F){let b=await r.getMaxAccessTokenForBranch(g);await I.push({fs:m,http:Ee,dir:s,remote:j,url:e,ref:g,headers:{Authorization:`Bearer ${b}`}})}}n(d,"push");let h=Promise.resolve();async function u(F){h=h.then(()=>d(F)),await h}n(u,"sequentialPush");async function f(){await I.getConfig({fs:m,dir:s,path:`remote.${j}.fetch`})||await I.setConfig({fs:m,dir:s,path:`remote.${j}.fetch`,value:`+refs/heads/*:refs/remotes/${j}/*`});try{await c();let g=[...new Set(l)].filter(b=>b.indexOf(t)===-1);await u(g),l=[]}catch(g){console.error("Error monitoring changes:",g)}finally{o&&setTimeout(f,1e3)}}n(f,"pullPushTick");function p(){o=!0,f()}n(p,"startSync");function w(){o=!1}return n(w,"stopSync"),{start:n(()=>{o||(p(),o=!0)},"start"),stop:n(()=>{w()},"stop"),isRunning:n(()=>o,"isRunning"),loadBranch:a,sequentialPush:u}},"createLegitSyncService");import L from"@legit-sdk/isomorphic-git";import{createFsFromVolume as Re,Volume as $e}from"memfs";var et=n((m,s)=>{let e={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"};return{getUser:n(async()=>e,"getUser"),signInAnonymously:n(async()=>{e.type="anonymous",e.id=crypto.randomUUID(),e.email=`anonymous-sha1-${e.id}-@legitcontrol.com`},"signInAnonymously"),addAccessToken:n(async r=>{let t=await m.getUserTokens(e.id);t.accessTokens.push(r),await m.setUserTokens(e.id,t)},"addAccessToken"),getMaxAccessTokenForBranch:n(async r=>{let t=await m.getUserTokens(e.id);if(!(t.accessTokens===void 0||t.accessTokens.length===0))return t.accessTokens[0]},"getMaxAccessTokenForBranch")}},"createSessionManager");import it from"@legit-sdk/isomorphic-git";function tt(m){let s=JSON.stringify(m),e=new TextEncoder().encode(s),r="";return typeof btoa=="function"?r=btoa(String.fromCharCode(...e)):r=Buffer.from(e).toString("base64"),r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}n(tt,"encodeConfigJson");function rt(m){let s=m.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((m.length+3)%4),e;typeof atob=="function"?e=atob(s):e=Buffer.from(s,"base64").toString("binary");let r=Uint8Array.from(e,i=>i.charCodeAt(0)),t=new TextDecoder().decode(r);return JSON.parse(t)}n(rt,"decodeConfigJson");var st="user.legit-tokens";function ot({storageFs:m,gitRoot:s}){return{getUserTokens:n(async e=>{let r=await it.getConfig({fs:m,dir:s,path:st});return r?rt(r):{accessTokens:[]}},"getUserTokens"),setUserTokens:n(async(e,r)=>await it.setConfig({fs:m,dir:s,path:st,value:tt(r)}),"setUserTokens")}}n(ot,"createGitConfigTokenStore");import S from"@legit-sdk/isomorphic-git";var me=class me extends Error{constructor(e,r){super(e);y(this,"code","ENOENT");y(this,"path");this.name="ENOENTError",this.path=r,Object.setPrototypeOf(this,me.prototype)}};n(me,"ENOENTError");var J=me;function de(m){return m&&m.gitCache!==void 0?m.gitCache:m&&m.parentFs?de(m.parentFs):{}}n(de,"getGitCacheFromFs");function nt({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"branch-file",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitBranchFileVirtualFile",rootType:"folder",getStats:n(async({gitRoot:t,nodeFs:i,filePath:o,cacheFs:a,pathParams:l,userSpaceFs:c})=>{l.branchName===void 0&&(l.branchName=await v(t,i));let d=await P(i,t,l.branchName);if(!d)throw new J(`ENOENT: no such file or directory, stat '${o}'`,o);let h=await G({filePath:o,gitRoot:t,nodeFs:i,commitSha:d,pathParams:l,gitCache:de(c)});if(!h)throw new J(`ENOENT: no such file or directory, stat '${o}'`,o);let u=await S.readCommit({fs:i,dir:t,oid:d}),{commit:f}=u,p=await S.log({fs:i,dir:t,ref:d,filepath:l.filePath,depth:1}),w=f.committer.timestamp*1e3,F=p.length>0?p[0].commit.committer.timestamp*1e3:w;if(h.type==="tree")return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!0,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:F,mtimeMs:F,ctimeMs:F,birthtimeMs:w,atime:new Date(F),mtime:new Date(F),ctime:new Date(F),birthtime:new Date(F)};{let{blob:g}=await S.readBlob({fs:i,dir:t,oid:h.oid});return{mode:420,size:g.length,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(g.length/4096),atimeMs:F,mtimeMs:F,ctimeMs:F,birthtimeMs:F,atime:new Date(F),mtime:new Date(F),ctime:new Date(F),birthtime:new Date(F)}}},"getStats"),getFile:n(async({filePath:t,gitRoot:i,nodeFs:o,cacheFs:a,pathParams:l,userSpaceFs:c})=>{l.branchName===void 0&&(l.branchName=await v(i,o));try{let d=await P(o,i,l.branchName);if(!d){let u=await S.resolveRef({fs:o,dir:i,ref:"HEAD"});if(await S.branch({fs:o,dir:i,ref:l.branchName,object:u}),d=await P(o,i,l.branchName),!d)throw new Error("Could not create branch for getFile")}let h=await G({filePath:t,gitRoot:i,nodeFs:o,commitSha:d,pathParams:l,gitCache:de(c)});if(!h)return;if(h.type==="blob"){let{blob:u}=await S.readBlob({fs:o,dir:i,oid:h.oid});return{type:"file",content:Buffer.from(u),mode:420,size:u.length,oid:h.oid}}else{let u=[];try{let p=await a.promises.stat(t);if(p&&p.isDirectory()){let w=await a.promises.readdir(t,{withFileTypes:!0});u.push(...w)}}catch{}return{type:"directory",content:Array.from(new Set([...u,...h.entries])).map(p=>({...p,name:p.name.toString(),path:`${t}`,parentPath:`${t}`})),mode:493}}}catch{return}},"getFile"),unlink:n(async({filePath:t,gitRoot:i,nodeFs:o,cacheFs:a,pathParams:l,author:c})=>{if(l.branchName===void 0&&(l.branchName=await v(i,o)),!l.filePath)throw new Error("filePath should be in pathParams");let d=await P(o,i,l.branchName);if(!d)throw new Error("Invalid branch file path - branch must exist");let h=await S.readTree({fs:o,dir:i,oid:d}),u=await V({dir:i,fs:o,treeOid:h.oid,deletePathParts:l.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(u!==h.oid){let f=await S.commit({fs:o,dir:i,message:`Delete ${l.filePath}`,tree:u,noUpdateBranch:!0,parent:[d],author:c});await S.writeRef({fs:o,dir:i,ref:`refs/heads/${O(l.branchName)}`,value:f,force:!0})}},"unlink"),writeFile:n(async({filePath:t,gitRoot:i,nodeFs:o,content:a,cacheFs:l,pathParams:c,author:d})=>{if(c.branchName===void 0&&(c.branchName=await v(i,o)),c.filePath===void 0)throw new Error("filePath should be in pathParams");let h;typeof a=="string"?h=new TextEncoder().encode(a):h=new Uint8Array(a);let u=await S.writeBlob({fs:o,dir:i,blob:h}),f=await P(o,i,c.branchName);if(!f){let F=await S.resolveRef({fs:o,dir:i,ref:"HEAD"});if(await S.branch({fs:o,dir:i,ref:O(c.branchName),object:F}),f=await P(o,i,c.branchName),!f)throw new Error("Could not create branch for writeFile")}let p=await S.readTree({fs:o,dir:i,oid:f}),w=await V({dir:i,fs:o,treeOid:p.oid,deletePathParts:void 0,addPathParts:c.filePath.split("/"),addObj:{type:"blob",oid:u},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!1,keepFilename:".keep"});if(w!==p.oid){let F=await S.commit({fs:o,dir:i,message:`\u{1F4BE} Change '${c.filePath}'`,tree:w,noUpdateBranch:!0,parent:[f],author:d});await S.writeRef({fs:o,dir:i,ref:`refs/heads/${O(c.branchName)}`,value:F,force:!0});let g=await P(o,i,c.branchName);if(F!==g)throw new Error("Failed to update branch after file deletion")}},"writeFile"),rename:n(async function({filePath:t,newPath:i,gitRoot:o,nodeFs:a,pathParams:l,newPathParams:c,author:d,userSpaceFs:h}){if(l.branchName===void 0&&(l.branchName=await v(o,a)),l.filePath===void 0)throw new Error("filePath should be in pathParams");if(c.branchName===void 0&&(c.branchName=await v(o,a)),c.filePath===void 0)throw new Error("filePath should be in newPathParams");let u=await P(a,o,l.branchName);if(!u)throw new Error("Invalid branch file path - source branch must exist");let f=await P(a,o,c.branchName);if(!f){let g=await S.resolveRef({fs:a,dir:o,ref:"HEAD"});if(await S.branch({fs:a,dir:o,ref:O(c.branchName),object:g}),f=await P(a,o,c.branchName),f===void 0)throw new Error("Could not create branch for rename operation")}if(c.branchName!==l.branchName)throw new Error("cross branch move not implemented yet");let p=await G({gitRoot:o,nodeFs:a,commitSha:u,filePath:t,pathParams:l,gitCache:de(h)});if(p===void 0)throw new Error("no obj at path exists");let w=await V({dir:o,fs:a,deletePathParts:l.filePath.split("/"),addPathParts:c.filePath.split("/"),addObj:p.type==="blob"?{type:"blob",oid:p.oid}:{type:"tree",oid:p.oid,entries:p.entries.map(g=>g.name.toString())},treeOid:f,addKeepIfEmpty:!0,deleteKeepIfNotEmpty:!0}),F=await S.readTree({fs:a,dir:o,oid:u});if(w!==F.oid){let g=await S.commit({fs:a,dir:o,message:`\u{1F500} Rename '${l.filePath}' to '${c.filePath}'`,tree:w,noUpdateBranch:!0,parent:[f],author:d});await S.writeRef({fs:a,dir:o,ref:`refs/heads/${O(c.branchName)}`,value:g,force:!0})}},"rename"),mkdir:n(async function(t){t.pathParams.branchName===void 0&&(t.pathParams.branchName=await v(t.gitRoot,t.nodeFs));let i=await P(t.nodeFs,t.gitRoot,t.pathParams.branchName);if(t.pathParams.filePath===""&&(t.pathParams.filePath="/",i!==void 0))throw new Error("Folder exists");try{throw await this.getStats(t),new Error("Folder exists")}catch{}if(t.filePath.endsWith("/")&&(t.filePath=t.filePath.replace(/\/+$/,"")),t.pathParams&&typeof t.pathParams.filePath=="string"&&(t.pathParams.filePath=t.pathParams.filePath.replace(/\/+$/,"")),!i){let d=await S.resolveRef({fs:t.nodeFs,dir:t.gitRoot,ref:"HEAD"});if(await S.branch({fs:t.nodeFs,dir:t.gitRoot,ref:O(t.pathParams.branchName),object:d}),i=await P(t.nodeFs,t.gitRoot,t.pathParams.branchName),i===void 0)throw new Error("Could not create branch for mkdir operation")}let o=await S.readTree({fs:t.nodeFs,dir:t.gitRoot,oid:i}),a=new Uint8Array(0),l=await S.writeBlob({fs:t.nodeFs,dir:t.gitRoot,blob:a}),c=await V({dir:t.gitRoot,fs:t.nodeFs,treeOid:o.oid,deletePathParts:void 0,addPathParts:[...t.pathParams.filePath.split("/"),".keep"],addObj:{type:"blob",oid:l},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!0,keepFilename:".keep"});if(c!==o.oid){let d=await S.commit({fs:t.nodeFs,dir:t.gitRoot,message:`\u{1F4BE} Change '${t.pathParams.filePath}'`,tree:c,noUpdateBranch:!0,parent:[i],author:t.author});await S.writeRef({fs:t.nodeFs,dir:t.gitRoot,ref:`refs/heads/${O(t.pathParams.branchName)}`,value:d,force:!0})}},"mkdir"),rmdir:n(async({filePath:t,gitRoot:i,nodeFs:o,cacheFs:a,pathParams:l,author:c})=>{if(l.branchName===void 0&&(l.branchName=await v(i,o)),!l.filePath)throw new Error("filePath should be in pathParams");let d=await P(o,i,l.branchName);if(!d)throw new Error("Invalid branch file path - branch must exist");let h=await S.readTree({fs:o,dir:i,oid:d}),u=await V({dir:i,fs:o,treeOid:h.oid,deletePathParts:l.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(u!==h.oid){let f=await S.commit({fs:o,dir:i,message:`Delete ${l.filePath}`,tree:u,noUpdateBranch:!0,parent:[d],author:c});await S.writeRef({fs:o,dir:i,ref:`refs/heads/${O(l.branchName)}`,value:f,force:!0})}},"rmdir")}})}n(nt,"createBranchFileAdapter");import at from"@legit-sdk/isomorphic-git";function lt({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"branches-list",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitBranchesListVirtualFile",rootType:"folder",getStats:n(async({gitRoot:t,nodeFs:i})=>{let o=t+"/.git";try{return await i.promises.stat(o)}catch{throw new Error(`ENOENT: no such file or directory, stat '${o}'`)}},"getStats"),getFile:n(async({gitRoot:t,nodeFs:i,filePath:o})=>{try{let a=await at.listBranches({fs:i,dir:t}),l=await Promise.all(a.map(async c=>{let d=await at.resolveRef({fs:i,dir:t,ref:c});return $({parent:o,name:R(c),isDir:!0})}));return{type:"directory",content:l,mode:493,size:l}}catch(a){throw a}},"getFile"),rename:n(async t=>{throw new Error("not implemented")},"rename"),mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(lt,"createBranchesListAdapter");import te from"@legit-sdk/isomorphic-git";function Ae(m){return m&&m.gitCache!==void 0?m.gitCache:m&&m.parentFs?Ae(m.parentFs):{}}n(Ae,"getGitCacheFromFs");function ct({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"branch-head",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitBranchHeadVirtualFile",rootType:"file",getStats:n(async({gitRoot:t,nodeFs:i,pathParams:o,userSpaceFs:a})=>{o.branchName===void 0&&(o.branchName=await v(t,i));let l=await P(i,t,o.branchName);if(!l)throw new Error(`Branch ${o.branchName} does not exist in the repository`);let c=await te.readCommit({fs:i,dir:t,oid:l,cache:Ae(a)}),{commit:d}=c,h=d.committer.timestamp*1e3;return{mode:420,size:40,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:h,mtimeMs:h,ctimeMs:h,birthtimeMs:h,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)}},"getStats"),getFile:n(async({gitRoot:t,nodeFs:i,pathParams:o,userSpaceFs:a})=>{o.branchName===void 0&&(o.branchName=await v(t,i));try{let l;try{l=await te.resolveRef({fs:i,dir:t,ref:o.branchName})}catch{l=await te.resolveRef({fs:i,dir:t,ref:`refs/heads/${o.branchName}`})}return{type:"file",content:l+`
4
- `,mode:420,size:l.length}}catch{return}},"getFile"),writeFile:n(async({filePath:t,gitRoot:i,nodeFs:o,content:a,cacheFs:l,pathParams:c,userSpaceFs:d})=>{c.branchName===void 0&&(c.branchName=await v(i,o));let h=a.toString().trim();try{await te.readCommit({fs:o,dir:i,oid:h,cache:Ae(d)})}catch{throw new Error(`Commit ${h} does not exist in the repository`)}await te.writeRef({fs:o,dir:i,ref:"refs/heads/"+c.branchName,value:h,force:!0})},"writeFile"),rename(t){throw new Error("not implementsd")},mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(ct,"createBranchHeadAdapter");function mt({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"legit-virtual-file",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"legitVirtualFile",rootType:"folder",getStats:n(async({gitRoot:t,nodeFs:i})=>{let o=t+"/.git";try{return await i.promises.stat(o)}catch{throw new Error(`ENOENT: no such file or directory, stat '${o}'`)}},"getStats"),getFile:n(async({gitRoot:t,nodeFs:i})=>({type:"directory",content:[],mode:493,size:0}),"getFile"),rename(t){throw new Error("not implemented")},mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(mt,"createLegitVirtualFileAdapter");import Le from"@legit-sdk/isomorphic-git";function he(m){return m&&m.gitCache!==void 0?m.gitCache:m&&m.parentFs?he(m.parentFs):{}}n(he,"getGitCacheFromFs");function dt({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"commit-file",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitCommitFileVirtualFile",rootType:"file",getStats:n(async({filePath:t,gitRoot:i,nodeFs:o,pathParams:a,userSpaceFs:l})=>{if(!a.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!a.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let c=a.sha_1_1_2+a.sha1_3__40,d=await G({filePath:t,gitRoot:i,nodeFs:o,commitSha:c,pathParams:a,gitCache:he(l)});if(!d)throw new J(`ENOENT: no such file or directory, stat '${t}'`,t);let h=await Le.readCommit({fs:o,dir:i,oid:c}),{commit:u}=h,f=u.committer.timestamp*1e3;if(d.type==="tree")return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!0,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:f,mtimeMs:f,ctimeMs:f,birthtimeMs:f,atime:new Date(f),mtime:new Date(f),ctime:new Date(f),birthtime:new Date(f)};{let{blob:p}=await Le.readBlob({fs:o,dir:i,oid:d.oid});return{mode:420,size:p.length,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(p.length/4096),atimeMs:f,mtimeMs:f,ctimeMs:f,birthtimeMs:f,atime:new Date(f),mtime:new Date(f),ctime:new Date(f),birthtime:new Date(f)}}},"getStats"),getFile:n(async({filePath:t,gitRoot:i,nodeFs:o,pathParams:a,userSpaceFs:l})=>{if(!a.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!a.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let c=a.sha_1_1_2+a.sha1_3__40;try{let d=await G({filePath:t,gitRoot:i,nodeFs:o,commitSha:c,pathParams:a,gitCache:he(l)});if(!d)return;if(d.type==="blob"){let{blob:h}=await Le.readBlob({fs:o,dir:i,oid:d.oid,cache:he(l)});return{type:"file",content:Buffer.from(h),mode:420,size:h.length,oid:d.oid}}else return{type:"directory",content:Array.from(new Set([...d.entries.filter(u=>u.name!==".keep")])).map(u=>({...u,name:u.name.toString(),path:`${t}`,parentPath:`${t}`})),mode:493}}catch{return}},"getFile"),rename(t){throw new Error("not implementsd")},mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(dt,"createCommitFileAdapter");import He from"@legit-sdk/isomorphic-git";function ht({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"commit-folder",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitCommitVirtualFolder",rootType:"folder",getStats:n(async t=>{let i=t.gitRoot+"/.git";try{return await t.nodeFs.promises.stat(i)}catch{throw new Error(`ENOENT: no such file or directory, stat '${i}'`)}},"getStats"),getFile:n(async({filePath:t,gitRoot:i,nodeFs:o,pathParams:a})=>{let l=await He.listBranches({fs:o,dir:i}),c=new Set,d=new Set;for(let f of l){let p=`refs/heads/${f}`;try{let w=await He.resolveRef({fs:o,dir:i,ref:p});c.add(w)}catch{}}for(let f of c){let p=await He.log({fs:o,dir:i,ref:f});for(let w of p)d.add(w.oid)}if(!a.sha_1_1_2){let f=new Set;for(let w of d)if(f.add(w.slice(0,2)),f.size>=256)break;let p=Array.from(f).sort().map(w=>$({parent:t,name:w,isDir:!0}));return{type:"directory",content:p,mode:493,size:p}}let h=new Set;for(let f of d)f.startsWith(a.sha_1_1_2)&&h.add(f.slice(2,40));let u=Array.from(h).sort().map(f=>$({parent:t,name:f,isDir:!0}));return{type:"directory",content:u,mode:493,size:u.length}},"getFile"),rename(t){throw new Error("not implementsd")},mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(ht,"createCommitFolderAdapter");import M from"@legit-sdk/isomorphic-git";function pt({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"branch-operation",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitBranchOperationVirtualFile",rootType:"file",getStats:n(async t=>{let{gitRoot:i,nodeFs:o,pathParams:a}=t;a.branchName===void 0&&(a.branchName=await v(i,o));let l=await P(o,i,a.branchName);if(!l)throw new Error(`Base Branch ${a.branchName} for operations does not exis`);let c=await x(o,i,a.branchName),d=!1;if(c)try{l=await M.resolveRef({fs:o,dir:i,ref:c}),d=!0}catch{try{l=await M.resolveRef({fs:o,dir:i,ref:`refs/heads/${c}`}),d=!0}catch{}}let h=await M.readCommit({fs:o,dir:i,oid:l}),{commit:u}=h,f=u.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:f,mtimeMs:f,ctimeMs:f,birthtimeMs:f,atime:new Date(f),mtime:new Date(f),ctime:new Date(f),birthtime:new Date(f),isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:n(async t=>{let{gitRoot:i,nodeFs:o,pathParams:a}=t;a.branchName===void 0&&(a.branchName=await v(i,o));let l=await x(o,i,a.branchName),c,d=!1;if(l){if(c=await P(o,i,l),d=!0,!c)throw new Error(`Base Branch ${l} for operations does not exis`)}else if(c=await P(o,i,a.branchName),!c)throw new Error(`Base Branch ${a.branchName} for operations does not exis`);return{type:"file",content:Buffer.from(c),mode:420,size:c.length}},"getFile"),writeFile:n(async({filePath:t,gitRoot:i,nodeFs:o,content:a,cacheFs:l,pathParams:c,author:d})=>{c.branchName===void 0&&(c.branchName=await v(i,o));let h;typeof a=="string"?h=new TextEncoder().encode(a):h=new Uint8Array(a);let u=await M.writeBlob({fs:o,dir:i,blob:h}),f=await P(o,i,c.branchName);if(!f)throw new Error("Invalid branch file path - branch doesn't exist");let p=await x(o,i,c.branchName),w=!1;if(!p){p=c.branchName+Be,await M.branch({fs:o,dir:i,ref:O(p),object:f});let D=await M.listBranches({fs:o,dir:i});w=!0}let F=await P(o,i,p),g=await M.readTree({fs:o,dir:i,oid:f}),b;a instanceof ArrayBuffer?b=Buffer.from(a).toString("utf-8"):typeof a=="string"?b=a:a instanceof Uint8Array?b=Buffer.from(a).toString("utf-8"):b=String(a);let k=!1;if(!w){let D=await M.findMergeBase({fs:o,dir:i,oids:k?[F]:[F,f]});D.length===1&&D[0]===f&&(k=!0)}let T=await M.commit({fs:o,dir:i,message:b,tree:g.oid,noUpdateBranch:!0,author:d,parent:k?w?[f,f]:[F]:[F,f]});await M.writeRef({fs:o,dir:i,ref:`refs/heads/${O(p)}`,value:T,force:!0})},"writeFile"),rename:n(async function({filePath:t,newPath:i,gitRoot:o,nodeFs:a,pathParams:l,newPathParams:c}){throw new Error("not implemented")},"rename"),mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(pt,"createBranchOperationAdapter");import ft from"@legit-sdk/isomorphic-git";function ut({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"branch-history",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitBranchHistory",rootType:"file",getStats:n(async({gitRoot:t,nodeFs:i,pathParams:o})=>{o.branchName===void 0&&(o.branchName=await v(t,i));let a=await P(i,t,o.branchName);if(!a)throw new Error(`Branch ${o.branchName} does not exist`);let l=await ft.readCommit({fs:i,dir:t,oid:a}),{commit:c}=l,d=c.committer.timestamp*1e3;return{mode:420,size:1e5,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:d,mtimeMs:d,ctimeMs:d,birthtimeMs:d,atime:new Date(d),mtime:new Date(d),ctime:new Date(d),birthtime:new Date(d)}},"getStats"),getFile:n(async t=>{let{gitRoot:i,nodeFs:o,pathParams:a}=t,l=a.branchName;l===void 0&&(l=await v(i,o));let c=[];if(l){let h=await P(o,i,l),u=!1,f=h;for(;f&&!u;){let p=await ft.readCommit({fs:o,dir:i,oid:f});c.push({oid:p.oid,...p.commit}),f=p.commit.parent[0]}}let d=Buffer.from(JSON.stringify(c,null,2),"utf-8");return{type:"file",content:d,mode:420,size:d.length}},"getFile"),rename:n(async t=>{throw new Error("not implemented")},"rename"),mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(ut,"createBranchHistoryAdapter");import U from"@legit-sdk/isomorphic-git";function Ft({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"branch-operation-head",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitBranchOperationHeadVirtualFile",rootType:"file",getStats:n(async({gitRoot:t,nodeFs:i,pathParams:o})=>{o.branchName===void 0&&(o.branchName=await v(t,i));let a=await x(i,t,o.branchName);if(!a){let u=new Date(0);return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:u.getTime(),mtimeMs:u.getTime(),ctimeMs:u.getTime(),birthtimeMs:u.getTime(),atime:u,mtime:u,ctime:u,birthtime:u}}let l;try{l=await U.resolveRef({fs:i,dir:t,ref:a})}catch{l=await U.resolveRef({fs:i,dir:t,ref:`refs/heads/${a}`})}let c=await U.readCommit({fs:i,dir:t,oid:l}),{commit:d}=c,h=d.committer.timestamp*1e3;return{mode:420,size:40,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:h,mtimeMs:h,ctimeMs:h,birthtimeMs:h,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)}},"getStats"),getFile:n(async({gitRoot:t,nodeFs:i,pathParams:o})=>{o.branchName===void 0&&(o.branchName=await v(t,i));let a=await x(i,t,o.branchName);if(!a)return{type:"file",content:"",mode:420,size:0};try{let l;try{l=await U.resolveRef({fs:i,dir:t,ref:a})}catch{l=await U.resolveRef({fs:i,dir:t,ref:`refs/heads/${a}`})}return{type:"file",content:l+`
5
- `,mode:420,size:l.length}}catch{return}},"getFile"),writeFile:n(async({filePath:t,gitRoot:i,nodeFs:o,content:a,cacheFs:l,pathParams:c})=>{c.branchName===void 0&&(c.branchName=await v(i,o));let d=await x(o,i,c.branchName);if(!d)throw new Error(`Operation branch name could not be resolved for branch ${c.branchName}`);let h=await P(o,i,d),u=a.toString().trim(),f,p,w=!1;if(!h)throw new Error(`Operation branch ref could not be resolved for branch ${d}`);let F=h;for(;F&&!w;){let g=await U.readCommit({fs:o,dir:i,oid:F});if(g.oid===u&&(f=g.oid),F=g.commit.parent&&g.commit.parent.length>0?g.commit.parent[0]:null,g.commit.parent.length===2){if(g.commit.parent[0]===g.commit.parent[1])w=!0;else if(f!==void 0){p=g.commit.parent[1];break}}}if(f===void 0)throw new Error(`Cant rollback to ${u} couldn't find newOperationBranchHead ${f}`);if(p===void 0)throw new Error(`Cant rollback to ${u} couldn't find newBranchHead ${p}`);await U.writeRef({fs:o,dir:i,ref:"refs/heads/"+d,value:f,force:!0}),await U.writeRef({fs:o,dir:i,ref:"refs/heads/"+c.branchName,value:p,force:!0})},"writeFile"),rename(t){throw new Error("not implementsd")},mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(Ft,"createBranchOperationHeadAdapter");import Ut from"@legit-sdk/isomorphic-git";import Ie from"@legit-sdk/isomorphic-git";async function K(m,s){try{let e=await Ie.getConfig({fs:s,dir:m,path:"user.legit-reference-branch"});if(e)return R(e)}catch{}try{let e=await Ie.getConfig({fs:s,dir:m,path:"init.defaultBranch"});return R(e)||"main"}catch{return"main"}}n(K,"getReferenceBranch");async function gt(m,s,e){await Ie.setConfig({fs:s,dir:m,path:"user.legit-reference-branch",value:O(e)})}n(gt,"setReferenceBranch");function yt({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"current-branch",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitCurrentBranchVirtualFile",rootType:"file",getStats:n(async({gitRoot:t,nodeFs:i})=>{let a=(await v(t,i)).length;return{mode:420,size:a,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(a/4096),atimeMs:Date.now(),mtimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date}},"getStats"),getFile:n(async({gitRoot:t,nodeFs:i})=>{let o=await v(t,i);return{type:"file",content:o+`
6
- `,mode:420,size:o.length+1}},"getFile"),writeFile:n(async({gitRoot:t,nodeFs:i,content:o})=>{let a=o.toString().trim();if(!await P(i,t,a)){let c=await K(t,i),d=await P(i,t,c);if(!d)throw new Error(`Ref branch ${c} does not exist in the repository`);await Ut.branch({fs:i,dir:t,ref:O(a),object:d})}await Qe(t,i,a)},"writeFile"),rename(t){throw new Error("not implemented")},mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(yt,"createCurrentBranchAdapter");import X from"@legit-sdk/isomorphic-git";function Ne(m){return m&&m.gitCache!==void 0?m.gitCache:m&&m.parentFs?Ne(m.parentFs):{}}n(Ne,"getGitCacheFromFs");function wt({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"apply-changes",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitApplyCurrentChangesToVirtualFile",rootType:"file",getStats:n(async({gitRoot:t,nodeFs:i,pathParams:o,userSpaceFs:a})=>{let l=new Date(0);return{mode:420,size:40,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:l,mtimeMs:l,ctimeMs:l,birthtimeMs:l,atime:l,mtime:l,ctime:l,birthtime:l}},"getStats"),getFile:n(async({gitRoot:t,nodeFs:i,pathParams:o,userSpaceFs:a})=>{try{return{type:"file",content:`
7
- `,mode:420,size:2}}catch{return}},"getFile"),writeFile:n(async({gitRoot:t,nodeFs:i,content:o,userSpaceFs:a,author:l})=>{let c=await v(t,i),d=await K(t,i),h=o.toString().trim(),u=await P(i,t,c,Ne(a));if(!u)throw new Error(`Source branch ${c} does not exist`);let f=await P(i,t,d,Ne(a));if(!f)throw new Error(`Target branch ${d} does not exist`);let p=await X.readTree({fs:i,dir:t,oid:u});if(await X.readTree({fs:i,dir:t,oid:f})===p)return;let F=Math.floor(Date.now()/1e3),g=await X.commit({fs:i,dir:t,message:h,tree:p.oid,noUpdateBranch:!0,author:{...l,timestamp:F},parent:[f]}),b=await X.commit({fs:i,dir:t,message:"Changes from "+c+" applied to "+d,tree:p.oid,noUpdateBranch:!0,author:{...l,timestamp:F-3},parent:[u,g]});await X.writeRef({fs:i,dir:t,ref:"refs/heads/"+O(d),value:g,force:!0}),await X.writeRef({fs:i,dir:t,ref:"refs/heads/"+O(c),value:b,force:!0})},"writeFile"),rename(t){throw new Error("not implementsd")},mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(wt,"createApplyChangesAdapter");function bt({gitStorageFs:m,gitRoot:s,rootPath:e}){return new C({name:"reference-branch",gitStorageFs:m,gitRoot:s,rootPath:e||s,handler:{type:"gitReferenceBranchVirtualFile",rootType:"file",getStats:n(async({gitRoot:t,nodeFs:i})=>{let a=(await K(t,i)).length;return{mode:420,size:a,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(a/4096),atimeMs:Date.now(),mtimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date}},"getStats"),getFile:n(async({gitRoot:t,nodeFs:i})=>{let o=await K(t,i);return{type:"file",content:o+`
8
- `,mode:420,size:o.length+1}},"getFile"),writeFile:n(async({gitRoot:t,nodeFs:i,content:o})=>{let a=o.toString().trim();if(!await P(i,t,a))throw new Error(`Branch ${a} does not exist in the repository`);await gt(t,i,a)},"writeFile"),rename(t){throw new Error("not implemented")},mkdir:n(async function(t){throw new Error("not implemented")},"mkdir")}})}n(bt,"createReferenceBranchAdapter");import*as Pt from"path";var xe=class xe extends A{constructor({name:e,rootPath:r,passThroughFs:t}){super({name:e,rootPath:r});y(this,"openFh",new Map);y(this,"targetFs");this.targetFs=t}async responsible(e){return!0}fileType(){return 4}async open(e,r,t){let i=Pt.dirname(e),o=await this.targetFs.promises.open(e,r,t);return this.openFh.set(o.fd,o),new H({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:o.fd,parentFsFileDescriptors:[]})}async access(e,r){return await this.targetFs.promises.access(e,r)}async stat(e,...r){return this.targetFs.promises.stat(e,{bigint:!1})}async lstat(e,...r){return this.targetFs.promises.lstat(e,{bigint:!1})}async opendir(e,r){let t=await this.targetFs.promises.opendir(e,r);return new W(this.compositeFs,e.toString())}async link(e,r){return await this.targetFs.promises.link(e,r)}async mkdir(e,r){await this.targetFs.promises.mkdir(e,r)}async readdir(e,...r){return this.targetFs.promises.readdir(e,...r)}async readlink(e,...r){throw new Error("not implemented")}async unlink(e){return await this.targetFs.promises.unlink(e)}async rename(e,r){return await this.targetFs.promises.rename(e,r)}async rmdir(e,r){return await this.targetFs.promises.rmdir(e,r)}async symlink(e,r,t){return await this.targetFs.promises.symlink(e,r,t)}async lookup(e){throw new Error(`lookup is not implemented for: ${B(e)}`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(this.openFh.delete(e.subFsFileDescriptor),await r.close())}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.sync()}async read(e,r,t,i,o){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.read(r,t,i,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.chmod(r)}async fchown(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(r,t)}async write(e,r,t,i,o){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.write(r,t,i,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.truncate(r)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,r){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(r,t)}async writev(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(r,t??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,t){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.readv(r,t??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){return this.targetFs.promises.readFile(e,r)}async writeFile(e,r,t){return this.targetFs.promises.writeFile(e,r,t)}};n(xe,"PassThroughToAsyncFsSubFs");var pe=xe;function Me(m){return m&&m.gitCache!==void 0?m.gitCache:m&&m.parentFs?Me(m.parentFs):{}}n(Me,"getGitCache");async function xo(m){let s=new $e,e=Re(s);return _t({...m,storageFs:m?.storageFs?m.storageFs:e,gitRoot:m?.gitRoot||"/"})}n(xo,"openLegitFsWithMemoryFs");async function _t({storageFs:m,gitRoot:s,anonymousBranch:e="anonymous",showKeepFiles:r=!1,initialAuthor:t={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"},serverUrl:i="https://hub.legitcontrol.com",publicKey:o,ephemaralGitConfig:a=!1,additionalFilterLayers:l}){await m.promises.readdir(s+"/.git").then(()=>!0).catch(()=>!1)||(await L.init({fs:m,dir:"/",defaultBranch:e}),await m.promises.writeFile(s+"/.gitignore",""),await m.promises.writeFile(s+"/.keep",""),await L.add({fs:m,dir:"/",filepath:".keep",cache:Me(m)}),await L.commit({fs:m,dir:"/",message:"Initial commit",author:{name:"Test",email:"test@example.com"},cache:Me(m)}),await L.setConfig({fs:m,dir:s,path:"init.defaultBranch",value:e})),await L.getConfig({fs:m,dir:s,path:"user.legit_user_id"})||await L.setConfig({fs:m,dir:s,path:"user.legit_user_id",value:t.name}),await L.getConfig({fs:m,dir:s,path:"user.name"})||await L.setConfig({fs:m,dir:s,path:"user.name",value:t.name}),await L.getConfig({fs:m,dir:s,path:"user.email"})||await L.setConfig({fs:m,dir:s,path:"user.email",value:t.email});let f=Re(new $e),p=new ee({name:"root-copy-on-write",sourceFs:m,copyToFs:f,copyToRootPath:"/copies",rootPath:s,patterns:a?["**/.git/config"]:[]}),w=new pe({name:"root-passthrough",passThroughFs:m,rootPath:s}),F=new Z({name:"root",filterLayers:[p],rootPath:s,routes:{"[[...relativePath]]":w}}),g={gitStorageFs:F,gitRoot:s,rootPath:s},b=mt(g),k=pt(g),T=ct(g),D=Ft(g),N=Ye(g),re=ut(g),ie=yt(g),se=bt(g),ze=wt(g),Ve=lt(g),oe=nt(g),Q=ht(g),vt=dt(g),kt=r?[".git"]:[".git",".keep"],St=new le({name:"git-hidden-subfs",hiddenFiles:kt,rootPath:s}),We=[];try{let E=s+"/.gitignore";We=(await F.readFile(E,"utf8")).split(`
9
- `).filter(Y=>Y.trim()!==""&&!Y.trim().startsWith("#")).map(Y=>Y.trim())}catch{}let Dt=["**/._*","**/.DS_Store","**/.AppleDouble/","**/.AppleDB","**/.AppleDesktop","**/.Spotlight-V100","**/.TemporaryItems","**/.Trashes","**/.fseventsd","**/.VolumeIcon.icns","**/.ql_disablethumbnails","**/.~lock.*","**/lu[0-9a-zA-Z]*.tmp","**/.metaentries.json.tmp","**/**.tmp.**","**/**.sb-**",...We],Ct=Re(new $e),Tt=new ee({name:"git-copy-on-write-subfs",sourceFs:F,copyToFs:Ct,copyToRootPath:"/user-copies",rootPath:s,patterns:Dt}),je=new Z({name:"git",rootPath:s,filterLayers:[St,Tt,...l||[]],routes:{".legit":{".":b,operation:k,head:T,operationHead:D,operationHistory:N,history:re,currentBranch:ie,"reference-branch":se,"apply-changes":ze,branches:{".":Ve,"[branchName]":{".legit":{".":b,operation:k,head:T,operationHead:D,operationHistory:N,history:re},"[[...filePath]]":oe}},commits:{".":Q,"[sha_1_1_2]":{".":Q,"[sha1_3__40]":{"[[...filePath]]":vt}}}},"[[...filePath]]":oe}}),Bt=ot({storageFs:F,gitRoot:s}),ne=et(Bt,o),fe=Ze({fs:m,gitRepoPath:s,serverUrl:i,auth:ne,anonymousBranch:e}),ue=Object.assign(je,{auth:ne,sync:fe,_storageFs:F,setLogger(E){je.setLoggger(E)},push:n(async E=>{},"push"),shareCurrentBranch:n(async()=>{if((await ne.getUser()).type==="local")throw new Error("login first - for example anonymously using legitfs.auth.signInAnonymously()");let E=await ue.getCurrentBranch();return E===e&&(E=(await ne.getUser()).id,await L.renameBranch({fs:m,dir:s,oldref:e,ref:E})),await fe.sequentialPush([E]),ue.setCurrentBranch(E),E},"shareCurrentBranch"),setCurrentBranch:n(async E=>{(await L.listBranches({fs:m,dir:s})).includes(E)||await fe?.loadBranch(E);let Ue=(await L.listBranches({fs:m,dir:s})).includes(E);if(console.log("branchExistsAfter",Ue),!Ue)throw new Error(`Branch ${E} does not exist`);await L.setConfig({fs:m,dir:s,path:"init.defaultBranch",value:E})},"setCurrentBranch"),getCurrentBranch:n(async()=>{let E=await L.getConfig({fs:m,dir:s,path:"init.defaultBranch"});if(!E)throw new Error("No current branch set");return E},"getCurrentBranch")});return ue}n(_t,"openLegitFs");var Mo=n(m=>async s=>{if(!s.path.includes(".legit/branches/")||(s.path.match(/\.legit/g)||[]).length>1)return;let[e,r]=s.path.split(".legit/branches/"),[t,...i]=r.split("/"),o=i.join("/"),a=e+".legit/branches/"+t+"/.legit/operation",l=JSON.stringify(s.operationArgs,(c,d)=>Buffer.isBuffer(d)?{__buffer__:d.toString("base64")}:d);console.log(a,`[${s.fsName}].${s.operation}(${s.fd?s.fd.fd+" - ":""}${s.path})
3
+ var er=Object.defineProperty;var oa=(t,i,e)=>i in t?er(t,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[i]=e;var c=(t,i)=>er(t,"name",{value:i,configurable:!0});var g=(t,i,e)=>oa(t,typeof i!="symbol"?i+"":i,e);var Xt=class Xt{constructor(i,e){g(this,"entries",[]);g(this,"currentIndex",0);g(this,"closed",!1);g(this,"compositFs");g(this,"dirPath");g(this,"initialized",!1);this.compositFs=i,this.dirPath=e}async initialize(){if(this.initialized)return;let i=new Set;for(let e of[...this.compositFs.filterLayers].reverse())if(e.readDirFiltering)i=new Set(await e.readDirFiltering(this.dirPath,Array.from(i)));else{let r=await e.readdir(this.dirPath);for(let n of r)i.add(n)}this.initialized=!0}async*[Symbol.asyncIterator](){for(await this.initialize();this.currentIndex<this.entries.length&&!this.closed;){let i=this.entries[this.currentIndex++];try{let e=await this.compositFs.stat(i.path);yield{name:i.name,isFile:c(()=>e.isFile(),"isFile"),isDirectory:c(()=>e.isDirectory(),"isDirectory"),isBlockDevice:c(()=>e.isBlockDevice(),"isBlockDevice"),isCharacterDevice:c(()=>e.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:c(()=>e.isSymbolicLink(),"isSymbolicLink"),isFIFO:c(()=>e.isFIFO(),"isFIFO"),isSocket:c(()=>e.isSocket(),"isSocket")}}catch(e){console.debug(`Failed to stat ${i.path}:`,e)}}}async read(){if(this.closed)throw new Error("Directory handle is closed");if(await this.initialize(),this.currentIndex>=this.entries.length)return null;let i=this.entries[this.currentIndex++];try{let e=await this.compositFs.stat(i.path);return{name:i.name,isFile:c(()=>e.isFile(),"isFile"),isDirectory:c(()=>e.isDirectory(),"isDirectory"),isBlockDevice:c(()=>e.isBlockDevice(),"isBlockDevice"),isCharacterDevice:c(()=>e.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:c(()=>e.isSymbolicLink(),"isSymbolicLink"),isFIFO:c(()=>e.isFIFO(),"isFIFO"),isSocket:c(()=>e.isSocket(),"isSocket")}}catch{return this.read()}}async close(){this.closed=!0,this.entries=[]}get path(){return this.dirPath}};c(Xt,"CompositeFsDir");var be=Xt;function la(t){let i=t.split("/").filter(Boolean),e=[],r=[],n=!1,a;for(let s of i)if(s.startsWith("[[")&&s.endsWith("]]")){let o=s.slice(2,-2).replace(/^\.\.\./,"");if(e.push(o),s.startsWith("[[..."))n=!0,r.push("(/.*)*"),a=o;else throw new Error("Optional single-segment parameters [[param]] are not supported. Use [[...param]] for catch-all or [param] for required single segment.")}else if(s.startsWith("[")&&s.endsWith("]")){if(s.startsWith("[..."))throw new Error("Required catch-all parameters [...param] are not supported. Use [[...param]] instead.");{let o=s.slice(1,-1);e.push(o),r.push("/([^\\/]+)")}}else s==="."?n=!0:r.push("/"+s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return{regexStr:r.join("")+"$",paramNames:e,folderRoute:n,pathParameter:a}}c(la,"compilePattern");function Yt(t){if(t===".")return 1;let i=t.split("/").filter(Boolean),e=Math.pow(2,i.length);for(let r=0;r<i.length;r++){let n=i[r],a;n.startsWith("[[...")?a=10:n.startsWith("[[")?a=50:n.startsWith("[")?a=100:a=1e3+n.length;let s=Math.pow(.9,r);e+=a*s}return e}c(Yt,"calculatePriority");function ca(t){if(typeof t.name!="string")return"folder";let i=t;return i.fsType==="folder"?"folder":i.fsType==="file"?"file":"readdir"in i&&typeof i.readdir=="function"?"folder":"file"}c(ca,"getNodeType");function da(t){let i=[];function e(r,n){if(typeof r.name=="string"){i.push({pattern:n||".",handler:r,priority:Yt(n||"."),staticBaseChildren:[]});return}let a=r,s=[],o=Object.keys(a).filter(d=>d.startsWith("[[")||d===".");if(o.length>1)throw new Error(`Expected exactly one folder handler for ${n||"/"} expected but multuple found: ${o.join(", ")}`);if(o.length===0)throw new Error(`No folder handler for ${n||"/"} founds`);for(let[d,l]of Object.entries(a)){let h=n?`${n}/${d}`:d;if(d==="."){if(typeof l.name!="string")throw new Error(`Folder root '.' at path '${n}' must be a handler, not a folder`);if(l.fsType!=="folder"&&l.fsType!=="fs")throw new Error(`Folder root handler '.' at path '${n}' must be of type 'folder' or 'fs'`);i.push({pattern:n+"/.",handler:l,priority:Yt(n),staticBaseChildren:s})}else if(d.startsWith("[["))if(d.startsWith("[[..."))if(typeof l.name=="string"){if(i.push({pattern:h,handler:l,priority:Yt(h),staticBaseChildren:s}),l.fsType!=="folder"&&l.fsType!=="fs")throw new Error(`Folder root handler '.' at path '${n}' must be of type 'folder' or 'fs'`)}else e(l,h);else e(l,h);else if(d.startsWith("[")){if(d.startsWith("[..."))throw new Error(`Required catch-all '${d}' is not supported. Use '[[...${d.slice(5,-1)}]]' instead`);e(l,h)}else s.push({segment:d,type:ca(l)}),e(l,h)}}return c(e,"walk"),e(t,""),i}c(da,"flattenRoutes");var Jt=class Jt{constructor(i,e){this.routes=i;this.rootPath=e;g(this,"compiledRoutes");let r=da(i);this.compiledRoutes=r.map(n=>{let{regexStr:a,paramNames:s,folderRoute:o,pathParameter:d}=la(n.pattern);return{regex:new RegExp(a),paramNames:s,staticBaseChildren:n.staticBaseChildren,handler:n.handler,priority:n.priority,pattern:n.pattern,folderRoute:o,pathParameter:d}})}match(i){let e=i;e.startsWith(this.rootPath+"/")?e=e.slice(this.rootPath.length+1):e.startsWith(this.rootPath)&&(e=e.slice(this.rootPath.length)),e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1));let r,n={},a=-1,s=this.compiledRoutes,o=[];for(let l of s){let h=e.match(l.regex);if(h)o.push(l);else continue;if(!(!h||l.priority<=a)){n={};for(let f=0;f<l.paramNames.length;f++){let p=h[f+1]||"";p.startsWith("/")&&(p=p.slice(1)),n[l.paramNames[f]]=p}a=l.priority,r=l}}if(!r||r.handler===void 0)return;let d=[];return r.folderRoute&&(r.pathParameter?n[r.pathParameter]===""&&(d=r.staticBaseChildren.map(l=>({segment:l.segment,type:l.type}))):d=r.staticBaseChildren.map(l=>({segment:l.segment,type:l.type}))),{handler:r.handler,matchingPattern:r.pattern,params:n,staticSiblings:d}}};c(Jt,"PathRouter");var xt=Jt;function z(t){return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString():String(t)}c(z,"pathToString");var qt=class qt{constructor({name:i,rootPath:e}){g(this,"compositeFs");g(this,"context");g(this,"newContext");g(this,"fsType","fs");g(this,"rootInstanceId");g(this,"name");g(this,"rootPath");this.name=i,this.rootPath=e,this.rootInstanceId=`${i}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}attach(i){this.compositeFs=i}withContext(i){let e=Object.create(Object.getPrototypeOf(this));return Object.assign(e,this),e.context=i,e}async open(i,e,r){throw new Error(`open not implemented for: ${z(i)}`)}async access(i,e){throw new Error(`access not implemented for: ${z(i)}`)}async stat(i,e){throw new Error(`lstat not implemented for: ${z(i)}`)}async lstat(i,e){throw new Error(`lstat not implemented for: ${z(i)}`)}async opendir(i,e){throw new Error(`opendir not implemented for: ${z(i)}`)}async link(i,e){throw new Error(`link not implemented for: ${z(i)}`)}async mkdir(i,e){throw new Error(`mkdir not implemented for: ${z(i)}`)}async readdir(i,e){throw new Error(`readdir not implemented for: ${z(i)}`)}async readlink(i,...e){throw new Error(`readlink not implemented for: ${z(i)}`)}async unlink(i){throw new Error(`unlink not implemented for: ${z(i)}`)}async rename(i,e){throw new Error(`rename not implemented for: ${z(i)}`)}async rmdir(i,...e){throw new Error(`rmdir not implemented for: ${z(i)}`)}async symlink(i,e,r){throw new Error(`symlink not implemented for: ${z(e)}`)}async lookup(i){throw new Error(`lookup not implemented for: ${z(i)}`)}resolvePath(i){throw new Error(`resolvePath not implemented for fd: ${i}`)}async close(i){this.compositeFs.close(i)}async dataSync(i){throw new Error(`dataSync not implemented for: ${i.subFsFileDescriptor}`)}async read(i,e,r,n,a){throw new Error(`read not implemented for: ${i.subFsFileDescriptor}`)}async appendFile(i,e,r){throw new Error(`appendFile not implemented for: ${i.subFsFileDescriptor}`)}async fchmod(i,e){throw new Error(`fchmod not implemented for: ${i.subFsFileDescriptor}`)}async fchown(i,e,r){throw new Error(`fchown not implemented for: ${i.subFsFileDescriptor}`)}async ftruncate(i,e){throw new Error(`ftruncate not implemented for: ${i.subFsFileDescriptor}`)}async fstat(i,e){throw new Error(`fstat not implemented for: ${i.subFsFileDescriptor}`)}async futimes(i,e,r){throw new Error(`futimes not implemented for: ${i.subFsFileDescriptor}`)}async write(i,e,r,n,a){throw new Error(`write not implemented for: ${i.subFsFileDescriptor}`)}async writev(i,e,r){throw new Error(`writev not implemented for: ${i.subFsFileDescriptor}`)}async readv(i,e,r){throw new Error(`readv not implemented for: ${i.subFsFileDescriptor}`)}async readFile(i,e){throw new Error(`readFile not implemented for: ${i}`)}async writeFile(i,e,r){throw new Error(`writeFile not implemented for: ${i}`)}};c(qt,"BaseCompositeSubFs");var j=qt;var Qt=class Qt{constructor({name:i,filterLayers:e,routes:r,rootPath:n}){g(this,"promises");g(this,"filterLayers",[]);g(this,"router");g(this,"parentFs");g(this,"name");g(this,"rootPath");g(this,"pathToFileDescriptors",new Map);g(this,"openFileHandles",new Map);g(this,"logOperation");this.name=i,this.rootPath=n;for(let a of e)this.filterLayers.push(a),a.attach(this);this.router=new xt(r,this.rootPath),this.promises={access:this.access.bind(this),opendir:this.opendir.bind(this),mkdir:this.mkdir.bind(this),readdir:this.readdir.bind(this),open:this.open.bind(this),stat:this.stat.bind(this),lstat:this.lstat.bind(this),link:this.link.bind(this),readlink:this.readlink.bind(this),unlink:this.unlink.bind(this),rename:this.rename.bind(this),rmdir:this.rmdir.bind(this),symlink:this.symlink.bind(this),readFile:this.readFile.bind(this),writeFile:this.writeFile.bind(this),getFilehandle:this.getFilehandle.bind(this)}}getNextFileDescriptor(){let i=Array.from(this.openFileHandles.keys());return i.length===0?1:Math.max(...i)+1}setLoggger(i){this.logOperation=i}async logOperationOnFileDescsriptor(i,e,r){if(!this.logOperation)return;let n=[];for(let[a,s]of this.pathToFileDescriptors.entries())s.includes(i.fd)&&n.push(a);if(n.length!==0)return this.logOperation?.({fsName:i.delegate.name,fd:i,path:n[0],operation:e,operationArgs:r})}getFilehandle(i){return this.openFileHandles.get(i)}async getResponsibleFs(i){let e=i.toString();for(let a of this.filterLayers)if(await a.responsible(e)){if(a.withContext!==void 0)return a.withContext({fullPath:e,params:{},staticSiblings:[]});throw new Error(`Filter layer filesystem ${a.name} is not a BaseCompositeSubFs`)}let r=this.router.match(e);if(!r)throw new Error(`No route match for: ${e}`);let n=r.handler;return n.attach(this),n.withContext({fullPath:e,params:r.params,staticSiblings:r.staticSiblings})}async access(i,e){let r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:i,operation:"access",operationArgs:{mode:e}}),r.access(i,e)}async stat(i,e){let r=i.toString(),n=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:n.name,path:r,operation:"stat",operationArgs:{opts:e}}),n.stat(i)}async lstat(i,e){let r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:i.toString(),operation:"lstat",operationArgs:{opts:e}}),r.lstat(i,e)}async unlink(i){let e=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:e.name,path:i.toString(),operation:"unlink",operationArgs:{}}),e.unlink(i)}async mkdir(i,e){let r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:i.toString(),operation:"mkdir",operationArgs:{options:e}}),r.mkdir(i,e)}async rmdir(i,e){let r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:i.toString(),operation:"rmdir",operationArgs:{dirPath:i,options:e}}),r.rmdir(i,e)}async opendir(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"opendir",operationArgs:{options:e}});let r=i.toString();return new be(this,r)}async readdir(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"readdir",operationArgs:{options:e}});let r=new Set,n=this.router.match(i.toString());if(n?.handler instanceof j){let a=n?.handler.withContext({fullPath:i.toString(),params:n.params,staticSiblings:n.staticSiblings});a.attach(this),r=new Set(await a.readdir(i,e))}for(let a of[...this.filterLayers].reverse())if(a.readDirFiltering)r=new Set(await a.readDirFiltering(i,Array.from(r)));else{let s=await a.readdir(i,e);for(let o of s)r.add(o)}return Array.from(r)}async open(i,e,r){let n=await this.getResponsibleFs(i);await this.logOperation?.({fsName:n.name,path:i,operation:"open",operationArgs:{flags:e,mode:r}});let a=await n.open(i,e,r),s=this.getNextFileDescriptor();return a.realize(s),this.openFileHandles.set(s,a),this.pathToFileDescriptors.get(i)||this.pathToFileDescriptors.set(i,[]),this.pathToFileDescriptors.get(i).push(s),a}async close(i){try{await i.delegate.close(i)}catch(e){throw e}finally{for(let[e,r]of this.pathToFileDescriptors.entries()){let n=r.indexOf(i.fd);if(n!==-1){r.splice(n,1),r.length===0&&this.pathToFileDescriptors.delete(e);break}}this.openFileHandles.delete(i.fd)}}async link(i,e){throw new Error("not implemented")}async readlink(i,e){throw new Error("not implemented")}async rename(i,e){let r=await this.getResponsibleFs(i),n=await this.getResponsibleFs(e);if(r.rootInstanceId===n.rootInstanceId)return await this.logOperation?.({fsName:r.name,path:i.toString(),operation:"rename",operationArgs:{oldPath:i,newPath:e}}),r.newContext=n.context,r.rename(i,e);let a=await r.open(i.toString(),"r");try{let s=await r.fstat(a),o=Buffer.alloc(s.size);await r.read(a,o,0,s.size,0),await r.close(a),await n.writeFile(e.toString(),o,"utf8"),await r.unlink(i)}catch(s){try{await r.close(a)}catch{}throw s}}async symlink(i,e,r){throw new Error("not implemented")}async readFile(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"readFile",operationArgs:{path:i,options:e}});let r=!0,n;if(typeof i=="number"){r=!1;let a=this.getFilehandle(i);if(!a)throw new Error("Invalid file descriptor");n=a}else if(typeof i=="string")n=await this.open(i,"r");else throw new Error("only filehandle and path are supported atm");try{let s=(await n.stat()).size;if(typeof s=="bigint"){if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("File too large to read into buffer");s=Number(s)}let o=Buffer.alloc(s),{bytesRead:d}=await n.read(o,0,s,0);if(e&&typeof e.encoding=="string")return o.slice(0,d).toString(e.encoding);if(typeof e=="string"){if(e==="utf8"||e==="utf-8")return o.slice(0,d).toString(e);throw new Error("Unsupported encoding: "+e)}return o.slice(0,d)}finally{n&&r&&await n.close()}}async writeFile(i,e,r){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"writeFile",operationArgs:{data:e,options:r}});let n=typeof i!="number",a,s,o,d="w";if(typeof r=="string"?s=r:r&&typeof r=="object"&&(s=r.encoding,o=r.mode,d=r.flag||"w"),typeof i=="number"){let l=this.getFilehandle(i);if(!l)throw new Error("Invalid file descriptor");a=l}else if(typeof i=="string")a=await this.open(i,d,o);else throw new Error("only filehandle and path are supported atm");try{let l;if(typeof e=="string")l=Buffer.from(e,s||"utf8");else if(e instanceof Buffer)l=e;else if(e instanceof Uint8Array)l=Buffer.from(e);else throw new Error("Invalid data type for writeFile");let h=0;for(;h<l.length;){let{bytesWritten:f}=await a.write(l,h,l.length-h,h);h+=f}}finally{a&&n&&await a.close()}}};c(Qt,"CompositeFs");var it=Qt;import ha from"ignore";var ei=class ei extends j{constructor({name:e,hiddenFiles:r,rootPath:n}){super({name:e,rootPath:n});g(this,"ig");this.ig=ha(),this.ig.add(r)}async responsible(e){let r=e.replace(/\\/g,"/"),n=r;if(this.rootPath){let a=this.rootPath;r.startsWith(a+"/")?n=r.slice(a.length+1):r.startsWith(a)&&(n=r.slice(a.length))}return n=n.startsWith("./")?n.slice(2):n,n=n.startsWith("/")?n.slice(1):n,n===""||n==="."?!1:this.ig.ignores(n)}fileType(){return 255}error(e){return new Error(`Access to hidden file is not allowed: ${z(e)}`)}async open(e,r,n){throw this.error(e)}async access(e){throw this.error(e)}async stat(e){throw this.error(e)}async lstat(e){throw this.error(e)}async opendir(e){throw this.error(e)}async link(e){throw this.error(e)}async mkdir(e){throw this.error(e)}async readDirFiltering(e,r){let n=[];for(let a of r){let s=z(e)!=="/"?z(e)+"/"+a:"/"+a;await this.responsible(s)||n.push(a)}return n}async readdir(e){throw this.error(e)}async readlink(e){throw this.error(e)}async unlink(e){throw this.error(e)}async rename(e){throw this.error(e)}async rmdir(e){throw this.error(e)}async symlink(e,r){throw this.error(r)}async lookup(e){throw this.error(e)}resolvePath(e){throw new Error(`Access to hidden file is not allowed: resolvePath(${e})`)}async close(e){throw new Error("Access to hidden file is not allowed: close: "+e.subFsFileDescriptor)}async dataSync(e){throw new Error("Access to hidden file is not allowed: dataSync: "+e.subFsFileDescriptor)}async read(e,r,n,a,s){throw new Error("Access to hidden file is not allowed: readFileHandle: "+e.subFsFileDescriptor)}};c(ei,"HiddenFileSubFs");var Et=ei;var ti=class ti{constructor(i){g(this,"delegate");g(this,"compositeFs");g(this,"_subFsFileDescriptor");g(this,"handleType","file");g(this,"_compositFsFileDescriptor",-1);this.delegate=i.fs,this._subFsFileDescriptor=i.subFsFileDescriptor,this._compositFsFileDescriptor=-1,this.compositeFs=i.compositeFs;let e=this._subFsFileDescriptor}get fsType(){return this.delegate.fileType()}get subFsFileDescriptor(){return this._subFsFileDescriptor}get fd(){return this._compositFsFileDescriptor}realize(i){if(this._compositFsFileDescriptor!==-1)throw new Error("was already realized");this._compositFsFileDescriptor=i}readableWebStream(i){throw new Error("Method not implemented.")}async appendFile(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"appendFile",{data:i,options:e}),await this.delegate.appendFile(this,i,e)}async chmod(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chmod",{mode:i}),this.delegate.fchmod(this,i)}async chown(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chown",{uid:i,gid:e}),this.delegate.fchown(this,i,e)}async close(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"close",{}),this.compositeFs.close(this)}async datasync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"datasync",{}),this.delegate.dataSync(this)}async read(i,e,r,n){return await this.compositeFs.logOperationOnFileDescsriptor(this,"read",{targetBufferLength:i.length,offset:e,length:r,position:n}),await this.delegate.read(this,i,e,r,n)}async readv(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"readv",{buffers:i,position:e}),this.delegate.readv(this,i,e)}async stat(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"stat",{options:i}),this.delegate.fstat(this,i)}async truncate(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"truncate",{len:i}),this.delegate.ftruncate(this,i)}async utimes(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"utimes",{atime:i,mtime:e}),this.delegate.futimes(this,i,e)}async write(i,e,r,n){return await this.compositeFs.logOperationOnFileDescsriptor(this,"write",{buffer:i,offset:e,length:r,position:n}),this.delegate.write(this,i,e,r,n)}async writev(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"writev",{buffers:i,position:e}),this.delegate.writev(this,i,e)}async sync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"sync",{}),this.delegate.dataSync(this)}};c(ti,"CompositFsFileHandle");var G=ti;import*as Dt from"path";import{createFsFromVolume as fa,Volume as ma}from"memfs";import pa from"ignore";var ii=class ii extends j{constructor({name:e,rootPath:r,ephemeralPatterns:n}){super({name:e,rootPath:r});g(this,"openFh",new Map);g(this,"memFs",fa(new ma));g(this,"ig");g(this,"patterns");this.ig=pa(),this.ig.add(n),this.patterns=n}normalizePath(e){let r=typeof e=="string"?e:e.toString();return r.startsWith("/")?r:"/"+r}async responsible(e){let r=e.replace(/\\/g,"/"),n=r;return this.rootPath&&(r.startsWith(this.rootPath+"/")?n=r.slice(this.rootPath.length+1):r.startsWith(this.rootPath)&&(n=r.slice(this.rootPath.length))),n=n.startsWith("./")?n.slice(2):n,n=n.startsWith("/")?n.slice(1):n,n===""||n==="."?!1:this.ig.ignores(n)}fileType(){return 5}async open(e,r,n){let a=this.normalizePath(e),s=Dt.dirname(a);s&&s!=="/"&&s!=="."&&await this.memFs.promises.mkdir(s,{recursive:!0});let o=await this.memFs.promises.open(a,r,n);return this.openFh.set(o.fd,o),new G({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:o.fd,parentFsFileDescriptors:[o.fd]})}async access(e,r){let n=this.normalizePath(e);return await this.memFs.promises.access(n,r)}async stat(e,r){let n=this.normalizePath(e);return this.memFs.promises.stat(n,{bigint:!1})}async lstat(e,r){let n=this.normalizePath(e);return this.memFs.promises.lstat(n,{bigint:!1})}async opendir(e,r){let n=this.normalizePath(e);return await this.memFs.promises.opendir(n,r)}async link(e,r){let n=this.normalizePath(e),a=this.normalizePath(r);return await this.memFs.promises.link(n,a)}async mkdir(e,r){let n=this.normalizePath(e);if(!(typeof r=="object"&&r&&"recursive"in r&&r.recursive)){let s=Dt.dirname(n);if(s&&s!=="/"&&s!==".")try{await this.memFs.promises.stat(s)}catch{await this.memFs.promises.mkdir(s,{recursive:!0})}}await this.memFs.promises.mkdir(n,r)}async readdir(e,...r){let n=this.normalizePath(e),a=await this.memFs.promises.readdir(n,...r);return console.log("EPHEMERAL: READDIR: ",a),a}async readlink(e){throw new Error("readlink is not implemented for EphemeralFileSubFs")}async unlink(e){let r=this.normalizePath(e);return await this.memFs.promises.unlink(r)}async rename(e,r){let n=this.normalizePath(e),a=this.normalizePath(r);return await this.memFs.promises.rename(n,a)}async rmdir(e,r){let n=this.normalizePath(e);return await this.memFs.promises.rmdir(n,r)}async symlink(e,r,n){let a=this.normalizePath(e),s=this.normalizePath(r);return await this.memFs.promises.symlink(a,s,n)}async lookup(e){throw new Error(`lookup is not implemented for: ${z(e)}`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(await r.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.datasync()}async read(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.chmod(r)}async fchown(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.chown(r,n)}async write(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.truncate(r)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.utimes(r,n)}async writev(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.writev(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.readv(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){if(typeof e=="string"||Buffer.isBuffer(e)){let n=this.normalizePath(e);return this.memFs.promises.readFile(n,r)}return super.readFile(e,r)}async writeFile(e,r,n){let a=this.normalizePath(e),s=Dt.dirname(a);return s&&s!=="/"&&s!=="."&&await this.memFs.promises.mkdir(s,{recursive:!0}),this.memFs.promises.writeFile(a,r,n)}};c(ii,"EphemeralSubFs");var tr=ii;import*as De from"path";import ua from"ignore";var ri=class ri extends j{constructor({name:e,sourceFs:r,copyToFs:n,copyToRootPath:a,rootPath:s,patterns:o}){super({rootPath:s,name:e});g(this,"openFh",new Map);g(this,"sourceFs");g(this,"copyToFs");g(this,"copyPath");g(this,"ig");g(this,"patterns");this.sourceFs=r,this.copyToFs=n,this.copyPath=a,this.patterns=o,this.ig=ua(),this.ig.add(o)}normalizeCopyPath(e){let r=typeof e=="string"?e:e.toString(),n=r.startsWith("/")?r:"/"+r;return De.join(this.copyPath,n)}normalizePath(e){let r=typeof e=="string"?e:e.toString();return r.startsWith("/")?r:"/"+r}async responsible(e){let r=e.replace(/\\/g,"/"),n=r;if(this.compositeFs.rootPath){let a=this.compositeFs.rootPath;r.startsWith(a+"/")?n=r.slice(a.length+1):r.startsWith(a)&&(n=r.slice(a.length))}return n=n.startsWith("./")?n.slice(2):n,n=n.startsWith("/")?n.slice(1):n,n===""||n==="."?!1:this.ig.ignores(n)}fileType(){return 6}async isCopied(e){let r=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.access(r),!0}catch{return!1}}async copyFromSource(e){let r=this.normalizeCopyPath(e),n=this.normalizePath(e),a=De.dirname(r);a&&a!=="/"&&a!=="."&&await this.copyToFs.promises.mkdir(a,{recursive:!0});try{let s=await this.sourceFs.promises.readFile(n);await this.copyToFs.promises.writeFile(r,s)}catch(s){if(s.code!=="ENOENT")throw s}}async open(e,r,n){let a=this.normalizePath(e),s=this.normalizeCopyPath(e);if(r.includes("w")||r.includes("a")||r.includes("+")){let d=De.dirname(s);if(d&&d!=="/"&&d!=="."&&await this.copyToFs.promises.mkdir(d,{recursive:!0}),!await this.isCopied(e))try{await this.sourceFs.promises.access(a),await this.copyFromSource(e)}catch{}let h=await this.copyToFs.promises.open(s,r,n);return this.openFh.set(h.fd,h),new G({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:h.fd,parentFsFileDescriptors:[h.fd]})}else{let d=await this.isCopied(e),l=d?this.copyToFs:this.sourceFs,h=d?s:a,f=await l.promises.open(h,r,n);return this.openFh.set(f.fd,f),new G({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:f.fd,parentFsFileDescriptors:[f.fd]})}}async access(e,r){let n=this.normalizePath(e),a=this.normalizeCopyPath(e);try{await this.copyToFs.promises.access(a,r);return}catch{return await this.sourceFs.promises.access(n,r)}}async stat(e,r){let n=this.normalizePath(e),a=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.stat(a,{bigint:r?.bigint??!1})}catch{return this.sourceFs.promises.stat(n,{bigint:r?.bigint??!1})}}async lstat(e,r){let n=this.normalizePath(e),a=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.lstat(a,{bigint:r?.bigint??!1})}catch{return this.sourceFs.promises.lstat(n,{bigint:r?.bigint??!1})}}async opendir(e,r){let n=this.normalizePath(e);return new be(this.compositeFs,n)}async link(e,r){let n=this.normalizeCopyPath(e),a=this.normalizeCopyPath(r);return await this.copyToFs.promises.link(n,a)}async mkdir(e,r){let n=this.normalizeCopyPath(e);if(!(typeof r=="object"&&r&&"recursive"in r&&r.recursive)){let s=De.dirname(n);if(s&&s!=="/"&&s!==".")try{await this.copyToFs.promises.stat(s)}catch{await this.copyToFs.promises.mkdir(s,{recursive:!0})}}await this.copyToFs.promises.mkdir(n,r)}async readdir(e,...r){let n=this.normalizePath(e),a=this.normalizeCopyPath(e),s=new Set,o=new Set;try{let l=await this.sourceFs.promises.readdir(n,...r);Array.isArray(l)&&l.forEach(h=>s.add(typeof h=="string"?h:h.name))}catch(l){if(l.code!=="ENOENT")throw l}try{let l=await this.copyToFs.promises.readdir(a,...r);Array.isArray(l)&&l.forEach(h=>o.add(typeof h=="string"?h:h.name))}catch(l){if(l.code!=="ENOENT")throw l}return Array.from(new Set([...s,...o]))}async readlink(e){throw new Error("readlink is not implemented for CopyOnWriteSubFs")}async unlink(e){let r=this.normalizeCopyPath(e);return await this.copyToFs.promises.unlink(r)}async rename(e,r){let n=this.normalizeCopyPath(e),a=this.normalizeCopyPath(r);return await this.copyToFs.promises.rename(n,a)}async rmdir(e,r){let n=this.normalizeCopyPath(e);return await this.copyToFs.promises.rmdir(n,r)}async symlink(e,r,n){let a=this.normalizeCopyPath(e),s=this.normalizeCopyPath(r);return await this.copyToFs.promises.symlink(a,s,n)}async lookup(e){throw new Error(`lookup is not implemented for: ${z(e)}`)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(await r.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.datasync()}async read(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.chmod(r)}async fchown(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.chown(r,n)}async write(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.truncate(r)}async fstat(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.utimes(r,n)}async writev(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.writev(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.readv(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){if(typeof e!="string"&&!Buffer.isBuffer(e))return super.readFile(e,r);let n=this.normalizePath(e),a=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.readFile(a,r)}catch{return this.sourceFs.promises.readFile(n,r)}}async writeFile(e,r,n){let a=this.normalizeCopyPath(e);await this.isCopied(e)||await this.copyFromSource(e);let o=De.dirname(a);o&&o!=="/"&&o!=="."&&await this.copyToFs.promises.mkdir(o,{recursive:!0}),await this.copyToFs.promises.writeFile(a,r,n)}};c(ri,"CopyOnWriteSubFs");var rt=ri;import ir from"@legit-sdk/isomorphic-git";import*as ni from"path";import{createFsFromVolume as wa,Volume as ya}from"memfs";function V(t){return{name:t.name,isFile:c(()=>!t.isDir,"isFile"),isDirectory:c(()=>t.isDir,"isDirectory"),isBlockDevice:c(()=>!0,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isFIFO:c(()=>!1,"isFIFO"),isSocket:c(()=>!1,"isSocket"),parentPath:t.parent,path:t.parent}}c(V,"toDirEntry");var ai=class ai extends j{constructor({name:e,gitStorageFs:r,gitRoot:n,handler:a,rootPath:s}){super({name:e,rootPath:s});g(this,"memFs");g(this,"openFh",{});g(this,"storageFs");g(this,"gitRoot");g(this,"handler");this.handler=a,this.gitRoot=n,this.storageFs=r,this.memFs=wa(new ya)}async getAuthor(){if(this.storageFs===void 0||this.storageFs===null)return{};let e=await ir.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.name"}),r=await ir.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.email"}),n=Math.floor(Date.now()/1e3),a=new Date().getTimezoneOffset();return{name:e,email:r,date:n,timezoneOffset:a}}async responsible(e){return!0}getRouteParams(){return this.context?.params||{}}getStaticSiblings(){return this.context?.staticSiblings||[]}async open(e,r,n){if(!(this.handler.writeFile!==void 0)&&(r.includes("w")||r.includes("a")))throw new Error(`Write operations not allowed for ${this.handler.type}`);if(r.includes("x")&&this.handler.type!=="gitBranchFileVirtualFile"&&this.handler.type!=="claudeVirtualSessionFileVirtualFile")throw new Error(`Exclusive operations not allowed for ${this.handler.type}`);let s=await this.getAuthor(),o=this.getRouteParams(),d=await this.handler.getFile({cacheFs:this.memFs,filePath:e,userSpaceFs:this.compositeFs,pathParams:o,author:s}),l=!1;for(let u of Object.values(this.openFh))u.path===e&&(l=!0);if((d||l)&&r.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!d&&!l&&!(r.includes("w")||r.includes("a")))throw Object.assign(new Error(`ENOENT: no such file or directory, open '${e}'`),{code:"ENOENT",errno:-2,syscall:"open",path:e});let h=ni.dirname(e);if(await this.memFs.promises.mkdir(h,{recursive:!0}),d===void 0&&!r.includes("x")||d&&d.type==="file")try{let u=await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let f=await this.memFs.promises.open(e,r,n),p=f.fd,m=new G({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:p,parentFsFileDescriptors:[]});return this.openFh[p]={path:e,mode:r,fh:f,openSha:d?.oid,readSha:void 0,unflushed:[]},(r.includes("x")||r.includes("w"))&&this.openFh[p].unflushed.push({length:0,start:0}),m}async mkdir(e,r){let n=e.toString(),a=this.getRouteParams(),s=r?{options:r}:{};try{let o=await this.getAuthor();await this.handler.mkdir({cacheFs:this.memFs,filePath:e.toString(),userSpaceFs:this.compositeFs,pathParams:a,...s,author:o});let d=typeof r=="object"?{...r,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,d);let l=n.split("/"),h="";for(let f=1;f<=l.length;f++){h=l.slice(0,f).join("/");try{if((await this.memFs.promises.stat(h)).isDirectory()){let m=await this.memFs.promises.open(h,"r");this.openFh[m.fd]={path:h,mode:"r",fh:m,openSha:void 0,readSha:void 0,unflushed:[]}}}catch{}}}catch(o){throw o}}async access(e,r){await this.stat(e)}async futimes(e,r,n){let a=this.openFh[e.subFsFileDescriptor];if(!a)throw new Error("Invalid file handle");return await a.fh.utimes(r,n)}async fstat(e,r){let n=this.openFh[e.subFsFileDescriptor];if(!n)throw new Error("Invalid file handle");return this.stat(n.path,r)}async ftruncate(e,r){let n=this.openFh[e.subFsFileDescriptor];if(!n)throw new Error("Invalid file handle");return n.unflushed.push({length:0,start:0}),await n.fh.truncate(r)}async stat(e,r){let n=e.toString(),a=Object.values(this.openFh).find(l=>l.path===n&&l.unflushed.length>0);if(a&&a.unflushed.length>0)return await a.fh.stat(r);let s=this.getRouteParams(),o=await this.getAuthor();return await this.handler.getStats({cacheFs:this.memFs,filePath:n,userSpaceFs:this.compositeFs,pathParams:s,author:o})}async lstat(e,r){return this.stat(e,r)}async readdir(e,r){let n=e.toString(),a=this.getRouteParams(),s=this.getStaticSiblings(),o=await this.getAuthor(),d=await this.handler.getFile({cacheFs:this.memFs,filePath:n,userSpaceFs:this.compositeFs,pathParams:a,author:o});if(d){if(d.type!=="directory")throw new Error("not a folder");let l=Array.from(new Set([...d.content,...s.map(h=>V({name:h.segment,parent:n,isDir:h.type==="folder"}))])).sort((h,f)=>h.name.localeCompare(f.name,void 0,{numeric:!0,sensitivity:"base"}));return r?.withFileTypes?l:l.map(h=>h.name)}return[]}async read(e,r,n,a,s){let o=e.subFsFileDescriptor,d=this.openFh[o];if(!d)throw new Error("Invalid file handle");if(d.unflushed.length===0){let l=this.getRouteParams(),h=await this.getAuthor(),f=await this.handler.getFile({cacheFs:this.memFs,filePath:d.path,userSpaceFs:this.compositeFs,pathParams:l,author:h});if(!f?.content)throw new Error("couldnt access content");if(f.type!=="file")throw new Error("not a file");let p=typeof f.content=="string"?Buffer.from(f.content):f.content,m=typeof s=="number"?s:0,u=Math.min(m+a,p.length),v=Math.max(0,u-m);return p.copy(r,n,m,m+v),{bytesRead:v,buffer:r}}return await d.fh.read(r,n,a,s)}async write(e,r,n,a,s){let o=this.openFh[e.subFsFileDescriptor];if(!o)throw new Error("Invalid file handle");let d=o.mode;if(!d.includes("w")&&!d.includes("a")&&!d.includes("+"))throw Object.assign(new Error("EBADF: bad file descriptor, write"),{code:"EBADF",errno:-9,syscall:"write"});if(o.unflushed.length===0){let p=this.getRouteParams(),m=await this.getAuthor(),u=await this.handler.getFile({cacheFs:this.memFs,filePath:o.path,userSpaceFs:this.compositeFs,pathParams:p,author:m});u&&u.oid&&(await this.memFs.promises.writeFile(o.path,u.content),o.readSha=u.oid)}let l=await o.fh.write(r,n,a,s),h=n??0,f=s??0;return o.unflushed.push({start:f,length:a||r.byteLength-h+f}),l}async close(e){let r=e.subFsFileDescriptor,n=this.openFh[r];if(!n)throw new Error("Invalid file handle");try{await this.dataSync(e),await n.fh.close()}finally{delete this.openFh[r]}}async dataSync(e){let r=e.subFsFileDescriptor,n=this.openFh[r];if(!n)throw new Error("Invalid file handle");if(n.unflushed.length>0){if(this.handler.writeFile){let a=await this.memFs.promises.readFile(n.path),s=this.getRouteParams(),o=await this.getAuthor();await this.handler.writeFile({cacheFs:this.memFs,filePath:n.path,userSpaceFs:this.compositeFs,content:a,pathParams:s,author:o})}n.unflushed=[]}}async readFile(e,r){let n=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),a=null;typeof r=="string"?a=r:r&&typeof r=="object"&&r.encoding&&(a=r.encoding);let s=await this.open(n,"r");try{let d=(await this.fstat(s)).size,l=Buffer.alloc(d);return await this.read(s,l,0,d,0),await this.close(s),a?l.toString(a):l}catch(o){try{await this.close(s)}catch{}throw o}}async writeFile(e,r,n){let a="w",s="utf8",o;typeof n=="string"?s=n:n&&typeof n=="object"&&(n.flag&&(a=String(n.flag)),n.encoding&&(s=n.encoding),n.mode&&(o=typeof n.mode=="string"?parseInt(n.mode,8):n.mode));let d=await this.open(e,a,o);try{let l;typeof r=="string"?l=Buffer.from(r,s):Buffer.isBuffer(r)?l=r:r instanceof Uint8Array?l=Buffer.from(r):ArrayBuffer.isView(r)?l=Buffer.from(r.buffer,r.byteOffset,r.byteLength):l=Buffer.from(r),await this.write(d,l,0,l.length,0)}finally{await this.close(d)}}async rename(e,r){let n=e.toString(),a=r.toString();if(!this.handler.rename)throw new Error(`Rename not supported for ${this.handler.type} files`);let s=await this.memFs.promises.access(a).then(()=>!0).catch(()=>!1),o=await this.stat(a).then(()=>!0).catch(()=>!1),d=await this.stat(n).then(()=>!0).catch(()=>!1);if(await this.memFs.promises.access(n).then(()=>!0).catch(()=>!1)){let p=ni.dirname(a);try{await this.memFs.promises.access(p)}catch{await this.memFs.promises.mkdir(p,{recursive:!0})}await this.memFs.promises.rename(e,r)}let h=this.getRouteParams(),f=await this.getAuthor();await this.handler.rename({cacheFs:this.memFs,filePath:n,userSpaceFs:this.compositeFs,newPath:a,pathParams:h,newPathParams:this.newContext?.params||{},author:f})}async fchmod(e,r){}async unlink(e){let r=e.toString();if(!this.handler.unlink)throw new Error(`Cannot unlink ${this.handler.type} files`);try{let n=this.getRouteParams(),a=await this.getAuthor();await this.handler.unlink({cacheFs:this.memFs,filePath:r,userSpaceFs:this.compositeFs,pathParams:n,author:a})}catch(n){let a=!1;for(let[s,o]of Object.entries(this.openFh))o.path===r&&o.unflushed.length>0&&(a=!0);if(!a)throw n}finally{let n=!1;for(let[a,s]of Object.entries(this.openFh))s.path===r&&(n=!0,await s.fh.close(),delete this.openFh[Number(a)]);n&&await this.memFs.promises.unlink(r)}}async rmdir(e,...r){let n=e.toString();if(!this.handler.rmdir)throw new Error(`Cannot rmdir ${this.handler.type} directories`);let a=this.getRouteParams(),s=await this.getAuthor();await this.handler.rmdir({cacheFs:this.memFs,filePath:n,userSpaceFs:this.compositeFs,pathParams:a,author:s});let o=!1;for(let[d,l]of Object.entries(this.openFh))l.path===n&&(o=!0,await l.fh.close(),delete this.openFh[Number(d)]);o&&await this.memFs.promises.rmdir(n,{recursive:!0})}fileType(){return 10}};c(ai,"CompositeSubFsAdapter");var N=ai;function rr({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"legit-virtual-file",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"legitVirtualFile",rootType:"folder",getStats:c(async n=>{let a=i+"/.git";try{return await t.promises.stat(a)}catch{throw new Error(`ENOENT: no such file or directory, stat '${a}'`)}},"getStats"),getFile:c(async n=>({type:"directory",content:[],mode:493,size:0}),"getFile"),rename(n){throw new Error("not implemented")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(rr,"createLegitVirtualFileAdapter");import li from"@legit-sdk/isomorphic-git";import Fa from"@legit-sdk/isomorphic-git";function se(t){return t.replace(/\./g,"%2E").replace(/\//g,".")}c(se,"encodeBranchNameForVfs");function H(t){return t.replace(/\./g,"/").replace(/%2E/g,".")}c(H,"decodeBranchNameFromVfs");var si="-operation";async function ne(t,i,e){let n=(await Fa.listBranches({fs:t,dir:i})).filter(a=>a.endsWith(H(e)+si))[0];return n?se(n):void 0}c(ne,"resolveOperationBranchName");import oi from"@legit-sdk/isomorphic-git";async function O(t,i){try{let e=await oi.getConfig({fs:i,dir:t,path:"user.legit-current-branch"});if(e)return se(e)}catch{}try{let e=await oi.getConfig({fs:i,dir:t,path:"init.defaultBranch"});return se(e)||"main"}catch{return"main"}}c(O,"getCurrentBranch");async function nr(t,i,e){await oi.setConfig({fs:i,dir:t,path:"user.legit-current-branch",value:H(e)})}c(nr,"setCurrentBranch");import me from"@legit-sdk/isomorphic-git";async function E(t,i,e){try{return await me.resolveRef({fs:t,dir:i,ref:`refs/heads/${H(e)}`})}catch{return}}c(E,"tryResolveRef");async function pe({dir:t,fs:i,treeOid:e,deletePathParts:r,addPathParts:n,addObj:a,addKeepIfEmpty:s,deleteKeepIfNotEmpty:o,keepFilename:d=".keep",gitCache:l}){let[h,...f]=n??[],[p,...m]=r??[],u=[];if(e){let{tree:v}=await me.readTree({fs:i,dir:t,oid:e,cache:l||{}});u=[...v]}if(h===p){let v=h;if(v===void 0)throw new Error("illegal arguement - called with out a path part");if(f.length===0)throw new Error("can not move into it self");if(m.length===0)throw new Error("can not move from it self");let b=u.findIndex(P=>P.path===v),y=(b!==-1?u[b]:void 0)?.oid,_=await pe({dir:t,fs:i,treeOid:y,addPathParts:f,deletePathParts:m,addObj:a,addKeepIfEmpty:s,deleteKeepIfNotEmpty:o});if(_===void 0)throw new Error("on the same path we expect an update - respectivly a newly created subTreeOid");let w=!1;if(_!==y){w=!0;let P={mode:"040000",path:v,oid:_,type:"tree"};b!==-1?u[b]=P:u.push(P)}if(e==null&&!w)throw new Error("Illegal state - if the currentOid is undefined - a new tree should have been created (an update should have happened)");if(w)return await me.writeTree({fs:i,dir:t,tree:u});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}else{let v=!1,b;if(p){let F=u.findIndex(_=>_.path===p),y=F!==-1?u[F]:void 0;if(y===void 0)throw new Error("Element doesnt exist in tree");if(m.length>0){if(y&&y.type!=="tree")throw new Error("SubPart of the path for the obj to delete is not a tree");let _=await pe({dir:t,fs:i,treeOid:y.oid,addPathParts:void 0,deletePathParts:m,addObj:a,addKeepIfEmpty:s,deleteKeepIfNotEmpty:o});if(_===y.oid)throw new Error("in case of a delete we expect a different subtree oid");v=!0,_===void 0?u.splice(F,1):u[F]={mode:"040000",path:p,oid:_,type:"tree"}}else if(v=!0,u.splice(F,1),u.length===0&&s){let _=new Uint8Array(0),w=await me.writeBlob({fs:i,dir:t,blob:_});u.push({mode:"100644",oid:w,path:d,type:"blob"})}b=y}if(h){let F=u.findIndex(_=>_.path===h),y=F!==-1?u[F]:void 0;if(f.length>0){if(y&&y.type!=="tree")throw new Error("SubPart of the path for the obj to add is not a tree");let _=await pe({dir:t,fs:i,treeOid:y?.oid,addPathParts:f,deletePathParts:void 0,addObj:a,addKeepIfEmpty:s,deleteKeepIfNotEmpty:o});if(_===void 0)throw new Error("in case we add, we expect an update - respectivly a newly created subTreeOid");if(_!==y?.oid){v=!0;let w={mode:"040000",path:h,oid:_,type:"tree"};if(F!==-1)u[F]=w;else if(u.push(w),o&&u.length>1){let P=u.findIndex(A=>A.path===d);P!==-1&&u.splice(P,1)}}}else{if(v=!0,a){let _={mode:a.type==="tree"?"040000":"100644",path:h,oid:a.oid,type:a.type};if(F!==-1)u[F]=_;else{if(o&&u.length>0){let w=u.findIndex(P=>P.path===d);w!==-1&&u.splice(w,1)}u.push(_)}}if(s&&u.length===0){let _=new Uint8Array(0),w=await me.writeBlob({fs:i,dir:t,blob:_});u.push({mode:"100644",oid:w,path:d,type:"blob"})}}}if(u.length===0)return;if(v)return await me.writeTree({fs:i,dir:t,tree:u});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}}c(pe,"buildUpdatedTree");async function ar(t,i,e,r,n=0,a={}){let{tree:s}=await me.readTree({fs:t,dir:i,oid:e,cache:a});if(r.length===n)return{type:"tree",entries:s.map(l=>V({parent:r.join("/"),name:l.path,isDir:l.type==="tree"})),oid:e};let o=r[n],d=s.find(l=>l.path===o);if(d){if(r.length===n+1){if(d.type==="blob")return{type:"blob",oid:d.oid};if(d.type==="tree"){let l=await me.readTree({fs:t,dir:i,oid:d.oid,cache:a});return{type:"tree",entries:l.tree.map(h=>V({parent:r.join("/"),name:h.path,isDir:h.type==="tree"})),oid:l.oid}}}else if(d.type==="tree")return await ar(t,i,d.oid,r,n+1,a)}}c(ar,"findGitObjectAtPath");async function Se({filePath:t,gitRoot:i,nodeFs:e,commitSha:r,pathParams:n,gitCache:a}){let s=a||{};if(!n.filePath){let l=await me.readTree({fs:e,dir:i,oid:r,cache:s});return{type:"tree",entries:l.tree.map(f=>V({parent:t,name:f.path,isDir:f.type==="tree"})),oid:l.oid}}let o=n.filePath?n.filePath.split("/"):[];return await ar(e,i,r,o,0,s)}c(Se,"resolveGitObjAtPath");function sr({gitStorageFs:t,gitRoot:i,rootPath:e}){let r={type:"gitBranchOperationsVirtualFile",rootType:"file",getStats:c(async a=>{let{pathParams:s}=a;s.branchName===void 0&&(s.branchName=await O(i,t));let o=await ne(t,i,s.branchName),d=await li.listBranches({fs:t,dir:i}),l,h=!1;if(o){if(l=await E(t,i,o),l===void 0)throw new Error(`Base Branch ${s.branchName} for operations does not exis`);h=l!==void 0}else if(l=await E(t,i,s.branchName),l===void 0)throw new Error(`Base Branch ${s.branchName} for operations does not exis`);let f=await li.readCommit({fs:t,dir:i,oid:l}),{commit:p}=f,m=p.committer.timestamp*1e3;try{return{mode:420,size:(h?await n.handler.getFile(a):void 0)?.content?.length??0,atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m),isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:c(async a=>{let{pathParams:s}=a;s.branchName===void 0&&(s.branchName=await O(i,t));let o=await ne(t,i,s.branchName),d=[];if(o){let f=await E(t,i,o);if(f!==void 0){let p=!1,m=f;for(;m&&!p;){let u=await li.readCommit({fs:t,dir:i,oid:m});d.push({oid:u.oid,parentOids:u.commit.parent,message:u.commit.message,originBranchOid:"unset"}),m=u.commit.parent&&u.commit.parent.length>0?u.commit.parent[0]:null,u.commit.parent.length===2&&u.commit.parent[0]===u.commit.parent[1]&&(p=!0)}}}let l;for(let f=d.length-1;f>=0;f--){let p=d[f];if(l===void 0){if(p.parentOids.length!==2&&p.parentOids[0]!==p.parentOids[1])throw new Error(`Operation commit ${p.oid} does not have two parents as expected`);l=p.parentOids[1]}p.parentOids.length===2&&(l=p.parentOids[1]),p.originBranchOid=l}let h=Buffer.from(JSON.stringify(d,null,2),"utf-8");return{type:"file",content:h,mode:420,size:h.length}},"getFile"),rename:c(async function(a){throw new Error("not implemented")},"rename"),mkdir:c(async function(a){throw new Error("not implemented")},"mkdir")},n=new N({name:"branch-operations",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:r});return n}c(sr,"createBranchOperationsAdapter");import K from"@legit-sdk/isomorphic-git";import ci from"@legit-sdk/isomorphic-git/http/node";var ge="legit",or=c(({fs:t,gitRepoPath:i,serverUrl:e="https://hub.legitcontrol.com",auth:r,anonymousBranch:n,authHeaderPrefix:a="Bearer "})=>{let s=!1;async function o(b){let F=await r.getMaxAccessTokenForBranch(b);if(!F)throw new Error(`No access token for branch ${b}`);await K.fetch({fs:t,http:ci,dir:i,singleBranch:!0,ref:`${b}`,remote:ge,url:e,headers:{Authorization:`${a}${F}`}});let y=await K.resolveRef({fs:t,dir:i,ref:`${ge}/${b}`});await K.writeRef({fs:t,dir:i,ref:`refs/heads/${b}`,value:y})}c(o,"loadBranch");let d=[];async function l(){let b=await r.getMaxAccessTokenForBranch("todo");await K.fetch({fs:t,http:ci,dir:i,remote:ge,url:e,headers:{Authorization:`${a}${b}`}});let F=await K.listBranches({fs:t,dir:i});for(let y of F){if(y===n)continue;let _=`${ge}/${y}`,w,P;try{w=await K.resolveRef({fs:t,dir:i,ref:y})}catch(A){console.log(`Could not resolve local ref ${y}:`,A)}try{P=await K.resolveRef({fs:t,dir:i,ref:_})}catch{P=void 0}if(w&&P){if(w!==P){let A=await K.findMergeBase({fs:t,dir:i,oids:[w,P]});if(A[0]!==w&&A[0]!==P){let k=await K.merge({fs:t,dir:i,ours:w,theirs:P,fastForwardOnly:!1,abortOnConflict:!1,author:{name:"Your Name",email:"your.email@example.com"},mergeDriver:c(async({branches:C,contents:D,path:x})=>{let[S,te,Fe]=D;return console.log(`Merging ${C[0]} with ${C[1]}...`),console.log("merged:"),console.log(D),{cleanMerge:!0,mergedText:Fe===void 0?te:Fe}},"mergeDriver")});await K.writeRef({fs:t,dir:i,ref:`refs/heads/${y}`,value:k.oid,force:!0})}A[0]===w?(console.log(`branch ${y} differs - remote ahaed, not behind`),await K.writeRef({fs:t,dir:i,ref:`refs/heads/${y}`,value:P,force:!0})):A[0]===P?(console.log(`branch ${y} differs - local ahead, not behind`),d.push(y)):(console.log(`branch ${y} differs - both changed`),d.push(y))}}else w&&!P&&d.push(y)}}c(l,"pull");async function h(b){if((await r.getUser()).type!=="local")for(let F of b){let y=await r.getMaxAccessTokenForBranch(F);await K.push({fs:t,http:ci,dir:i,remote:ge,url:e,ref:F,headers:{Authorization:`Bearer ${y}`}})}}c(h,"push");let f=Promise.resolve();async function p(b){f=f.then(()=>h(b)),await f}c(p,"sequentialPush");async function m(){await K.getConfig({fs:t,dir:i,path:`remote.${ge}.fetch`})||await K.setConfig({fs:t,dir:i,path:`remote.${ge}.fetch`,value:`+refs/heads/*:refs/remotes/${ge}/*`});try{await l();let F=[...new Set(d)].filter(y=>y.indexOf(n)===-1);await p(F),d=[]}catch(F){console.error("Error monitoring changes:",F)}finally{s&&setTimeout(m,1e3)}}c(m,"pullPushTick");function u(){s=!0,m()}c(u,"startSync");function v(){s=!1}return c(v,"stopSync"),{start:c(()=>{s||(u(),s=!0)},"start"),stop:c(()=>{v()},"stop"),isRunning:c(()=>s,"isRunning"),loadBranch:o,sequentialPush:p}},"createLegitSyncService");import R from"@legit-sdk/isomorphic-git";function Ze(t){let i=t.length;for(;--i>=0;)t[i]=0}c(Ze,"zero$1");var ba=0,Wr=1,ga=2,_a=3,va=258,Bi=29,Ft=256,dt=Ft+1+Bi,Ue=30,Ii=19,Gr=2*dt+1,Te=15,di=16,Pa=7,Ni=256,Kr=16,Xr=17,Yr=18,ki=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Bt=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),ka=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Jr=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),xa=512,we=new Array((dt+2)*2);Ze(we);var ot=new Array(Ue*2);Ze(ot);var ht=new Array(xa);Ze(ht);var ft=new Array(va-_a+1);Ze(ft);var Li=new Array(Bi);Ze(Li);var It=new Array(Ue);Ze(It);function hi(t,i,e,r,n){this.static_tree=t,this.extra_bits=i,this.extra_base=e,this.elems=r,this.max_length=n,this.has_stree=t&&t.length}c(hi,"StaticTreeDesc");var qr,Qr,en;function fi(t,i){this.dyn_tree=t,this.max_code=0,this.stat_desc=i}c(fi,"TreeDesc");var tn=c(t=>t<256?ht[t]:ht[256+(t>>>7)],"d_code"),mt=c((t,i)=>{t.pending_buf[t.pending++]=i&255,t.pending_buf[t.pending++]=i>>>8&255},"put_short"),X=c((t,i,e)=>{t.bi_valid>di-e?(t.bi_buf|=i<<t.bi_valid&65535,mt(t,t.bi_buf),t.bi_buf=i>>di-t.bi_valid,t.bi_valid+=e-di):(t.bi_buf|=i<<t.bi_valid&65535,t.bi_valid+=e)},"send_bits"),le=c((t,i,e)=>{X(t,e[i*2],e[i*2+1])},"send_code"),rn=c((t,i)=>{let e=0;do e|=t&1,t>>>=1,e<<=1;while(--i>0);return e>>>1},"bi_reverse"),Ea=c(t=>{t.bi_valid===16?(mt(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)},"bi_flush"),Da=c((t,i)=>{let e=i.dyn_tree,r=i.max_code,n=i.stat_desc.static_tree,a=i.stat_desc.has_stree,s=i.stat_desc.extra_bits,o=i.stat_desc.extra_base,d=i.stat_desc.max_length,l,h,f,p,m,u,v=0;for(p=0;p<=Te;p++)t.bl_count[p]=0;for(e[t.heap[t.heap_max]*2+1]=0,l=t.heap_max+1;l<Gr;l++)h=t.heap[l],p=e[e[h*2+1]*2+1]+1,p>d&&(p=d,v++),e[h*2+1]=p,!(h>r)&&(t.bl_count[p]++,m=0,h>=o&&(m=s[h-o]),u=e[h*2],t.opt_len+=u*(p+m),a&&(t.static_len+=u*(n[h*2+1]+m)));if(v!==0){do{for(p=d-1;t.bl_count[p]===0;)p--;t.bl_count[p]--,t.bl_count[p+1]+=2,t.bl_count[d]--,v-=2}while(v>0);for(p=d;p!==0;p--)for(h=t.bl_count[p];h!==0;)f=t.heap[--l],!(f>r)&&(e[f*2+1]!==p&&(t.opt_len+=(p-e[f*2+1])*e[f*2],e[f*2+1]=p),h--)}},"gen_bitlen"),nn=c((t,i,e)=>{let r=new Array(Te+1),n=0,a,s;for(a=1;a<=Te;a++)n=n+e[a-1]<<1,r[a]=n;for(s=0;s<=i;s++){let o=t[s*2+1];o!==0&&(t[s*2]=rn(r[o]++,o))}},"gen_codes"),Sa=c(()=>{let t,i,e,r,n,a=new Array(Te+1);for(e=0,r=0;r<Bi-1;r++)for(Li[r]=e,t=0;t<1<<ki[r];t++)ft[e++]=r;for(ft[e-1]=r,n=0,r=0;r<16;r++)for(It[r]=n,t=0;t<1<<Bt[r];t++)ht[n++]=r;for(n>>=7;r<Ue;r++)for(It[r]=n<<7,t=0;t<1<<Bt[r]-7;t++)ht[256+n++]=r;for(i=0;i<=Te;i++)a[i]=0;for(t=0;t<=143;)we[t*2+1]=8,t++,a[8]++;for(;t<=255;)we[t*2+1]=9,t++,a[9]++;for(;t<=279;)we[t*2+1]=7,t++,a[7]++;for(;t<=287;)we[t*2+1]=8,t++,a[8]++;for(nn(we,dt+1,a),t=0;t<Ue;t++)ot[t*2+1]=5,ot[t*2]=rn(t,5);qr=new hi(we,ki,Ft+1,dt,Te),Qr=new hi(ot,Bt,0,Ue,Te),en=new hi(new Array(0),ka,0,Ii,Pa)},"tr_static_init"),an=c(t=>{let i;for(i=0;i<dt;i++)t.dyn_ltree[i*2]=0;for(i=0;i<Ue;i++)t.dyn_dtree[i*2]=0;for(i=0;i<Ii;i++)t.bl_tree[i*2]=0;t.dyn_ltree[Ni*2]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},"init_block"),sn=c(t=>{t.bi_valid>8?mt(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},"bi_windup"),lr=c((t,i,e,r)=>{let n=i*2,a=e*2;return t[n]<t[a]||t[n]===t[a]&&r[i]<=r[e]},"smaller"),mi=c((t,i,e)=>{let r=t.heap[e],n=e<<1;for(;n<=t.heap_len&&(n<t.heap_len&&lr(i,t.heap[n+1],t.heap[n],t.depth)&&n++,!lr(i,r,t.heap[n],t.depth));)t.heap[e]=t.heap[n],e=n,n<<=1;t.heap[e]=r},"pqdownheap"),cr=c((t,i,e)=>{let r,n,a=0,s,o;if(t.sym_next!==0)do r=t.pending_buf[t.sym_buf+a++]&255,r+=(t.pending_buf[t.sym_buf+a++]&255)<<8,n=t.pending_buf[t.sym_buf+a++],r===0?le(t,n,i):(s=ft[n],le(t,s+Ft+1,i),o=ki[s],o!==0&&(n-=Li[s],X(t,n,o)),r--,s=tn(r),le(t,s,e),o=Bt[s],o!==0&&(r-=It[s],X(t,r,o)));while(a<t.sym_next);le(t,Ni,i)},"compress_block"),xi=c((t,i)=>{let e=i.dyn_tree,r=i.stat_desc.static_tree,n=i.stat_desc.has_stree,a=i.stat_desc.elems,s,o,d=-1,l;for(t.heap_len=0,t.heap_max=Gr,s=0;s<a;s++)e[s*2]!==0?(t.heap[++t.heap_len]=d=s,t.depth[s]=0):e[s*2+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=d<2?++d:0,e[l*2]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=r[l*2+1]);for(i.max_code=d,s=t.heap_len>>1;s>=1;s--)mi(t,e,s);l=a;do s=t.heap[1],t.heap[1]=t.heap[t.heap_len--],mi(t,e,1),o=t.heap[1],t.heap[--t.heap_max]=s,t.heap[--t.heap_max]=o,e[l*2]=e[s*2]+e[o*2],t.depth[l]=(t.depth[s]>=t.depth[o]?t.depth[s]:t.depth[o])+1,e[s*2+1]=e[o*2+1]=l,t.heap[1]=l++,mi(t,e,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],Da(t,i),nn(e,d,t.bl_count)},"build_tree"),dr=c((t,i,e)=>{let r,n=-1,a,s=i[0*2+1],o=0,d=7,l=4;for(s===0&&(d=138,l=3),i[(e+1)*2+1]=65535,r=0;r<=e;r++)a=s,s=i[(r+1)*2+1],!(++o<d&&a===s)&&(o<l?t.bl_tree[a*2]+=o:a!==0?(a!==n&&t.bl_tree[a*2]++,t.bl_tree[Kr*2]++):o<=10?t.bl_tree[Xr*2]++:t.bl_tree[Yr*2]++,o=0,n=a,s===0?(d=138,l=3):a===s?(d=6,l=3):(d=7,l=4))},"scan_tree"),hr=c((t,i,e)=>{let r,n=-1,a,s=i[0*2+1],o=0,d=7,l=4;for(s===0&&(d=138,l=3),r=0;r<=e;r++)if(a=s,s=i[(r+1)*2+1],!(++o<d&&a===s)){if(o<l)do le(t,a,t.bl_tree);while(--o!==0);else a!==0?(a!==n&&(le(t,a,t.bl_tree),o--),le(t,Kr,t.bl_tree),X(t,o-3,2)):o<=10?(le(t,Xr,t.bl_tree),X(t,o-3,3)):(le(t,Yr,t.bl_tree),X(t,o-11,7));o=0,n=a,s===0?(d=138,l=3):a===s?(d=6,l=3):(d=7,l=4)}},"send_tree"),Ta=c(t=>{let i;for(dr(t,t.dyn_ltree,t.l_desc.max_code),dr(t,t.dyn_dtree,t.d_desc.max_code),xi(t,t.bl_desc),i=Ii-1;i>=3&&t.bl_tree[Jr[i]*2+1]===0;i--);return t.opt_len+=3*(i+1)+5+5+4,i},"build_bl_tree"),Ca=c((t,i,e,r)=>{let n;for(X(t,i-257,5),X(t,e-1,5),X(t,r-4,4),n=0;n<r;n++)X(t,t.bl_tree[Jr[n]*2+1],3);hr(t,t.dyn_ltree,i-1),hr(t,t.dyn_dtree,e-1)},"send_all_trees"),Oa=c(t=>{let i=4093624447,e;for(e=0;e<=31;e++,i>>>=1)if(i&1&&t.dyn_ltree[e*2]!==0)return 0;if(t.dyn_ltree[9*2]!==0||t.dyn_ltree[10*2]!==0||t.dyn_ltree[13*2]!==0)return 1;for(e=32;e<Ft;e++)if(t.dyn_ltree[e*2]!==0)return 1;return 0},"detect_data_type"),fr=!1,Aa=c(t=>{fr||(Sa(),fr=!0),t.l_desc=new fi(t.dyn_ltree,qr),t.d_desc=new fi(t.dyn_dtree,Qr),t.bl_desc=new fi(t.bl_tree,en),t.bi_buf=0,t.bi_valid=0,an(t)},"_tr_init$1"),on=c((t,i,e,r)=>{X(t,(ba<<1)+(r?1:0),3),sn(t),mt(t,e),mt(t,~e),e&&t.pending_buf.set(t.window.subarray(i,i+e),t.pending),t.pending+=e},"_tr_stored_block$1"),Ba=c(t=>{X(t,Wr<<1,3),le(t,Ni,we),Ea(t)},"_tr_align$1"),Ia=c((t,i,e,r)=>{let n,a,s=0;t.level>0?(t.strm.data_type===2&&(t.strm.data_type=Oa(t)),xi(t,t.l_desc),xi(t,t.d_desc),s=Ta(t),n=t.opt_len+3+7>>>3,a=t.static_len+3+7>>>3,a<=n&&(n=a)):n=a=e+5,e+4<=n&&i!==-1?on(t,i,e,r):t.strategy===4||a===n?(X(t,(Wr<<1)+(r?1:0),3),cr(t,we,ot)):(X(t,(ga<<1)+(r?1:0),3),Ca(t,t.l_desc.max_code+1,t.d_desc.max_code+1,s+1),cr(t,t.dyn_ltree,t.dyn_dtree)),an(t),r&&sn(t)},"_tr_flush_block$1"),Na=c((t,i,e)=>(t.pending_buf[t.sym_buf+t.sym_next++]=i,t.pending_buf[t.sym_buf+t.sym_next++]=i>>8,t.pending_buf[t.sym_buf+t.sym_next++]=e,i===0?t.dyn_ltree[e*2]++:(t.matches++,i--,t.dyn_ltree[(ft[e]+Ft+1)*2]++,t.dyn_dtree[tn(i)*2]++),t.sym_next===t.sym_end),"_tr_tally$1"),La=Aa,za=on,Ha=Ia,$a=Na,Ma=Ba,Ra={_tr_init:La,_tr_stored_block:za,_tr_flush_block:Ha,_tr_tally:$a,_tr_align:Ma},Ua=c((t,i,e,r)=>{let n=t&65535|0,a=t>>>16&65535|0,s=0;for(;e!==0;){s=e>2e3?2e3:e,e-=s;do n=n+i[r++]|0,a=a+n|0;while(--s);n%=65521,a%=65521}return n|a<<16|0},"adler32"),pt=Ua,ja=c(()=>{let t,i=[];for(var e=0;e<256;e++){t=e;for(var r=0;r<8;r++)t=t&1?3988292384^t>>>1:t>>>1;i[e]=t}return i},"makeTable"),Va=new Uint32Array(ja()),Za=c((t,i,e,r)=>{let n=Va,a=r+e;t^=-1;for(let s=r;s<a;s++)t=t>>>8^n[(t^i[s])&255];return t^-1},"crc32"),M=Za,Ae={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},We={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},{_tr_init:Wa,_tr_stored_block:Ei,_tr_flush_block:Ga,_tr_tally:Pe,_tr_align:Ka}=Ra,{Z_NO_FLUSH:ke,Z_PARTIAL_FLUSH:Xa,Z_FULL_FLUSH:Ya,Z_FINISH:Q,Z_BLOCK:mr,Z_OK:U,Z_STREAM_END:pr,Z_STREAM_ERROR:ce,Z_DATA_ERROR:Ja,Z_BUF_ERROR:pi,Z_DEFAULT_COMPRESSION:qa,Z_FILTERED:Qa,Z_HUFFMAN_ONLY:St,Z_RLE:es,Z_FIXED:ts,Z_DEFAULT_STRATEGY:is,Z_UNKNOWN:rs,Z_DEFLATED:zt}=We,ns=9,as=15,ss=8,os=29,ls=256,Di=ls+1+os,cs=30,ds=19,hs=2*Di+1,fs=15,T=3,ve=258,de=ve+T+1,ms=32,je=42,zi=57,Si=69,Ti=73,Ci=91,Oi=103,Ce=113,at=666,Z=1,Ge=2,Be=3,Ke=4,ps=3,Oe=c((t,i)=>(t.msg=Ae[i],i),"err"),ur=c(t=>t*2-(t>4?9:0),"rank"),_e=c(t=>{let i=t.length;for(;--i>=0;)t[i]=0},"zero"),us=c(t=>{let i,e,r,n=t.w_size;i=t.hash_size,r=i;do e=t.head[--r],t.head[r]=e>=n?e-n:0;while(--i);i=n,r=i;do e=t.prev[--r],t.prev[r]=e>=n?e-n:0;while(--i)},"slide_hash"),ws=c((t,i,e)=>(i<<t.hash_shift^e)&t.hash_mask,"HASH_ZLIB"),xe=ws,Y=c(t=>{let i=t.state,e=i.pending;e>t.avail_out&&(e=t.avail_out),e!==0&&(t.output.set(i.pending_buf.subarray(i.pending_out,i.pending_out+e),t.next_out),t.next_out+=e,i.pending_out+=e,t.total_out+=e,t.avail_out-=e,i.pending-=e,i.pending===0&&(i.pending_out=0))},"flush_pending"),J=c((t,i)=>{Ga(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,i),t.block_start=t.strstart,Y(t.strm)},"flush_block_only"),B=c((t,i)=>{t.pending_buf[t.pending++]=i},"put_byte"),nt=c((t,i)=>{t.pending_buf[t.pending++]=i>>>8&255,t.pending_buf[t.pending++]=i&255},"putShortMSB"),Ai=c((t,i,e,r)=>{let n=t.avail_in;return n>r&&(n=r),n===0?0:(t.avail_in-=n,i.set(t.input.subarray(t.next_in,t.next_in+n),e),t.state.wrap===1?t.adler=pt(t.adler,i,n,e):t.state.wrap===2&&(t.adler=M(t.adler,i,n,e)),t.next_in+=n,t.total_in+=n,n)},"read_buf"),ln=c((t,i)=>{let e=t.max_chain_length,r=t.strstart,n,a,s=t.prev_length,o=t.nice_match,d=t.strstart>t.w_size-de?t.strstart-(t.w_size-de):0,l=t.window,h=t.w_mask,f=t.prev,p=t.strstart+ve,m=l[r+s-1],u=l[r+s];t.prev_length>=t.good_match&&(e>>=2),o>t.lookahead&&(o=t.lookahead);do if(n=i,!(l[n+s]!==u||l[n+s-1]!==m||l[n]!==l[r]||l[++n]!==l[r+1])){r+=2,n++;do;while(l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&r<p);if(a=ve-(p-r),r=p-ve,a>s){if(t.match_start=i,s=a,a>=o)break;m=l[r+s-1],u=l[r+s]}}while((i=f[i&h])>d&&--e!==0);return s<=t.lookahead?s:t.lookahead},"longest_match"),Ve=c(t=>{let i=t.w_size,e,r,n;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=i+(i-de)&&(t.window.set(t.window.subarray(i,i+i-r),0),t.match_start-=i,t.strstart-=i,t.block_start-=i,t.insert>t.strstart&&(t.insert=t.strstart),us(t),r+=i),t.strm.avail_in===0)break;if(e=Ai(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=e,t.lookahead+t.insert>=T)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=xe(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=xe(t,t.ins_h,t.window[n+T-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<T)););}while(t.lookahead<de&&t.strm.avail_in!==0)},"fill_window"),cn=c((t,i)=>{let e=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r,n,a,s=0,o=t.strm.avail_in;do{if(r=65535,a=t.bi_valid+42>>3,t.strm.avail_out<a||(a=t.strm.avail_out-a,n=t.strstart-t.block_start,r>n+t.strm.avail_in&&(r=n+t.strm.avail_in),r>a&&(r=a),r<e&&(r===0&&i!==Q||i===ke||r!==n+t.strm.avail_in)))break;s=i===Q&&r===n+t.strm.avail_in?1:0,Ei(t,0,0,s),t.pending_buf[t.pending-4]=r,t.pending_buf[t.pending-3]=r>>8,t.pending_buf[t.pending-2]=~r,t.pending_buf[t.pending-1]=~r>>8,Y(t.strm),n&&(n>r&&(n=r),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+n),t.strm.next_out),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n,t.block_start+=n,r-=n),r&&(Ai(t.strm,t.strm.output,t.strm.next_out,r),t.strm.next_out+=r,t.strm.avail_out-=r,t.strm.total_out+=r)}while(s===0);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),s?Ke:i!==ke&&i!==Q&&t.strm.avail_in===0&&t.strstart===t.block_start?Ge:(a=t.window_size-t.strstart,t.strm.avail_in>a&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(Ai(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,e=a>t.w_size?t.w_size:a,n=t.strstart-t.block_start,(n>=e||(n||i===Q)&&i!==ke&&t.strm.avail_in===0&&n<=a)&&(r=n>a?a:n,s=i===Q&&t.strm.avail_in===0&&r===n?1:0,Ei(t,t.block_start,r,s),t.block_start+=r,Y(t.strm)),s?Be:Z)},"deflate_stored"),ui=c((t,i)=>{let e,r;for(;;){if(t.lookahead<de){if(Ve(t),t.lookahead<de&&i===ke)return Z;if(t.lookahead===0)break}if(e=0,t.lookahead>=T&&(t.ins_h=xe(t,t.ins_h,t.window[t.strstart+T-1]),e=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),e!==0&&t.strstart-e<=t.w_size-de&&(t.match_length=ln(t,e)),t.match_length>=T)if(r=Pe(t,t.strstart-t.match_start,t.match_length-T),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=T){t.match_length--;do t.strstart++,t.ins_h=xe(t,t.ins_h,t.window[t.strstart+T-1]),e=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart;while(--t.match_length!==0);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=xe(t,t.ins_h,t.window[t.strstart+1]);else r=Pe(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(r&&(J(t,!1),t.strm.avail_out===0))return Z}return t.insert=t.strstart<T-1?t.strstart:T-1,i===Q?(J(t,!0),t.strm.avail_out===0?Be:Ke):t.sym_next&&(J(t,!1),t.strm.avail_out===0)?Z:Ge},"deflate_fast"),Me=c((t,i)=>{let e,r,n;for(;;){if(t.lookahead<de){if(Ve(t),t.lookahead<de&&i===ke)return Z;if(t.lookahead===0)break}if(e=0,t.lookahead>=T&&(t.ins_h=xe(t,t.ins_h,t.window[t.strstart+T-1]),e=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=T-1,e!==0&&t.prev_length<t.max_lazy_match&&t.strstart-e<=t.w_size-de&&(t.match_length=ln(t,e),t.match_length<=5&&(t.strategy===Qa||t.match_length===T&&t.strstart-t.match_start>4096)&&(t.match_length=T-1)),t.prev_length>=T&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-T,r=Pe(t,t.strstart-1-t.prev_match,t.prev_length-T),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=n&&(t.ins_h=xe(t,t.ins_h,t.window[t.strstart+T-1]),e=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart);while(--t.prev_length!==0);if(t.match_available=0,t.match_length=T-1,t.strstart++,r&&(J(t,!1),t.strm.avail_out===0))return Z}else if(t.match_available){if(r=Pe(t,0,t.window[t.strstart-1]),r&&J(t,!1),t.strstart++,t.lookahead--,t.strm.avail_out===0)return Z}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(r=Pe(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<T-1?t.strstart:T-1,i===Q?(J(t,!0),t.strm.avail_out===0?Be:Ke):t.sym_next&&(J(t,!1),t.strm.avail_out===0)?Z:Ge},"deflate_slow"),ys=c((t,i)=>{let e,r,n,a,s=t.window;for(;;){if(t.lookahead<=ve){if(Ve(t),t.lookahead<=ve&&i===ke)return Z;if(t.lookahead===0)break}if(t.match_length=0,t.lookahead>=T&&t.strstart>0&&(n=t.strstart-1,r=s[n],r===s[++n]&&r===s[++n]&&r===s[++n])){a=t.strstart+ve;do;while(r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&n<a);t.match_length=ve-(a-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=T?(e=Pe(t,1,t.match_length-T),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(e=Pe(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),e&&(J(t,!1),t.strm.avail_out===0))return Z}return t.insert=0,i===Q?(J(t,!0),t.strm.avail_out===0?Be:Ke):t.sym_next&&(J(t,!1),t.strm.avail_out===0)?Z:Ge},"deflate_rle"),Fs=c((t,i)=>{let e;for(;;){if(t.lookahead===0&&(Ve(t),t.lookahead===0)){if(i===ke)return Z;break}if(t.match_length=0,e=Pe(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,e&&(J(t,!1),t.strm.avail_out===0))return Z}return t.insert=0,i===Q?(J(t,!0),t.strm.avail_out===0?Be:Ke):t.sym_next&&(J(t,!1),t.strm.avail_out===0)?Z:Ge},"deflate_huff");function oe(t,i,e,r,n){this.good_length=t,this.max_lazy=i,this.nice_length=e,this.max_chain=r,this.func=n}c(oe,"Config");var st=[new oe(0,0,0,0,cn),new oe(4,4,8,4,ui),new oe(4,5,16,8,ui),new oe(4,6,32,32,ui),new oe(4,4,16,16,Me),new oe(8,16,32,32,Me),new oe(8,16,128,128,Me),new oe(8,32,128,256,Me),new oe(32,128,258,1024,Me),new oe(32,258,258,4096,Me)],bs=c(t=>{t.window_size=2*t.w_size,_e(t.head),t.max_lazy_match=st[t.level].max_lazy,t.good_match=st[t.level].good_length,t.nice_match=st[t.level].nice_length,t.max_chain_length=st[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=T-1,t.match_available=0,t.ins_h=0},"lm_init");function gs(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=zt,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(hs*2),this.dyn_dtree=new Uint16Array((2*cs+1)*2),this.bl_tree=new Uint16Array((2*ds+1)*2),_e(this.dyn_ltree),_e(this.dyn_dtree),_e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(fs+1),this.heap=new Uint16Array(2*Di+1),_e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Di+1),_e(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}c(gs,"DeflateState");var bt=c(t=>{if(!t)return 1;let i=t.state;return!i||i.strm!==t||i.status!==je&&i.status!==zi&&i.status!==Si&&i.status!==Ti&&i.status!==Ci&&i.status!==Oi&&i.status!==Ce&&i.status!==at?1:0},"deflateStateCheck"),dn=c(t=>{if(bt(t))return Oe(t,ce);t.total_in=t.total_out=0,t.data_type=rs;let i=t.state;return i.pending=0,i.pending_out=0,i.wrap<0&&(i.wrap=-i.wrap),i.status=i.wrap===2?zi:i.wrap?je:Ce,t.adler=i.wrap===2?0:1,i.last_flush=-2,Wa(i),U},"deflateResetKeep"),hn=c(t=>{let i=dn(t);return i===U&&bs(t.state),i},"deflateReset"),_s=c((t,i)=>bt(t)||t.state.wrap!==2?ce:(t.state.gzhead=i,U),"deflateSetHeader"),fn=c((t,i,e,r,n,a)=>{if(!t)return ce;let s=1;if(i===qa&&(i=6),r<0?(s=0,r=-r):r>15&&(s=2,r-=16),n<1||n>ns||e!==zt||r<8||r>15||i<0||i>9||a<0||a>ts||r===8&&s!==1)return Oe(t,ce);r===8&&(r=9);let o=new gs;return t.state=o,o.strm=t,o.status=je,o.wrap=s,o.gzhead=null,o.w_bits=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+T-1)/T),o.window=new Uint8Array(o.w_size*2),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<n+6,o.pending_buf_size=o.lit_bufsize*4,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=(o.lit_bufsize-1)*3,o.level=i,o.strategy=a,o.method=e,hn(t)},"deflateInit2"),vs=c((t,i)=>fn(t,i,zt,as,ss,is),"deflateInit"),Ps=c((t,i)=>{if(bt(t)||i>mr||i<0)return t?Oe(t,ce):ce;let e=t.state;if(!t.output||t.avail_in!==0&&!t.input||e.status===at&&i!==Q)return Oe(t,t.avail_out===0?pi:ce);let r=e.last_flush;if(e.last_flush=i,e.pending!==0){if(Y(t),t.avail_out===0)return e.last_flush=-1,U}else if(t.avail_in===0&&ur(i)<=ur(r)&&i!==Q)return Oe(t,pi);if(e.status===at&&t.avail_in!==0)return Oe(t,pi);if(e.status===je&&e.wrap===0&&(e.status=Ce),e.status===je){let n=zt+(e.w_bits-8<<4)<<8,a=-1;if(e.strategy>=St||e.level<2?a=0:e.level<6?a=1:e.level===6?a=2:a=3,n|=a<<6,e.strstart!==0&&(n|=ms),n+=31-n%31,nt(e,n),e.strstart!==0&&(nt(e,t.adler>>>16),nt(e,t.adler&65535)),t.adler=1,e.status=Ce,Y(t),e.pending!==0)return e.last_flush=-1,U}if(e.status===zi){if(t.adler=0,B(e,31),B(e,139),B(e,8),e.gzhead)B(e,(e.gzhead.text?1:0)+(e.gzhead.hcrc?2:0)+(e.gzhead.extra?4:0)+(e.gzhead.name?8:0)+(e.gzhead.comment?16:0)),B(e,e.gzhead.time&255),B(e,e.gzhead.time>>8&255),B(e,e.gzhead.time>>16&255),B(e,e.gzhead.time>>24&255),B(e,e.level===9?2:e.strategy>=St||e.level<2?4:0),B(e,e.gzhead.os&255),e.gzhead.extra&&e.gzhead.extra.length&&(B(e,e.gzhead.extra.length&255),B(e,e.gzhead.extra.length>>8&255)),e.gzhead.hcrc&&(t.adler=M(t.adler,e.pending_buf,e.pending,0)),e.gzindex=0,e.status=Si;else if(B(e,0),B(e,0),B(e,0),B(e,0),B(e,0),B(e,e.level===9?2:e.strategy>=St||e.level<2?4:0),B(e,ps),e.status=Ce,Y(t),e.pending!==0)return e.last_flush=-1,U}if(e.status===Si){if(e.gzhead.extra){let n=e.pending,a=(e.gzhead.extra.length&65535)-e.gzindex;for(;e.pending+a>e.pending_buf_size;){let o=e.pending_buf_size-e.pending;if(e.pending_buf.set(e.gzhead.extra.subarray(e.gzindex,e.gzindex+o),e.pending),e.pending=e.pending_buf_size,e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),e.gzindex+=o,Y(t),e.pending!==0)return e.last_flush=-1,U;n=0,a-=o}let s=new Uint8Array(e.gzhead.extra);e.pending_buf.set(s.subarray(e.gzindex,e.gzindex+a),e.pending),e.pending+=a,e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),e.gzindex=0}e.status=Ti}if(e.status===Ti){if(e.gzhead.name){let n=e.pending,a;do{if(e.pending===e.pending_buf_size){if(e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),Y(t),e.pending!==0)return e.last_flush=-1,U;n=0}e.gzindex<e.gzhead.name.length?a=e.gzhead.name.charCodeAt(e.gzindex++)&255:a=0,B(e,a)}while(a!==0);e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),e.gzindex=0}e.status=Ci}if(e.status===Ci){if(e.gzhead.comment){let n=e.pending,a;do{if(e.pending===e.pending_buf_size){if(e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),Y(t),e.pending!==0)return e.last_flush=-1,U;n=0}e.gzindex<e.gzhead.comment.length?a=e.gzhead.comment.charCodeAt(e.gzindex++)&255:a=0,B(e,a)}while(a!==0);e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n))}e.status=Oi}if(e.status===Oi){if(e.gzhead.hcrc){if(e.pending+2>e.pending_buf_size&&(Y(t),e.pending!==0))return e.last_flush=-1,U;B(e,t.adler&255),B(e,t.adler>>8&255),t.adler=0}if(e.status=Ce,Y(t),e.pending!==0)return e.last_flush=-1,U}if(t.avail_in!==0||e.lookahead!==0||i!==ke&&e.status!==at){let n=e.level===0?cn(e,i):e.strategy===St?Fs(e,i):e.strategy===es?ys(e,i):st[e.level].func(e,i);if((n===Be||n===Ke)&&(e.status=at),n===Z||n===Be)return t.avail_out===0&&(e.last_flush=-1),U;if(n===Ge&&(i===Xa?Ka(e):i!==mr&&(Ei(e,0,0,!1),i===Ya&&(_e(e.head),e.lookahead===0&&(e.strstart=0,e.block_start=0,e.insert=0))),Y(t),t.avail_out===0))return e.last_flush=-1,U}return i!==Q?U:e.wrap<=0?pr:(e.wrap===2?(B(e,t.adler&255),B(e,t.adler>>8&255),B(e,t.adler>>16&255),B(e,t.adler>>24&255),B(e,t.total_in&255),B(e,t.total_in>>8&255),B(e,t.total_in>>16&255),B(e,t.total_in>>24&255)):(nt(e,t.adler>>>16),nt(e,t.adler&65535)),Y(t),e.wrap>0&&(e.wrap=-e.wrap),e.pending!==0?U:pr)},"deflate$2"),ks=c(t=>{if(bt(t))return ce;let i=t.state.status;return t.state=null,i===Ce?Oe(t,Ja):U},"deflateEnd"),xs=c((t,i)=>{let e=i.length;if(bt(t))return ce;let r=t.state,n=r.wrap;if(n===2||n===1&&r.status!==je||r.lookahead)return ce;if(n===1&&(t.adler=pt(t.adler,i,e,0)),r.wrap=0,e>=r.w_size){n===0&&(_e(r.head),r.strstart=0,r.block_start=0,r.insert=0);let d=new Uint8Array(r.w_size);d.set(i.subarray(e-r.w_size,e),0),i=d,e=r.w_size}let a=t.avail_in,s=t.next_in,o=t.input;for(t.avail_in=e,t.next_in=0,t.input=i,Ve(r);r.lookahead>=T;){let d=r.strstart,l=r.lookahead-(T-1);do r.ins_h=xe(r,r.ins_h,r.window[d+T-1]),r.prev[d&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=d,d++;while(--l);r.strstart=d,r.lookahead=T-1,Ve(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=T-1,r.match_available=0,t.next_in=s,t.input=o,t.avail_in=a,r.wrap=n,U},"deflateSetDictionary"),Es=vs,Ds=fn,Ss=hn,Ts=dn,Cs=_s,Os=Ps,As=ks,Bs=xs,Is="pako deflate (from Nodeca project)",lt={deflateInit:Es,deflateInit2:Ds,deflateReset:Ss,deflateResetKeep:Ts,deflateSetHeader:Cs,deflate:Os,deflateEnd:As,deflateSetDictionary:Bs,deflateInfo:Is},Ns=c((t,i)=>Object.prototype.hasOwnProperty.call(t,i),"_has"),Ls=c(function(t){let i=Array.prototype.slice.call(arguments,1);for(;i.length;){let e=i.shift();if(e){if(typeof e!="object")throw new TypeError(e+"must be non-object");for(let r in e)Ns(e,r)&&(t[r]=e[r])}}return t},"assign"),zs=c(t=>{let i=0;for(let r=0,n=t.length;r<n;r++)i+=t[r].length;let e=new Uint8Array(i);for(let r=0,n=0,a=t.length;r<a;r++){let s=t[r];e.set(s,n),n+=s.length}return e},"flattenChunks"),Ht={assign:Ls,flattenChunks:zs},mn=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{mn=!1}var ut=new Uint8Array(256);for(let t=0;t<256;t++)ut[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;ut[254]=ut[254]=1;var Hs=c(t=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(t);let i,e,r,n,a,s=t.length,o=0;for(n=0;n<s;n++)e=t.charCodeAt(n),(e&64512)===55296&&n+1<s&&(r=t.charCodeAt(n+1),(r&64512)===56320&&(e=65536+(e-55296<<10)+(r-56320),n++)),o+=e<128?1:e<2048?2:e<65536?3:4;for(i=new Uint8Array(o),a=0,n=0;a<o;n++)e=t.charCodeAt(n),(e&64512)===55296&&n+1<s&&(r=t.charCodeAt(n+1),(r&64512)===56320&&(e=65536+(e-55296<<10)+(r-56320),n++)),e<128?i[a++]=e:e<2048?(i[a++]=192|e>>>6,i[a++]=128|e&63):e<65536?(i[a++]=224|e>>>12,i[a++]=128|e>>>6&63,i[a++]=128|e&63):(i[a++]=240|e>>>18,i[a++]=128|e>>>12&63,i[a++]=128|e>>>6&63,i[a++]=128|e&63);return i},"string2buf"),$s=c((t,i)=>{if(i<65534&&t.subarray&&mn)return String.fromCharCode.apply(null,t.length===i?t:t.subarray(0,i));let e="";for(let r=0;r<i;r++)e+=String.fromCharCode(t[r]);return e},"buf2binstring"),Ms=c((t,i)=>{let e=i||t.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(t.subarray(0,i));let r,n,a=new Array(e*2);for(n=0,r=0;r<e;){let s=t[r++];if(s<128){a[n++]=s;continue}let o=ut[s];if(o>4){a[n++]=65533,r+=o-1;continue}for(s&=o===2?31:o===3?15:7;o>1&&r<e;)s=s<<6|t[r++]&63,o--;if(o>1){a[n++]=65533;continue}s<65536?a[n++]=s:(s-=65536,a[n++]=55296|s>>10&1023,a[n++]=56320|s&1023)}return $s(a,n)},"buf2string"),Rs=c((t,i)=>{i=i||t.length,i>t.length&&(i=t.length);let e=i-1;for(;e>=0&&(t[e]&192)===128;)e--;return e<0||e===0?i:e+ut[t[e]]>i?e:i},"utf8border"),wt={string2buf:Hs,buf2string:Ms,utf8border:Rs};function Us(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}c(Us,"ZStream");var pn=Us,un=Object.prototype.toString,{Z_NO_FLUSH:js,Z_SYNC_FLUSH:Vs,Z_FULL_FLUSH:Zs,Z_FINISH:Ws,Z_OK:Nt,Z_STREAM_END:Gs,Z_DEFAULT_COMPRESSION:Ks,Z_DEFAULT_STRATEGY:Xs,Z_DEFLATED:Ys}=We;function gt(t){this.options=Ht.assign({level:Ks,method:Ys,chunkSize:16384,windowBits:15,memLevel:8,strategy:Xs},t||{});let i=this.options;i.raw&&i.windowBits>0?i.windowBits=-i.windowBits:i.gzip&&i.windowBits>0&&i.windowBits<16&&(i.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new pn,this.strm.avail_out=0;let e=lt.deflateInit2(this.strm,i.level,i.method,i.windowBits,i.memLevel,i.strategy);if(e!==Nt)throw new Error(Ae[e]);if(i.header&&lt.deflateSetHeader(this.strm,i.header),i.dictionary){let r;if(typeof i.dictionary=="string"?r=wt.string2buf(i.dictionary):un.call(i.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(i.dictionary):r=i.dictionary,e=lt.deflateSetDictionary(this.strm,r),e!==Nt)throw new Error(Ae[e]);this._dict_set=!0}}c(gt,"Deflate$1");gt.prototype.push=function(t,i){let e=this.strm,r=this.options.chunkSize,n,a;if(this.ended)return!1;for(i===~~i?a=i:a=i===!0?Ws:js,typeof t=="string"?e.input=wt.string2buf(t):un.call(t)==="[object ArrayBuffer]"?e.input=new Uint8Array(t):e.input=t,e.next_in=0,e.avail_in=e.input.length;;){if(e.avail_out===0&&(e.output=new Uint8Array(r),e.next_out=0,e.avail_out=r),(a===Vs||a===Zs)&&e.avail_out<=6){this.onData(e.output.subarray(0,e.next_out)),e.avail_out=0;continue}if(n=lt.deflate(e,a),n===Gs)return e.next_out>0&&this.onData(e.output.subarray(0,e.next_out)),n=lt.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Nt;if(e.avail_out===0){this.onData(e.output);continue}if(a>0&&e.next_out>0){this.onData(e.output.subarray(0,e.next_out)),e.avail_out=0;continue}if(e.avail_in===0)break}return!0};gt.prototype.onData=function(t){this.chunks.push(t)};gt.prototype.onEnd=function(t){t===Nt&&(this.result=Ht.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Hi(t,i){let e=new gt(i);if(e.push(t,!0),e.err)throw e.msg||Ae[e.err];return e.result}c(Hi,"deflate$1");function Js(t,i){return i=i||{},i.raw=!0,Hi(t,i)}c(Js,"deflateRaw$1");function qs(t,i){return i=i||{},i.gzip=!0,Hi(t,i)}c(qs,"gzip$1");var Qs=gt,eo=Hi,to=Js,io=qs,ro=We,no={Deflate:Qs,deflate:eo,deflateRaw:to,gzip:io,constants:ro},Tt=16209,ao=16191,so=c(function(i,e){let r,n,a,s,o,d,l,h,f,p,m,u,v,b,F,y,_,w,P,A,k,C,D,x,S=i.state;r=i.next_in,D=i.input,n=r+(i.avail_in-5),a=i.next_out,x=i.output,s=a-(e-i.avail_out),o=a+(i.avail_out-257),d=S.dmax,l=S.wsize,h=S.whave,f=S.wnext,p=S.window,m=S.hold,u=S.bits,v=S.lencode,b=S.distcode,F=(1<<S.lenbits)-1,y=(1<<S.distbits)-1;e:do{u<15&&(m+=D[r++]<<u,u+=8,m+=D[r++]<<u,u+=8),_=v[m&F];t:for(;;){if(w=_>>>24,m>>>=w,u-=w,w=_>>>16&255,w===0)x[a++]=_&65535;else if(w&16){P=_&65535,w&=15,w&&(u<w&&(m+=D[r++]<<u,u+=8),P+=m&(1<<w)-1,m>>>=w,u-=w),u<15&&(m+=D[r++]<<u,u+=8,m+=D[r++]<<u,u+=8),_=b[m&y];i:for(;;){if(w=_>>>24,m>>>=w,u-=w,w=_>>>16&255,w&16){if(A=_&65535,w&=15,u<w&&(m+=D[r++]<<u,u+=8,u<w&&(m+=D[r++]<<u,u+=8)),A+=m&(1<<w)-1,A>d){i.msg="invalid distance too far back",S.mode=Tt;break e}if(m>>>=w,u-=w,w=a-s,A>w){if(w=A-w,w>h&&S.sane){i.msg="invalid distance too far back",S.mode=Tt;break e}if(k=0,C=p,f===0){if(k+=l-w,w<P){P-=w;do x[a++]=p[k++];while(--w);k=a-A,C=x}}else if(f<w){if(k+=l+f-w,w-=f,w<P){P-=w;do x[a++]=p[k++];while(--w);if(k=0,f<P){w=f,P-=w;do x[a++]=p[k++];while(--w);k=a-A,C=x}}}else if(k+=f-w,w<P){P-=w;do x[a++]=p[k++];while(--w);k=a-A,C=x}for(;P>2;)x[a++]=C[k++],x[a++]=C[k++],x[a++]=C[k++],P-=3;P&&(x[a++]=C[k++],P>1&&(x[a++]=C[k++]))}else{k=a-A;do x[a++]=x[k++],x[a++]=x[k++],x[a++]=x[k++],P-=3;while(P>2);P&&(x[a++]=x[k++],P>1&&(x[a++]=x[k++]))}}else if(w&64){i.msg="invalid distance code",S.mode=Tt;break e}else{_=b[(_&65535)+(m&(1<<w)-1)];continue i}break}}else if(w&64)if(w&32){S.mode=ao;break e}else{i.msg="invalid literal/length code",S.mode=Tt;break e}else{_=v[(_&65535)+(m&(1<<w)-1)];continue t}break}}while(r<n&&a<o);P=u>>3,r-=P,u-=P<<3,m&=(1<<u)-1,i.next_in=r,i.next_out=a,i.avail_in=r<n?5+(n-r):5-(r-n),i.avail_out=a<o?257+(o-a):257-(a-o),S.hold=m,S.bits=u},"inflate_fast"),Re=15,wr=852,yr=592,Fr=0,wi=1,br=2,oo=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lo=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),co=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),ho=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),fo=c((t,i,e,r,n,a,s,o)=>{let d=o.bits,l=0,h=0,f=0,p=0,m=0,u=0,v=0,b=0,F=0,y=0,_,w,P,A,k,C=null,D,x=new Uint16Array(Re+1),S=new Uint16Array(Re+1),te=null,Fe,Ee,He;for(l=0;l<=Re;l++)x[l]=0;for(h=0;h<r;h++)x[i[e+h]]++;for(m=d,p=Re;p>=1&&x[p]===0;p--);if(m>p&&(m=p),p===0)return n[a++]=1<<24|64<<16|0,n[a++]=1<<24|64<<16|0,o.bits=1,0;for(f=1;f<p&&x[f]===0;f++);for(m<f&&(m=f),b=1,l=1;l<=Re;l++)if(b<<=1,b-=x[l],b<0)return-1;if(b>0&&(t===Fr||p!==1))return-1;for(S[1]=0,l=1;l<Re;l++)S[l+1]=S[l]+x[l];for(h=0;h<r;h++)i[e+h]!==0&&(s[S[i[e+h]]++]=h);if(t===Fr?(C=te=s,D=20):t===wi?(C=oo,te=lo,D=257):(C=co,te=ho,D=0),y=0,h=0,l=f,k=a,u=m,v=0,P=-1,F=1<<m,A=F-1,t===wi&&F>wr||t===br&&F>yr)return 1;for(;;){Fe=l-v,s[h]+1<D?(Ee=0,He=s[h]):s[h]>=D?(Ee=te[s[h]-D],He=C[s[h]-D]):(Ee=96,He=0),_=1<<l-v,w=1<<u,f=w;do w-=_,n[k+(y>>v)+w]=Fe<<24|Ee<<16|He|0;while(w!==0);for(_=1<<l-1;y&_;)_>>=1;if(_!==0?(y&=_-1,y+=_):y=0,h++,--x[l]===0){if(l===p)break;l=i[e+s[h]]}if(l>m&&(y&A)!==P){for(v===0&&(v=m),k+=f,u=l-v,b=1<<u;u+v<p&&(b-=x[u+v],!(b<=0));)u++,b<<=1;if(F+=1<<u,t===wi&&F>wr||t===br&&F>yr)return 1;P=y&A,n[P]=m<<24|u<<16|k-a|0}}return y!==0&&(n[k+y]=l-v<<24|64<<16|0),o.bits=m,0},"inflate_table"),ct=fo,mo=0,wn=1,yn=2,{Z_FINISH:gr,Z_BLOCK:po,Z_TREES:Ct,Z_OK:Ie,Z_STREAM_END:uo,Z_NEED_DICT:wo,Z_STREAM_ERROR:ee,Z_DATA_ERROR:Fn,Z_MEM_ERROR:bn,Z_BUF_ERROR:yo,Z_DEFLATED:_r}=We,$t=16180,vr=16181,Pr=16182,kr=16183,xr=16184,Er=16185,Dr=16186,Sr=16187,Tr=16188,Cr=16189,Lt=16190,ue=16191,yi=16192,Or=16193,Fi=16194,Ar=16195,Br=16196,Ir=16197,Nr=16198,Ot=16199,At=16200,Lr=16201,zr=16202,Hr=16203,$r=16204,Mr=16205,bi=16206,Rr=16207,Ur=16208,$=16209,gn=16210,_n=16211,Fo=852,bo=592,go=15,_o=go,jr=c(t=>(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24),"zswap32");function vo(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}c(vo,"InflateState");var Ne=c(t=>{if(!t)return 1;let i=t.state;return!i||i.strm!==t||i.mode<$t||i.mode>_n?1:0},"inflateStateCheck"),vn=c(t=>{if(Ne(t))return ee;let i=t.state;return t.total_in=t.total_out=i.total=0,t.msg="",i.wrap&&(t.adler=i.wrap&1),i.mode=$t,i.last=0,i.havedict=0,i.flags=-1,i.dmax=32768,i.head=null,i.hold=0,i.bits=0,i.lencode=i.lendyn=new Int32Array(Fo),i.distcode=i.distdyn=new Int32Array(bo),i.sane=1,i.back=-1,Ie},"inflateResetKeep"),Pn=c(t=>{if(Ne(t))return ee;let i=t.state;return i.wsize=0,i.whave=0,i.wnext=0,vn(t)},"inflateReset"),kn=c((t,i)=>{let e;if(Ne(t))return ee;let r=t.state;return i<0?(e=0,i=-i):(e=(i>>4)+5,i<48&&(i&=15)),i&&(i<8||i>15)?ee:(r.window!==null&&r.wbits!==i&&(r.window=null),r.wrap=e,r.wbits=i,Pn(t))},"inflateReset2"),xn=c((t,i)=>{if(!t)return ee;let e=new vo;t.state=e,e.strm=t,e.window=null,e.mode=$t;let r=kn(t,i);return r!==Ie&&(t.state=null),r},"inflateInit2"),Po=c(t=>xn(t,_o),"inflateInit"),Vr=!0,gi,_i,ko=c(t=>{if(Vr){gi=new Int32Array(512),_i=new Int32Array(32);let i=0;for(;i<144;)t.lens[i++]=8;for(;i<256;)t.lens[i++]=9;for(;i<280;)t.lens[i++]=7;for(;i<288;)t.lens[i++]=8;for(ct(wn,t.lens,0,288,gi,0,t.work,{bits:9}),i=0;i<32;)t.lens[i++]=5;ct(yn,t.lens,0,32,_i,0,t.work,{bits:5}),Vr=!1}t.lencode=gi,t.lenbits=9,t.distcode=_i,t.distbits=5},"fixedtables"),En=c((t,i,e,r)=>{let n,a=t.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new Uint8Array(a.wsize)),r>=a.wsize?(a.window.set(i.subarray(e-a.wsize,e),0),a.wnext=0,a.whave=a.wsize):(n=a.wsize-a.wnext,n>r&&(n=r),a.window.set(i.subarray(e-r,e-r+n),a.wnext),r-=n,r?(a.window.set(i.subarray(e-r,e),0),a.wnext=r,a.whave=a.wsize):(a.wnext+=n,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=n))),0},"updatewindow"),xo=c((t,i)=>{let e,r,n,a,s,o,d,l,h,f,p,m,u,v,b=0,F,y,_,w,P,A,k,C,D=new Uint8Array(4),x,S,te=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Ne(t)||!t.output||!t.input&&t.avail_in!==0)return ee;e=t.state,e.mode===ue&&(e.mode=yi),s=t.next_out,n=t.output,d=t.avail_out,a=t.next_in,r=t.input,o=t.avail_in,l=e.hold,h=e.bits,f=o,p=d,C=Ie;e:for(;;)switch(e.mode){case $t:if(e.wrap===0){e.mode=yi;break}for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.wrap&2&&l===35615){e.wbits===0&&(e.wbits=15),e.check=0,D[0]=l&255,D[1]=l>>>8&255,e.check=M(e.check,D,2,0),l=0,h=0,e.mode=vr;break}if(e.head&&(e.head.done=!1),!(e.wrap&1)||(((l&255)<<8)+(l>>8))%31){t.msg="incorrect header check",e.mode=$;break}if((l&15)!==_r){t.msg="unknown compression method",e.mode=$;break}if(l>>>=4,h-=4,k=(l&15)+8,e.wbits===0&&(e.wbits=k),k>15||k>e.wbits){t.msg="invalid window size",e.mode=$;break}e.dmax=1<<e.wbits,e.flags=0,t.adler=e.check=1,e.mode=l&512?Cr:ue,l=0,h=0;break;case vr:for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.flags=l,(e.flags&255)!==_r){t.msg="unknown compression method",e.mode=$;break}if(e.flags&57344){t.msg="unknown header flags set",e.mode=$;break}e.head&&(e.head.text=l>>8&1),e.flags&512&&e.wrap&4&&(D[0]=l&255,D[1]=l>>>8&255,e.check=M(e.check,D,2,0)),l=0,h=0,e.mode=Pr;case Pr:for(;h<32;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.head&&(e.head.time=l),e.flags&512&&e.wrap&4&&(D[0]=l&255,D[1]=l>>>8&255,D[2]=l>>>16&255,D[3]=l>>>24&255,e.check=M(e.check,D,4,0)),l=0,h=0,e.mode=kr;case kr:for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.head&&(e.head.xflags=l&255,e.head.os=l>>8),e.flags&512&&e.wrap&4&&(D[0]=l&255,D[1]=l>>>8&255,e.check=M(e.check,D,2,0)),l=0,h=0,e.mode=xr;case xr:if(e.flags&1024){for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.length=l,e.head&&(e.head.extra_len=l),e.flags&512&&e.wrap&4&&(D[0]=l&255,D[1]=l>>>8&255,e.check=M(e.check,D,2,0)),l=0,h=0}else e.head&&(e.head.extra=null);e.mode=Er;case Er:if(e.flags&1024&&(m=e.length,m>o&&(m=o),m&&(e.head&&(k=e.head.extra_len-e.length,e.head.extra||(e.head.extra=new Uint8Array(e.head.extra_len)),e.head.extra.set(r.subarray(a,a+m),k)),e.flags&512&&e.wrap&4&&(e.check=M(e.check,r,m,a)),o-=m,a+=m,e.length-=m),e.length))break e;e.length=0,e.mode=Dr;case Dr:if(e.flags&2048){if(o===0)break e;m=0;do k=r[a+m++],e.head&&k&&e.length<65536&&(e.head.name+=String.fromCharCode(k));while(k&&m<o);if(e.flags&512&&e.wrap&4&&(e.check=M(e.check,r,m,a)),o-=m,a+=m,k)break e}else e.head&&(e.head.name=null);e.length=0,e.mode=Sr;case Sr:if(e.flags&4096){if(o===0)break e;m=0;do k=r[a+m++],e.head&&k&&e.length<65536&&(e.head.comment+=String.fromCharCode(k));while(k&&m<o);if(e.flags&512&&e.wrap&4&&(e.check=M(e.check,r,m,a)),o-=m,a+=m,k)break e}else e.head&&(e.head.comment=null);e.mode=Tr;case Tr:if(e.flags&512){for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.wrap&4&&l!==(e.check&65535)){t.msg="header crc mismatch",e.mode=$;break}l=0,h=0}e.head&&(e.head.hcrc=e.flags>>9&1,e.head.done=!0),t.adler=e.check=0,e.mode=ue;break;case Cr:for(;h<32;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}t.adler=e.check=jr(l),l=0,h=0,e.mode=Lt;case Lt:if(e.havedict===0)return t.next_out=s,t.avail_out=d,t.next_in=a,t.avail_in=o,e.hold=l,e.bits=h,wo;t.adler=e.check=1,e.mode=ue;case ue:if(i===po||i===Ct)break e;case yi:if(e.last){l>>>=h&7,h-=h&7,e.mode=bi;break}for(;h<3;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}switch(e.last=l&1,l>>>=1,h-=1,l&3){case 0:e.mode=Or;break;case 1:if(ko(e),e.mode=Ot,i===Ct){l>>>=2,h-=2;break e}break;case 2:e.mode=Br;break;case 3:t.msg="invalid block type",e.mode=$}l>>>=2,h-=2;break;case Or:for(l>>>=h&7,h-=h&7;h<32;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if((l&65535)!==(l>>>16^65535)){t.msg="invalid stored block lengths",e.mode=$;break}if(e.length=l&65535,l=0,h=0,e.mode=Fi,i===Ct)break e;case Fi:e.mode=Ar;case Ar:if(m=e.length,m){if(m>o&&(m=o),m>d&&(m=d),m===0)break e;n.set(r.subarray(a,a+m),s),o-=m,a+=m,d-=m,s+=m,e.length-=m;break}e.mode=ue;break;case Br:for(;h<14;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.nlen=(l&31)+257,l>>>=5,h-=5,e.ndist=(l&31)+1,l>>>=5,h-=5,e.ncode=(l&15)+4,l>>>=4,h-=4,e.nlen>286||e.ndist>30){t.msg="too many length or distance symbols",e.mode=$;break}e.have=0,e.mode=Ir;case Ir:for(;e.have<e.ncode;){for(;h<3;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.lens[te[e.have++]]=l&7,l>>>=3,h-=3}for(;e.have<19;)e.lens[te[e.have++]]=0;if(e.lencode=e.lendyn,e.lenbits=7,x={bits:e.lenbits},C=ct(mo,e.lens,0,19,e.lencode,0,e.work,x),e.lenbits=x.bits,C){t.msg="invalid code lengths set",e.mode=$;break}e.have=0,e.mode=Nr;case Nr:for(;e.have<e.nlen+e.ndist;){for(;b=e.lencode[l&(1<<e.lenbits)-1],F=b>>>24,y=b>>>16&255,_=b&65535,!(F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(_<16)l>>>=F,h-=F,e.lens[e.have++]=_;else{if(_===16){for(S=F+2;h<S;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(l>>>=F,h-=F,e.have===0){t.msg="invalid bit length repeat",e.mode=$;break}k=e.lens[e.have-1],m=3+(l&3),l>>>=2,h-=2}else if(_===17){for(S=F+3;h<S;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}l>>>=F,h-=F,k=0,m=3+(l&7),l>>>=3,h-=3}else{for(S=F+7;h<S;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}l>>>=F,h-=F,k=0,m=11+(l&127),l>>>=7,h-=7}if(e.have+m>e.nlen+e.ndist){t.msg="invalid bit length repeat",e.mode=$;break}for(;m--;)e.lens[e.have++]=k}}if(e.mode===$)break;if(e.lens[256]===0){t.msg="invalid code -- missing end-of-block",e.mode=$;break}if(e.lenbits=9,x={bits:e.lenbits},C=ct(wn,e.lens,0,e.nlen,e.lencode,0,e.work,x),e.lenbits=x.bits,C){t.msg="invalid literal/lengths set",e.mode=$;break}if(e.distbits=6,e.distcode=e.distdyn,x={bits:e.distbits},C=ct(yn,e.lens,e.nlen,e.ndist,e.distcode,0,e.work,x),e.distbits=x.bits,C){t.msg="invalid distances set",e.mode=$;break}if(e.mode=Ot,i===Ct)break e;case Ot:e.mode=At;case At:if(o>=6&&d>=258){t.next_out=s,t.avail_out=d,t.next_in=a,t.avail_in=o,e.hold=l,e.bits=h,so(t,p),s=t.next_out,n=t.output,d=t.avail_out,a=t.next_in,r=t.input,o=t.avail_in,l=e.hold,h=e.bits,e.mode===ue&&(e.back=-1);break}for(e.back=0;b=e.lencode[l&(1<<e.lenbits)-1],F=b>>>24,y=b>>>16&255,_=b&65535,!(F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(y&&!(y&240)){for(w=F,P=y,A=_;b=e.lencode[A+((l&(1<<w+P)-1)>>w)],F=b>>>24,y=b>>>16&255,_=b&65535,!(w+F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}l>>>=w,h-=w,e.back+=w}if(l>>>=F,h-=F,e.back+=F,e.length=_,y===0){e.mode=Mr;break}if(y&32){e.back=-1,e.mode=ue;break}if(y&64){t.msg="invalid literal/length code",e.mode=$;break}e.extra=y&15,e.mode=Lr;case Lr:if(e.extra){for(S=e.extra;h<S;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.length+=l&(1<<e.extra)-1,l>>>=e.extra,h-=e.extra,e.back+=e.extra}e.was=e.length,e.mode=zr;case zr:for(;b=e.distcode[l&(1<<e.distbits)-1],F=b>>>24,y=b>>>16&255,_=b&65535,!(F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(!(y&240)){for(w=F,P=y,A=_;b=e.distcode[A+((l&(1<<w+P)-1)>>w)],F=b>>>24,y=b>>>16&255,_=b&65535,!(w+F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}l>>>=w,h-=w,e.back+=w}if(l>>>=F,h-=F,e.back+=F,y&64){t.msg="invalid distance code",e.mode=$;break}e.offset=_,e.extra=y&15,e.mode=Hr;case Hr:if(e.extra){for(S=e.extra;h<S;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.offset+=l&(1<<e.extra)-1,l>>>=e.extra,h-=e.extra,e.back+=e.extra}if(e.offset>e.dmax){t.msg="invalid distance too far back",e.mode=$;break}e.mode=$r;case $r:if(d===0)break e;if(m=p-d,e.offset>m){if(m=e.offset-m,m>e.whave&&e.sane){t.msg="invalid distance too far back",e.mode=$;break}m>e.wnext?(m-=e.wnext,u=e.wsize-m):u=e.wnext-m,m>e.length&&(m=e.length),v=e.window}else v=n,u=s-e.offset,m=e.length;m>d&&(m=d),d-=m,e.length-=m;do n[s++]=v[u++];while(--m);e.length===0&&(e.mode=At);break;case Mr:if(d===0)break e;n[s++]=e.length,d--,e.mode=At;break;case bi:if(e.wrap){for(;h<32;){if(o===0)break e;o--,l|=r[a++]<<h,h+=8}if(p-=d,t.total_out+=p,e.total+=p,e.wrap&4&&p&&(t.adler=e.check=e.flags?M(e.check,n,p,s-p):pt(e.check,n,p,s-p)),p=d,e.wrap&4&&(e.flags?l:jr(l))!==e.check){t.msg="incorrect data check",e.mode=$;break}l=0,h=0}e.mode=Rr;case Rr:if(e.wrap&&e.flags){for(;h<32;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.wrap&4&&l!==(e.total&4294967295)){t.msg="incorrect length check",e.mode=$;break}l=0,h=0}e.mode=Ur;case Ur:C=uo;break e;case $:C=Fn;break e;case gn:return bn;case _n:default:return ee}return t.next_out=s,t.avail_out=d,t.next_in=a,t.avail_in=o,e.hold=l,e.bits=h,(e.wsize||p!==t.avail_out&&e.mode<$&&(e.mode<bi||i!==gr))&&En(t,t.output,t.next_out,p-t.avail_out),f-=t.avail_in,p-=t.avail_out,t.total_in+=f,t.total_out+=p,e.total+=p,e.wrap&4&&p&&(t.adler=e.check=e.flags?M(e.check,n,p,t.next_out-p):pt(e.check,n,p,t.next_out-p)),t.data_type=e.bits+(e.last?64:0)+(e.mode===ue?128:0)+(e.mode===Ot||e.mode===Fi?256:0),(f===0&&p===0||i===gr)&&C===Ie&&(C=yo),C},"inflate$2"),Eo=c(t=>{if(Ne(t))return ee;let i=t.state;return i.window&&(i.window=null),t.state=null,Ie},"inflateEnd"),Do=c((t,i)=>{if(Ne(t))return ee;let e=t.state;return e.wrap&2?(e.head=i,i.done=!1,Ie):ee},"inflateGetHeader"),So=c((t,i)=>{let e=i.length,r,n,a;return Ne(t)||(r=t.state,r.wrap!==0&&r.mode!==Lt)?ee:r.mode===Lt&&(n=1,n=pt(n,i,e,0),n!==r.check)?Fn:(a=En(t,i,e,e),a?(r.mode=gn,bn):(r.havedict=1,Ie))},"inflateSetDictionary"),To=Pn,Co=kn,Oo=vn,Ao=Po,Bo=xn,Io=xo,No=Eo,Lo=Do,zo=So,Ho="pako inflate (from Nodeca project)",ye={inflateReset:To,inflateReset2:Co,inflateResetKeep:Oo,inflateInit:Ao,inflateInit2:Bo,inflate:Io,inflateEnd:No,inflateGetHeader:Lo,inflateSetDictionary:zo,inflateInfo:Ho};function $o(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}c($o,"GZheader");var Mo=$o,Dn=Object.prototype.toString,{Z_NO_FLUSH:Ro,Z_FINISH:Uo,Z_OK:yt,Z_STREAM_END:vi,Z_NEED_DICT:Pi,Z_STREAM_ERROR:jo,Z_DATA_ERROR:Zr,Z_MEM_ERROR:Vo}=We;function _t(t){this.options=Ht.assign({chunkSize:1024*64,windowBits:15,to:""},t||{});let i=this.options;i.raw&&i.windowBits>=0&&i.windowBits<16&&(i.windowBits=-i.windowBits,i.windowBits===0&&(i.windowBits=-15)),i.windowBits>=0&&i.windowBits<16&&!(t&&t.windowBits)&&(i.windowBits+=32),i.windowBits>15&&i.windowBits<48&&(i.windowBits&15||(i.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new pn,this.strm.avail_out=0;let e=ye.inflateInit2(this.strm,i.windowBits);if(e!==yt)throw new Error(Ae[e]);if(this.header=new Mo,ye.inflateGetHeader(this.strm,this.header),i.dictionary&&(typeof i.dictionary=="string"?i.dictionary=wt.string2buf(i.dictionary):Dn.call(i.dictionary)==="[object ArrayBuffer]"&&(i.dictionary=new Uint8Array(i.dictionary)),i.raw&&(e=ye.inflateSetDictionary(this.strm,i.dictionary),e!==yt)))throw new Error(Ae[e])}c(_t,"Inflate$1");_t.prototype.push=function(t,i){let e=this.strm,r=this.options.chunkSize,n=this.options.dictionary,a,s,o;if(this.ended)return!1;for(i===~~i?s=i:s=i===!0?Uo:Ro,Dn.call(t)==="[object ArrayBuffer]"?e.input=new Uint8Array(t):e.input=t,e.next_in=0,e.avail_in=e.input.length;;){for(e.avail_out===0&&(e.output=new Uint8Array(r),e.next_out=0,e.avail_out=r),a=ye.inflate(e,s),a===Pi&&n&&(a=ye.inflateSetDictionary(e,n),a===yt?a=ye.inflate(e,s):a===Zr&&(a=Pi));e.avail_in>0&&a===vi&&e.state.wrap>0&&t[e.next_in]!==0;)ye.inflateReset(e),a=ye.inflate(e,s);switch(a){case jo:case Zr:case Pi:case Vo:return this.onEnd(a),this.ended=!0,!1}if(o=e.avail_out,e.next_out&&(e.avail_out===0||a===vi))if(this.options.to==="string"){let d=wt.utf8border(e.output,e.next_out),l=e.next_out-d,h=wt.buf2string(e.output,d);e.next_out=l,e.avail_out=r-l,l&&e.output.set(e.output.subarray(d,d+l),0),this.onData(h)}else this.onData(e.output.length===e.next_out?e.output:e.output.subarray(0,e.next_out));if(!(a===yt&&o===0)){if(a===vi)return a=ye.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,!0;if(e.avail_in===0)break}}return!0};_t.prototype.onData=function(t){this.chunks.push(t)};_t.prototype.onEnd=function(t){t===yt&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Ht.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function $i(t,i){let e=new _t(i);if(e.push(t),e.err)throw e.msg||Ae[e.err];return e.result}c($i,"inflate$1");function Zo(t,i){return i=i||{},i.raw=!0,$i(t,i)}c(Zo,"inflateRaw$1");var Wo=_t,Go=$i,Ko=Zo,Xo=$i,Yo=We,Jo={Inflate:Wo,inflate:Go,inflateRaw:Ko,ungzip:Xo,constants:Yo},{Deflate:Bc,deflate:qo,deflateRaw:Ic,gzip:Nc}=no,{Inflate:Lc,inflate:Qo,inflateRaw:zc,ungzip:Hc}=Jo;var Sn=qo;var Tn=Qo;import{createFsFromVolume as Zi,Volume as Wi}from"memfs";var Cn=c((t,i)=>{let e={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"};return{getUser:c(async()=>e,"getUser"),signInAnonymously:c(async()=>{e.type="anonymous",e.id=crypto.randomUUID(),e.email=`anonymous-sha1-${e.id}-@legitcontrol.com`},"signInAnonymously"),addAccessToken:c(async r=>{let n=await t.getUserTokens(e.id);n.accessTokens.push(r),await t.setUserTokens(e.id,n)},"addAccessToken"),getMaxAccessTokenForBranch:c(async r=>{let n=await t.getUserTokens(e.id);if(!(n.accessTokens===void 0||n.accessTokens.length===0))return n.accessTokens[0]},"getMaxAccessTokenForBranch")}},"createSessionManager");import Bn from"@legit-sdk/isomorphic-git";function On(t){let i=JSON.stringify(t),e=new TextEncoder().encode(i),r="";return typeof btoa=="function"?r=btoa(String.fromCharCode(...e)):r=Buffer.from(e).toString("base64"),r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(On,"encodeConfigJson");function An(t){let i=t.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((t.length+3)%4),e;typeof atob=="function"?e=atob(i):e=Buffer.from(i,"base64").toString("binary");let r=Uint8Array.from(e,a=>a.charCodeAt(0)),n=new TextDecoder().decode(r);return JSON.parse(n)}c(An,"decodeConfigJson");var In="user.legit-tokens";function Nn({storageFs:t,gitRoot:i}){return{getUserTokens:c(async e=>{let r=await Bn.getConfig({fs:t,dir:i,path:In});return r?An(r):{accessTokens:[]}},"getUserTokens"),setUserTokens:c(async(e,r)=>await Bn.setConfig({fs:t,dir:i,path:In,value:On(r)}),"setUserTokens")}}c(Nn,"createGitConfigTokenStore");import I from"@legit-sdk/isomorphic-git";var Mt=class Mt extends Error{constructor(e,r){super(e);g(this,"code","ENOENT");g(this,"path");this.name="ENOENTError",this.path=r,Object.setPrototypeOf(this,Mt.prototype)}};c(Mt,"ENOENTError");var Le=Mt;function Rt(t){return t&&t.gitCache!==void 0?t.gitCache:t&&t.parentFs?Rt(t.parentFs):{}}c(Rt,"getGitCacheFromFs");function Ln({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-file",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchFileVirtualFile",rootType:"folder",getStats:c(async n=>{let{filePath:a,pathParams:s,userSpaceFs:o}=n;s.branchName===void 0&&(s.branchName=await O(i,t));let d=await E(t,i,s.branchName);if(!d)throw new Le(`ENOENT: no such file or directory, stat '${a}'`,a);let l=await Se({filePath:a,gitRoot:i,nodeFs:t,commitSha:d,pathParams:s,gitCache:Rt(o)});if(!l)throw new Le(`ENOENT: no such file or directory, stat '${a}'`,a);let h=await I.readCommit({fs:t,dir:i,oid:d}),{commit:f}=h,p=await I.log({fs:t,dir:i,ref:d,filepath:s.filePath,depth:1}),m=f.committer.timestamp*1e3,u=p.length>0?p[0].commit.committer.timestamp*1e3:m;if(l.type==="tree")return{mode:420,size:0,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!0,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:u,mtimeMs:u,ctimeMs:u,birthtimeMs:m,atime:new Date(u),mtime:new Date(u),ctime:new Date(u),birthtime:new Date(u)};{let{blob:v}=await I.readBlob({fs:t,dir:i,oid:l.oid});return{mode:420,size:v.length,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(v.length/4096),atimeMs:u,mtimeMs:u,ctimeMs:u,birthtimeMs:u,atime:new Date(u),mtime:new Date(u),ctime:new Date(u),birthtime:new Date(u)}}},"getStats"),getFile:c(async n=>{let{filePath:a,cacheFs:s,pathParams:o,userSpaceFs:d}=n;o.branchName===void 0&&(o.branchName=await O(i,t));try{let l=await E(t,i,o.branchName);if(!l){let f=await I.resolveRef({fs:t,dir:i,ref:"HEAD"});if(await I.branch({fs:t,dir:i,ref:o.branchName,object:f}),l=await E(t,i,o.branchName),!l)throw new Error("Could not create branch for getFile")}let h=await Se({filePath:a,gitRoot:i,nodeFs:t,commitSha:l,pathParams:o,gitCache:Rt(d)});if(!h)return;if(h.type==="blob"){let{blob:f}=await I.readBlob({fs:t,dir:i,oid:h.oid});return{type:"file",content:Buffer.from(f),mode:420,size:f.length,oid:h.oid}}else{let f=[];try{let m=await s.promises.stat(a);if(m&&m.isDirectory()){let u=await s.promises.readdir(a,{withFileTypes:!0});f.push(...u)}}catch{}return{type:"directory",content:Array.from(new Set([...f,...h.entries])).map(m=>({...m,name:m.name.toString(),path:`${a}`,parentPath:`${a}`})),mode:493}}}catch{return}},"getFile"),unlink:c(async n=>{let{pathParams:a,author:s}=n;if(a.branchName===void 0&&(a.branchName=await O(i,t)),!a.filePath)throw new Error("filePath should be in pathParams");let o=await E(t,i,a.branchName);if(!o)throw new Error("Invalid branch file path - branch must exist");let d=await I.readTree({fs:t,dir:i,oid:o}),l=await pe({dir:i,fs:t,treeOid:d.oid,deletePathParts:a.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(l!==d.oid){let h=await I.commit({fs:t,dir:i,message:`Delete ${a.filePath}`,tree:l,noUpdateBranch:!0,parent:[o],author:s});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(a.branchName)}`,value:h,force:!0})}},"unlink"),writeFile:c(async n=>{let{filePath:a,content:s,cacheFs:o,pathParams:d,author:l}=n;if(d.branchName===void 0&&(d.branchName=await O(i,t)),d.filePath===void 0)throw new Error("filePath should be in pathParams");let h;typeof s=="string"?h=new TextEncoder().encode(s):h=new Uint8Array(s);let f=await I.writeBlob({fs:t,dir:i,blob:h}),p=await E(t,i,d.branchName);if(!p){let v=await I.resolveRef({fs:t,dir:i,ref:"HEAD"});if(await I.branch({fs:t,dir:i,ref:H(d.branchName),object:v}),p=await E(t,i,d.branchName),!p)throw new Error("Could not create branch for writeFile")}let m=await I.readTree({fs:t,dir:i,oid:p}),u=await pe({dir:i,fs:t,treeOid:m.oid,deletePathParts:void 0,addPathParts:d.filePath.split("/"),addObj:{type:"blob",oid:f},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!1,keepFilename:".keep"});if(u!==m.oid){let v=await I.commit({fs:t,dir:i,message:`\u{1F4BE} Change '${d.filePath}'`,tree:u,noUpdateBranch:!0,parent:[p],author:l});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(d.branchName)}`,value:v,force:!0});let b=await E(t,i,d.branchName);if(v!==b)throw new Error("Failed to update branch after file deletion")}},"writeFile"),rename:c(async function(n){let{filePath:a,newPath:s,pathParams:o,newPathParams:d,author:l,userSpaceFs:h}=n;if(o.branchName===void 0&&(o.branchName=await O(i,t)),o.filePath===void 0)throw new Error("filePath should be in pathParams");if(d.branchName===void 0&&(d.branchName=await O(i,t)),d.filePath===void 0)throw new Error("filePath should be in newPathParams");let f=await E(t,i,o.branchName);if(!f)throw new Error("Invalid branch file path - source branch must exist");let p=await E(t,i,d.branchName);if(!p){let b=await I.resolveRef({fs:t,dir:i,ref:"HEAD"});if(await I.branch({fs:t,dir:i,ref:H(d.branchName),object:b}),p=await E(t,i,d.branchName),p===void 0)throw new Error("Could not create branch for rename operation")}if(d.branchName!==o.branchName)throw new Error("cross branch move not implemented yet");let m=await Se({gitRoot:i,nodeFs:t,commitSha:f,filePath:a,pathParams:o,gitCache:Rt(h)});if(m===void 0)throw new Error("no obj at path exists");let u=await pe({dir:i,fs:t,deletePathParts:o.filePath.split("/"),addPathParts:d.filePath.split("/"),addObj:m.type==="blob"?{type:"blob",oid:m.oid}:{type:"tree",oid:m.oid,entries:m.entries.map(b=>b.name.toString())},treeOid:p,addKeepIfEmpty:!0,deleteKeepIfNotEmpty:!0}),v=await I.readTree({fs:t,dir:i,oid:f});if(u!==v.oid){let b=await I.commit({fs:t,dir:i,message:`\u{1F500} Rename '${o.filePath}' to '${d.filePath}'`,tree:u,noUpdateBranch:!0,parent:[p],author:l});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(d.branchName)}`,value:b,force:!0})}},"rename"),mkdir:c(async function(n){n.pathParams.branchName===void 0&&(n.pathParams.branchName=await O(i,t));let a=await E(t,i,n.pathParams.branchName);if(n.pathParams.filePath===""&&(n.pathParams.filePath="/",a!==void 0))throw new Error("Folder exists");try{throw await this.getStats(n),new Error("Folder exists")}catch{}if(n.filePath.endsWith("/")&&(n.filePath=n.filePath.replace(/\/+$/,"")),n.pathParams&&typeof n.pathParams.filePath=="string"&&(n.pathParams.filePath=n.pathParams.filePath.replace(/\/+$/,"")),!a){let h=await I.resolveRef({fs:t,dir:i,ref:"HEAD"});if(await I.branch({fs:t,dir:i,ref:H(n.pathParams.branchName),object:h}),a=await E(t,i,n.pathParams.branchName),a===void 0)throw new Error("Could not create branch for mkdir operation")}let s=await I.readTree({fs:t,dir:i,oid:a}),o=new Uint8Array(0),d=await I.writeBlob({fs:t,dir:i,blob:o}),l=await pe({dir:i,fs:t,treeOid:s.oid,deletePathParts:void 0,addPathParts:[...n.pathParams.filePath.split("/"),".keep"],addObj:{type:"blob",oid:d},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!0,keepFilename:".keep"});if(l!==s.oid){let h=await I.commit({fs:t,dir:i,message:`\u{1F4BE} Change '${n.pathParams.filePath}'`,tree:l,noUpdateBranch:!0,parent:[a],author:n.author});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(n.pathParams.branchName)}`,value:h,force:!0})}},"mkdir"),rmdir:c(async n=>{let{pathParams:a,author:s}=n;if(a.branchName===void 0&&(a.branchName=await O(i,t)),!a.filePath)throw new Error("filePath should be in pathParams");let o=await E(t,i,a.branchName);if(!o)throw new Error("Invalid branch file path - branch must exist");let d=await I.readTree({fs:t,dir:i,oid:o}),l=await pe({dir:i,fs:t,treeOid:d.oid,deletePathParts:a.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(l!==d.oid){let h=await I.commit({fs:t,dir:i,message:`Delete ${a.filePath}`,tree:l,noUpdateBranch:!0,parent:[o],author:s});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(a.branchName)}`,value:h,force:!0})}},"rmdir")}})}c(Ln,"createBranchFileAdapter");import tl from"@legit-sdk/isomorphic-git";function zn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branches-list",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchesListVirtualFile",rootType:"folder",getStats:c(async()=>{let n=i+"/.git";try{return await t.promises.stat(n)}catch{throw new Error(`ENOENT: no such file or directory, stat '${n}'`)}},"getStats"),getFile:c(async({filePath:n})=>{try{let s=(await tl.listBranches({fs:t,dir:i})).map(o=>V({parent:n,name:se(o),isDir:!0}));return{type:"directory",content:s,mode:493,size:s}}catch(a){throw a}},"getFile"),rename:c(async n=>{throw new Error("not implemented")},"rename"),mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(zn,"createBranchesListAdapter");import vt from"@legit-sdk/isomorphic-git";function Mi(t){return t&&t.gitCache!==void 0?t.gitCache:t&&t.parentFs?Mi(t.parentFs):{}}c(Mi,"getGitCacheFromFs");function Hn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-head",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchHeadVirtualFile",rootType:"file",getStats:c(async({pathParams:n,userSpaceFs:a})=>{n.branchName===void 0&&(n.branchName=await O(i,t));let s=await E(t,i,n.branchName);if(!s)throw new Error(`Branch ${n.branchName} does not exist in the repository`);let o=await vt.readCommit({fs:t,dir:i,oid:s,cache:Mi(a)}),{commit:d}=o,l=d.committer.timestamp*1e3;return{mode:420,size:40,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:l,mtimeMs:l,ctimeMs:l,birthtimeMs:l,atime:new Date(l),mtime:new Date(l),ctime:new Date(l),birthtime:new Date(l)}},"getStats"),getFile:c(async({pathParams:n,userSpaceFs:a})=>{n.branchName===void 0&&(n.branchName=await O(i,t));try{let s;try{s=await vt.resolveRef({fs:t,dir:i,ref:n.branchName})}catch{s=await vt.resolveRef({fs:t,dir:i,ref:`refs/heads/${n.branchName}`})}return{type:"file",content:s+`
4
+ `,mode:420,size:s.length}}catch{return}},"getFile"),writeFile:c(async({content:n,pathParams:a,userSpaceFs:s})=>{a.branchName===void 0&&(a.branchName=await O(i,t));let o=n.toString().trim();try{await vt.readCommit({fs:t,dir:i,oid:o,cache:Mi(s)})}catch{throw new Error(`Commit ${o} does not exist in the repository`)}await vt.writeRef({fs:t,dir:i,ref:"refs/heads/"+a.branchName,value:o,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Hn,"createBranchHeadAdapter");import Ri from"@legit-sdk/isomorphic-git";import*as $n from"node:fs";function Ut(t){return t&&t.gitCache!==void 0?t.gitCache:t&&t.parentFs?Ut(t.parentFs):{}}c(Ut,"getGitCacheFromFs");function Mn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"commit-file",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitCommitFileVirtualFile",rootType:"file",getStats:c(async({filePath:n,pathParams:a,userSpaceFs:s})=>{if(!a.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!a.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let o=a.sha_1_1_2+a.sha1_3__40,d=await Se({filePath:n,gitRoot:i,nodeFs:t,commitSha:o,pathParams:a,gitCache:Ut(s)});if(!d)throw new Le(`ENOENT: no such file or directory, stat '${n}'`,n);let l=await Ri.readCommit({fs:$n,dir:i,oid:o}),{commit:h}=l,f=h.committer.timestamp*1e3;if(d.type==="tree")return{mode:420,size:0,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!0,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:f,mtimeMs:f,ctimeMs:f,birthtimeMs:f,atime:new Date(f),mtime:new Date(f),ctime:new Date(f),birthtime:new Date(f)};{let{blob:p}=await Ri.readBlob({fs:$n,dir:i,oid:d.oid});return{mode:420,size:p.length,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(p.length/4096),atimeMs:f,mtimeMs:f,ctimeMs:f,birthtimeMs:f,atime:new Date(f),mtime:new Date(f),ctime:new Date(f),birthtime:new Date(f)}}},"getStats"),getFile:c(async({filePath:n,pathParams:a,userSpaceFs:s})=>{if(!a.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!a.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let o=a.sha_1_1_2+a.sha1_3__40;try{let d=await Se({filePath:n,gitRoot:i,nodeFs:t,commitSha:o,pathParams:a,gitCache:Ut(s)});if(!d)return;if(d.type==="blob"){let{blob:l}=await Ri.readBlob({fs:t,dir:i,oid:d.oid,cache:Ut(s)});return{type:"file",content:Buffer.from(l),mode:420,size:l.length,oid:d.oid}}else return{type:"directory",content:Array.from(new Set([...d.entries.filter(h=>h.name!==".keep")])).map(h=>({...h,name:h.name.toString(),path:`${n}`,parentPath:`${n}`})),mode:493}}catch{return}},"getFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Mn,"createCommitFileAdapter");import Ui from"@legit-sdk/isomorphic-git";function Rn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"commit-folder",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitCommitVirtualFolder",rootType:"folder",getStats:c(async n=>{let a=i+"/.git";try{return await t.promises.stat(a)}catch{throw new Error(`ENOENT: no such file or directory, stat '${a}'`)}},"getStats"),getFile:c(async n=>{let{filePath:a,pathParams:s}=n,o=await Ui.listBranches({fs:t,dir:i}),d=new Set,l=new Set;for(let p of o){let m=`refs/heads/${p}`;try{let u=await Ui.resolveRef({fs:t,dir:i,ref:m});d.add(u)}catch{}}for(let p of d){let m=await Ui.log({fs:t,dir:i,ref:p});for(let u of m)l.add(u.oid)}if(!s.sha_1_1_2){let p=new Set;for(let u of l)if(p.add(u.slice(0,2)),p.size>=256)break;let m=Array.from(p).sort().map(u=>V({parent:a,name:u,isDir:!0}));return{type:"directory",content:m,mode:493,size:m}}let h=new Set;for(let p of l)p.startsWith(s.sha_1_1_2)&&h.add(p.slice(2,40));let f=Array.from(h).sort().map(p=>V({parent:a,name:p,isDir:!0}));return{type:"directory",content:f,mode:493,size:f.length}},"getFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Rn,"createCommitFolderAdapter");import he from"@legit-sdk/isomorphic-git";function Un({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-operation",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchOperationVirtualFile",rootType:"file",getStats:c(async n=>{let{pathParams:a}=n;a.branchName===void 0&&(a.branchName=await O(i,t));let s=await E(t,i,a.branchName);if(!s)throw new Error(`Base Branch ${a.branchName} for operations does not exis`);let o=await ne(t,i,a.branchName),d=!1;if(o)try{s=await he.resolveRef({fs:t,dir:i,ref:o}),d=!0}catch{try{s=await he.resolveRef({fs:t,dir:i,ref:`refs/heads/${o}`}),d=!0}catch{}}let l=await he.readCommit({fs:t,dir:i,oid:s}),{commit:h}=l,f=h.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:f,mtimeMs:f,ctimeMs:f,birthtimeMs:f,atime:new Date(f),mtime:new Date(f),ctime:new Date(f),birthtime:new Date(f),isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:c(async n=>{let{pathParams:a}=n;a.branchName===void 0&&(a.branchName=await O(i,t));let s=await ne(t,i,a.branchName),o,d=!1;if(s){if(o=await E(t,i,s),d=!0,!o)throw new Error(`Base Branch ${s} for operations does not exis`)}else if(o=await E(t,i,a.branchName),!o)throw new Error(`Base Branch ${a.branchName} for operations does not exis`);return{type:"file",content:Buffer.from(o),mode:420,size:o.length}},"getFile"),writeFile:c(async n=>{let{content:a,pathParams:s,author:o}=n;s.branchName===void 0&&(s.branchName=await O(i,t));let d;typeof a=="string"?d=new TextEncoder().encode(a):d=new Uint8Array(a);let l=await he.writeBlob({fs:t,dir:i,blob:d}),h=await E(t,i,s.branchName);if(!h)throw new Error("Invalid branch file path - branch doesn't exist");let f=await ne(t,i,s.branchName),p=!1;if(!f){f=s.branchName+si,await he.branch({fs:t,dir:i,ref:H(f),object:h});let y=await he.listBranches({fs:t,dir:i});p=!0}let m=await E(t,i,f),u=await he.readTree({fs:t,dir:i,oid:h}),v;a instanceof ArrayBuffer?v=Buffer.from(a).toString("utf-8"):typeof a=="string"?v=a:a instanceof Uint8Array?v=Buffer.from(a).toString("utf-8"):v=String(a);let b=!1;if(!p){let y=await he.findMergeBase({fs:t,dir:i,oids:b?[m]:[m,h]});y.length===1&&y[0]===h&&(b=!0)}let F=await he.commit({fs:t,dir:i,message:v,tree:u.oid,noUpdateBranch:!0,author:o,parent:b?p?[h,h]:[m]:[m,h]});await he.writeRef({fs:t,dir:i,ref:`refs/heads/${H(f)}`,value:F,force:!0})},"writeFile"),rename:c(async function(n){throw new Error("not implemented")},"rename"),mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Un,"createBranchOperationAdapter");import jn from"@legit-sdk/isomorphic-git";function Vn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-history",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchHistory",rootType:"file",getStats:c(async({pathParams:n})=>{n.branchName===void 0&&(n.branchName=await O(i,t));let a=await E(t,i,n.branchName);if(!a)throw new Error(`Branch ${n.branchName} does not exist`);let s=await jn.readCommit({fs:t,dir:i,oid:a}),{commit:o}=s,d=o.committer.timestamp*1e3;return{mode:420,size:1e5,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:d,mtimeMs:d,ctimeMs:d,birthtimeMs:d,atime:new Date(d),mtime:new Date(d),ctime:new Date(d),birthtime:new Date(d)}},"getStats"),getFile:c(async n=>{let{pathParams:a}=n,s=a.branchName;s===void 0&&(s=await O(i,t));let o=[];if(s){let l=await E(t,i,s),h=!1,f=l;for(;f&&!h;){let p=await jn.readCommit({fs:t,dir:i,oid:f});o.push({oid:p.oid,...p.commit}),f=p.commit.parent[0]}}let d=Buffer.from(JSON.stringify(o,null,2),"utf-8");return{type:"file",content:d,mode:420,size:d.length}},"getFile"),rename:c(async n=>{throw new Error("not implemented")},"rename"),mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Vn,"createBranchHistoryAdapter");import Xe from"@legit-sdk/isomorphic-git";function Zn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-operation-head",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchOperationHeadVirtualFile",rootType:"file",getStats:c(async n=>{let{pathParams:a}=n;a.branchName===void 0&&(a.branchName=await O(i,t));let s=await ne(t,i,a.branchName);if(!s){let f=new Date(0);return{mode:420,size:0,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:f.getTime(),mtimeMs:f.getTime(),ctimeMs:f.getTime(),birthtimeMs:f.getTime(),atime:f,mtime:f,ctime:f,birthtime:f}}let o=await E(t,i,s);if(!o)throw new Error(`Operation Branch ${s} for base branch ${a.branchName} does not exist`);let d=await Xe.readCommit({fs:t,dir:i,oid:o}),{commit:l}=d,h=l.committer.timestamp*1e3;return{mode:420,size:40,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:h,mtimeMs:h,ctimeMs:h,birthtimeMs:h,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)}},"getStats"),getFile:c(async n=>{let{pathParams:a}=n;a.branchName===void 0&&(a.branchName=await O(i,t));let s=await ne(t,i,a.branchName);if(!s)return{type:"file",content:"",mode:420,size:0};try{let o;try{o=await Xe.resolveRef({fs:t,dir:i,ref:s})}catch{o=await Xe.resolveRef({fs:t,dir:i,ref:`refs/heads/${s}`})}return{type:"file",content:o+`
5
+ `,mode:420,size:o.length}}catch{return}},"getFile"),writeFile:c(async n=>{let{content:a,pathParams:s}=n;s.branchName===void 0&&(s.branchName=await O(i,t));let o=await ne(t,i,s.branchName);if(!o)throw new Error(`Operation branch name could not be resolved for branch ${s.branchName}`);let d=await E(t,i,o),l=a.toString().trim(),h,f,p=!1;if(!d)throw new Error(`Operation branch ref could not be resolved for branch ${o}`);let m=d;for(;m&&!p;){let u=await Xe.readCommit({fs:t,dir:i,oid:m});if(u.oid===l&&(h=u.oid),m=u.commit.parent&&u.commit.parent.length>0?u.commit.parent[0]:null,u.commit.parent.length===2){if(u.commit.parent[0]===u.commit.parent[1])p=!0;else if(h!==void 0){f=u.commit.parent[1];break}}}if(h===void 0)throw new Error(`Cant rollback to ${l} couldn't find newOperationBranchHead ${h}`);if(f===void 0)throw new Error(`Cant rollback to ${l} couldn't find newBranchHead ${f}`);await Xe.writeRef({fs:t,dir:i,ref:"refs/heads/"+o,value:h,force:!0}),await Xe.writeRef({fs:t,dir:i,ref:"refs/heads/"+s.branchName,value:f,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Zn,"createBranchOperationHeadAdapter");import il from"@legit-sdk/isomorphic-git";import ji from"@legit-sdk/isomorphic-git";async function ze(t,i){try{let e=await ji.getConfig({fs:i,dir:t,path:"user.legit-reference-branch"});if(e)return se(e)}catch{}try{let e=await ji.getConfig({fs:i,dir:t,path:"init.defaultBranch"});return se(e)||"main"}catch{return"main"}}c(ze,"getReferenceBranch");async function Wn(t,i,e){await ji.setConfig({fs:i,dir:t,path:"user.legit-reference-branch",value:H(e)})}c(Wn,"setReferenceBranch");function Gn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"current-branch",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitCurrentBranchVirtualFile",rootType:"file",getStats:c(async n=>{let s=(await O(i,t)).length;return{mode:420,size:s,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(s/4096),atimeMs:Date.now(),mtimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date}},"getStats"),getFile:c(async n=>{let a=await O(i,t);return{type:"file",content:a+`
6
+ `,mode:420,size:a.length+1}},"getFile"),writeFile:c(async n=>{let{content:a}=n,s=a.toString().trim();if(!await E(t,i,s)){let d=await ze(i,t),l=await E(t,i,d);if(!l)throw new Error(`Ref branch ${d} does not exist in the repository`);await il.branch({fs:t,dir:i,ref:H(s),object:l})}await nr(i,t,s)},"writeFile"),rename(n){throw new Error("not implemented")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Gn,"createCurrentBranchAdapter");import Ye from"@legit-sdk/isomorphic-git";function Kn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"apply-changes",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitApplyCurrentChangesToVirtualFile",rootType:"file",getStats:c(async({pathParams:n,userSpaceFs:a})=>{let s=new Date(0);return{mode:420,size:40,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:s,mtimeMs:s,ctimeMs:s,birthtimeMs:s,atime:s,mtime:s,ctime:s,birthtime:s}},"getStats"),getFile:c(async({pathParams:n,userSpaceFs:a})=>{try{return{type:"file",content:`
7
+ `,mode:420,size:2}}catch{return}},"getFile"),writeFile:c(async n=>{let{content:a,userSpaceFs:s}=n,o=await O(i,t),d=await ze(i,t),l=a.toString().trim(),h=await E(t,i,o);if(!h)throw new Error(`Source branch ${o} does not exist`);let f=await E(t,i,d);if(!f)throw new Error(`Target branch ${d} does not exist`);let p=await Ye.readTree({fs:t,dir:i,oid:h});if(await Ye.readTree({fs:t,dir:i,oid:f})===p)return;let u=Math.floor(Date.now()/1e3),v=await Ye.commit({fs:t,dir:i,message:l,tree:p.oid,noUpdateBranch:!0,author:{...n.author,timestamp:u},parent:[f]}),b=await Ye.commit({fs:t,dir:i,message:"Changes from "+o+" applied to "+d,tree:p.oid,noUpdateBranch:!0,author:{...n.author,timestamp:u-3},parent:[h,v]});await Ye.writeRef({fs:t,dir:i,ref:"refs/heads/"+H(d),value:v,force:!0}),await Ye.writeRef({fs:t,dir:i,ref:"refs/heads/"+H(o),value:b,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Kn,"createApplyChangesAdapter");function Xn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"reference-branch",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitReferenceBranchVirtualFile",rootType:"file",getStats:c(async n=>{let s=(await ze(i,t)).length;return{mode:420,size:s,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(s/4096),atimeMs:Date.now(),mtimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date}},"getStats"),getFile:c(async n=>{let a=await ze(i,t);return{type:"file",content:a+`
8
+ `,mode:420,size:a.length+1}},"getFile"),writeFile:c(async n=>{let{content:a}=n,s=a.toString().trim();if(!await E(t,i,s))throw new Error(`Branch ${s} does not exist in the repository`);await Wn(i,t,s)},"writeFile"),rename(n){throw new Error("not implemented")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Xn,"createReferenceBranchAdapter");import*as Yn from"path";var Vi=class Vi extends j{constructor({name:e,rootPath:r,passThroughFs:n}){super({name:e,rootPath:r});g(this,"openFh",new Map);g(this,"targetFs");this.targetFs=n}async responsible(e){return!0}fileType(){return 4}async open(e,r,n){let a=Yn.dirname(e),s=await this.targetFs.promises.open(e,r,n);return this.openFh.set(s.fd,s),new G({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:s.fd,parentFsFileDescriptors:[]})}async access(e,r){return await this.targetFs.promises.access(e,r)}async stat(e,...r){return this.targetFs.promises.stat(e,{bigint:!1})}async lstat(e,...r){return this.targetFs.promises.lstat(e,{bigint:!1})}async opendir(e,r){let n=await this.targetFs.promises.opendir(e,r);return new be(this.compositeFs,e.toString())}async link(e,r){return await this.targetFs.promises.link(e,r)}async mkdir(e,r){await this.targetFs.promises.mkdir(e,r)}async readdir(e,...r){return this.targetFs.promises.readdir(e,...r)}async readlink(e,...r){throw new Error("not implemented")}async unlink(e){return await this.targetFs.promises.unlink(e)}async rename(e,r){return await this.targetFs.promises.rename(e,r)}async rmdir(e,r){return await this.targetFs.promises.rmdir(e,r)}async symlink(e,r,n){return await this.targetFs.promises.symlink(e,r,n)}async lookup(e){throw new Error(`lookup is not implemented for: ${z(e)}`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(this.openFh.delete(e.subFsFileDescriptor),await r.close())}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.sync()}async read(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.chmod(r)}async fchown(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.chown(r,n)}async write(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.truncate(r)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.utimes(r,n)}async writev(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.writev(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.readv(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){return this.targetFs.promises.readFile(e,r)}async writeFile(e,r,n){return this.targetFs.promises.writeFile(e,r,n)}};c(Vi,"PassThroughToAsyncFsSubFs");var jt=Vi;function Jn(t){return typeof t=="object"&&t!==null&&t!==void 0&&!Array.isArray(t)}c(Jn,"isLegitRouteFolder");function qn(t,i){let e={...t};for(let r of Object.keys(i)){let n=t[r],a=i[r];n!==void 0&&Jn(n)&&Jn(a)?e[r]=qn(n,a):e[r]=a}return e}c(qn,"mergeLegitRouteFolders");function Gi(t){return t&&t.gitCache!==void 0?t.gitCache:t&&t.parentFs?Gi(t.parentFs):{}}c(Gi,"getGitCache");async function Qh(t){let i=new Wi,e=Zi(i);return rl({...t,storageFs:t?.storageFs?t.storageFs:e,gitRoot:t?.gitRoot||"/"})}c(Qh,"openLegitFsWithMemoryFs");async function rl({storageFs:t,gitRoot:i,anonymousBranch:e="anonymous",showKeepFiles:r=!1,initialAuthor:n={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"},serverUrl:a="https://hub.legitcontrol.com",publicKey:s,ephemaralGitConfig:o=!1,additionalFilterLayers:d,routeOverrides:l}){await t.promises.readdir(i+"/.git").then(()=>!0).catch(()=>!1)||(await R.init({fs:t,dir:"/",defaultBranch:e}),await t.promises.writeFile(i+"/.gitignore",""),await t.promises.writeFile(i+"/.keep",""),await R.add({fs:t,dir:"/",filepath:".keep",cache:Gi(t)}),await R.commit({fs:t,dir:"/",message:"Initial commit",author:{name:"Test",email:"test@example.com"},cache:Gi(t)}),await R.setConfig({fs:t,dir:i,path:"init.defaultBranch",value:e})),await R.getConfig({fs:t,dir:i,path:"user.legit_user_id"})||await R.setConfig({fs:t,dir:i,path:"user.legit_user_id",value:n.name}),await R.getConfig({fs:t,dir:i,path:"user.name"})||await R.setConfig({fs:t,dir:i,path:"user.name",value:n.name}),await R.getConfig({fs:t,dir:i,path:"user.email"})||await R.setConfig({fs:t,dir:i,path:"user.email",value:n.email});let u=Zi(new Wi),v=new rt({name:"root-copy-on-write",sourceFs:t,copyToFs:u,copyToRootPath:"/copies",rootPath:i,patterns:o?["**/.git/config"]:[]}),b=new jt({name:"root-passthrough",passThroughFs:t,rootPath:i}),F=new it({name:"root",filterLayers:[v],rootPath:i,routes:{"[[...relativePath]]":b}}),y={gitStorageFs:F,gitRoot:i,rootPath:i},_=rr(y),w=Un(y),P=Hn(y),A=Zn(y),k=sr(y),C=Vn(y),D=Gn(y),x=Xn(y),S=Kn(y),te=zn(y),Fe=Ln(y),Ee=Rn(y),He=Mn(y),ea=r?[".git"]:[".git",".keep"],ta=new Et({name:"git-hidden-subfs",hiddenFiles:ea,rootPath:i}),Ji=[];try{let L=i+"/.gitignore";Ji=(await F.readFile(L,"utf8")).split(`
9
+ `).filter(fe=>fe.trim()!==""&&!fe.trim().startsWith("#")).map(fe=>fe.trim())}catch{}let ia=["**/._*","**/.DS_Store","**/.AppleDouble/","**/.AppleDB","**/.AppleDesktop","**/.Spotlight-V100","**/.TemporaryItems","**/.Trashes","**/.fseventsd","**/.VolumeIcon.icns","**/.ql_disablethumbnails","**/.~lock.*","**/lu[0-9a-zA-Z]*.tmp","**/.metaentries.json.tmp","**/**.tmp.**","**/**.sb-**",...Ji],ra=Zi(new Wi),na=new rt({name:"git-copy-on-write-subfs",sourceFs:F,copyToFs:ra,copyToRootPath:"/user-copies",rootPath:i,patterns:ia}),qi={".legit":{".":_,operation:w,head:P,operationHead:A,operationHistory:k,history:C,currentBranch:D,"reference-branch":x,"apply-changes":S,branches:{".":te,"[branchName]":{".legit":{".":_,operation:w,head:P,operationHead:A,operationHistory:k,history:C},"[[...filePath]]":Fe}},commits:{".":Ee,"[sha_1_1_2]":{".":Ee,"[sha1_3__40]":{"[[...filePath]]":He}}}},"[[...filePath]]":Fe},aa=l?qn(qi,l):qi,Qi=new it({name:"git",rootPath:i,filterLayers:[ta,na,...d||[]],routes:aa}),sa=Nn({storageFs:F,gitRoot:i}),Pt=Cn(sa,s),Zt=or({fs:t,gitRepoPath:i,serverUrl:a,auth:Pt,anonymousBranch:e}),Wt=Object.assign(Qi,{auth:Pt,sync:Zt,_storageFs:F,setLogger(L){Qi.setLoggger(L)},push:c(async L=>{},"push"),shareCurrentBranch:c(async()=>{if((await Pt.getUser()).type==="local")throw new Error("login first - for example anonymously using legitfs.auth.signInAnonymously()");let L=await Wt.getCurrentBranch();return L===e&&(L=(await Pt.getUser()).id,await R.renameBranch({fs:t,dir:i,oldref:e,ref:L})),await Zt.sequentialPush([L]),Wt.setCurrentBranch(L),L},"shareCurrentBranch"),setCurrentBranch:c(async L=>{(await R.listBranches({fs:t,dir:i})).includes(L)||await Zt?.loadBranch(L);let Je=(await R.listBranches({fs:t,dir:i})).includes(L);if(console.log("branchExistsAfter",Je),!Je)throw new Error(`Branch ${L} does not exist`);await R.setConfig({fs:t,dir:i,path:"init.defaultBranch",value:L})},"setCurrentBranch"),getCurrentBranch:c(async()=>{let L=await R.getConfig({fs:t,dir:i,path:"init.defaultBranch"});if(!L)throw new Error("No current branch set");return L},"getCurrentBranch"),loadArchive:c(async({legitArchive:L,clearExisting:$e=!1})=>{let fe=Tn(L),kt=new TextDecoder().decode(fe),Je=JSON.parse(kt),qe=new Map;if($e){let q=`${i}/.git`,ie=await t.promises.readdir(q,{withFileTypes:!0});for(let W of ie){let re=`${q}/${W.name}`;W.isDirectory()?await t.promises.rm(re,{recursive:!0,force:!0}):W.isFile()&&await t.promises.unlink(re)}}else try{let q=await R.listBranches({fs:t,dir:i});for(let ie of q){let W=await R.resolveRef({fs:t,dir:i,ref:ie});qe.set(ie,W)}}catch{}for(let[q,ie]of Object.entries(Je.files)){let W=`${i}/.git/${q}`;if(q==="config")continue;let re=Buffer.from(ie,"base64");if(q.startsWith("refs/heads/")||q.startsWith("refs/tags/")){let ae=q.replace(/^refs\/(heads|tags)\//,"");if(!qe.has(ae))await t.promises.mkdir(W.split("/").slice(0,-1).join("/"),{recursive:!0}),await t.promises.writeFile(W,re);else{let Qe=qe.get(ae),et=re.toString("utf-8").trim();try{if(await R.isDescendent({fs:t,dir:i,oid:et,ancestor:Qe})||Qe===et)await t.promises.writeFile(W,re);else{let Kt=`${ae}-conflict-${crypto.randomUUID()}`,tt=`${i}/.git/refs/heads/${Kt}`;await t.promises.mkdir(tt.split("/").slice(0,-1).join("/"),{recursive:!0}),await t.promises.writeFile(tt,re)}}catch{let Kt=`${ae}-conflict-${crypto.randomUUID()}`,tt=`${i}/.git/refs/heads/${Kt}`;await t.promises.mkdir(tt.split("/").slice(0,-1).join("/"),{recursive:!0}),await t.promises.writeFile(tt,re)}}}else await t.promises.mkdir(W.split("/").slice(0,-1).join("/"),{recursive:!0}),await t.promises.writeFile(W,re)}},"loadArchive"),saveArchive:c(async()=>{let L={version:1,files:{}};async function $e(ie,W=""){let re=await t.promises.readdir(ie,{withFileTypes:!0});for(let ae of re){let Qe=`${ie}/${ae.name}`,et=W?`${W}/${ae.name}`:ae.name;if(ae.isDirectory())await $e(Qe,et);else if(ae.isFile()){let Gt=await t.promises.readFile(Qe);L.files[et]=Buffer.from(Gt).toString("base64")}}}c($e,"readDirectoryRecursive");let fe=`${i}/.git`;try{await $e(fe)}catch(ie){console.warn("Failed to read .git folder:",ie)}let kt=JSON.stringify(L),qe=new TextEncoder().encode(kt);return Sn(qe)},"saveArchive")});return Wt}c(rl,"openLegitFs");var rf=c(t=>async i=>{if(!i.path.includes(".legit/branches/")||(i.path.match(/\.legit/g)||[]).length>1)return;let[e,r]=i.path.split(".legit/branches/"),[n,...a]=r.split("/"),s=a.join("/"),o=e+".legit/branches/"+n+"/.legit/operation",d=JSON.stringify(i.operationArgs,(l,h)=>Buffer.isBuffer(h)?{__buffer__:h.toString("base64")}:h);console.log(o,`[${i.fsName}].${i.operation}(${i.fd?i.fd.fd+" - ":""}${i.path})
10
10
 
11
- ${l}
11
+ ${d}
12
12
 
13
- `)},"createFsOperationFileLogger");export{Z as CompositeFs,C as CompositeSubFsAdapter,ee as CopyOnWriteSubFs,Ge as EphemeralSubFs,le as HiddenFileSubFs,Je as PassThroughSubFs,Ye as createBranchOperationsAdapter,Mo as createFsOperationFileLogger,Ze as createLegitSyncService,_t as openLegitFs,xo as openLegitFsWithMemoryFs};
13
+ `)},"createFsOperationFileLogger");import{Stats as sl}from"node:fs";import*as Ki from"path";import{createFsFromVolume as nl,Volume as al}from"memfs";var Xi=class Xi extends j{constructor({name:e,rootPath:r}){super({name:e,rootPath:r});g(this,"memFs");g(this,"openFh",{});this.memFs=nl(new al)}isWriteSupported(){return!0}async responsible(e){return!0}getRouteParams(){return this.context?.params||{}}getStaticSiblings(){return this.context?.staticSiblings||[]}async open(e,r,n){if(!this.isWriteSupported()&&(r.includes("w")||r.includes("a")))throw new Error("Write operations not allowed");r.includes("x");let s=!1;try{await this.getStats({path:e,context:this.context}),s=!0}catch{s=!1}let o=!1;for(let p of Object.values(this.openFh))p.path===e&&(o=!0);if((s||o)&&r.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!s&&!o&&!(r.includes("w")||r.includes("a")))throw Object.assign(new Error(`ENOENT: no such file or directory, open '${e}'`),{code:"ENOENT",errno:-2,syscall:"open",path:e});let d=Ki.dirname(e);if(await this.memFs.promises.mkdir(d,{recursive:!0}),s)try{await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let l=await this.memFs.promises.open(e,r,n),h=l.fd,f=new G({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:h,parentFsFileDescriptors:[]});return this.openFh[h]={path:e,mode:r,fh:l,unflushed:[]},(r.includes("x")||r.includes("w"))&&this.openFh[h].unflushed.push({length:0,start:0}),f}async mkdir(e,r){let n=e.toString();try{await this.createDirectory({path:n,recursive:!0,context:this.context});let a=typeof r=="object"?{...r,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,a);let s=n.split("/"),o="";for(let d=1;d<=s.length;d++){o=s.slice(0,d).join("/");try{if((await this.memFs.promises.stat(o)).isDirectory()){let h=await this.memFs.promises.open(o,"r");this.openFh[h.fd]={path:o,mode:"r",fh:h,unflushed:[]}}}catch{}}}catch(a){throw a}}async access(e,r){await this.stat(e)}async futimes(e,r,n){let a=this.openFh[e.subFsFileDescriptor];if(!a)throw new Error("Invalid file handle");return await a.fh.utimes(r,n)}async fstat(e,r){let n=this.openFh[e.subFsFileDescriptor];if(!n)throw new Error("Invalid file handle");return this.stat(n.path,r)}async ftruncate(e,r){let n=this.openFh[e.subFsFileDescriptor];if(!n)throw new Error("Invalid file handle");return n.unflushed.push({length:0,start:0}),await n.fh.truncate(r)}async stat(e,r){let n=e.toString(),a=Object.values(this.openFh).find(s=>s.path===n&&s.unflushed.length>0);return a&&a.unflushed.length>0?await a.fh.stat(r):this.getStats({path:n,context:this.context})}async lstat(e,r){return this.stat(e,r)}async readdir(e,r){let n=e.toString(),a=this.getStaticSiblings(),s=await this.readDirectory({path:n,context:this.context}),o=Array.from(new Set([...s,...a.map(d=>V({name:d.segment,parent:n,isDir:d.type==="folder"}))])).sort((d,l)=>d.name.localeCompare(l.name,void 0,{numeric:!0,sensitivity:"base"}));return r?.withFileTypes?o:o.map(d=>d.name)}async read(e,r,n,a,s){let o=e.subFsFileDescriptor,d=this.openFh[o];if(!d)throw new Error("Invalid file handle");if(d.unflushed.length===0){let l=await this.readFileContent({path:d.path,context:this.context});if(!l?.content)throw new Error("couldnt access content");let h=typeof l.content=="string"?Buffer.from(l.content):l.content,f=typeof s=="number"?s:0,p=Math.min(f+a,h.length),m=Math.max(0,p-f);return h.copy(r,n,f,f+m),{bytesRead:m,buffer:r}}return await d.fh.read(r,n,a,s)}async write(e,r,n,a,s){let o=this.openFh[e.subFsFileDescriptor];if(!o)throw new Error("Invalid file handle");let d=o.mode;if(!d.includes("w")&&!d.includes("a")&&!d.includes("+"))throw Object.assign(new Error("EBADF: bad file descriptor, write"),{code:"EBADF",errno:-9,syscall:"write"});if(o.unflushed.length===0){let p=await this.readFileContent({path:o.path,context:this.context});p&&p.content&&await this.memFs.promises.writeFile(o.path,p.content)}let l=await o.fh.write(r,n,a,s),h=n??0,f=s??0;return o.unflushed.push({start:f,length:a||r.byteLength-h+f}),l}async close(e){let r=e.subFsFileDescriptor,n=this.openFh[r];if(!n)throw new Error("Invalid file handle");try{await this.dataSync(e),await n.fh.close()}finally{delete this.openFh[r]}}async dataSync(e){let r=e.subFsFileDescriptor,n=this.openFh[r];if(!n)throw new Error("Invalid file handle");if(n.unflushed.length>0){let a=await this.memFs.promises.readFile(n.path);await this.writeFileContent({path:n.path,content:a,context:this.context}),n.unflushed=[]}}async readFile(e,r){let n=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),a=null;typeof r=="string"?a=r:r&&typeof r=="object"&&r.encoding&&(a=r.encoding);let s=await this.open(n,"r");try{let d=(await this.fstat(s)).size,l=Buffer.alloc(d);return await this.read(s,l,0,d,0),await this.close(s),a?l.toString(a):l}catch(o){try{await this.close(s)}catch{}throw o}}async writeFile(e,r,n){let a="w",s="utf8",o;typeof n=="string"?s=n:n&&typeof n=="object"&&(n.flag&&(a=String(n.flag)),n.encoding&&(s=n.encoding),n.mode&&(o=typeof n.mode=="string"?parseInt(n.mode,8):n.mode));let d=await this.open(e,a,o);try{let l;typeof r=="string"?l=Buffer.from(r,s):Buffer.isBuffer(r)?l=r:r instanceof Uint8Array?l=Buffer.from(r):ArrayBuffer.isView(r)?l=Buffer.from(r.buffer,r.byteOffset,r.byteLength):l=Buffer.from(r),await this.write(d,l,0,l.length,0)}finally{await this.close(d)}}async rename(e,r){let n=e.toString(),a=r.toString();if(await this.memFs.promises.access(n).then(()=>!0).catch(()=>!1)){let o=Ki.dirname(a);try{await this.memFs.promises.access(o)}catch{await this.memFs.promises.mkdir(o,{recursive:!0})}await this.memFs.promises.rename(e,r)}await this.renamePath({oldPath:n,newPath:a,oldContext:this.context,newContext:this.newContext||this.context})}async fchmod(e,r){}async unlink(e){let r=e.toString();try{await this.deleteFile({path:r,context:this.context})}catch(n){let a=!1;for(let[s,o]of Object.entries(this.openFh))o.path===r&&o.unflushed.length>0&&(a=!0);if(!a)throw n}finally{let n=!1;for(let[a,s]of Object.entries(this.openFh))s.path===r&&(n=!0,await s.fh.close(),delete this.openFh[Number(a)]);n&&await this.memFs.promises.unlink(r)}}async rmdir(e,...r){let n=e.toString();await this.removeDirectory({path:n,context:this.context});let a=!1;for(let[s,o]of Object.entries(this.openFh))o.path===n&&(a=!0,await o.fh.close(),delete this.openFh[Number(s)]);a&&await this.memFs.promises.rmdir(n,{recursive:!0})}fileType(){return 10}};c(Xi,"ASimpleCompositeSubfs");var Vt=Xi;var Yi=class Yi extends Vt{constructor({name:e,rootPath:r,initialData:n}){super({name:e,rootPath:r});g(this,"storage",new Map);g(this,"nextFileType",1);this.storage.set("/",{type:"directory",entries:new Set,mode:493,createdAt:new Date,modifiedAt:new Date}),n&&this.populateFromInitialData(n,"/")}_debugGetStorage(){return this.storage}populateFromInitialData(e,r){if(typeof e=="string"){this.storage.set(r,{type:"file",content:Buffer.from(e,"utf8"),mode:420,createdAt:new Date,modifiedAt:new Date});let n=this.getParentPath(r);if(n){let a=this.storage.get(n);a&&a.type==="directory"&&a.entries.add(this.getBaseName(r))}}else{let n=this.storage.get(r);if(n&&n.type==="directory")for(let[a,s]of Object.entries(e)){let o=r==="/"?`/${a}`:`${r}/${a}`;n.entries.add(a),this.populateFromInitialData(s,o)}else{let a=new Date;this.storage.set(r,{type:"directory",entries:new Set,mode:493,createdAt:a,modifiedAt:a});let s=this.getParentPath(r);if(s){let d=this.storage.get(s);d&&d.type==="directory"&&d.entries.add(this.getBaseName(r))}let o=this.storage.get(r);if(o&&o.type==="directory")for(let[d,l]of Object.entries(e)){let h=r==="/"?`/${d}`:`${r}/${d}`;o.entries.add(d),this.populateFromInitialData(l,h)}}}}fileType(){return this.nextFileType}async createDirectory(e){let{path:r,recursive:n=!1}=e,a=this.normalizePath(r);if(this.storage.has(a)){if(this.storage.get(a)?.type==="directory")return;throw Object.assign(new Error(`EEXIST: file already exists, mkdir '${r}'`),{code:"EEXIST",errno:-17,syscall:"mkdir",path:a})}if(n){let d=this.getParentPath(a);d&&d!==a&&!this.storage.has(d)&&await this.createDirectory({path:d,recursive:!0,context:e.context})}let s=new Date;this.storage.set(a,{type:"directory",entries:new Set,mode:493,createdAt:s,modifiedAt:s});let o=this.getParentPath(a);if(o){let d=this.storage.get(o);d&&d.type==="directory"&&(d.entries.add(this.getBaseName(a)),d.modifiedAt=s)}}async getStats(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!n)throw Object.assign(new Error(`ENOENT: no such file or directory, stat '${e.path}'`),{code:"ENOENT",errno:-2,syscall:"stat",path:r});let a=new sl,s=n.type==="directory"?16877:33188;return a.mode=s,a.size=n.type==="file"?n.content.length:4096,a.mtimeMs=n.modifiedAt.getTime(),a.birthtimeMs=n.createdAt.getTime(),a.ctimeMs=n.modifiedAt.getTime(),a}async readFileContent(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!(!n||n.type!=="file"))return{content:n.content}}async writeFileContent(e){let r=this.normalizePath(e.path),n=new Date,a=typeof e.content=="string"?Buffer.from(e.content,"utf8"):e.content,s=this.storage.get(r);if(s){if(s.type==="directory")throw Object.assign(new Error(`EISDIR: illegal operation on a directory, write '${e.path}'`),{code:"EISDIR",errno:-21,syscall:"write",path:r});s.content=a,s.modifiedAt=n}else{this.storage.set(r,{type:"file",content:a,mode:420,createdAt:n,modifiedAt:n});let o=this.getParentPath(r);if(o){let d=this.storage.get(o);d||(await this.createDirectory({path:o,recursive:!0,context:e.context}),d=this.storage.get(o)),d&&d.type==="directory"&&(d.entries.add(this.getBaseName(r)),d.modifiedAt=n)}}}async readDirectory(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!n)throw Object.assign(new Error(`ENOENT: no such file or directory, scandir '${e.path}'`),{code:"ENOENT",errno:-2,syscall:"scandir",path:r});if(n.type!=="directory")throw Object.assign(new Error(`ENOTDIR: not a directory, scandir '${e.path}'`),{code:"ENOTDIR",errno:-20,syscall:"scandir",path:r});let a=[];for(let s of n.entries){let o;r==="/"?o="/"+s:o=r+"/"+s;let d=this.storage.get(o);d&&a.push(V({name:s,parent:r,isDir:d.type==="directory"}))}return a}async renamePath(e){let r=this.normalizePath(e.oldPath),n=this.normalizePath(e.newPath),a=this.storage.get(r);if(!a)throw Object.assign(new Error(`ENOENT: no such file or directory, rename '${e.oldPath}'`),{code:"ENOENT",errno:-2,syscall:"rename",path:r});let s=this.getParentPath(r);if(s){let d=this.storage.get(s);d&&d.type==="directory"&&d.entries.delete(this.getBaseName(r))}this.storage.delete(r),this.storage.set(n,a),a.modifiedAt=new Date;let o=this.getParentPath(n);if(o){let d=this.storage.get(o);d&&d.type==="directory"&&(d.entries.add(this.getBaseName(n)),d.modifiedAt=new Date)}if(a.type==="directory"){let d=Array.from(a.entries);for(let l of d){let h=this.joinPath(r,l),f=this.joinPath(n,l);await this.renamePath({oldPath:h,newPath:f,oldContext:e.oldContext,newContext:e.newContext})}}}async deleteFile(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!n)throw Object.assign(new Error(`ENOENT: no such file or directory, unlink '${e.path}'`),{code:"ENOENT",errno:-2,syscall:"unlink",path:r});if(n.type==="directory")throw Object.assign(new Error(`EISDIR: illegal operation on a directory, unlink '${e.path}'`),{code:"EISDIR",errno:-21,syscall:"unlink",path:r});let a=this.getParentPath(r);if(a){let s=this.storage.get(a);s&&s.type==="directory"&&(s.entries.delete(this.getBaseName(r)),s.modifiedAt=new Date)}this.storage.delete(r)}async removeDirectory(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!n)throw Object.assign(new Error(`ENOENT: no such file or directory, rmdir '${e.path}'`),{code:"ENOENT",errno:-2,syscall:"rmdir",path:r});if(n.type!=="directory")throw Object.assign(new Error(`ENOTDIR: not a directory, rmdir '${e.path}'`),{code:"ENOTDIR",errno:-20,syscall:"rmdir",path:r});let a=Array.from(n.entries);for(let o of a){let d=this.joinPath(r,o),l=this.storage.get(d);l&&(l.type==="directory"?await this.removeDirectory({path:d,context:e.context}):await this.deleteFile({path:d,context:e.context}))}let s=this.getParentPath(r);if(s){let o=this.storage.get(s);o&&o.type==="directory"&&(o.entries.delete(this.getBaseName(r)),o.modifiedAt=new Date)}this.storage.delete(r)}normalizePath(e){if(!e||e===".")return"/";let r=e.startsWith("/")?e:"/"+e;r!=="/"&&r.endsWith("/")&&(r=r.slice(0,-1));let n=r.split("/").filter(Boolean),a=[];for(let s of n)s!=="."&&(s===".."?a.pop():a.push(s));return"/"+a.join("/")}getParentPath(e){let r=this.normalizePath(e);if(r==="/")return null;let n=r.lastIndexOf("/");return n===0?"/":r.substring(0,n)||"/"}getBaseName(e){let r=this.normalizePath(e);if(r==="/")return"";let n=r.lastIndexOf("/");return r.substring(n+1)}joinPath(...e){return"/"+e.filter(Boolean).map(n=>n.startsWith("/")?n.slice(1):n).filter(n=>n!==".").join("/")}};c(Yi,"SimpleMemorySubFs");var Qn=Yi;export{Vt as ASimpleCompositeSubfs,it as CompositeFs,N as CompositeSubFsAdapter,rt as CopyOnWriteSubFs,tr as EphemeralSubFs,Et as HiddenFileSubFs,Qn as SimpleMemorySubFs,sr as createBranchOperationsAdapter,rf as createFsOperationFileLogger,or as createLegitSyncService,rr as createLegitVirtualFileAdapter,qn as mergeLegitRouteFolders,rl as openLegitFs,Qh as openLegitFsWithMemoryFs,V as toDirEntry};
14
+ /*! Bundled license information:
15
+
16
+ pako/dist/pako.esm.mjs:
17
+ (*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) *)
18
+ */