UNPKG

barro

Version:

Flexible barrel file generation for Javascript and Typescript with watching built-in.

45 lines 2.14 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.watchBarrelFiles = void 0; const chokidar_1 = __importDefault(require("chokidar")); const getBarrelIgnoreGlobs_1 = require("./getBarrelIgnoreGlobs"); let eventIdCounter = 1; function watchBarrelFiles(barrel, onChange) { let watchCancelled = false; let currentEventId = 0; // Used to determine if a watch event is stale and should cancel writing let queue = Promise.resolve(); // Promise queue to avoid compiling the same index multiple times concurrently const watcher = chokidar_1.default.watch(barrel.match, { cwd: barrel.matchDirectory, ignored: getBarrelIgnoreGlobs_1.getBarrelIgnoreGlobs(barrel), ignoreInitial: true, }); // Wait until all previous calls have run before running again const handleWatchEvent = async (eventType, filepath) => { const eventId = (currentEventId = eventIdCounter); eventIdCounter += 1; // if another event was received before this one finishes, allow `onChange` to react accordingly const isCancelled = () => watchCancelled || currentEventId !== eventId; const nextInQueue = async () => onChange(eventType, filepath, isCancelled); queue = queue.then(nextInQueue, nextInQueue); await queue; }; // Watch event listeners const onAddFile = async (path) => handleWatchEvent("add", path); const onUnlinkFile = async (path) => handleWatchEvent("unlink", path); const onUnlinkDir = async (path) => handleWatchEvent("unlinkDir", path); const teardown = () => { watchCancelled = true; watcher.off("add", onAddFile); watcher.off("unlink", onUnlinkFile); watcher.off("unlinkDir", onUnlinkDir); }; watcher.on("add", onAddFile); watcher.on("unlink", onUnlinkFile); watcher.on("unlinkDir", onUnlinkDir); return teardown; } exports.watchBarrelFiles = watchBarrelFiles; //# sourceMappingURL=watchBarrelFiles.js.map