UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

1 lines • 2.63 kB
import{readFile}from"node:fs/promises";import{dirname,extname,isAbsolute,relative,resolve}from"node:path";import{realpathSync}from"node:fs";const AUTHORED_ASSET_CODE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createAuthoredAssetImportPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-authored-asset-import`,resolveId(e,n){if(!isPotentialAuthoredAssetImport(e)||n===void 0)return;let{path:r,suffix:i}=splitImportSuffix(e),a=toCanonicalPath(isAbsolute(r)?r:resolve(dirname(n),r));if(!isPathInsideOrEqual(a,t))throw Error(`Authored asset import "${e}" from "${n}" resolves outside package root "${t}".`);return`${a}${i}`},async load(e){let{path:t,suffix:n}=splitImportSuffix(e);if(!isPotentialAuthoredAssetImport(t))return;if(n===`?raw`){let e=await readAssetText(t);return e===void 0?void 0:{code:`export default ${JSON.stringify(e)};`,moduleType:`js`}}let r=await readAssetDataUrl(t);if(r!==void 0)return{code:`export default ${JSON.stringify(r)};`,moduleType:`js`}}}}function isPathInsideOrEqual(e,t){let n=relative(t,resolve(e));return n===``||!n.startsWith(`..`)&&!isAbsolute(n)}function toCanonicalPath(e){let t=resolve(e);try{return realpathSync.native(t)}catch{return t}}async function readAssetText(e){try{return await readFile(e,`utf8`)}catch(e){if(isPathNotFoundError(e))return;throw e}}function isPotentialAuthoredAssetImport(e){if(e.startsWith(`\0`)||e.startsWith(`node:`)||e.startsWith(`data:`)||e.startsWith(`file:`))return!1;let{path:t}=splitImportSuffix(e);if(!t.startsWith(`.`)&&!t.startsWith(`/`)&&!/^[A-Za-z]:[\\/]/.test(t))return!1;let n=extname(t);return n.length>0&&n!==`.node`&&!AUTHORED_ASSET_CODE_EXTENSIONS.includes(n)}function splitImportSuffix(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?{path:e,suffix:``}:{path:e.slice(0,r),suffix:e.slice(r)}}async function readAssetDataUrl(e){try{let t=await readFile(e);return`data:${getAssetMimeType(e)};base64,${t.toString(`base64`)}`}catch(e){if(isPathNotFoundError(e))return;throw e}}function isPathNotFoundError(e){return typeof e==`object`&&!!e&&`code`in e&&(e.code===`ENOENT`||e.code===`ENOTDIR`)}function getAssetMimeType(e){switch(extname(e).toLowerCase()){case`.css`:return`text/css`;case`.csv`:return`text/csv`;case`.gif`:return`image/gif`;case`.html`:return`text/html`;case`.jpg`:case`.jpeg`:return`image/jpeg`;case`.png`:return`image/png`;case`.svg`:return`image/svg+xml`;case`.txt`:return`text/plain`;case`.wasm`:return`application/wasm`;case`.webp`:return`image/webp`;default:return`application/octet-stream`}}export{createAuthoredAssetImportPlugin};