import EventEmitter from"node:events";import path from"node:path";import fs from"node:fs";import Files from"../files/files.mjs";import{PACKAGE_TYPE_MAPPING}from"./_module.mjs";export default class PackageInstaller extends EventEmitter{constructor(t,s,i,e,a){super(),this.#t=t,this.#s=s,this.#i=i,this.#e=e,this.#a=a}#i;#e;#a;#t;#s;#r={step:null,pct:0};async install(){this.#r={step:null,pct:0};try{return(await this.#n()).vend()}catch(t){this.emit("error",t)}finally{fs.unlinkSync(this.#e)}}async#n(){if(this.#i.startsWith(".."))throw new Error("You are not allowed to install packages outside of the designated directory path");const t=path.join(this.#s,this.#i);let s="",i=await Files.summarizeArchive(this.#e,{manifestPath:`${this.#t}.json`});if(null===i.manifest){const t=i.contents.find((t=>t.endsWith(`${this.#t}.json`)));s=`${path.dirname(t)}/`,i=await Files.summarizeArchive(this.#e,{manifestPath:`${s}${this.#t}.json`})}if(!i.manifest)throw fs.unlinkSync(this.#e),new Error(`The downloaded package ${this.#i} did not contain the expected ${this.#t}.json manifest file.`);const e=new(0,PACKAGE_TYPE_MAPPING[this.#t])(JSON.parse(i.manifest),{installed:!1});if(e.persistentStorage&&fs.existsSync(path.join(t,"storage"))){const s=fs.readdirSync(t);for(let i of s){if("storage"===i)continue;const s=path.join(t,i);await fs.promises.rm(s,{recursive:!0})}}else await fs.promises.rm(t,{force:!0,recursive:!0});if(await Files.extractArchive(this.#e,t,{removeRoot:s,onProgress:this.#o.bind(this)}),e.persistentStorage){const s=path.join(t,"storage");fs.existsSync(s)||fs.mkdirSync(s)}if(this.#a){const s=path.join(t,"signature.json"),i="signatureV2"in this.#a?{key:this.#a.key,package:this.#i,signature:this.#a.signatureV2}:{key:this.#a.key,signature:this.#a.signature};fs.writeFileSync(s,JSON.stringify(i,null,2))}return e}#o(t,s,i){return this.emit("progress",CONST.SETUP_PACKAGE_PROGRESS.STEPS.INSTALL,s,i)}}