"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const pnpm_logger_1 = require("pnpm-logger");
const path = require("path");
const lockfile = require("proper-lockfile");
function delay(ms) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise(resolve => setTimeout(resolve, ms));
    });
}
function lock(lockFilename, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const promise = new Promise((resolve, reject) => {
            lockfile.lock(lockFilename, { realpath: false, stale: opts.stale }, (err) => __awaiter(this, void 0, void 0, function* () {
                if (err && err.code === 'ELOCKED') {
                    if (opts.firstTime) {
                        pnpm_logger_1.default.warn('waiting for another installation to complete...');
                    }
                    yield delay(200);
                    yield lock(lockFilename, { firstTime: false, stale: opts.stale });
                    resolve();
                }
                else if (err) {
                    reject(err);
                }
                else {
                    resolve();
                }
            }));
        });
        return promise;
    });
}
function unlock(lockFilename) {
    return __awaiter(this, void 0, void 0, function* () {
        const promise = new Promise(resolve => lockfile.unlock(lockFilename, { realpath: false }, resolve));
        return promise;
    });
}
function withLock(storePath, fn, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const lockFilename = path.resolve(storePath, 'lock');
        yield lock(lockFilename, { firstTime: true, stale: opts.stale });
        try {
            const result = yield fn();
            yield unlock(lockFilename);
            return result;
        }
        catch (err) {
            yield unlock(lockFilename);
            throw err;
        }
    });
}
exports.default = withLock;
//# sourceMappingURL=lock.js.map