import{dirname}from"node:path";import{mkdir,rename,rm,stat}from"node:fs/promises";import{pathExists}from"#shared/path-exists.js";async function assertStagedPublicationExists(e){await Promise.all([stat(e.stagedOutputDir),stat(e.stagedSummaryPath)])}async function prepareOutputPublication(n){[n.hadOutput,n.hadSummary]=await Promise.all([pathExists(n.finalOutputDir),pathExists(n.finalSummaryPath)]),await Promise.all([mkdir(dirname(n.finalOutputDir),{recursive:!0}),mkdir(dirname(n.finalSummaryPath),{recursive:!0})])}async function backupOutputPublication(e){e.hadOutput&&await rename(e.finalOutputDir,e.outputBackupPath),e.hadSummary&&await rename(e.finalSummaryPath,e.summaryBackupPath)}async function installOutputPublication(e,t){await rename(e.stagedOutputDir,e.finalOutputDir),await t(),await rename(e.stagedSummaryPath,e.finalSummaryPath)}async function rollbackOutputPublication(e){let t=(await Promise.allSettled([rollbackArtifact({backupPath:e.outputBackupPath,finalPath:e.finalOutputDir,hadPrevious:e.hadOutput,stagedPath:e.stagedOutputDir}),rollbackArtifact({backupPath:e.summaryBackupPath,finalPath:e.finalSummaryPath,hadPrevious:e.hadSummary,stagedPath:e.stagedSummaryPath})])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length>0)throw AggregateError(t,`Failed to restore the previous build publication.`)}async function removeOutputPublicationBackups(e){await Promise.all([rm(e.outputBackupPath,{force:!0,recursive:!0}),rm(e.summaryBackupPath,{force:!0,recursive:!0})])}async function rollbackArtifact(r){if(await pathExists(r.backupPath)){!await pathExists(r.stagedPath)&&await pathExists(r.finalPath)?(await mkdir(dirname(r.stagedPath),{recursive:!0}),await rename(r.finalPath,r.stagedPath)):await rm(r.finalPath,{force:!0,recursive:!0}),await rename(r.backupPath,r.finalPath);return}!r.hadPrevious&&!await pathExists(r.stagedPath)&&await pathExists(r.finalPath)&&(await mkdir(dirname(r.stagedPath),{recursive:!0}),await rename(r.finalPath,r.stagedPath))}export{assertStagedPublicationExists,backupOutputPublication,installOutputPublication,prepareOutputPublication,removeOutputPublicationBackups,rollbackOutputPublication};