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