Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 180x 180x 79x 77x 75x 40x 180x 2x 2x 2x 94x 29x 29x 29x 1x 1x 1x 28x 29x 94x 2x 2x 2x 154x 130x 130x 24x 24x 154x 24x 36x 1x 1x 1x 154x 2x 2x 2x 73x 73x 78x 78x 73x 73x 2x 2x 2x 110x 110x 132x 132x 105x 105x 2x 2x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 236x 236x 236x 236x 236x 236x 236x 124x 108x 108x 236x 81x 72x 236x 1x 1x 236x 1x 1x 236x 236x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 2x 2x 11x 11x 11x 2x 2x 10x 10x 10x 10x 10x 10x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x | import { storage as storageConfig } from '@/../config.json';
import { Logger } from '@/utils/Logger';
import { compressToUTF16, decompressFromUTF16 } from 'lz-string';
import { getErrorMessage } from '@/helpers/exceptions';
/**
* Transparent lz-string compression layer for chrome.storage.
*
* @remarks
* Wraps `chrome.storage.local` and `chrome.storage.session` so that values written
* are LZ-compressed (UTF-16) before being stored, and decompressed automatically on
* read. Pre-existing uncompressed values are passed through unchanged on read so the
* wrapper is fully backward-compatible with data already in users' browsers.
*
* The module is split into two layers:
* - **Pure codec** ({@link encodeValue}, {@link decodeValue}, {@link encodeItems},
* {@link decodeItems}, {@link decodeChanges}): no `chrome.*` access; directly
* unit-testable.
* - **Adapter** ({@link cstorage}): a thin shim that delegates to the codec and
* talks to `chrome.storage`.
* @category Utils
* @source
*/
const logger = new Logger('storage');
/**
* Wire-format version. Bumped if the envelope shape ever changes.
* @category Utils
*/
export const LZ_VERSION = 1 as const;
/**
* Envelope wrapping a compressed JSON payload.
* Detected on read via {@link isLzEnvelope}.
* @category Utils
*/
export interface LzEnvelope {
__lz: typeof LZ_VERSION;
d: string;
}
/**
* Type-guard: returns `true` if `value` is an {@link LzEnvelope}.
* @category Utils
* @param value - Arbitrary value pulled from chrome.storage.
*/
export function isLzEnvelope(value: unknown): value is LzEnvelope {
return (
typeof value === 'object' &&
value !== null &&
!Array.isArray(value) &&
Reflect.get(value, '__lz') === LZ_VERSION &&
typeof Reflect.get(value, 'd') === 'string'
);
}
/**
* JSON-stringifies and LZ-compresses a value, returning an {@link LzEnvelope}.
* When `storage.useStorageCompression` is `false` in config.json, the value is stored
* as-is (no compression). If serialization fails (e.g. circular structures)
* the original value is returned untouched and an error is logged.
* @category Utils
* @param value - Any JSON-serializable value.
*/
export function encodeValue(value: unknown): LzEnvelope | unknown {
if (!storageConfig.useStorageCompression) return value;
try {
const json = JSON.stringify(value);
if (json === undefined) {
// value was undefined or a function — store as-is
return value;
}
return { __lz: LZ_VERSION, d: compressToUTF16(json) };
} catch (error) {
logger.error(`Failed to encode value, storing raw: ${getErrorMessage(error)}`, { error });
return value;
}
}
/**
* Decodes a value read from chrome.storage. If the value is an
* {@link LzEnvelope}, it is decompressed and JSON-parsed; otherwise the value
* is returned unchanged (backward-compatible passthrough for legacy data).
* @category Utils
* @param value - Raw value read from chrome.storage.
*/
export function decodeValue(value: unknown): unknown {
if (!isLzEnvelope(value)) {
return value;
}
try {
const json = decompressFromUTF16(value.d);
if (json === null || json === '') {
logger.error('Failed to decompress envelope, returning raw', { d: value.d });
return value;
}
return JSON.parse(json);
} catch (error) {
logger.error(`Failed to decode envelope, returning raw: ${getErrorMessage(error)}`, { error });
return value;
}
}
/**
* Encodes every value of an items map for `chrome.storage.X.set`.
* @category Utils
* @param items - Record of key/value pairs to write.
*/
export function encodeItems(items: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(items)) {
out[key] = encodeValue(value);
}
return out;
}
/**
* Decodes every value of an items map returned from `chrome.storage.X.get`.
* Tolerates mixed compressed and legacy entries (used by full-scan reads
* such as `chrome.storage.local.get(null)`).
* @category Utils
* @param items - Record returned from chrome.storage.
*/
export function decodeItems(items: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(items)) {
out[key] = decodeValue(value);
}
return out;
}
/**
* Decodes the `oldValue` / `newValue` of every change in a
* `chrome.storage.onChanged` payload.
* @category Utils
* @param changes - Raw changes object from chrome.storage.onChanged.
*/
export function decodeChanges(
changes: Record<string, chrome.storage.StorageChange>,
): Record<string, chrome.storage.StorageChange> {
const out: Record<string, chrome.storage.StorageChange> = {};
for (const [key, change] of Object.entries(changes)) {
const decoded: chrome.storage.StorageChange = {};
if ('oldValue' in change) decoded.oldValue = decodeValue(change.oldValue);
if ('newValue' in change) decoded.newValue = decodeValue(change.newValue);
out[key] = decoded;
}
return out;
}
/* -------------------------------------------------------------------------- */
/* Adapter (Layer B) */
/* -------------------------------------------------------------------------- */
type StorageAreaKeys = string | string[] | Record<string, unknown> | null;
/**
* Builds a per-area storage facade (`local` / `session`) that mirrors the
* native `chrome.storage.StorageArea` shape but transparently compresses on
* write and decompresses on read.
* @param area - "local" or "session".
*/
function makeArea(area: 'local' | 'session') {
return {
// Return type intentionally permissive ({ [key: string]: any }) to mirror
// the native `chrome.storage.StorageArea.get` shape, so existing call
// sites that index into the result continue to type-check unchanged.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async get(keys?: StorageAreaKeys): Promise<{ [key: string]: any }> {
const raw = await chrome.storage[area].get(keys ?? null);
return decodeItems(raw);
},
async set(items: Record<string, unknown>): Promise<void> {
await chrome.storage[area].set(encodeItems(items));
},
async remove(keys: string | string[]): Promise<void> {
await chrome.storage[area].remove(keys);
},
async clear(): Promise<void> {
await chrome.storage[area].clear();
},
};
}
/**
* Listener registered by callers of `cstorage.onChanged.addListener`.
* @category Utils
*/
export type ChangedListener = (
changes: Record<string, chrome.storage.StorageChange>,
areaName: chrome.storage.AreaName,
) => void;
/**
* Inner listener registered with `chrome.storage.onChanged`.
*/
type InnerChangedListener = (
changes: Record<string, chrome.storage.StorageChange>,
areaName: chrome.storage.AreaName,
) => void;
const listenerMap = new WeakMap<ChangedListener, InnerChangedListener>();
/**
* Compression-aware wrapper around `chrome.storage`. Use exactly like
* `chrome.storage.local` / `chrome.storage.session`, but values are
* transparently LZ-compressed at rest.
*
* @category Utils
* @example
* ```ts
* await cstorage.local.set({ USER_SETTINGS: settings });
* const { USER_SETTINGS } = await cstorage.local.get<{ USER_SETTINGS: UserSettings }>("USER_SETTINGS");
* ```
*/
export const cstorage = {
local: makeArea('local'),
session: makeArea('session'),
onChanged: {
/**
* Registers a listener that receives change events with `oldValue` /
* `newValue` already decompressed.
*/
addListener(listener: ChangedListener): void {
const inner: InnerChangedListener = (changes, areaName) => {
listener(decodeChanges(changes), areaName);
};
listenerMap.set(listener, inner);
chrome.storage.onChanged?.addListener(inner);
},
/** Removes a listener previously added via `addListener`. */
removeListener(listener: ChangedListener): void {
const inner = listenerMap.get(listener);
if (inner) {
chrome.storage.onChanged?.removeListener(inner);
listenerMap.delete(listener);
}
},
},
};
/* -------------------------------------------------------------------------- */
/* Console debug utility (_decodeCache) */
/* -------------------------------------------------------------------------- */
/**
* Reads and decodes a compressed value from chrome.storage, logging the
* result to the console. Registered as `window._decodeCache` for quick
* inspection during development.
*
* @example
* ```js
* // From the browser console:
* _decodeCache('table_state')
* _decodeCache('search_results', 'local')
* ```
* @param key - The storage key to look up (e.g. `'table_state'`).
* @param area - `'session'` (default) or `'local'`.
* @returns The decoded value (also logged to the console).
*/
async function decodeCache(key: string, area: 'session' | 'local' = 'session'): Promise<unknown> {
try {
const data = await cstorage[area].get([key]);
const value = data[key];
//console.log(`%c_decodeCache("${key}", "${area}"):`, "color: #4fc3f7; font-weight: bold", value);
return value;
} catch (error) {
logger.error(`Failed to decode cache key "${key}" from ${area}: ${getErrorMessage(error)}`, {
error,
});
return undefined;
}
}
// Register the global so it's callable from the browser console.
if (typeof window !== 'undefined') {
Reflect.set(window, '_decodeCache', decodeCache);
}
|