@legit-sdk/core 0.2.0 → 0.2.2

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 ADDED
@@ -0,0 +1,11 @@
1
+ // legit-sdk server bundle (Node.js)
2
+
3
+ var Be=Object.defineProperty;var Ze=(a,i,e)=>i in a?Be(a,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[i]=e;var n=(a,i)=>Be(a,"name",{value:i,configurable:!0});var p=(a,i,e)=>Ze(a,typeof i!="symbol"?i+"":i,e);import*as pe from"path";var de=class de{constructor(i,e){p(this,"entries",[]);p(this,"currentIndex",0);p(this,"closed",!1);p(this,"compositFs");p(this,"dirPath");p(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.subFilesystems].reverse()){let t=await e.readdir(this.dirPath);for(let r of t)i.add(r)}for(let e of Array.from(i)){let t=this.dirPath+"/"+e;await this.compositFs.hiddenFilesFileSystem?.responsible(t)||this.entries.push({name:e,path:t})}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: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 ${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: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(de,"CompositeFsDir");var _=de;var me=class me{constructor(i){p(this,"delegate");p(this,"compositeFs");p(this,"_subFsFileDescriptor");p(this,"handleType","file");p(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,t,r){return await this.compositeFs.logOperationOnFileDescsriptor(this,"read",{targetBufferLength:i.length,offset:e,length:t,position:r}),await this.delegate.read(this,i,e,t,r)}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,t,r){return await this.compositeFs.logOperationOnFileDescsriptor(this,"write",{buffer:i,offset:e,length:t,position:r}),this.delegate.write(this,i,e,t,r)}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)}};n(me,"CompositFsFileHandle");var L=me;import*as Ce from"path";import{createFsFromVolume as et,Volume as tt}from"memfs";var ce=class ce{constructor({name:i,parentFs:e,gitRoot:t}){p(this,"compositFs");p(this,"gitRoot");p(this,"name");this.name=i,this.compositFs=e,this.gitRoot=t}toStr(i){return typeof i=="string"?i:Buffer.isBuffer(i)?i.toString():i&&typeof i=="object"&&"fd"in i?`FileHandle(fd=${i.fd})`:String(i)}async open(i,e,t){throw new Error(`open not implemented for: ${this.toStr(i)}`)}async access(i,e){throw new Error(`access not implemented for: ${this.toStr(i)}`)}async stat(i,e){throw new Error(`lstat not implemented for: ${this.toStr(i)}`)}async lstat(i,e){throw new Error(`lstat not implemented for: ${this.toStr(i)}`)}async opendir(i,e){throw new Error(`opendir not implemented for: ${this.toStr(i)}`)}async link(i,e){throw new Error(`link not implemented for: ${this.toStr(i)}`)}async mkdir(i,e){throw new Error(`mkdir not implemented for: ${this.toStr(i)}`)}async readdir(i,e){throw new Error(`readdir not implemented for: ${this.toStr(i)}`)}async readlink(i,...e){throw new Error(`readlink not implemented for: ${this.toStr(i)}`)}async unlink(i){throw new Error(`unlink not implemented for: ${this.toStr(i)}`)}async rename(i,e){throw new Error(`rename not implemented for: ${this.toStr(i)}`)}async rmdir(i,...e){throw new Error(`rmdir not implemented for: ${this.toStr(i)}`)}async symlink(i,e,t){throw new Error(`symlink not implemented for: ${this.toStr(e)}`)}async lookup(i){throw new Error(`lookup not implemented for: ${this.toStr(i)}`)}resolvePath(i){throw new Error(`resolvePath not implemented for fd: ${i}`)}async close(i){this.compositFs.close(i)}async dataSync(i){throw new Error(`dataSync not implemented for: ${i.subFsFileDescriptor}`)}async read(i,e,t,r,s){throw new Error(`read not implemented for: ${i.subFsFileDescriptor}`)}async appendFile(i,e,t){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,t){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,t){throw new Error(`futimes not implemented for: ${i.subFsFileDescriptor}`)}async write(i,e,t,r,s){throw new Error(`write not implemented for: ${i.subFsFileDescriptor}`)}async writev(i,e,t){throw new Error(`writev not implemented for: ${i.subFsFileDescriptor}`)}async readv(i,e,t){throw new Error(`readv not implemented for: ${i.subFsFileDescriptor}`)}async readFile(i,e){throw new Error(`readFile not implemented for: ${this.toStr(i)}`)}async writeFile(i,e,t){throw new Error(`writeFile not implemented for: ${this.toStr(i)}`)}};n(ce,"BaseCompositeSubFs");var C=ce;var he=class he extends C{constructor({name:e,parentFs:t,gitRoot:r}){super({name:e,parentFs:t,gitRoot:r});p(this,"openFh",new Map);p(this,"memFs",et(new tt));p(this,"targetFs");if(this.compositFs=t,this.gitRoot=r,this.compositFs.parentFs===void 0)throw new Error("PassThroughSubFs not allowed in root fs");this.targetFs=this.compositFs.parentFs}async responsible(e){return!0}fileType(){return 4}async open(e,t,r){let s=Ce.dirname(e),o=await this.targetFs.promises.open(e,t,r);return this.openFh.set(o.fd,o),new L({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:o.fd,parentFsFileDescriptors:[o.fd]})}async access(e,t){return await this.targetFs.promises.access(e,t)}async stat(e,t){return this.targetFs.promises.stat(e,{bigint:!1})}async lstat(e,t){return this.targetFs.promises.lstat(e,{bigint:!1})}async opendir(e,t){return await this.targetFs.promises.opendir(e,t)}async link(e,t){return await this.targetFs.promises.link(e,t)}async mkdir(e,t){let r=typeof e=="string"?e:e.toString();return await this.targetFs.promises.mkdir(r,t)}async readdir(e,...t){return this.targetFs.promises.readdir(e,...t)}async readlink(e,...t){throw new Error("not implemented")}async unlink(e){return await this.targetFs.promises.unlink(e)}async rename(e,t){return await this.targetFs.promises.rename(e,t)}async rmdir(e,t){return await this.targetFs.promises.rmdir(e,t)}async symlink(e,t,r){return await this.targetFs.promises.symlink(e,t,r)}async lookup(e){throw new Error(`lookup is not implemented for: ${this.toStr(e)}`)}async close(e){let t=this.openFh.get(e.subFsFileDescriptor);t&&(await t.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.sync()}async read(e,t,r,s,o){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.read(t,r,s,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.chmod(t)}async fchown(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.chown(t,r)}async write(e,t,r,s,o){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.write(t,r,s,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.truncate(t)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.stat(t);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.utimes(t,r)}async writev(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.readv(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,t){return typeof e=="string"||Buffer.isBuffer(e)?this.targetFs.readFile(e.toString(),t):super.readFile(e,t)}async writeFile(e,t,r){let s=typeof r=="object"&&r.flag?r.flag:"w",o=await this.targetFs.open(e,s);try{let l;if(typeof t=="string"){let d=typeof r=="object"&&r.encoding?r.encoding:"utf8";l=Buffer.from(t,d)}else Buffer.isBuffer(t)?l=t:l=Buffer.from(t);await o.write(l,0,l.length,0)}finally{await this.targetFs.close(o)}}};n(he,"PassThroughSubFs");var Q=he;import*as He from"path";import{createFsFromVolume as it,Volume as rt}from"memfs";var fe=class fe extends C{constructor({name:e,parentFs:t,gitRoot:r,passThroughFs:s}){super({name:e,parentFs:t,gitRoot:r});p(this,"openFh",new Map);p(this,"memFs",it(new rt));p(this,"targetFs");this.compositFs=t,this.gitRoot=r,this.targetFs=s}async responsible(e){return!0}fileType(){return 4}async open(e,t,r){let s=He.dirname(e),o=await this.targetFs.promises.open(e,t,r);return this.openFh.set(o.fd,o),new L({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:o.fd,parentFsFileDescriptors:[]})}async access(e,t){return await this.targetFs.promises.access(e,t)}async stat(e,...t){return this.targetFs.promises.stat(e,{bigint:!1})}async lstat(e,...t){return this.targetFs.promises.lstat(e,{bigint:!1})}async opendir(e,t){let r=await this.targetFs.promises.opendir(e,t);return new _(this.compositFs,e.toString())}async link(e,t){return await this.targetFs.promises.link(e,t)}async mkdir(e,t){await this.targetFs.promises.mkdir(e,t)}async readdir(e,...t){return this.targetFs.promises.readdir(e,...t)}async readlink(e,...t){throw new Error("not implemented")}async unlink(e){return await this.targetFs.promises.unlink(e)}async rename(e,t){return await this.targetFs.promises.rename(e,t)}async rmdir(e,t){return await this.targetFs.promises.rmdir(e,t)}async symlink(e,t,r){return await this.targetFs.promises.symlink(e,t,r)}async lookup(e){throw new Error(`lookup is not implemented for: ${this.toStr(e)}`)}async close(e){let t=this.openFh.get(e.subFsFileDescriptor);t&&(this.openFh.delete(e.subFsFileDescriptor),await t.close())}async dataSync(e){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.sync()}async read(e,t,r,s,o){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.read(t,r,s,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.chmod(t)}async fchown(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.chown(t,r)}async write(e,t,r,s,o){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.write(t,r,s,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.truncate(t)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.stat(t);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.utimes(t,r)}async writev(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.readv(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,t){return this.targetFs.promises.readFile(e,t)}async writeFile(e,t,r){return this.targetFs.promises.writeFile(e,t,r)}};n(fe,"PassThroughToAsyncFsSubFs");var Y=fe;var ue=class ue{constructor({name:i,parentFs:e,storageFs:t,gitRoot:r,defaultBranch:s="main"}){p(this,"promises");p(this,"gitRoot");p(this,"ephemeralFilesFileSystem");p(this,"hiddenFilesFileSystem");p(this,"passThroughFileSystem");p(this,"subFilesystems",[]);p(this,"parentFs");p(this,"name");p(this,"defaultBranch");p(this,"pathToFileDescriptors",new Map);p(this,"openFileHandles",new Map);p(this,"logOperation");if(this.name=i,this.parentFs=e,this.gitRoot=r,this.defaultBranch=s,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)},!e&&t){this.passThroughFileSystem=new Y({name:i+"-passthrough",passThroughFs:t,gitRoot:r,parentFs:this});return}if(!t&&e){this.passThroughFileSystem=new Q({name:i+"-passthrough",parentFs:this,gitRoot:r});return}throw new Error("invalid configuration")}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,t){if(!this.logOperation)return;let r=[];for(let[s,o]of this.pathToFileDescriptors.entries())o.includes(i.fd)&&r.push(s);if(r.length!==0)return this.logOperation?.({fsName:i.delegate.name,fd:i,path:r[0],operation:e,operationArgs:t})}getFilehandle(i){return this.openFileHandles.get(i)}setEphemeralFilesSubFs(i){this.ephemeralFilesFileSystem=i}setHiddenFilesSubFs(i){this.hiddenFilesFileSystem=i}addSubFs(i){this.subFilesystems.push(i)}async getResponsibleFs(i){if(!i.toString().startsWith(this.gitRoot)&&this.gitRoot!=="./")throw new Error("tried to access a file ("+i+") outside of the legit folder: "+this.gitRoot);if(!this.hiddenFilesFileSystem)throw new Error(this.name+" intialize hidden fs first!");if(!this.ephemeralFilesFileSystem)throw new Error(this.name+" intialize ephemeral fs first!");if(await this.hiddenFilesFileSystem.responsible(i.toString()))return this.hiddenFilesFileSystem;if(await this.ephemeralFilesFileSystem.responsible(i.toString()))return this.ephemeralFilesFileSystem;for(let e of this.subFilesystems)if(await e.responsible(i.toString()))return e;return this.passThroughFileSystem}async access(i,e){let t=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:t.name,path:i,operation:"access",operationArgs:{mode:e}}),t.access(i,e)}async opendir(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"opendir",operationArgs:{options:e}});let t=i.toString();if(!t.startsWith(this.gitRoot))throw new Error("tried to access a directory ("+t+") outside of the legit folder: "+this.gitRoot);return new _(this,t)}async mkdir(i,e){let t=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:t.name,path:i.toString(),operation:"mkdir",operationArgs:{options:e}}),t.mkdir(i,e)}async readdir(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"readdir",operationArgs:{options:e}});let t=new Set;for(let r of[...this.subFilesystems].reverse()){let s=await r.readdir(i,e);for(let o of s)await this.ephemeralFilesFileSystem?.responsible((i=="/"?"":i)+"/"+o)||t.add(o)}try{let r=await this.passThroughFileSystem.readdir(i,e);for(let s of r)await this.ephemeralFilesFileSystem?.responsible((i=="/"?"":i)+"/"+s)||t.add(s)}catch(r){if(r.code!=="ENOENT")throw new Error("error reading ephemeral fs: "+r)}try{let r=await this.ephemeralFilesFileSystem.readdir(i,e);for(let s of r)t.add(s)}catch(r){if(r.code!=="ENOENT")throw new Error("error reading ephemeral fs: "+r)}for(let r of t){let s=(i=="/"?"":i)+"/"+r;await this.hiddenFilesFileSystem.responsible(s)&&t.delete(r)}return Array.from(t)}async open(i,e,t){let r=await this.getResponsibleFs(i);await this.logOperation?.({fsName:r.name,path:i,operation:"open",operationArgs:{flags:e,mode:t}});let s=await r.open(i,e,t),o=this.getNextFileDescriptor();return s.realize(o),this.openFileHandles.set(o,s),this.pathToFileDescriptors.get(i)||this.pathToFileDescriptors.set(i,[]),this.pathToFileDescriptors.get(i).push(o),s}async close(i){try{await i.delegate.close(i)}catch(e){throw e}finally{for(let[e,t]of this.pathToFileDescriptors.entries()){let r=t.indexOf(i.fd);if(r!==-1){t.splice(r,1),t.length===0&&this.pathToFileDescriptors.delete(e);break}}this.openFileHandles.delete(i.fd)}}async stat(i,e){let t=i.toString(),r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:t,operation:"stat",operationArgs:{opts:e}}),r.stat(i)}async lstat(i,e){let t=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:t.name,path:i.toString(),operation:"lstat",operationArgs:{opts:e}}),t.lstat(i,e)}async link(i,e){throw new Error("not implemented")}async readlink(i,e){throw new Error("not implemented")}async unlink(i){return(await this.getResponsibleFs(i)).unlink(i)}async rename(i,e){if(this.hiddenFilesFileSystem){if(await this.hiddenFilesFileSystem.responsible(pe.basename(i.toString())))throw new Error("Renaming of hidden Files is not allowed "+i);if(await this.hiddenFilesFileSystem.responsible(pe.basename(e.toString())))throw new Error("Renaming to hidden Files is not allowed "+e)}let t=await this.getResponsibleFs(i),r=await this.getResponsibleFs(e);if(t===r)return await this.logOperation?.({fsName:t.name,path:i.toString(),operation:"rename",operationArgs:{oldPath:i,newPath:e}}),t.rename(i,e);let s=await t.open(i.toString(),"r");try{let o=await t.fstat(s),l=Buffer.alloc(o.size);await t.read(s,l,0,o.size,0),await t.close(s),await r.writeFile(e.toString(),l,"utf8"),await t.unlink(i)}catch(o){try{await t.close(s)}catch{}throw o}}async rmdir(i,e){let t=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:t.name,path:i.toString(),operation:"rmdir",operationArgs:{dirPath:i,options:e}}),t.rmdir(i,e)}async symlink(i,e,t){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 t=!0,r;if(typeof i=="number"){t=!1;let s=this.getFilehandle(i);if(!s)throw new Error("Invalid file descriptor");r=s}else if(typeof i=="string")r=await this.open(i,"r");else throw new Error("only filehandle and path are supported atm");try{let o=(await r.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 l=Buffer.alloc(o),{bytesRead:d}=await r.read(l,0,o,0);if(e&&typeof e.encoding=="string")return l.slice(0,d).toString(e.encoding);if(typeof e=="string"){if(e==="utf8"||e==="utf-8")return l.slice(0,d).toString(e);throw new Error("Unsupported encoding: "+e)}return l.slice(0,d)}finally{r&&t&&await r.close()}}async writeFile(i,e,t){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"writeFile",operationArgs:{data:e,options:t}});let r=typeof i!="number",s,o,l,d="w";if(typeof t=="string"?o=t:t&&typeof t=="object"&&(o=t.encoding,l=t.mode,d=t.flag||"w"),typeof i=="number"){let m=this.getFilehandle(i);if(!m)throw new Error("Invalid file descriptor");s=m}else if(typeof i=="string")s=await this.open(i,d,l);else throw new Error("only filehandle and path are supported atm");try{let m;if(typeof e=="string")m=Buffer.from(e,o||"utf8");else if(e instanceof Buffer)m=e;else if(e instanceof Uint8Array)m=Buffer.from(e);else throw new Error("Invalid data type for writeFile");let c=0;for(;c<m.length;){let{bytesWritten:h}=await s.write(m,c,m.length-c,c);c+=h}}finally{s&&r&&await s.close()}}};n(ue,"CompositeFs");var W=ue;import st from"ignore";var Fe=class Fe extends C{constructor({name:e,parentFs:t,gitRoot:r,hiddenFiles:s}){super({name:e,parentFs:t,gitRoot:r});p(this,"ig");this.ig=st(),this.ig.add(s)}async responsible(e){let t=e.replace(/\\/g,"/"),r=t.startsWith("./")?t.slice(2):t;return r=r.startsWith("/")?r.slice(1):r,r===""||r==="."?!1:this.ig.ignores(r)}fileType(){return 255}error(e){return new Error(`Access to hidden file is not allowed: ${this.toStr(e)}`)}async open(e,t,r){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 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,t){throw this.error(t)}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,t,r,s,o){throw new Error("Access to hidden file is not allowed: readFileHandle: "+e.subFsFileDescriptor)}};n(Fe,"HiddenFileSubFs");var U=Fe;import*as Z from"path";import{createFsFromVolume as nt,Volume as ot}from"memfs";import at from"ignore";var ge=class ge extends C{constructor({name:e,parentFs:t,gitRoot:r,ephemeralPatterns:s}){super({name:e,parentFs:t,gitRoot:r});p(this,"openFh",new Map);p(this,"memFs",nt(new ot));p(this,"ig");p(this,"patterns");this.compositFs=t,this.gitRoot=r,this.ig=at(),this.ig.add(s),this.patterns=s}normalizePath(e){let t=typeof e=="string"?e:e.toString();return t.startsWith("/")?t:"/"+t}async responsible(e){let t=e.replace(/\\/g,"/"),r=t.startsWith("./")?t.slice(2):t;return r=r.startsWith("/")?r.slice(1):r,r===""||r==="."?!1:this.ig.ignores(r)}fileType(){return 5}async open(e,t,r){let s=this.normalizePath(e),o=Z.dirname(s);o&&o!=="/"&&o!=="."&&await this.memFs.promises.mkdir(o,{recursive:!0});let l=await this.memFs.promises.open(s,t,r);return this.openFh.set(l.fd,l),new L({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:l.fd,parentFsFileDescriptors:[l.fd]})}async access(e,t){let r=this.normalizePath(e);return await this.memFs.promises.access(r,t)}async stat(e,t){let r=this.normalizePath(e);return this.memFs.promises.stat(r,{bigint:!1})}async lstat(e,t){let r=this.normalizePath(e);return this.memFs.promises.lstat(r,{bigint:!1})}async opendir(e,t){let r=this.normalizePath(e);return await this.memFs.promises.opendir(r,t)}async link(e,t){let r=this.normalizePath(e),s=this.normalizePath(t);return await this.memFs.promises.link(r,s)}async mkdir(e,t){let r=this.normalizePath(e);if(!(typeof t=="object"&&t&&"recursive"in t&&t.recursive)){let o=Z.dirname(r);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(r,t)}async readdir(e,...t){let r=this.normalizePath(e),s=await this.memFs.promises.readdir(r,...t);return console.log("EPHEMERAL: READDIR: ",s),s}async readlink(e){throw new Error("readlink is not implemented for EphemeralFileSubFs")}async unlink(e){let t=this.normalizePath(e);return await this.memFs.promises.unlink(t)}async rename(e,t){let r=this.normalizePath(e),s=this.normalizePath(t);return await this.memFs.promises.rename(r,s)}async rmdir(e,t){let r=this.normalizePath(e);return await this.memFs.promises.rmdir(r,t)}async symlink(e,t,r){let s=this.normalizePath(e),o=this.normalizePath(t);return await this.memFs.promises.symlink(s,o,r)}async lookup(e){throw new Error(`lookup is not implemented for: ${this.toStr(e)}`)}async close(e){let t=this.openFh.get(e.subFsFileDescriptor);t&&(await t.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.datasync()}async read(e,t,r,s,o){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.read(t,r,s,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.chmod(t)}async fchown(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.chown(t,r)}async write(e,t,r,s,o){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.write(t,r,s,o);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.truncate(t)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.stat(t);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.utimes(t,r)}async writev(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.readv(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,t){if(typeof e=="string"||Buffer.isBuffer(e)){let r=this.normalizePath(e);return this.memFs.promises.readFile(r,t)}return super.readFile(e,t)}async writeFile(e,t,r){let s=this.normalizePath(e),o=Z.dirname(s);return o&&o!=="/"&&o!=="."&&await this.memFs.promises.mkdir(o,{recursive:!0}),this.memFs.promises.writeFile(s,t,r)}};n(ge,"EphemeralSubFs");var G=ge;import je from"isomorphic-git";import*as Ee from"path";import{createFsFromVolume as ft,Volume as pt}from"memfs";import we from"isomorphic-git";var ee={type:"gitBranchesListVirtualFile",getStats:n(async({gitRoot:a,nodeFs:i})=>{let e=a+"/.git";try{return await i.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:n(async({gitRoot:a,nodeFs:i})=>{try{let e=(await we.listBranches({fs:i,dir:a})).filter(s=>s.indexOf("/")===-1),t=await we.currentBranch({fs:i,dir:a}),r=await Promise.all(e.map(async s=>{let o=await we.resolveRef({fs:i,dir:a,ref:s});return s}));return{type:"directory",content:r,mode:493,size:r}}catch(e){throw e}},"getFile"),rename:n(async a=>{throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import w from"isomorphic-git";import N from"isomorphic-git";async function R(a,i,e){try{return await N.resolveRef({fs:a,dir:i,ref:`refs/heads/${e}`})}catch{return}}n(R,"tryResolveRef");async function I({dir:a,fs:i,treeOid:e,deletePathParts:t,addPathParts:r,addObj:s,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l,keepFilename:d=".keep"}){let[m,...c]=r??[],[h,...u]=t??[],f=[];if(e){let{tree:g}=await N.readTree({fs:i,dir:a,oid:e});f=[...g]}if(m===h){let g=m;if(g===void 0)throw new Error("illegal arguement - called with out a path part");if(c.length===0)throw new Error("can not move into it self");if(u.length===0)throw new Error("can not move from it self");let O=f.findIndex(P=>P.path===g),b=(O!==-1?f[O]:void 0)?.oid,F=await I({dir:a,fs:i,treeOid:b,addPathParts:c,deletePathParts:u,addObj:s,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(F===void 0)throw new Error("on the same path we expect an update - respectivly a newly created subTreeOid");let k=!1;if(F!==b){k=!0;let P={mode:"040000",path:g,oid:F,type:"tree"};O!==-1?f[O]=P:f.push(P)}if(e==null&&!k)throw new Error("Illegal state - if the currentOid is undefined - a new tree should have been created (an update should have happened)");if(k)return await N.writeTree({fs:i,dir:a,tree:f});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}else{let g=!1,O;if(h){let y=f.findIndex(F=>F.path===h),b=y!==-1?f[y]:void 0;if(b===void 0)throw new Error("Element doesnt exist in tree");if(u.length>0){if(b&&b.type!=="tree")throw new Error("SubPart of the path for the obj to delete is not a tree");let F=await I({dir:a,fs:i,treeOid:b.oid,addPathParts:void 0,deletePathParts:u,addObj:s,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(F===b.oid)throw new Error("in case of a delete we expect a different subtree oid");g=!0,F===void 0?f.splice(y,1):f[y]={mode:"040000",path:h,oid:F,type:"tree"}}else if(g=!0,f.splice(y,1),f.length===0&&o){let F=new Uint8Array(0),k=await N.writeBlob({fs:i,dir:a,blob:F});f.push({mode:"100644",oid:k,path:d,type:"blob"})}O=b}if(m){let y=f.findIndex(F=>F.path===m),b=y!==-1?f[y]:void 0;if(c.length>0){if(b&&b.type!=="tree")throw new Error("SubPart of the path for the obj to add is not a tree");let F=await I({dir:a,fs:i,treeOid:b?.oid,addPathParts:c,deletePathParts:void 0,addObj:s,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(F===void 0)throw new Error("in case we add, we expect an update - respectivly a newly created subTreeOid");if(F!==b?.oid){g=!0;let k={mode:"040000",path:m,oid:F,type:"tree"};if(y!==-1)f[y]=k;else if(f.push(k),l&&f.length>1){let P=f.findIndex(S=>S.path===d);P!==-1&&f.splice(P,1)}}}else{if(g=!0,s){let F={mode:s.type==="tree"?"040000":"100644",path:m,oid:s.oid,type:s.type};if(y!==-1)f[y]=F;else{if(l&&f.length>0){let k=f.findIndex(P=>P.path===d);k!==-1&&f.splice(k,1)}f.push(F)}}if(o&&f.length===0){let F=new Uint8Array(0),k=await N.writeBlob({fs:i,dir:a,blob:F});f.push({mode:"100644",oid:k,path:d,type:"blob"})}}}if(f.length===0)return;if(g)return await N.writeTree({fs:i,dir:a,tree:f});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}}n(I,"buildUpdatedTree");async function V({filePath:a,gitRoot:i,nodeFs:e,commitSha:t,pathParams:r}){if(!r.filePath){let l=await N.readTree({fs:e,dir:i,oid:t});return{type:"tree",entries:l.tree.map(m=>m.path),oid:l.oid}}return(await N.walk({fs:e,dir:i,trees:[N.TREE({ref:t})],map:n(async(l,[d])=>{if(l===r.filePath&&d){let m=await d.type();if(m==="blob")return{type:"blob",oid:await d.oid()};if(m=="tree"){let c=await N.readTree({fs:e,dir:i,oid:await d.oid()});return{type:"tree",entries:c.tree.map(u=>u.path),oid:c.oid}}}},"map")})).find(l=>l!==void 0)}n(V,"resolveGitObjAtPath");var te=class te extends Error{constructor(e,t){super(e);p(this,"code","ENOENT");p(this,"path");this.name="ENOENTError",this.path=t,Object.setPrototypeOf(this,te.prototype)}};n(te,"ENOENTError");var M=te;var J={type:"gitBranchFileVirtualFile",getStats:n(async({gitRoot:a,nodeFs:i,filePath:e,cacheFs:t,pathParams:r})=>{if(r.branchName===void 0)throw new Error("branchName should be in pathParams");let s=await R(i,a,r.branchName);if(!s)throw new M(`ENOENT: no such file or directory, stat '${e}'`,e);let o=await V({filePath:e,gitRoot:a,nodeFs:i,commitSha:s,pathParams:r});if(!o)throw new M(`ENOENT: no such file or directory, stat '${e}'`,e);let l=await w.readCommit({fs:i,dir:a,oid:s}),{commit:d}=l,m=await w.log({fs:i,dir:a,ref:s,filepath:r.filePath,depth:1}),c=d.committer.timestamp*1e3,h=m.length>0?m[0].commit.committer.timestamp*1e3:c;if(o.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:h,mtimeMs:h,ctimeMs:h,birthtimeMs:c,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)};{let{blob:u}=await w.readBlob({fs:i,dir:a,oid:o.oid});return{mode:420,size:u.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(u.length/4096),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({filePath:a,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r})=>{if(r.branchName===void 0)throw new Error("branchName should be in pathParams");let s=[];try{let o=await R(e,i,r.branchName);if(!o){let d=await w.resolveRef({fs:e,dir:i,ref:"HEAD"});await w.branch({fs:e,dir:i,ref:r.branchName,object:d}),o=await w.resolveRef({fs:e,ref:`refs/heads/${r.branchName}`,dir:i})}let l=await V({filePath:a,gitRoot:i,nodeFs:e,commitSha:o,pathParams:r});if(!l)return;if(l.type==="blob"){let{blob:d}=await w.readBlob({fs:e,dir:i,oid:l.oid});return{type:"file",content:Buffer.from(d),mode:420,size:d.length,oid:l.oid}}else{let d=[];try{let c=await t.promises.stat(a);if(c&&c.isDirectory()){let h=await t.promises.readdir(a,{withFileTypes:!1,encoding:"utf-8"});d.push(...h)}}catch{}return{type:"directory",content:Array.from(new Set([...d,...l.entries])),mode:493}}}catch{return}},"getFile"),unlink:n(async({filePath:a,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r,author:s})=>{if(!r.branchName)throw new Error("branchName should be in pathParams");if(!r.filePath)throw new Error("filePath should be in pathParams");let o=await w.resolveRef({fs:e,dir:i,ref:r.branchName}),l=await w.readTree({fs:e,dir:i,oid:o}),d=await I({dir:i,fs:e,treeOid:l.oid,deletePathParts:r.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(d!==l.oid){let m=await w.commit({fs:e,dir:i,message:`Delete ${r.filePath}`,tree:d,noUpdateBranch:!0,parent:[o],author:s});await w.writeRef({fs:e,dir:i,ref:`refs/heads/${r.branchName}`,value:m,force:!0})}},"unlink"),writeFile:n(async({filePath:a,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s,author:o})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");if(s.filePath===void 0)throw new Error("filePath should be in pathParams");let l;typeof t=="string"?l=new TextEncoder().encode(t):l=new Uint8Array(t);let d=await w.writeBlob({fs:e,dir:i,blob:l}),m=await R(e,i,s.branchName);if(!m){let u=await w.resolveRef({fs:e,dir:i,ref:"HEAD"});await w.branch({fs:e,dir:i,ref:s.branchName,object:u}),m=await w.resolveRef({fs:e,dir:i,ref:`refs/heads/${s.branchName}`})}let c=await w.readTree({fs:e,dir:i,oid:m}),h=await I({dir:i,fs:e,treeOid:c.oid,deletePathParts:void 0,addPathParts:s.filePath.split("/"),addObj:{type:"blob",oid:d},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!1,keepFilename:".keep"});if(h!==c.oid){let u=await w.commit({fs:e,dir:i,message:`\u{1F4BE} Change '${s.filePath}'`,tree:h,noUpdateBranch:!0,parent:[m],author:o});await w.writeRef({fs:e,dir:i,ref:`refs/heads/${s.branchName}`,value:u,force:!0})}},"writeFile"),rename:n(async function({filePath:a,newPath:i,gitRoot:e,nodeFs:t,pathParams:r,newPathParams:s,author:o}){if(r.branchName===void 0)throw new Error("branchName should be in pathParams");if(r.filePath===void 0)throw new Error("filePath should be in pathParams");if(s.branchName===void 0)throw new Error("branchName should be in newPathParams");if(s.filePath===void 0)throw new Error("filePath should be in newPathParams");let l=await R(t,e,r.branchName);if(!l)throw new Error("Invalid branch file path - source branch must exist");let d=await R(t,e,s.branchName);if(!d){let u=await w.resolveRef({fs:t,dir:e,ref:"HEAD"});await w.branch({fs:t,dir:e,ref:s.branchName,object:u}),d=await w.resolveRef({fs:t,dir:e,ref:`refs/heads/${s.branchName}`})}if(s.branchName!==r.branchName)throw new Error("cross branch move not implemented yet");let m=await V({gitRoot:e,nodeFs:t,commitSha:l,filePath:a,pathParams:r});if(m===void 0)throw new Error("no obj at path exists");let c=await I({dir:e,fs:t,deletePathParts:r.filePath.split("/"),addPathParts:s.filePath.split("/"),addObj:m,treeOid:d,addKeepIfEmpty:!0,deleteKeepIfNotEmpty:!0}),h=await w.readTree({fs:t,dir:e,oid:l});if(c!==h.oid){let u=await w.commit({fs:t,dir:e,message:`\u{1F500} Rename '${r.filePath}' to '${s.filePath}'`,tree:c,noUpdateBranch:!0,parent:[d],author:o});await w.writeRef({fs:t,dir:e,ref:`refs/heads/${s.branchName}`,value:u,force:!0})}},"rename"),mkdir:n(async function(a){if(a.pathParams.branchName===void 0)throw new Error("branchName should be in pathParams");if(a.pathParams.filePath===void 0)throw new Error("filePath should be in pathParams");try{throw await J.getStats(a),new Error("Folder exists")}catch{}a.filePath.endsWith("/")&&(a.filePath=a.filePath.replace(/\/+$/,"")),a.pathParams&&typeof a.pathParams.filePath=="string"&&(a.pathParams.filePath=a.pathParams.filePath.replace(/\/+$/,""));let i=await R(a.nodeFs,a.gitRoot,a.pathParams.branchName);if(!i){let o=await w.resolveRef({fs:a.nodeFs,dir:a.gitRoot,ref:"HEAD"});await w.branch({fs:a.nodeFs,dir:a.gitRoot,ref:a.pathParams.branchName,object:o}),i=await w.resolveRef({fs:a.nodeFs,dir:a.gitRoot,ref:`refs/heads/${a.pathParams.branchName}`})}let e=await w.readTree({fs:a.nodeFs,dir:a.gitRoot,oid:i}),t=new Uint8Array(0),r=await w.writeBlob({fs:a.nodeFs,dir:a.gitRoot,blob:t}),s=await I({dir:a.gitRoot,fs:a.nodeFs,treeOid:e.oid,deletePathParts:void 0,addPathParts:[...a.pathParams.filePath.split("/"),".keep"],addObj:{type:"blob",oid:r},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!0,keepFilename:".keep"});if(s!==e.oid){let o=await w.commit({fs:a.nodeFs,dir:a.gitRoot,message:`\u{1F4BE} Change '${a.pathParams.filePath}'`,tree:s,noUpdateBranch:!0,parent:[i],author:a.author});await w.writeRef({fs:a.nodeFs,dir:a.gitRoot,ref:`refs/heads/${a.pathParams.branchName}`,value:o,force:!0})}},"mkdir"),rmdir:n(async({filePath:a,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r,author:s})=>{if(!r.branchName)throw new Error("branchName should be in pathParams");if(!r.filePath)throw new Error("filePath should be in pathParams");let o=await w.resolveRef({fs:e,dir:i,ref:r.branchName}),l=await w.readTree({fs:e,dir:i,oid:o}),d=await I({dir:i,fs:e,treeOid:l.oid,deletePathParts:r.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(d!==l.oid){let m=await w.commit({fs:e,dir:i,message:`Delete ${r.filePath}`,tree:d,noUpdateBranch:!0,parent:[o],author:s});await w.writeRef({fs:e,dir:i,ref:`refs/heads/${r.branchName}`,value:m,force:!0})}},"rmdir")};import z from"isomorphic-git";var ie={type:"gitBranchHeadVirtualFile",getStats:n(async({gitRoot:a,nodeFs:i,pathParams:e})=>{if(e.branchName===void 0)throw new Error("branchName should be in pathParams");let t;try{t=await z.resolveRef({fs:i,dir:a,ref:e.branchName})}catch{t=await z.resolveRef({fs:i,dir:a,ref:`refs/heads/${e.branchName}`})}let r=await z.readCommit({fs:i,dir:a,oid:t}),{commit:s}=r,o=s.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(40/4096),atimeMs:o,mtimeMs:o,ctimeMs:o,birthtimeMs:o,atime:new Date(o),mtime:new Date(o),ctime:new Date(o),birthtime:new Date(o)}},"getStats"),getFile:n(async({gitRoot:a,nodeFs:i,pathParams:e})=>{if(e.branchName===void 0)throw new Error("branchName should be in pathParams");try{let t;try{t=await z.resolveRef({fs:i,dir:a,ref:e.branchName})}catch{t=await z.resolveRef({fs:i,dir:a,ref:`refs/heads/${e.branchName}`})}return{type:"file",content:t+`
4
+ `,mode:420,size:t.length}}catch{return}},"getFile"),writeFile:n(async({filePath:a,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s})=>{if(console.log("gitBranchHeadVirtualFile writeFile called",{pathParams:s,content:t}),s.branchName===void 0)throw new Error("branchName should be in pathParams");let o=t.toString().trim();try{await z.readCommit({fs:e,dir:i,oid:o})}catch{throw new Error(`Commit ${o} does not exist in the repository`)}await z.writeRef({fs:e,dir:i,ref:"refs/heads/"+s.branchName,value:o,force:!0})},"writeFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import lt from"isomorphic-git";var Le={type:"gitBranchTipVirtualFile",getStats:n(async a=>{let i=a.gitRoot+"/.git";try{return await a.nodeFs.stat(i)}catch{throw new Error(`ENOENT: no such file or directory, stat '${i}'`)}},"getStats"),getFile:n(async({filePath:a,gitRoot:i,nodeFs:e,pathParams:t})=>{if(!t.branchName)throw new Error("branchName should be in pathParams");try{let r=await lt.resolveRef({fs:e,dir:i,ref:`refs/heads/${t.branchName}`});return{type:"file",content:r+`
5
+ `,mode:420,size:r.length+1}}catch{return}},"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import ye from"isomorphic-git";var re={type:"gitCommitFileVirtualFile",getStats:n(async({filePath:a,gitRoot:i,nodeFs:e,pathParams:t})=>{if(!t.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!t.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let r=t.sha_1_1_2+t.sha1_3__40,s=await V({filePath:a,gitRoot:i,nodeFs:e,commitSha:r,pathParams:t});if(!s)throw new M(`ENOENT: no such file or directory, stat '${a}'`,a);let o=await ye.readCommit({fs:e,dir:i,oid:r}),{commit:l}=o,d=l.committer.timestamp*1e3;if(s.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:d,mtimeMs:d,ctimeMs:d,birthtimeMs:d,atime:new Date(d),mtime:new Date(d),ctime:new Date(d),birthtime:new Date(d)};{let{blob:m}=await ye.readBlob({fs:e,dir:i,oid:s.oid});return{mode:420,size:m.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(m.length/4096),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({filePath:a,gitRoot:i,nodeFs:e,pathParams:t})=>{if(!t.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!t.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let r=t.sha_1_1_2+t.sha1_3__40;try{let s=await V({filePath:a,gitRoot:i,nodeFs:e,commitSha:r,pathParams:t});if(!s)return;if(s.type==="blob"){let{blob:o}=await ye.readBlob({fs:e,dir:i,oid:s.oid});return{type:"file",content:Buffer.from(o),mode:420,size:o.length,oid:s.oid}}else return{type:"directory",content:Array.from(new Set([...s.entries.filter(l=>l!==".keep")])),mode:493}}catch{return}},"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import be from"isomorphic-git";function dt(a,i,e){return a===0&&i===2&&e===0?"untracked":a===1&&i===0&&e===0?"deleted":a===1&&i===2&&e!==0?"modified":a===0&&i===2&&e===2?"added":"unknown"}n(dt,"getFileStatus");var Ne={type:"gitStatusVirtualFile",getStats:n(async a=>{let i=a.gitRoot+"/.git";try{return await a.nodeFs.stat(i)}catch{throw new Error(`ENOENT: no such file or directory, stat '${i}'`)}},"getStats"),getFile:n(async({gitRoot:a,nodeFs:i})=>{try{let e=await be.currentBranch({fs:i,dir:a})||"HEAD",t=await be.resolveRef({fs:i,dir:a,ref:"HEAD"}),s=(await be.statusMatrix({fs:i,dir:a})).filter(([,l,d,m])=>l!==d||d!==m).map(([l,d,m,c])=>({path:l,status:dt(d,m,c)})),o=JSON.stringify({branch:e,commit:t,clean:s.length===0,files:s},null,2);return{type:"file",content:o,mode:33188,size:Buffer.byteLength(o)}}catch(e){throw console.error(e),e}},"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};var K={type:"legitVirtualFile",getStats:n(async({gitRoot:a,nodeFs:i})=>{let e=a+"/.git";try{return await i.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:n(async({gitRoot:a,nodeFs:i})=>({type:"directory",content:[],mode:493,size:0}),"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};var Ie=[K,Ne,re,ee,J,ie,Le];var Pe=class Pe{constructor(i){this.routes=i;p(this,"compiledRoutes");let e={},t=n((r,s)=>{if(typeof r.type=="string"){e[s]={handler:r,siblings:[]};let o=r}else{let o=[];for(let[l,d]of Object.entries(r))if(l==="."){if(e[s])throw new Error(`Conflict: multiple handlers for path '${s}', '.' and optional '[[parameter_name]]' defined?`);e[s]={handler:d,siblings:o}}else if(l.startsWith("[[")&&l.endsWith("]]")){if(e[s])throw new Error(`Conflict: multiple handlers for path '${s}', '.' and optional '[[parameter_name]]' defined?`);e[s]={handler:d,siblings:o},l.startsWith("[[...")?e[s?`${s}/${l}`:l]={handler:d,siblings:[]}:t(d,s?`${s}/${l}`:l)}else l.startsWith("[")&&l.endsWith("]")?l.startsWith("[...")?e[s?`${s}/${l}`:l]={handler:d,siblings:[]}:t(d,s?`${s}/${l}`:l):(o.push(l),t(d,s?`${s}/${l}`:l))}},"walk");for(let[r,s]of Object.entries(i))t(s,r);this.compiledRoutes=Object.entries(e).map(([r,s])=>{let o=[],l=r.split("/").map(m=>{if(m.startsWith("[[")&&m.endsWith("]]")){let c=m.slice(2,-2).replace(/^\.\.\./,"");return o.push(c),"(.*)"}if(m.startsWith("[")&&m.endsWith("]")){let c=m.slice(1,-1);return o.push(c),"([^/]+)"}return m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{regex:new RegExp(`^${l}$`),paramNames:o,staticSiblings:s.siblings,handler:s.handler}})}match(i){i.length>1&&i.endsWith("/")&&(i=i.replace(/\/+$/,""));for(let{regex:e,paramNames:t,handler:r,staticSiblings:s}of this.compiledRoutes){let o=i.match(e);if(!o)continue;let l={};for(let d=0;d<t.length;d++)l[t[d]]=decodeURIComponent(o[d+1]||"");return{handler:r,params:l,staticSiblings:s}}}};n(Pe,"LegitPathRouter");var se=Pe;import ve from"isomorphic-git";var ke={type:"gitCommitVirtualFolder",getStats:n(async a=>{let i=a.gitRoot+"/.git";try{return await a.nodeFs.stat(i)}catch{throw new Error(`ENOENT: no such file or directory, stat '${i}'`)}},"getStats"),getFile:n(async({filePath:a,gitRoot:i,nodeFs:e,pathParams:t})=>{let r=await ve.listBranches({fs:e,dir:i}),s=new Set,o=new Set;for(let m of r){let c=`refs/heads/${m}`;try{let h=await ve.resolveRef({fs:e,dir:i,ref:c});s.add(h)}catch{}}for(let m of s){let c=await ve.log({fs:e,dir:i,ref:m});for(let h of c)o.add(h.oid)}if(!t.sha_1_1_2){let m=new Set;for(let h of o)if(m.add(h.slice(0,2)),m.size>=256)break;let c=Array.from(m).sort();return{type:"directory",content:c,mode:493,size:c}}let l=new Set;for(let m of o)m.startsWith(t.sha_1_1_2)&&l.add(m.slice(2,40));let d=Array.from(l).sort();return{type:"directory",content:d,mode:493,size:d.length}},"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import B from"isomorphic-git";import mt from"isomorphic-git";var Se="-operation";async function D(a,i,e){return(await mt.listBranches({fs:a,dir:i})).filter(r=>r.endsWith("__"+e+Se))[0]}n(D,"resolveOperationBranchName");var Re={type:"gitBranchOperationVirtualFile",getStats:n(async a=>{let{gitRoot:i,nodeFs:e,pathParams:t}=a,r;try{r=await B.resolveRef({fs:e,dir:i,ref:`refs/heads/${t.branchName}`})}catch{throw new Error(`Base Branch ${t.branchName} for operations does not exis`)}let s=await D(e,i,t.branchName),o=!1;if(s)try{r=await B.resolveRef({fs:e,dir:i,ref:s}),o=!0}catch{try{r=await B.resolveRef({fs:e,dir:i,ref:`refs/heads/${s}`}),o=!0}catch{}}let l=await B.readCommit({fs:e,dir:i,oid:r}),{commit:d}=l,m=d.committer.timestamp*1e3;try{return{mode:420,size:40,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: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 a=>{let{gitRoot:i,nodeFs:e,pathParams:t}=a,r=await D(e,i,t.branchName),s,o=!1;return r?(s=await B.resolveRef({fs:e,dir:i,ref:`refs/heads/${r}`}),o=!0):s=await B.resolveRef({fs:e,dir:i,ref:`refs/heads/${t.branchName}`}),{type:"file",content:Buffer.from(s),mode:420,size:s.length}},"getFile"),writeFile:n(async({filePath:a,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s,author:o})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");let l;typeof t=="string"?l=new TextEncoder().encode(t):l=new Uint8Array(t);let d=await B.writeBlob({fs:e,dir:i,blob:l}),m=await R(e,i,s.branchName);if(!m)throw new Error("Invalid branch file path - branch doesn't exist");let c=await D(e,i,s.branchName),h=!1;c||(c="legit/__"+s.branchName+Se,await B.branch({fs:e,dir:i,ref:c,object:m}),h=!0);let u=await B.resolveRef({fs:e,dir:i,ref:`refs/heads/${c}`}),f=await B.readTree({fs:e,dir:i,oid:m}),g;t instanceof ArrayBuffer?g=Buffer.from(t).toString("utf-8"):typeof t=="string"?g=t:t instanceof Uint8Array?g=Buffer.from(t).toString("utf-8"):g=String(t);let O=!1;if(!h){let b=await B.findMergeBase({fs:e,dir:i,oids:O?[u]:[u,m]});b.length===1&&b[0]===m&&(O=!0)}let y=await B.commit({fs:e,dir:i,message:g,tree:f.oid,noUpdateBranch:!0,author:o,parent:O?h?[m,m]:[u]:[u,m]});await B.writeRef({fs:e,dir:i,ref:`refs/heads/${c}`,value:y,force:!0})},"writeFile"),rename:n(async function({filePath:a,newPath:i,gitRoot:e,nodeFs:t,pathParams:r,newPathParams:s}){throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import j from"isomorphic-git";var De={type:"gitBranchOperationsVirtualFile",getStats:n(async a=>{let{gitRoot:i,nodeFs:e,pathParams:t}=a;if(t.branchName===void 0)throw new Error("branchName should be in pathParams");let r=await D(e,i,t.branchName),s,o=!1;if(r)try{s=await j.resolveRef({fs:e,dir:i,ref:r}),o=!0}catch{try{s=await j.resolveRef({fs:e,dir:i,ref:`refs/heads/${r}`}),o=!0}catch{throw new Error(`Base Branch ${t.branchName} for operations does not exis`)}}else try{s=await j.resolveRef({fs:e,dir:i,ref:`refs/heads/${t.branchName}`})}catch{throw new Error(`Base Branch ${t.branchName} for operations does not exis`)}let l=await j.readCommit({fs:e,dir:i,oid:s}),{commit:d}=l,m=d.committer.timestamp*1e3;try{return{mode:420,size:(o?await De.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: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 a=>{let{gitRoot:i,nodeFs:e,pathParams:t}=a,r=await D(e,i,t.branchName),s=[];if(r){let d=await j.resolveRef({fs:e,dir:i,ref:`refs/heads/${r}`}),m=!1,c=d;for(;c&&!m;){let h=await j.readCommit({fs:e,dir:i,oid:c});s.push({oid:h.oid,parentOids:h.commit.parent,message:h.commit.message,originBranchOid:"unset"}),c=h.commit.parent&&h.commit.parent.length>0?h.commit.parent[0]:null,h.commit.parent.length===2&&h.commit.parent[0]===h.commit.parent[1]&&(m=!0)}}let o;for(let d=s.length-1;d>=0;d--){let m=s[d];if(o===void 0){if(m.parentOids.length!==2&&m.parentOids[0]!==m.parentOids[1])throw new Error(`Operation commit ${m.oid} does not have two parents as expected`);o=m.parentOids[1]}m.parentOids.length===2&&(o=m.parentOids[1]),m.originBranchOid=o}let l=Buffer.from(JSON.stringify(s,null,2),"utf-8");return{type:"file",content:l,mode:420,size:l.length}},"getFile"),rename:n(async function(a){throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import q from"isomorphic-git";var ct=new Set([" ","~","^",":","?","*","[","\\"]),ht=[/^\/|\/$/,/\/\//,/\.$/,/\.lock$/,/^@$/,/@\{/],$e="\u2002";function Ae(a){let i=a.codePointAt(0);return!(i>=0&&i<=31||i===127||ct.has(a))}n(Ae,"isValidChar");function xe(a){let i="";for(let e of a)e===" "?i+=$e:Ae(e)?i+=e:i+="%"+e.codePointAt(0);for(let e of ht)if(e.test(i))return Array.from(i).map(t=>Ae(t)?t:"%"+t.codePointAt(0)).join("");return i}n(xe,"encodeName");function Ve(a){return a.replace(/%(\d+)/g,(i,e)=>String.fromCodePoint(parseInt(e,10))).replace(new RegExp($e,"g")," ")}n(Ve,"decodeName");var Me={type:"getThreadName",getStats:n(async a=>{let{gitRoot:i,nodeFs:e,pathParams:t}=a,r;try{r=await q.resolveRef({fs:e,dir:i,ref:`refs/heads/${t.branchName}`})}catch{throw new Error(`Base Branch ${t.branchName} for operations does not exis`)}let s=await D(e,i,t.branchName),o=!1;if(s)try{r=await q.resolveRef({fs:e,dir:i,ref:s}),o=!0}catch{try{r=await q.resolveRef({fs:e,dir:i,ref:`refs/heads/${s}`}),o=!0}catch{}}let l=await q.readCommit({fs:e,dir:i,oid:r}),{commit:d}=l,m=d.committer.timestamp*1e3;try{return{mode:420,size:40,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: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 a=>{let{gitRoot:i,nodeFs:e,pathParams:t}=a,r=await D(e,i,t.branchName),s;if(r){let o="legit/",l=`__${t.branchName}-operation`;return r.startsWith(o)&&r.endsWith(l)?s=r.slice(o.length,r.length-l.length):s=r,{type:"file",content:Buffer.from(Ve(s)),mode:420,size:s.length}}return{type:"file",content:Buffer.from(""),mode:420,size:0}},"getFile"),writeFile:n(async({filePath:a,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");let o=await D(e,i,s.branchName);if(o){let l=`legit/${xe(t.toString())}__${s.branchName}-operation`;await q.renameBranch({fs:e,dir:i,oldref:o,ref:l}),o=l}},"writeFile"),rename:n(async function({filePath:a,newPath:i,gitRoot:e,nodeFs:t,pathParams:r,newPathParams:s}){throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import X from"isomorphic-git";var ze={type:"gitBranchHistory",getStats:n(async({gitRoot:a,nodeFs:i,pathParams:e})=>{if(e.branchName===void 0)throw new Error("branchName should be in pathParams");let t;try{t=await X.resolveRef({fs:i,dir:a,ref:e.branchName})}catch{t=await X.resolveRef({fs:i,dir:a,ref:`refs/heads/${e.branchName}`})}let r=await X.readCommit({fs:i,dir:a,oid:t}),{commit:s}=r,o=s.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(40/4096),atimeMs:o,mtimeMs:o,ctimeMs:o,birthtimeMs:o,atime:new Date(o),mtime:new Date(o),ctime:new Date(o),birthtime:new Date(o)}},"getStats"),getFile:n(async a=>{let{gitRoot:i,nodeFs:e,pathParams:t}=a,r=t.branchName,s=[];if(r){let l=await X.resolveRef({fs:e,dir:i,ref:`refs/heads/${r}`}),d=!1,m=l;for(;m&&!d;){let c=await X.readCommit({fs:e,dir:i,oid:m});s.push({oid:c.oid,...c.commit}),m=c.commit.parent[0]}}let o=Buffer.from(JSON.stringify(s,null,2),"utf-8");return{type:"file",content:o,mode:420,size:o.length}},"getFile"),rename:n(async a=>{throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};import A from"isomorphic-git";var _e={type:"gitBranchOperationHeadVirtualFile",getStats:n(async({gitRoot:a,nodeFs:i,pathParams:e})=>{if(e.branchName===void 0)throw new Error("branchName should be in pathParams");let t=await D(i,a,e.branchName);if(!t){let d=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(40/4096),atimeMs:d.getTime(),mtimeMs:d.getTime(),ctimeMs:d.getTime(),birthtimeMs:d.getTime(),atime:d,mtime:d,ctime:d,birthtime:d}}let r;try{r=await A.resolveRef({fs:i,dir:a,ref:t})}catch{r=await A.resolveRef({fs:i,dir:a,ref:`refs/heads/${t}`})}let s=await A.readCommit({fs:i,dir:a,oid:r}),{commit:o}=s,l=o.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(40/4096),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:n(async({gitRoot:a,nodeFs:i,pathParams:e})=>{if(e.branchName===void 0)throw new Error("branchName should be in pathParams");let t=await D(i,a,e.branchName);if(!t)return{type:"file",content:"",mode:420,size:0};try{let r;try{r=await A.resolveRef({fs:i,dir:a,ref:t})}catch{r=await A.resolveRef({fs:i,dir:a,ref:`refs/heads/${t}`})}return{type:"file",content:r+`
6
+ `,mode:420,size:r.length}}catch{return}},"getFile"),writeFile:n(async({filePath:a,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");let o=await D(e,i,s.branchName),l=await A.resolveRef({fs:e,dir:i,ref:`refs/heads/${o}`});if(!o)throw new Error(`Operation branch name could not be resolved for branch ${s.branchName}`);let d=t.toString().trim(),m,c,h=!1;if(!l)throw new Error(`Operation branch ref could not be resolved for branch ${o}`);let u=l;for(;u&&!h;){let f=await A.readCommit({fs:e,dir:i,oid:u});if(f.oid===d&&(m=f.oid),u=f.commit.parent&&f.commit.parent.length>0?f.commit.parent[0]:null,f.commit.parent.length===2){if(f.commit.parent[0]===f.commit.parent[1])h=!0;else if(m!==void 0){c=f.commit.parent[1];break}}}if(m===void 0)throw new Error(`Cant rollback to ${d} couldn't find newOperationBranchHead ${m}`);if(c===void 0)throw new Error(`Cant rollback to ${d} couldn't find newBranchHead ${c}`);await A.writeRef({fs:e,dir:i,ref:"refs/heads/"+o,value:m,force:!0}),await A.writeRef({fs:e,dir:i,ref:"refs/heads/"+s.branchName,value:c,force:!0})},"writeFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};var $=class $ extends C{constructor({name:e,parentFs:t,gitStorageFs:r,gitRoot:s,virtualFiles:o=Ie}){super({name:e,parentFs:t,gitRoot:s});p(this,"memFs");p(this,"openFh",{});p(this,"virtualFiles");p(this,"legitFileNames");p(this,"storageFs");this.gitRoot=s,this.storageFs=r,this.memFs=ft(new pt),this.virtualFiles=o,this.legitFileNames=["branches","commits"]}async getAuthor(){let e=await je.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.name"}),t=await je.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.email"}),r=Math.floor(Date.now()/1e3),s=new Date().getTimezoneOffset();return{name:e,email:t,date:r,timezoneOffset:s}}async responsible(e){return this.isLegitPath(e)}isLegitPath(e){return e.includes(`/${$.LEGIT_DIR}/`)||e.includes(`/${$.LEGIT_DIR}`)}getRouteHandler(e){let t=e.indexOf(`/${$.LEGIT_DIR}`);if(t===-1)throw new Error("Not a legit path");let r=e.slice(t+1);return $.pathRouter.match(r)}async open(e,t,r){let s=this.getRouteHandler(e);if(!s)throw new Error("Not a virtual legit file");if(!(s?.handler.writeFile!==void 0)&&(t.includes("w")||t.includes("a")))throw new Error(`Write operations not allowed for ${s?.handler.type}`);if(t.includes("x")&&s?.handler.type!=="gitBranchFileVirtualFile")throw new Error(`Exclusive operations not allowed for ${s?.handler.type}`);let l=await s.handler.getFile({cacheFs:this.memFs,filePath:e,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:s.params,author:await this.getAuthor()}),d=!1;for(let f of Object.values(this.openFh))f.path===e&&(d=!0);if((l||d)&&t.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!l&&!d&&!(t.includes("w")||t.includes("a")))throw Object.assign(new Error(`ENOENT: no such file or directory, open '${e}'`),{code:"ENOENT",errno:-2,syscall:"open",path:e});let m=Ee.dirname(e);if(await this.memFs.promises.mkdir(m,{recursive:!0}),l===void 0&&!t.includes("x")||l&&l.type==="file")try{let f=await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let c=await this.memFs.promises.open(e,t,r),h=c.fd,u=new L({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:h,parentFsFileDescriptors:[]});return this.openFh[h]={path:e,mode:t,fh:c,openSha:l?.oid,readSha:void 0,unflushed:[]},(t.includes("x")||t.includes("w"))&&this.openFh[h].unflushed.push({length:0,start:0}),u}async mkdir(e,t){let r=e.toString(),s=this.getRouteHandler(r),o=t?{options:t}:{};try{await s?.handler.mkdir({cacheFs:this.memFs,filePath:e.toString(),nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:s.params,...o,author:await this.getAuthor()});let l=typeof t=="object"?{...t,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,l);let d=r.split("/"),m="";for(let c=1;c<=d.length;c++){m=d.slice(0,c).join("/");try{if((await this.memFs.promises.stat(m)).isDirectory()){let u=await this.memFs.promises.open(m,"r");this.openFh[u.fd]={path:m,mode:"r",fh:u,openSha:void 0,readSha:void 0,unflushed:[]}}}catch{}}}catch(l){throw l}}async access(e,t){await this.stat(e)}async futimes(e,t,r){let s=this.openFh[e.subFsFileDescriptor];if(!s)throw new Error("Invalid file handle");return await s.fh.utimes(t,r)}async fstat(e,t){let r=this.openFh[e.subFsFileDescriptor];if(!r)throw new Error("Invalid file handle");return this.stat(r.path,t)}async ftruncate(e,t){let r=this.openFh[e.subFsFileDescriptor];if(!r)throw new Error("Invalid file handle");return r.unflushed.push({length:0,start:0}),await r.fh.truncate(t)}async stat(e,t){let r=e.toString(),s=Object.values(this.openFh).find(d=>d.path===r&&d.unflushed.length>0);if(s&&s.unflushed.length>0)return await s.fh.stat(t);let o=this.getRouteHandler(r);if(!o)throw new Error(`ENOENT: no such file or directory, stat '${r}'`);return await o.handler.getStats({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:o.params,author:await this.getAuthor()})}async lstat(e,t){return this.stat(e,t)}async readdir(e,t){let r=e.toString();if(!this.isLegitPath(r))return[".legit"];let s=this.getRouteHandler(r);if(!s)throw new Error(`ENOENT: no such file or directory, scandir '${r}'`);let o=await s?.handler.getFile({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:s.params,author:await this.getAuthor()});if(o){if(o.type!=="directory")throw new Error("not a folder");let l=s?.staticSiblings??[],d=o.content;return d&&!Array.isArray(o.content)&&(d=JSON.parse(o.content)),Array.from(new Set([...d,...l])).sort((c,h)=>c.localeCompare(h,void 0,{numeric:!0,sensitivity:"base"}))}return[]}async read(e,t,r,s,o){let l=e.subFsFileDescriptor,d=this.openFh[l];if(!d)throw new Error("Invalid file handle");if(d.unflushed.length===0){let m=this.getRouteHandler(d.path),c=await m.handler.getFile({cacheFs:this.memFs,filePath:d.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:m?.params,author:await this.getAuthor()});if(!c?.content)throw new Error("couldnt access content");if(c.type!=="file")throw new Error("not a file");let h=typeof c.content=="string"?Buffer.from(c.content):c.content,u=typeof o=="number"?o:0,f=Math.min(u+s,h.length),g=Math.max(0,f-u);return h.copy(t,r,u,u+g),{bytesRead:g,buffer:t}}return await d.fh.read(t,r,s,o)}async write(e,t,r,s,o){let l=this.openFh[e.subFsFileDescriptor];if(!l)throw new Error("Invalid file handle");let d=l.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(l.unflushed.length===0){let u=this.getRouteHandler(l.path),f=await u.handler.getFile({cacheFs:this.memFs,filePath:l.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:u.params,author:await this.getAuthor()});f&&f.oid&&(await this.memFs.promises.writeFile(l.path,f.content),l.readSha=f.oid)}let m=await l.fh.write(t,r,s,o),c=r??0,h=o??0;return l.unflushed.push({start:h,length:s||t.byteLength-c+h}),m}async close(e){let t=e.subFsFileDescriptor,r=this.openFh[t];if(!r)throw new Error("Invalid file handle");try{await this.dataSync(e),await r.fh.close()}finally{delete this.openFh[t]}}async dataSync(e){let t=e.subFsFileDescriptor,r=this.openFh[t];if(!r)throw new Error("Invalid file handle");if(r.unflushed.length>0){let s=this.getRouteHandler(r.path);if(s&&s.handler.writeFile){let o=await this.memFs.promises.readFile(r.path);await s.handler.writeFile({cacheFs:this.memFs,filePath:r.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,content:o,pathParams:s.params,author:await this.getAuthor()})}r.unflushed=[]}}async readFile(e,t){let r=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),s=null;typeof t=="string"?s=t:t&&typeof t=="object"&&t.encoding&&(s=t.encoding);let o=await this.open(r,"r");try{let d=(await this.fstat(o)).size,m=Buffer.alloc(d);return await this.read(o,m,0,d,0),await this.close(o),s?m.toString(s):m}catch(l){try{await this.close(o)}catch{}throw l}}async writeFile(e,t,r){let s="w",o="utf8",l;typeof r=="string"?o=r:r&&typeof r=="object"&&(r.flag&&(s=String(r.flag)),r.encoding&&(o=r.encoding),r.mode&&(l=typeof r.mode=="string"?parseInt(r.mode,8):r.mode));let d=await this.open(e,s,l);try{let m;typeof t=="string"?m=Buffer.from(t,o):Buffer.isBuffer(t)?m=t:t instanceof Uint8Array?m=Buffer.from(t):ArrayBuffer.isView(t)?m=Buffer.from(t.buffer,t.byteOffset,t.byteLength):m=Buffer.from(t),await this.write(d,m,0,m.length,0)}finally{await this.close(d)}}async rename(e,t){let r=e.toString(),s=t.toString(),o=this.getRouteHandler(r),l=this.getRouteHandler(s);if(o?.handler.type==="gitBranchFileVirtualFile"&&l?.handler.type==="gitBranchFileVirtualFile"){let d=!0;try{await this.memFs.promises.access(s)}catch{d=!1}let m=!0;try{await this.stat(s)}catch{m=!1}let c=!0;try{await this.stat(r)}catch{c=!1}let h=!0;try{await this.memFs.promises.access(r)}catch{h=!1}if(h){let g=Ee.dirname(s);try{await this.memFs.promises.access(g)}catch{await this.memFs.promises.mkdir(g,{recursive:!0})}await this.memFs.promises.rename(e,t)}let u=this.getRouteHandler(r);if(!u)throw new Error("VF not found");let f=await u.handler.rename({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,newPath:s,pathParams:u?.params??{},newPathParams:l?.params??{},author:await this.getAuthor()})}else throw new Error(`Unsupported rename operation from ${o?.handler.type} to ${l?.handler.type}`)}async fchmod(e,t){}async unlink(e){let t=e.toString(),r=this.getRouteHandler(t);if(r?.handler.unlink!==void 0)try{await r.handler.unlink({cacheFs:this.memFs,filePath:t,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:r.params,author:await this.getAuthor()})}catch(s){let o=!1;for(let[l,d]of Object.entries(this.openFh))d.path===t&&d.unflushed.length>0&&(o=!0);if(!o)throw s}finally{let s=!1;for(let[o,l]of Object.entries(this.openFh))l.path===t&&(s=!0,await l.fh.close(),delete this.openFh[Number(o)]);s&&await this.memFs.promises.unlink(t)}else throw new Error(`Cannot unlink ${r?.handler.type} files`)}async rmdir(e,...t){let r=e.toString(),s=this.getRouteHandler(r);if(s?.handler.rmdir!==void 0){await s.handler.rmdir({cacheFs:this.memFs,filePath:r,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:s.params,author:await this.getAuthor()});let o=!1;for(let[l,d]of Object.entries(this.openFh))d.path===r&&(o=!0,await d.fh.close(),delete this.openFh[Number(l)]);o&&await this.memFs.promises.rmdir(r,{recursive:!0})}else throw new Error(`Cannot rmdir
7
+ ${s?.handler.type} directories`)}fileType(){return 10}};n($,"GitSubFs"),p($,"LEGIT_DIR",".legit"),p($,"pathRouter",new se({".legit":{".":K,branches:{".":ee,"[branchName]":{".legit":{".":K,operation:Re,head:ie,operationHead:_e,operationHistory:De,threadName:Me,history:ze},"[[...filePath]]":J}},commits:{".":ke,"[sha_1_1_2]":{".":ke,"[sha1_3__40]":{"[[...filePath]]":re}}}}}));var ne=$;import T from"isomorphic-git";import Oe from"isomorphic-git/http/node";var x="legit",We=n(({fs:a,gitRepoPath:i,serverUrl:e="https://hub.legitcontrol.com",auth:t,anonymousBranch:r,authHeaderPrefix:s="Bearer "})=>{let o=!1;async function l(y){let b=await t.getMaxAccessTokenForBranch(y);if(!b)throw new Error(`No access token for branch ${y}`);await T.fetch({fs:a,http:Oe,dir:i,singleBranch:!0,ref:`${y}`,remote:x,url:e,headers:{Authorization:`${s}${b}`}});let F=await T.resolveRef({fs:a,dir:i,ref:`${x}/${y}`});await T.writeRef({fs:a,dir:i,ref:`refs/heads/${y}`,value:F})}n(l,"loadBranch");let d=[];async function m(){let y=await t.getMaxAccessTokenForBranch("todo");await T.fetch({fs:a,http:Oe,dir:i,remote:x,url:e,headers:{Authorization:`${s}${y}`}});let b=await T.listBranches({fs:a,dir:i});for(let F of b){if(F===r)continue;let k=`${x}/${F}`,P,S;try{P=await T.resolveRef({fs:a,dir:i,ref:F})}catch(H){console.log(`Could not resolve local ref ${F}:`,H)}try{S=await T.resolveRef({fs:a,dir:i,ref:k})}catch{S=void 0}if(P&&S){if(P!==S){let H=await T.findMergeBase({fs:a,dir:i,oids:[P,S]});if(H[0]!==P&&H[0]!==S){let v=await T.merge({fs:a,dir:i,ours:P,theirs:S,fastForwardOnly:!1,abortOnConflict:!1,author:{name:"Your Name",email:"your.email@example.com"},mergeDriver:n(async({branches:oe,contents:ae,path:Qe})=>{let[le,Ye,Te]=ae;return console.log(`Merging ${oe[0]} with ${oe[1]}...`),console.log("merged:"),console.log(ae),{cleanMerge:!0,mergedText:Te===void 0?Ye:Te}},"mergeDriver")});await T.writeRef({fs:a,dir:i,ref:`refs/heads/${F}`,value:v.oid,force:!0})}H[0]===P?(console.log(`branch ${F} differs - remote ahaed, not behind`),await T.writeRef({fs:a,dir:i,ref:`refs/heads/${F}`,value:S,force:!0})):H[0]===S?(console.log(`branch ${F} differs - local ahead, not behind`),d.push(F)):(console.log(`branch ${F} differs - both changed`),d.push(F))}}else P&&!S&&d.push(F)}}n(m,"pull");async function c(y){if((await t.getUser()).type!=="local")for(let b of y){let F=await t.getMaxAccessTokenForBranch(b);await T.push({fs:a,http:Oe,dir:i,remote:x,url:e,ref:b,headers:{Authorization:`Bearer ${F}`}})}}n(c,"push");let h=Promise.resolve();async function u(y){h=h.then(()=>c(y)),await h}n(u,"sequentialPush");async function f(){await T.getConfig({fs:a,dir:i,path:`remote.${x}.fetch`})||await T.setConfig({fs:a,dir:i,path:`remote.${x}.fetch`,value:`+refs/heads/*:refs/remotes/${x}/*`});try{await m();let b=[...new Set(d)].filter(F=>F.indexOf(r)===-1);await u(b),d=[]}catch(b){console.error("Error monitoring changes:",b)}finally{o&&setTimeout(f,1e3)}}n(f,"pullPushTick");function g(){o=!0,f()}n(g,"startSync");function O(){o=!1}return n(O,"stopSync"),{start:n(()=>{o||(g(),o=!0)},"start"),stop:n(()=>{O()},"stop"),isRunning:n(()=>o,"isRunning"),loadBranch:l,sequentialPush:u}},"createLegitSyncService");import E from"isomorphic-git";import{createFsFromVolume as ut,Volume as Ft}from"memfs";var Ue=n((a,i)=>{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 t=>{let r=await a.getUserTokens(e.id);r.accessTokens.push(t),await a.setUserTokens(e.id,r)},"addAccessToken"),getMaxAccessTokenForBranch:n(async t=>{let r=await a.getUserTokens(e.id);if(!(r.accessTokens===void 0||r.accessTokens.length===0))return r.accessTokens[0]},"getMaxAccessTokenForBranch")}},"createSessionManager");import Ke from"isomorphic-git";function Ge(a){let i=JSON.stringify(a),e=new TextEncoder().encode(i),t="";return typeof btoa=="function"?t=btoa(String.fromCharCode(...e)):t=Buffer.from(e).toString("base64"),t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}n(Ge,"encodeConfigJson");function Je(a){let i=a.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((a.length+3)%4),e;typeof atob=="function"?e=atob(i):e=Buffer.from(i,"base64").toString("binary");let t=Uint8Array.from(e,s=>s.charCodeAt(0)),r=new TextDecoder().decode(t);return JSON.parse(r)}n(Je,"decodeConfigJson");var qe="user.legit-tokens";function Xe({storageFs:a,gitRoot:i}){return{getUserTokens:n(async e=>{let t=await Ke.getConfig({fs:a,dir:i,path:qe});return t?Je(t):{accessTokens:[]}},"getUserTokens"),setUserTokens:n(async(e,t)=>await Ke.setConfig({fs:a,dir:i,path:qe,value:Ge(t)}),"setUserTokens")}}n(Xe,"createGitConfigTokenStore");async function cs(a){let i=new Ft,e=ut(i);return gt({...a,storageFs:a?.storageFs?a.storageFs:e,gitRoot:a?.gitRoot||"/"})}n(cs,"openLegitFsWithMemoryFs");async function gt({storageFs:a,gitRoot:i,anonymousBranch:e="anonymous",showKeepFiles:t=!1,initialAuthor:r={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"},serverUrl:s="https://sync.legitcontrol.com",publicKey:o}){await a.promises.readdir(i+"/.git").then(()=>!0).catch(()=>!1)||(await E.init({fs:a,dir:"/",defaultBranch:e}),await a.promises.writeFile(i+"/.keep",""),await E.add({fs:a,dir:"/",filepath:".keep"}),await E.commit({fs:a,dir:"/",message:"Initial commit",author:{name:"Test",email:"test@example.com"}}),await E.setConfig({fs:a,dir:i,path:"init.defaultBranch",value:e})),await E.getConfig({fs:a,dir:i,path:"user.legit_user_id"})||await E.setConfig({fs:a,dir:i,path:"user.legit_user_id",value:r.name}),await E.getConfig({fs:a,dir:i,path:"user.name"})||await E.setConfig({fs:a,dir:i,path:"user.name",value:r.name}),await E.getConfig({fs:a,dir:i,path:"user.email"})||await E.setConfig({fs:a,dir:i,path:"user.email",value:r.email});let h=new W({name:"root",parentFs:void 0,storageFs:a,gitRoot:i}),u=new G({name:"root-ephemeral",parentFs:h,gitRoot:i,ephemeralPatterns:[]}),f=new U({name:"root-hidden",parentFs:h,gitRoot:i,hiddenFiles:[]});h.setHiddenFilesSubFs(f),h.setEphemeralFilesSubFs(u);let g=new W({name:"git",parentFs:h,storageFs:void 0,gitRoot:i,defaultBranch:e}),O=new ne({name:"git-subfs",parentFs:g,gitRoot:i,gitStorageFs:h}),y=t?[".git"]:[".git",".keep"],b=new U({name:"git-hidden-subfs",parentFs:g,gitRoot:i,hiddenFiles:y}),F=new G({name:"git-ephemeral-subfs",parentFs:g,gitRoot:i,ephemeralPatterns:["**/._*","**/.DS_Store","**/.AppleDouble/","**/.AppleDB","**/.AppleDesktop","**/.Spotlight-V100","**/.TemporaryItems","**/.Trashes","**/.fseventsd","**/.VolumeIcon.icns","**/.ql_disablethumbnails","**/.~lock.*","**/lu[0-9a-zA-Z]*.tmp","**/.metaentries.json.tmp","**/**.sb-**"]});g.addSubFs(O),g.setHiddenFilesSubFs(b),g.setEphemeralFilesSubFs(F);let k=Xe({storageFs:a,gitRoot:i}),P=Ue(k,o),S=We({fs:a,gitRepoPath:i,serverUrl:s,auth:P,anonymousBranch:e}),H=Object.assign(g,{auth:P,sync:S,setLogger(v){h.setLoggger(v),g.setLoggger(v)},push:n(async v=>{},"push"),shareCurrentBranch:n(async()=>{if((await P.getUser()).type==="local")throw new Error("login first - for example anonymously using legitfs.auth.signInAnonymously()");let v=await H.getCurrentBranch();return v===e&&(v=(await P.getUser()).id,await E.renameBranch({fs:a,dir:i,oldref:e,ref:v})),await S.sequentialPush([v]),H.setCurrentBranch(v),v},"shareCurrentBranch"),setCurrentBranch:n(async v=>{(await E.listBranches({fs:a,dir:i})).includes(v)||await S?.loadBranch(v);let le=(await E.listBranches({fs:a,dir:i})).includes(v);if(console.log("branchExistsAfter",le),!le)throw new Error(`Branch ${v} does not exist`);await E.setConfig({fs:a,dir:i,path:"init.defaultBranch",value:v})},"setCurrentBranch"),getCurrentBranch:n(async()=>{let v=await E.getConfig({fs:a,dir:i,path:"init.defaultBranch"});if(!v)throw new Error("No current branch set");return v},"getCurrentBranch")});return H}n(gt,"openLegitFs");var ps=n(a=>async i=>{if(!i.path.includes(".legit/branches/")||(i.path.match(/\.legit/g)||[]).length>1)return;let[e,t]=i.path.split(".legit/branches/"),[r,...s]=t.split("/"),o=s.join("/"),l=e+".legit/branches/"+r+"/.legit/operation",d=JSON.stringify(i.operationArgs,(m,c)=>Buffer.isBuffer(c)?{__buffer__:c.toString("base64")}:c);await a.writeFile(l,`[${i.fsName}].${i.operation}(${i.fd?i.fd.fd+" - ":""}${i.path})
8
+
9
+ ${d}
10
+
11
+ `)},"createFsOperationFileLogger");export{W as CompositeFs,G as EphemeralSubFs,ne as GitSubFs,U as HiddenFileSubFs,Q as PassThroughSubFs,ps as createFsOperationFileLogger,We as createLegitSyncService,De as gitBranchOperationsVirtualFile,gt as openLegitFs,cs as openLegitFsWithMemoryFs};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@legit-sdk/core",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Legit SDK - Infrastructure for write-enabled AI",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -11,6 +11,11 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js",
13
13
  "require": "./dist/index.js"
14
+ },
15
+ "./server": {
16
+ "types": "./dist/server.d.ts",
17
+ "import": "./dist/server.js",
18
+ "require": "./dist/server.js"
14
19
  }
15
20
  },
16
21
  "keywords": [],
@@ -22,6 +27,8 @@
22
27
  "files": [
23
28
  "dist/index.js",
24
29
  "dist/index.d.ts",
30
+ "dist/server.js",
31
+ "dist/server.d.ts",
25
32
  "LICENSE"
26
33
  ],
27
34
  "devDependencies": {
@@ -29,6 +36,7 @@
29
36
  "browser-fs-access": "^0.38.0",
30
37
  "buffer": "^6.0.3",
31
38
  "esbuild": "^0.24.2",
39
+ "esbuild-plugins-node-modules-polyfill": "^1.7.1",
32
40
  "events": "^3.3.0",
33
41
  "https-browserify": "^1.0.0",
34
42
  "path-browserify": "^1.0.1",