UNPKG

unstorage

Version:
111 lines (107 loc) 2.82 kB
'use strict'; function wrapToPromise(value) { if (!value || typeof value.then !== "function") { return Promise.resolve(value); } return value; } function asyncCall(function_, ...arguments_) { try { return wrapToPromise(function_(...arguments_)); } catch (error) { return Promise.reject(error); } } function isPrimitive(value) { const type = typeof value; return value === null || type !== "object" && type !== "function"; } function isPureObject(value) { const proto = Object.getPrototypeOf(value); return !proto || proto.isPrototypeOf(Object); } function stringify(value) { if (isPrimitive(value)) { return String(value); } if (isPureObject(value) || Array.isArray(value)) { return JSON.stringify(value); } if (typeof value.toJSON === "function") { return stringify(value.toJSON()); } throw new Error("[unstorage] Cannot stringify value!"); } function checkBufferSupport() { if (typeof Buffer === void 0) { throw new TypeError("[unstorage] Buffer is not supported!"); } } const BASE64_PREFIX = "base64:"; function serializeRaw(value) { if (typeof value === "string") { return value; } checkBufferSupport(); const base64 = Buffer.from(value).toString("base64"); return BASE64_PREFIX + base64; } function deserializeRaw(value) { if (typeof value !== "string") { return value; } if (!value.startsWith(BASE64_PREFIX)) { return value; } checkBufferSupport(); return Buffer.from(value.slice(BASE64_PREFIX.length), "base64"); } const storageKeyProperties = [ "hasItem", "getItem", "setItem", "removeItem", "getMeta", "setMeta", "removeMeta", "getKeys", "clear", "mount", "unmount" ]; function prefixStorage(storage, base) { base = normalizeBaseKey(base); if (!base) { return storage; } const nsStorage = { ...storage }; for (const property of storageKeyProperties) { nsStorage[property] = (key = "", ...args) => ( // @ts-ignore storage[property](base + key, ...args) ); } nsStorage.getKeys = (key = "", ...arguments_) => storage.getKeys(base + key, ...arguments_).then((keys) => keys.map((key2) => key2.slice(base.length))); return nsStorage; } function normalizeKey(key) { if (!key) { return ""; } return key.split("?")[0].replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, ""); } function joinKeys(...keys) { return normalizeKey(keys.join(":")); } function normalizeBaseKey(base) { base = normalizeKey(base); return base ? base + ":" : ""; } exports.asyncCall = asyncCall; exports.deserializeRaw = deserializeRaw; exports.joinKeys = joinKeys; exports.normalizeBaseKey = normalizeBaseKey; exports.normalizeKey = normalizeKey; exports.prefixStorage = prefixStorage; exports.serializeRaw = serializeRaw; exports.stringify = stringify;