"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LevelWrapper = exports.createLevelDatabase = void 0;
var abort_js_1 = require("../utils/abort.js");
var time_js_1 = require("../utils/time.js");
function createLevelDatabase(location, options) {
    return __awaiter(this, void 0, void 0, function () {
        var Level;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, import('level')];
                case 1:
                    Level = (_a.sent()).Level;
                    return [2 /*return*/, new Level(location, __assign(__assign({}, options), { keyEncoding: 'utf8' }))];
            }
        });
    });
}
exports.createLevelDatabase = createLevelDatabase;
// `Level` works in Node.js 12+ and Electron 5+ on Linux, Mac OS, Windows and FreeBSD, including any
// future Node.js and Electron release thanks to Node-API, including ARM platforms like Raspberry Pi
// and Android, as well as in Chrome, Firefox, Edge, Safari, iOS Safari and Chrome for Android.
var LevelWrapper = /** @class */ (function () {
    /**
     * @param config.location - must be a directory path (relative or absolute) where `Level`` will
     * store its files, or in browsers, the name of the {@link https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase `IDBDatabase`}
     * to be opened.
     */
    function LevelWrapper(config, db) {
        this.config = __assign({ createLevelDatabase: createLevelDatabase }, config);
        this.db = db;
    }
    LevelWrapper.prototype.open = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.createLevelDatabase()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        if (!(this.db.status === 'opening' || this.db.status === 'closing')) return [3 /*break*/, 4];
                        return [4 /*yield*/, (0, time_js_1.sleep)(200)];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 2];
                    case 4:
                        if (this.db.status === 'open') {
                            return [2 /*return*/];
                        }
                        // `db.open()` is automatically called by the database constructor.  We're calling it explicitly
                        // in order to explicitly catch an error that would otherwise not surface until another method
                        // like `db.get()` is called.  Once `db.open()` has then been called, any read & write
                        // operations will again be queued internally until opening has finished.
                        return [2 /*return*/, this.db.open()];
                }
            });
        });
    };
    LevelWrapper.prototype.close = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.db) {
                            return [2 /*return*/];
                        }
                        _a.label = 1;
                    case 1:
                        if (!(this.db.status === 'opening' || this.db.status === 'closing')) return [3 /*break*/, 3];
                        return [4 /*yield*/, (0, time_js_1.sleep)(200)];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 1];
                    case 3:
                        if (this.db.status === 'closed') {
                            return [2 /*return*/];
                        }
                        return [2 /*return*/, this.db.close()];
                }
            });
        });
    };
    LevelWrapper.prototype.partition = function (name) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.createLevelDatabase()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, new LevelWrapper(this.config, this.db.sublevel(name, {
                                keyEncoding: 'utf8',
                                valueEncoding: this.config.valueEncoding
                            }))];
                }
            });
        });
    };
    LevelWrapper.prototype.get = function (key, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var value, error_1, e;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
                        return [4 /*yield*/, (0, abort_js_1.executeUnlessAborted)(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal)];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2:
                        _b.trys.push([2, 4, , 5]);
                        return [4 /*yield*/, (0, abort_js_1.executeUnlessAborted)(this.db.get(String(key)), options === null || options === void 0 ? void 0 : options.signal)];
                    case 3:
                        value = _b.sent();
                        return [2 /*return*/, value];
                    case 4:
                        error_1 = _b.sent();
                        e = error_1;
                        // `Level`` throws an error if the key is not present.  Return `undefined` in this case.
                        if (e.code === 'LEVEL_NOT_FOUND') {
                            return [2 /*return*/, undefined];
                        }
                        else {
                            throw error_1;
                        }
                        return [3 /*break*/, 5];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    LevelWrapper.prototype.has = function (key, options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.get(key, options)];
                    case 1: return [2 /*return*/, !!(_a.sent())];
                }
            });
        });
    };
    LevelWrapper.prototype.keys = function (options) {
        var _a, _b;
        return __asyncGenerator(this, arguments, function keys_1() {
            var _c, _d, key, e_1_1;
            var e_1, _e;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
                        return [4 /*yield*/, __await((0, abort_js_1.executeUnlessAborted)(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal))];
                    case 1:
                        _f.sent();
                        _f.label = 2;
                    case 2:
                        _f.trys.push([2, 9, 10, 15]);
                        _c = __asyncValues(this.db.keys());
                        _f.label = 3;
                    case 3: return [4 /*yield*/, __await(_c.next())];
                    case 4:
                        if (!(_d = _f.sent(), !_d.done)) return [3 /*break*/, 8];
                        key = _d.value;
                        (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted();
                        return [4 /*yield*/, __await(key)];
                    case 5: return [4 /*yield*/, _f.sent()];
                    case 6:
                        _f.sent();
                        _f.label = 7;
                    case 7: return [3 /*break*/, 3];
                    case 8: return [3 /*break*/, 15];
                    case 9:
                        e_1_1 = _f.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 15];
                    case 10:
                        _f.trys.push([10, , 13, 14]);
                        if (!(_d && !_d.done && (_e = _c.return))) return [3 /*break*/, 12];
                        return [4 /*yield*/, __await(_e.call(_c))];
                    case 11:
                        _f.sent();
                        _f.label = 12;
                    case 12: return [3 /*break*/, 14];
                    case 13:
                        if (e_1) throw e_1.error;
                        return [7 /*endfinally*/];
                    case 14: return [7 /*endfinally*/];
                    case 15: return [2 /*return*/];
                }
            });
        });
    };
    LevelWrapper.prototype.iterator = function (iteratorOptions, options) {
        var _a, _b;
        return __asyncGenerator(this, arguments, function iterator_1() {
            var _c, _d, entry, e_2_1;
            var e_2, _e;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
                        return [4 /*yield*/, __await((0, abort_js_1.executeUnlessAborted)(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal))];
                    case 1:
                        _f.sent();
                        _f.label = 2;
                    case 2:
                        _f.trys.push([2, 9, 10, 15]);
                        _c = __asyncValues(this.db.iterator(iteratorOptions));
                        _f.label = 3;
                    case 3: return [4 /*yield*/, __await(_c.next())];
                    case 4:
                        if (!(_d = _f.sent(), !_d.done)) return [3 /*break*/, 8];
                        entry = _d.value;
                        (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted();
                        return [4 /*yield*/, __await(entry)];
                    case 5: return [4 /*yield*/, _f.sent()];
                    case 6:
                        _f.sent();
                        _f.label = 7;
                    case 7: return [3 /*break*/, 3];
                    case 8: return [3 /*break*/, 15];
                    case 9:
                        e_2_1 = _f.sent();
                        e_2 = { error: e_2_1 };
                        return [3 /*break*/, 15];
                    case 10:
                        _f.trys.push([10, , 13, 14]);
                        if (!(_d && !_d.done && (_e = _c.return))) return [3 /*break*/, 12];
                        return [4 /*yield*/, __await(_e.call(_c))];
                    case 11:
                        _f.sent();
                        _f.label = 12;
                    case 12: return [3 /*break*/, 14];
                    case 13:
                        if (e_2) throw e_2.error;
                        return [7 /*endfinally*/];
                    case 14: return [7 /*endfinally*/];
                    case 15: return [2 /*return*/];
                }
            });
        });
    };
    LevelWrapper.prototype.put = function (key, value, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
                        return [4 /*yield*/, (0, abort_js_1.executeUnlessAborted)(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, (0, abort_js_1.executeUnlessAborted)(this.db.put(String(key), value), options === null || options === void 0 ? void 0 : options.signal)];
                }
            });
        });
    };
    LevelWrapper.prototype.delete = function (key, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
                        return [4 /*yield*/, (0, abort_js_1.executeUnlessAborted)(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, (0, abort_js_1.executeUnlessAborted)(this.db.del(String(key)), options === null || options === void 0 ? void 0 : options.signal)];
                }
            });
        });
    };
    LevelWrapper.prototype.isEmpty = function (options) {
        var e_3, _a;
        return __awaiter(this, void 0, void 0, function () {
            var _b, _c, _key, e_3_1;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 5, 6, 11]);
                        _b = __asyncValues(this.keys(options));
                        _d.label = 1;
                    case 1: return [4 /*yield*/, _b.next()];
                    case 2:
                        if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 4];
                        _key = _c.value;
                        return [2 /*return*/, false];
                    case 3: return [3 /*break*/, 1];
                    case 4: return [3 /*break*/, 11];
                    case 5:
                        e_3_1 = _d.sent();
                        e_3 = { error: e_3_1 };
                        return [3 /*break*/, 11];
                    case 6:
                        _d.trys.push([6, , 9, 10]);
                        if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 8];
                        return [4 /*yield*/, _a.call(_b)];
                    case 7:
                        _d.sent();
                        _d.label = 8;
                    case 8: return [3 /*break*/, 10];
                    case 9:
                        if (e_3) throw e_3.error;
                        return [7 /*endfinally*/];
                    case 10: return [7 /*endfinally*/];
                    case 11: return [2 /*return*/, true];
                }
            });
        });
    };
    LevelWrapper.prototype.clear = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.createLevelDatabase()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.db.clear()];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.compactUnderlyingStorage()];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    LevelWrapper.prototype.batch = function (operations, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
                        return [4 /*yield*/, (0, abort_js_1.executeUnlessAborted)(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, (0, abort_js_1.executeUnlessAborted)(this.db.batch(operations), options === null || options === void 0 ? void 0 : options.signal)];
                }
            });
        });
    };
    LevelWrapper.prototype.compactUnderlyingStorage = function (options) {
        var _a, _b, _c;
        return __awaiter(this, void 0, void 0, function () {
            var range, root;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
                        return [4 /*yield*/, (0, abort_js_1.executeUnlessAborted)(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal)];
                    case 1:
                        _d.sent();
                        range = this.sublevelRange;
                        if (!range) {
                            return [2 /*return*/];
                        }
                        root = this.root;
                        if (root.db.supports.additionalMethods.compactRange) {
                            return [2 /*return*/, (0, abort_js_1.executeUnlessAborted)((_c = (_b = root.db).compactRange) === null || _c === void 0 ? void 0 : _c.call.apply(_c, __spreadArray([_b], __read(range), false)), options === null || options === void 0 ? void 0 : options.signal)];
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(LevelWrapper.prototype, "sublevelRange", {
        /**
         * Gets the min and max key value of this partition.
         */
        get: function () {
            var prefix = this.db.prefix;
            if (!prefix) {
                return undefined;
            }
            // derive an exclusive `maxKey` by changing the last prefix character to the immediate succeeding character in unicode
            // (which matches how `abstract-level` creates a `boundary`)
            var maxKey = prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1);
            var minKey = prefix;
            return [minKey, maxKey];
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(LevelWrapper.prototype, "root", {
        get: function () {
            var db = this.db;
            for (var parent_1 = db.db; parent_1 && parent_1 !== db;) {
                db = parent_1;
            }
            return new LevelWrapper(this.config, db);
        },
        enumerable: false,
        configurable: true
    });
    LevelWrapper.prototype.createLevelDatabase = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var _b, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        if (!((_a = this.db) !== null && _a !== void 0)) return [3 /*break*/, 1];
                        _b = _a;
                        return [3 /*break*/, 3];
                    case 1:
                        _c = this;
                        return [4 /*yield*/, this.config.createLevelDatabase(this.config.location, {
                                keyEncoding: 'utf8',
                                valueEncoding: this.config.valueEncoding
                            })];
                    case 2:
                        _b = (_c.db = _d.sent());
                        _d.label = 3;
                    case 3:
                        _b;
                        return [2 /*return*/];
                }
            });
        });
    };
    LevelWrapper.prototype.dump = function () {
        var e_4, _a;
        return __awaiter(this, void 0, void 0, function () {
            var _b, _c, _d, key, value, e_4_1;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        if (!this.db) {
                            return [2 /*return*/];
                        }
                        _e.label = 1;
                    case 1:
                        _e.trys.push([1, 6, 7, 12]);
                        _b = __asyncValues(this.db.iterator());
                        _e.label = 2;
                    case 2: return [4 /*yield*/, _b.next()];
                    case 3:
                        if (!(_c = _e.sent(), !_c.done)) return [3 /*break*/, 5];
                        _d = __read(_c.value, 2), key = _d[0], value = _d[1];
                        console.debug(key, value);
                        _e.label = 4;
                    case 4: return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 12];
                    case 6:
                        e_4_1 = _e.sent();
                        e_4 = { error: e_4_1 };
                        return [3 /*break*/, 12];
                    case 7:
                        _e.trys.push([7, , 10, 11]);
                        if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
                        return [4 /*yield*/, _a.call(_b)];
                    case 8:
                        _e.sent();
                        _e.label = 9;
                    case 9: return [3 /*break*/, 11];
                    case 10:
                        if (e_4) throw e_4.error;
                        return [7 /*endfinally*/];
                    case 11: return [7 /*endfinally*/];
                    case 12: return [2 /*return*/];
                }
            });
        });
    };
    return LevelWrapper;
}());
exports.LevelWrapper = LevelWrapper;
//# sourceMappingURL=level-wrapper.js.map