import{resolve}from"node:path";import{randomUUID}from"node:crypto";import{assertStagedPublicationExists,backupOutputPublication,installOutputPublication,prepareOutputPublication,removeOutputPublicationBackups,rollbackOutputPublication}from"#internal/application/output-publication-artifacts.js";import{writeOutputPublicationJournal}from"#internal/application/output-publication-journal.js";import{acquireOutputPublicationLock,resolveOutputPublicationLockPath,startPublicationJournalHeartbeat}from"#internal/application/output-publication-lock.js";var RecoverablePublicationError=class extends AggregateError{constructor(e,t,n){super(e,t,n),this.name=`RecoverablePublicationError`}};const DEFAULT_OBSERVER={async afterBackup(){},async afterOutputInstall(){},async onContention(){}};async function publishApplicationBuildArtifacts(e){await publishApplicationBuildArtifactsWithObserver(e,DEFAULT_OBSERVER)}async function publishApplicationBuildArtifactsWithObserver(e,t){let o=createOutputPublicationJournal(e);await assertStagedPublicationExists(o);let s=resolveOutputPublicationLockPath(e.appRoot),c=await acquireOutputPublicationLock(s,o,t.onContention),l=startPublicationJournalHeartbeat(s),u=!1;try{await prepareOutputPublication(o),o.phase=`prepared`,await writeOutputPublicationJournal(s,o),await backupOutputPublication(o),o.phase=`backed-up`,await writeOutputPublicationJournal(s,o),await t.afterBackup(),await installOutputPublication(o,t.afterOutputInstall),o.phase=`committed`,await writeOutputPublicationJournal(s,o),u=!0,await removeOutputPublicationBackups(o)}catch(e){u&&await throwRecoverablePublicationError({errors:[e],journal:o,lockPath:s,message:`Build output was committed but backup cleanup failed.`});try{await rollbackOutputPublication(o)}catch(t){await throwRecoverablePublicationError({errors:[e,t],journal:o,lockPath:s,message:`Build output publication failed and could not fully restore the previous output.`})}throw await c(),e}finally{l()}await c()}function createOutputPublicationJournal(n){let r=randomUUID(),i=resolve(n.finalOutputDir),a=resolve(n.finalSummaryPath);return{finalOutputDir:i,finalSummaryPath:a,hadOutput:!1,hadSummary:!1,liveness:`active`,outputBackupPath:`${i}.eve-backup-${r}`,phase:`acquired`,pid:process.pid,scratchDir:resolve(n.scratchDir),stagedOutputDir:resolve(n.stagedOutputDir),stagedSummaryPath:resolve(n.stagedSummaryPath),summaryBackupPath:`${a}.eve-backup-${r}`,token:r}}async function throwRecoverablePublicationError(e){e.journal.liveness=`recoverable`;try{await writeOutputPublicationJournal(e.lockPath,e.journal)}catch(t){throw new RecoverablePublicationError([...e.errors,t],e.message,{cause:e.errors[0]})}throw new RecoverablePublicationError(e.errors,e.message,{cause:e.errors[0]})}export{RecoverablePublicationError,publishApplicationBuildArtifacts,publishApplicationBuildArtifactsWithObserver,resolveOutputPublicationLockPath};