UNPKG

piral-cli

Version:

The standard CLI for creating and building a Piral instance or a Pilet.

68 lines 1.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.watcherTask = watcherTask; const fs_1 = require("fs"); function watcherTask(cb) { let running = Promise.resolve(); let pending = false; let notify = () => { }; const disposers = []; const triggers = []; const end = new Promise((resolve) => { notify = resolve; }); const ref = { data: undefined, on(cb) { triggers.push(cb); }, off(cb) { const idx = triggers.indexOf(cb); idx >= 0 && triggers.splice(idx, 1); }, end, }; const reRun = async () => { if (!pending) { pending = true; await running; await Promise.all(disposers.splice(0, disposers.length).map((dispose) => dispose())); pending = false; context.status = 'reoccuring'; await run(); triggers.splice(0, triggers.length).forEach((trigger) => trigger()); } }; const context = { onClean(dispose) { disposers.push(dispose); }, watch(file) { if ((0, fs_1.existsSync)(file)) { const watcher = (0, fs_1.watch)(file, { persistent: false, }, reRun); disposers.push(() => watcher.close()); } }, dependOn(anotherRef) { anotherRef.on(reRun); }, close() { cb = () => Promise.resolve(undefined); reRun().then(notify); }, status: 'initial', }; const run = async () => { running = cb(context).then((data) => { ref.data = data; }); await running; return ref; }; return new Promise((resolve, reject) => { run().then(resolve, reject); }); } //# sourceMappingURL=watcher.js.map