eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1 lines • 2.53 kB
JavaScript
import{posix,sep}from"node:path";import{readFile,readdir,stat}from"node:fs/promises";function createDiskProjectSource(){return{kind:`disk`,async readDirectory(e){return await readdir(e,{withFileTypes:!0})},async readTextFile(e){return await readFile(e,`utf8`)},async stat(e){try{let t=await stat(e);return t.isDirectory()?`directory`:t.isFile()?`file`:`other`}catch{return`missing`}}}}function createMemoryProjectSource(t){let n=new Map,r=new Map;function registerDirectory(e){let t=r.get(e);return t===void 0&&(t=new Map,r.set(e,t)),t}function registerChildOfDirectory(t,n,r){if(registerDirectory(t).get(n)===`file`&&r===`directory`)throw TypeError(`MemoryProjectSource: path "${posix.join(t,n)}" registered as both a file and a directory.`);registerDirectory(t).set(n,r)}for(let[e,r]of Object.entries(t.files)){let t=normalizeToPosix(e),i=typeof r==`string`?r:r.content;n.set(t,i);let a=splitPosixPath(t);if(a.length===0)throw TypeError(`MemoryProjectSource: cannot register root path "${e}" as a file.`);let o=a[a.length-1];if(o===void 0)throw TypeError(`MemoryProjectSource: empty file name in "${e}".`);let s=`/`;for(let e=0;e<a.length-1;e+=1){let t=a[e];t!==void 0&&(registerChildOfDirectory(s,t,`directory`),s=s===`/`?`/${t}`:`${s}/${t}`)}registerChildOfDirectory(s,o,`file`)}for(let e of t.directories??[]){let t=normalizeToPosix(e),n=splitPosixPath(t);registerDirectory(t);let r=`/`;for(let e=0;e<n.length;e+=1){let t=n[e];t!==void 0&&(registerChildOfDirectory(r,t,`directory`),r=r===`/`?`/${t}`:`${r}/${t}`)}}return{kind:`memory`,async readDirectory(e){let n=normalizeToPosix(e),i=r.get(n);if(i===void 0)throw Error(`MemoryProjectSource: directory "${e}" does not exist${t.rootDir===void 0?``:` (root: ${t.rootDir})`}.`);return[...i.entries()].map(([e,t])=>createMemoryEntry(e,t))},async readTextFile(e){let r=normalizeToPosix(e),i=n.get(r);if(i===void 0)throw Error(`MemoryProjectSource: file "${e}" does not exist${t.rootDir===void 0?``:` (root: ${t.rootDir})`}.`);return i},async stat(e){let t=normalizeToPosix(e);return n.has(t)?`file`:r.has(t)?`directory`:`missing`}}}function createMemoryEntry(e,t){return{name:e,isDirectory(){return t===`directory`},isFile(){return t===`file`}}}function normalizeToPosix(n){let r=sep===`/`?n:n.replaceAll(sep,`/`);if(r.length===0)return`/`;let i=r.replace(/^[A-Za-z]:/,``),a=i.startsWith(`/`)?i:`/${i}`;return posix.normalize(a).replace(/\/+$/,``)||`/`}function splitPosixPath(e){return e.split(`/`).filter(e=>e.length>0)}export{createDiskProjectSource,createMemoryProjectSource};