import{dirname,join,relative,resolve,sep}from"node:path";import{readFile,writeFile}from"node:fs/promises";import{parseExtensionPackageRoots}from"#shared/extension-package-contract.js";async function tryReadExtensionBuildConfig(n){let o=resolve(n),c;try{c=JSON.parse(await readFile(join(o,`package.json`),`utf8`))}catch{return null}let l=parseExtensionPackageRoots(c.eve?.extension);if(l===null)return null;if(l.source===void 0)throw Error("`eve.extension.dist` is declared without `eve.extension.source`. Building an extension requires the authoring root; add `eve.extension.source` to package.json.");let u=resolve(o,l.source),d=resolve(o,l.dist),f=dirname(d);if(assertManagedPackagePath(o,u,`eve.extension.source`),assertManagedPackagePath(o,d,`eve.extension.dist`),assertManagedPackagePath(o,f,`eve.extension.dist output directory`),u===d)throw Error("`eve.extension.source` and `eve.extension.dist` must be different paths.");if(u===f||u.startsWith(`${f}${sep}`)||f.startsWith(`${u}${sep}`))throw Error("`eve.extension.source` and the managed dist output cannot overlap.");let p=typeof c.name==`string`&&c.name.length>0?c.name:`extension`;return{sourceRoot:u,distRoot:d,outDir:f,packageName:p,shortName:safeJsIdentifier(p.slice(p.lastIndexOf(`/`)+1)),runtimeDependencies:[...new Set([...Object.keys(c.dependencies??{}),...Object.keys(c.optionalDependencies??{}),...Object.keys(c.peerDependencies??{})])].sort()}}async function ensureExtensionExports(e,r){let i=join(e,`package.json`),s=await readFile(i,`utf8`),c=JSON.parse(s),l=relative(e,r).replaceAll(`\\`,`/`),u=l.startsWith(`.`)?l:`./${l}`,d={".":{types:`${u}/index.d.ts`,default:`${u}/index.mjs`},"./tools":{types:`${u}/tools/index.d.ts`,default:`${u}/tools/index.mjs`}},f=typeof c.exports==`object`&&c.exports!==null&&!Array.isArray(c.exports)?c.exports:{},p=!1;for(let[e,t]of Object.entries(d)){let n=f[e];typeof n==`object`&&n&&n.types===t.types&&n.default===t.default||(f[e]=t,p=!0)}p&&(c.exports=f,await writeFile(i,`${JSON.stringify(c,null,2)}\n`,`utf8`))}function assertManagedPackagePath(e,t,r){let a=relative(e,t);if(a===``||a===`..`||a.startsWith(`..${sep}`))throw Error(`\`${r}\` must point to a directory inside the extension package.`)}function safeJsIdentifier(e){let t=e.replace(/[^A-Za-z0-9_$]/g,`_`);return/^[A-Za-z_$]/.test(t)?t:`_${t}`}export{ensureExtensionExports,tryReadExtensionBuildConfig};