export let storage = {
    /** 通过 key 获取字符串类型的值，不存在时返回空字符串 ('') */
    getstr(key) {
        return (localStorage.getItem(key) || '');
    },
    /** 将字符串类型的值保存到 key */
    setstr(key, value = '') {
        localStorage.setItem(key, value);
    },
    /** 根据 key 获取 JSON 类型的值，不存在时返回通过第二个参数传入的默认值，默认为 null */
    get(key, _default = null) {
        const strvalue = localStorage.getItem(key);
        return strvalue === null
            ? _default
            : JSON.parse(strvalue);
    },
    /** 保存 JSON 类型的值到 key, 并返回 value */
    set(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
        return value;
    },
    list() {
        return Object.keys(localStorage);
    },
    delete(key) {
        localStorage.removeItem(key);
    },
    set_bool(key, value) {
        localStorage.setItem(key, value ? '1' : '0');
    },
    get_bool(key) {
        const v = localStorage.getItem(key);
        return v === null ? undefined : (v !== '0' && v !== 'false');
    }
};
export let db = {
    store_name: 'kv-store',
    db: null,
    async wait_request(request) {
        return new Promise((resolve, reject) => {
            request.onerror = event => {
                reject(request.error);
            };
            request.onsuccess = event => {
                resolve(request.result);
            };
        });
    },
    async open() {
        let request = indexedDB.open('storage');
        request.onupgradeneeded = event => {
            request.result.createObjectStore(this.store_name);
        };
        this.db = await this.wait_request(request);
    },
    transaction(mode) {
        return this.db.transaction(this.store_name, mode)
            .objectStore(this.store_name);
    },
    async get(key) {
        return this.wait_request(this.transaction('readonly').get(key));
    },
    async set(key, value) {
        // 当 uint8array 长度与底层的 arraybuffer 长度不同时，可能是其中的一个 view，为了存储效率直接创建一个独立的 arraybuffer
        if (value && value instanceof Uint8Array && value.byteLength !== value.buffer.byteLength)
            value = value.slice();
        await this.wait_request(this.transaction('readwrite').put(value, key));
    },
    async delete(key) {
        return this.wait_request(this.transaction('readwrite')
            .delete(key));
    }
};
//# sourceMappingURL=storage.js.map