Files
phx-frontend-plugin-webcomp…/scripts/copy-latest.mjs

50 lines
1.2 KiB
JavaScript

import { watch } from 'node:fs';
import { access, constants, copyFile, mkdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = join(__dirname, '..');
const source = join(root, 'dist/phx-frontend-plugin-demo/browser/main.js');
const dest = join(root, 'latest/main.js');
async function copyMainJs() {
try {
await access(source, constants.F_OK);
await mkdir(dirname(dest), { recursive: true });
await copyFile(source, dest);
console.log('[latest] Copied main.js');
} catch (err) {
if (err.code !== 'ENOENT') {
console.error('[latest] Copy failed:', err.message);
}
}
}
function watchMainJs() {
let timeout;
const debouncedCopy = () => {
clearTimeout(timeout);
timeout = setTimeout(copyMainJs, 100);
};
const tryWatch = () => {
access(source, constants.F_OK)
.then(() => {
copyMainJs();
watch(source, debouncedCopy);
console.log('[latest] Watching for main.js changes');
})
.catch(() => setTimeout(tryWatch, 500));
};
tryWatch();
}
if (process.argv.includes('--watch')) {
watchMainJs();
} else {
copyMainJs();
}