{"code":"import beforeExit from '@yolodev/before-exit';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport proc from 'child_process';\r\nimport { promisify } from 'util';\r\nconst access = promisify(fs.access);\r\nconst readFile = promisify(fs.readFile);\r\nconst open = promisify(fs.open);\r\nconst close = promisify(fs.close);\r\nconst write = promisify(fs.write);\r\nconst workdirPid = (name, workdir = process.cwd()) => {\r\n    const pidFile = path.resolve(workdir, `.${name}.pid`);\r\n    const exists = async () => {\r\n        try {\r\n            await access(pidFile, fs.constants.F_OK);\r\n            return true;\r\n        }\r\n        catch (e) {\r\n            return false;\r\n        }\r\n    };\r\n    const checkRunning = async () => {\r\n        try {\r\n            const pid = parseInt(await readFile(pidFile, { encoding: 'utf-8' }), 10);\r\n            // will throw if process is not running\r\n            process.kill(pid, 0);\r\n            return true;\r\n        }\r\n        catch (e) {\r\n            return false;\r\n        }\r\n    };\r\n    const start = async (spawn, liveHandler) => {\r\n        if (await checkRunning()) {\r\n            throw new Error(`Already started`);\r\n        }\r\n        let fs = 0;\r\n        try {\r\n            fs = await open(pidFile, 'wx');\r\n            const p = proc.spawn(spawn.command, spawn.args, spawn.options);\r\n            await liveHandler(p);\r\n            await write(fs, p.pid.toString(), null, 'utf-8');\r\n        }\r\n        finally {\r\n            await close(fs);\r\n        }\r\n    };\r\n    const maybeStart = async (spawn, liveHandler) => {\r\n        if (await checkRunning()) {\r\n            return false;\r\n        }\r\n        let fs = 0;\r\n        try {\r\n            fs = await open(pidFile, 'wx');\r\n            const p = proc.spawn(spawn.command, spawn.args, spawn.options);\r\n            await liveHandler(p);\r\n            await write(fs, p.pid.toString(), null, 'utf-8');\r\n        }\r\n        finally {\r\n            await close(fs);\r\n        }\r\n    };\r\n    const connect = () => {\r\n        beforeExit(() => {\r\n            fs.unlinkSync(pidFile);\r\n        });\r\n    };\r\n    return {\r\n        exists,\r\n        checkRunning,\r\n        start,\r\n        maybeStart,\r\n        connect,\r\n    };\r\n};\r\nexport default workdirPid;\r\n","map":{"mappings":""}}
