29 lines
2.0 KiB
JavaScript
29 lines
2.0 KiB
JavaScript
// Publish a tested static build to the *loopback* service. Retain older hashed
|
|
// chunks for already-open tabs; atomically change HTML only after all copies finish.
|
|
import path from 'node:path'
|
|
import {fileURLToPath} from 'node:url'
|
|
import {copyFile, mkdir, readFile, readdir, rename, writeFile} from 'node:fs/promises'
|
|
import {randomUUID} from 'node:crypto'
|
|
const root=fileURLToPath(new URL('../node_modules/.zyt-live-native/',import.meta.url))
|
|
const [action,name]=process.argv.slice(2)
|
|
if(!['apply','restore'].includes(action)||!/^[a-z][a-z0-9-]{1,48}$/.test(name??'')) throw Error('Usage: promote-local.mjs apply|restore <candidate>')
|
|
const candidate=path.join(root,'candidates',name), live=path.join(root,'dist'), entry='live-native/index.html', old=path.join(root,'checkpoints',name+'.html')
|
|
async function atomic(dst,bytes){const temp=dst+'.'+randomUUID()+'.tmp';await writeFile(temp,bytes);await rename(temp,dst)}
|
|
async function sync(dir,relative=''){
|
|
for (const item of await readdir(dir,{withFileTypes:true})){
|
|
const rel=path.join(relative,item.name),dst=path.join(live,rel)
|
|
if(item.isDirectory()){await mkdir(dst,{recursive:true});await sync(path.join(dir,item.name),rel)}
|
|
else if(item.isFile() && rel!==entry){const temp=dst+'.'+randomUUID()+'.tmp';await copyFile(path.join(dir,item.name),temp);await rename(temp,dst)}
|
|
}
|
|
}
|
|
const next=await readFile(path.join(candidate,entry),'utf8');const assets=[...next.matchAll(/(?:src|href)="\/admin\/(assets\/[^"?]+)"/g)].map(m=>m[1]);if(!assets.length)throw Error('No build assets referenced')
|
|
if(action==='apply'){
|
|
for(const a of assets) await readFile(path.join(candidate,a))
|
|
await mkdir(path.dirname(old),{recursive:true});await writeFile(old,await readFile(path.join(live,entry)),{flag:'wx'})
|
|
await sync(candidate);await atomic(path.join(live,entry),next)
|
|
}else{
|
|
if(await readFile(path.join(live,entry),'utf8')!==next)throw Error('The active version changed; refusing to overwrite it')
|
|
await atomic(path.join(live,entry),await readFile(old));
|
|
}
|
|
console.log(`local ${action}: ${name}`)
|