"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());
    });
};
const fs = require("mz/fs");
const path = require("path");
const mkdirp = require("mkdirp-promise");
const isWindows = require("is-windows");
// Always use "junctions" on Windows. Even though support for "symbolic links" was added in Vista+, users by default
// lack permission to create them
const symlinkType = isWindows() ? 'junction' : 'dir';
function symlinkDir(src, dest) {
    return __awaiter(this, void 0, void 0, function* () {
        src = path.resolve(src);
        dest = path.resolve(dest);
        // Junction points can't be relative
        const rel = symlinkType !== 'junction' ? path.relative(path.dirname(dest), src) : src;
        try {
            yield forceSymlink(rel, dest);
        }
        catch (err) {
            if (err.code === 'ENOENT') {
                yield mkdirp(path.dirname(dest));
                yield forceSymlink(rel, dest);
                return;
            }
            throw err;
        }
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = symlinkDir;
/**
 * Creates a symlink. Re-link if a symlink already exists at the supplied
 * srcPath. API compatible with [`fs#symlink`](https://nodejs.org/api/fs.html#fs_fs_symlink_srcpath_dstpath_type_callback).
 */
function forceSymlink(src, dest) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield fs.symlink(src, dest, symlinkType);
        }
        catch (err) {
            if (err.code !== 'EEXIST')
                throw err;
            const linkString = yield fs.readlink(dest);
            if (src === linkString) {
                return;
            }
            yield fs.unlink(dest);
            yield forceSymlink(src, dest);
        }
    });
}
//# sourceMappingURL=index.js.map