gm-storage
Version:
An ES6 Map wrapper for the synchronous userscript storage API
85 lines (82 loc) • 2.1 kB
JavaScript
/* gm-storage 4.1.1. @copyright 2020 chocolateboy. @license MIT */
;
const GM_API_KEYS = ["GM_deleteValue", "GM_getValue", "GM_listValues", "GM_setValue"];
const NOT_FOUND = Symbol();
const OPTIONS = { strict: true };
class GMStorageBase {
constructor(options = OPTIONS) {
if (!options.strict) {
return;
}
for (const key of GM_API_KEYS) {
const value = globalThis[key];
if (!value) {
throw new ReferenceError(`${key} is not defined`);
}
if (typeof value !== "function") {
throw new TypeError(`${key} is not a function`);
}
}
}
_has(key) {
return GM_getValue(key, NOT_FOUND) !== NOT_FOUND;
}
clear() {
const keys = GM_listValues();
for (let i = 0; i < keys.length; ++i) {
GM_deleteValue(keys[i]);
}
}
delete(key) {
const $key = this.stringify(key);
return this._has($key) && (GM_deleteValue($key), true);
}
*entries() {
const keys = GM_listValues();
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
yield [this.parse(key), GM_getValue(key)];
}
}
forEach(callback, $this = void 0) {
for (const [key, value] of this.entries()) {
callback.call($this, value, key, this);
}
}
get(key, $default = void 0) {
return GM_getValue(this.stringify(key), $default);
}
has(key) {
return this._has(this.stringify(key));
}
*keys() {
const keys = GM_listValues();
for (let i = 0; i < keys.length; ++i) {
yield this.parse(keys[i]);
}
}
set(key, value) {
GM_setValue(this.stringify(key), value);
return this;
}
setAll(values = []) {
for (const [key, value] of values) {
this.set(key, value);
}
return this;
}
get size() {
return GM_listValues().length;
}
*values() {
const keys = GM_listValues();
for (let i = 0; i < keys.length; ++i) {
yield GM_getValue(keys[i]);
}
}
}
Object.assign(GMStorageBase.prototype, {
[Symbol.iterator]: GMStorageBase.prototype.entries
});
exports.GMStorageBase = GMStorageBase;
exports.OPTIONS = OPTIONS;