New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@avanio/expire-cache

Package Overview
Dependencies
Maintainers
0
Versions
23
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@avanio/expire-cache - npm Package Compare versions

Comparing version 0.3.3 to 0.4.0

dist/index.cjs

291

dist/index.d.ts

@@ -1,5 +0,286 @@

export * from './interfaces/ICache';
export * from './interfaces/IAsyncCache';
export * from './interfaces/ICacheOrAsync';
export * from './ExpireCache';
export * from './ExpireTimeoutCache';
import { LogMapping, MapLogger, ILoggerLike } from '@avanio/logger-like';
/**
* Callback type for when entries are expired or cleared
*/
type ICacheOnClearCallback<Payload, Key = string> = (entries: Map<Key, Payload>) => void;
/**
* Synchronous cache interface
* @example
* function foo(cache: ICache<string>) {
* const value = cache.get('key');
* cache.set('key', 'value');
* cache.has('key'); // true
* cache.delete('key');
* cache.clear();
* cache.size(); // 0
* }
*/
interface ICache<Payload, Key = string> {
/**
* Gets a value from the cache
* @param key - The key to get the value for
* @returns The cached value or undefined if not found
*/
get(key: Key): Payload | undefined;
/**
* Sets a value in the cache with an optional expiration date
* @param key - The key to set the value for
* @param data - The data to set in the cache
* @param expires - The optional expiration date for the cache entry
*/
set(key: Key, value: Payload, expires?: Date): void;
/**
* Deletes a value from the cache
* @param key - The key to delete the value for
* @returns {boolean} True if the value was deleted, false otherwise
*/
delete(key: Key): boolean;
/**
* Checks if a key exists in the cache
* @param key - The key to check for
* @returns {boolean} True if the key exists in the cache, false otherwise
*/
has(key: Key): boolean;
/**
* Get key expiration Date object or undefined if not found in cache
* @param key - The key to get the expiration for
* @returns {Date | undefined} Date object or undefined if not found in cache
*/
expires(key: Key): Date | undefined;
/**
* Clear all cached values
*/
clear(): void;
/**
* Gets the number of items in the cache
* @returns {number} The number of items in the cache
*/
size(): number;
/**
* Called when a entries are expired, deleted or cleared
*/
onClear(callback: ICacheOnClearCallback<Payload, Key>): void;
/**
* Returns an iterator of key, value pairs for every entry in the cache.
* @example
* for(const [key, value] of cache.entries()) {
* console.log(key, value);
* }
*/
entries(): IterableIterator<[Key, Payload]>;
/**
* Returns an iterator of keys in the cache.
* @example
* for(const key of cache.keys()) {
* console.log(key);
* }
*/
keys(): IterableIterator<Key>;
/**
* Returns an iterator of values in the cache.
* @example
* for(const value of cache.values()) {
* console.log(value);
* }
*/
values(): IterableIterator<Payload>;
}
/**
* Async callback type for when entries are expired or cleared
*/
type IAsyncCacheOnClearCallback<Payload, Key = string> = (entries: Map<Key, Payload>) => Promise<void>;
/**
* Asynchronous cache interface
* @example
* function foo(cache: IAsyncCache<string>) {
* const value = await cache.get('key');
* await cache.set('key', 'value');
* await cache.has('key'); // true
* await cache.delete('key');
* await cache.clear();
* await cache.size(); // 0
* }
*/
interface IAsyncCache<Payload, Key = string> {
/**
* Gets a value from the cache
* @param key - The key to get the value for
* @returns {Promise<Payload | undefined>} Promise of the cached value or undefined if not found
*/
get(key: Key): Promise<Payload | undefined>;
/**
* Sets a value in the cache with an optional expiration date
* @param key - The key to set the value for
* @param data - The data to set in the cache
* @param expires - The optional expiration date for the cache entry
* @returns {Promise<void>} Promise of void
*/
set(key: Key, value: Payload, expires?: Date): Promise<void>;
/**
* Deletes a value from the cache
* @param key - The key to delete the value for
* @returns {Promise<boolean>} Promise of true if the value was deleted, false otherwise
*/
delete(key: Key): Promise<boolean>;
/**
* Checks if a key exists in the cache
* @param key - The key to check for
* @returns {Promise<boolean>} Promise of true if the key exists in the cache, false otherwise
*/
has(key: Key): Promise<boolean>;
/**
* Get key expiration Date object or undefined if not found in cache
* @param key - The key to get the expiration for
* @returns {Promise<Date | undefined>} Promise of Date object or undefined if not found in cache
*/
expires(key: Key): Promise<Date | undefined>;
/**
* Clear all cached values
*/
clear(): Promise<void>;
/**
* Gets the number of items in the cache
* @returns {Promise<number>} Promise of the number of items in the cache
*/
size(): Promise<number>;
/**
* Called when a entries are expired, deleted or cleared
*/
onClear(callback: IAsyncCacheOnClearCallback<Payload, Key>): void;
/**
* Returns an async iterator of key, value pairs for every entry in the cache.
* @example
* for await (const [key, value] of cache.entries()) {
* console.log(key, value);
* }
*/
entries(): AsyncIterableIterator<[Key, Payload]>;
/**
* Async iterator for cache keys
* @example
* for await (const key of cache.keys()) {
* console.log(key);
* }
*/
keys(): AsyncIterableIterator<Key>;
/**
* Async iterator for cache values
* @example
* for await (const value of cache.values()) {
* console.log(value);
* }
*/
values(): AsyncIterableIterator<Payload>;
}
/**
* A type that represents both synchronous and asynchronous cache interfaces.
* This type can be used to create functions that work with both types of cache interfaces.
* @example
* function foo(cache: ICacheOrAsync<string>) {
* const value = await cache.get('key');
* await cache.set('key', 'value');
* await cache.has('key'); // true
* await cache.delete('key');
* await cache.clear();
* await cache.size(); // 0
* }
*/
type ICacheOrAsync<Payload, Key = string> = ICache<Payload, Key> | IAsyncCache<Payload, Key>;
/**
* The default log mapping for the ExpireCache class.
* This maps each method to a log level, allowing you to control the logging output.
* By default, all logs are disabled (None level)
* @example
* const cache = new ExpireCache<string>(console, {
* get: LogLevel.Info,
* set: LogLevel.Debug,
* delete: LogLevel.Warn,
* });
*/
declare const defaultLogMap: {
readonly cleanExpired: 0;
readonly clear: 0;
readonly constructor: 0;
readonly delete: 0;
readonly expires: 0;
readonly get: 0;
readonly has: 0;
readonly onExpire: 0;
readonly set: 0;
readonly size: 0;
};
type ExpireCacheLogMapType = LogMapping<keyof typeof defaultLogMap>;
/**
* ExpireCache class that implements the ICache interface with value expiration and expires on read operations
* @template Payload - The type of the cached data
* @template Key - (optional) The type of the cache key (default is string)
*/
declare class ExpireCache<Payload, Key = string> extends MapLogger<ExpireCacheLogMapType> implements ICache<Payload, Key> {
private cache;
private handleOnClear;
private defaultExpireMs;
/**
* Creates a new instance of the ExpireCache class
* @param logger - The logger to use (optional)
* @param logMapping - The log mapping to use (optional). Default is all logging disabled
* @param defaultExpireMs - The default expiration time in milliseconds (optional)
*/
constructor(logger?: ILoggerLike, logMapping?: Partial<ExpireCacheLogMapType>, defaultExpireMs?: number);
set(key: Key, data: Payload, expires?: Date): void;
get(key: Key): Payload | undefined;
has(key: Key): boolean;
expires(key: Key): Date | undefined;
delete(key: Key): boolean;
clear(): void;
size(): number;
onClear(callback: ICacheOnClearCallback<Payload, Key>): void;
entries(): IterableIterator<[Key, Payload]>;
keys(): IterableIterator<Key>;
values(): IterableIterator<Payload>;
setExpireMs(expireMs: number | undefined): void;
/**
* Cleans expired cache entries
*/
private cleanExpired;
private notifyOnClear;
private cacheAsKeyPayloadMap;
}
/**
* ExpireCache class that implements the ICache interface with value expiration and expires with setTimeout
* @template Payload - The type of the cached data
* @template Key - (optional) The type of the cache key (default is string)
*/
declare class ExpireTimeoutCache<Payload, Key = string> extends MapLogger<ExpireCacheLogMapType> implements ICache<Payload, Key> {
private cache;
private handleOnClear;
private defaultExpireMs;
/**
* Creates a new instance of the ExpireTimeoutCache class
* @param logger - The logger to use (optional)
* @param logMapping - The log mapping to use (optional). Default is all logging disabled
* @param defaultExpireMs - The default expiration time in milliseconds (optional)
*/
constructor(logger?: ILoggerLike, logMapping?: Partial<ExpireCacheLogMapType>, defaultExpireMs?: number);
set(key: Key, data: Payload, expires?: Date): void;
get(key: Key): Payload | undefined;
has(key: Key): boolean;
expires(key: Key): Date | undefined;
delete(key: Key): boolean;
clear(): void;
size(): number;
onClear(callback: ICacheOnClearCallback<Payload, Key>): void;
entries(): IterableIterator<[Key, Payload]>;
keys(): IterableIterator<Key>;
values(): IterableIterator<Payload>;
setExpireMs(expireMs: number | undefined): void;
private clearTimeout;
private notifyOnClear;
private cacheAsKeyPayloadMap;
}
export { ExpireCache, type ExpireCacheLogMapType, ExpireTimeoutCache, type IAsyncCache, type IAsyncCacheOnClearCallback, type ICache, type ICacheOnClearCallback, type ICacheOrAsync };

@@ -1,22 +0,226 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
// src/ExpireCache.ts
import { LogLevel, MapLogger } from "@avanio/logger-like";
var defaultLogMap = {
cleanExpired: LogLevel.None,
clear: LogLevel.None,
constructor: LogLevel.None,
delete: LogLevel.None,
expires: LogLevel.None,
get: LogLevel.None,
has: LogLevel.None,
onExpire: LogLevel.None,
set: LogLevel.None,
size: LogLevel.None
};
var ExpireCache = class extends MapLogger {
/**
* Creates a new instance of the ExpireCache class
* @param logger - The logger to use (optional)
* @param logMapping - The log mapping to use (optional). Default is all logging disabled
* @param defaultExpireMs - The default expiration time in milliseconds (optional)
*/
constructor(logger, logMapping, defaultExpireMs) {
super(logger, Object.assign({}, defaultLogMap, logMapping));
this.cache = /* @__PURE__ */ new Map();
this.handleOnClear = /* @__PURE__ */ new Set();
this.logKey("constructor", `ExpireCache created, defaultExpireMs: ${String(defaultExpireMs)}`);
this.defaultExpireMs = defaultExpireMs;
}
set(key, data, expires) {
var _a;
const expireTs = (_a = expires == null ? void 0 : expires.getTime()) != null ? _a : this.defaultExpireMs && Date.now() + this.defaultExpireMs;
this.logKey("set", `ExpireCache set key: ${String(key)}, expireTs: ${String(expireTs)}`);
this.cache.set(key, { data, expires: expireTs });
}
get(key) {
var _a;
this.logKey("get", `ExpireCache get key: ${String(key)}`);
this.cleanExpired();
return (_a = this.cache.get(key)) == null ? void 0 : _a.data;
}
has(key) {
this.logKey("has", `ExpireCache has key: ${String(key)}`);
this.cleanExpired();
return this.cache.has(key);
}
expires(key) {
this.logKey("expires", `ExpireCache get expire for key: ${String(key)}`);
const entry = this.cache.get(key);
this.cleanExpired();
return (entry == null ? void 0 : entry.expires) ? new Date(entry.expires) : void 0;
}
delete(key) {
this.logKey("delete", `ExpireCache delete key: ${String(key)}`);
const entry = this.cache.get(key);
if (entry) {
this.notifyOnClear(/* @__PURE__ */ new Map([[key, entry.data]]));
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
return this.cache.delete(key);
}
clear() {
this.logKey("clear", `ExpireCache clear`);
this.notifyOnClear(this.cacheAsKeyPayloadMap());
this.cache.clear();
}
size() {
this.logKey("size", `ExpireCache size: ${this.cache.size.toString()}`);
return this.cache.size;
}
onClear(callback) {
this.logKey("onExpire", `ExpireCache onExpire`);
this.handleOnClear.add(callback);
}
entries() {
this.cleanExpired();
return this.cacheAsKeyPayloadMap().entries();
}
keys() {
this.cleanExpired();
return this.cacheAsKeyPayloadMap().keys();
}
values() {
this.cleanExpired();
return this.cacheAsKeyPayloadMap().values();
}
setExpireMs(expireMs) {
this.defaultExpireMs = expireMs;
}
/**
* Cleans expired cache entries
*/
cleanExpired() {
const now = (/* @__PURE__ */ new Date()).getTime();
const deleteEntries = /* @__PURE__ */ new Map();
for (const [key, value] of this.cache.entries()) {
if (value.expires !== void 0 && value.expires < now) {
deleteEntries.set(key, value.data);
this.cache.delete(key);
}
}
if (deleteEntries.size > 0) {
this.notifyOnClear(deleteEntries);
this.logKey("cleanExpired", `ExpireCache expired count: ${deleteEntries.size.toString()}`);
}
}
notifyOnClear(entries) {
this.handleOnClear.forEach((callback) => callback(entries));
}
cacheAsKeyPayloadMap() {
const map = /* @__PURE__ */ new Map();
for (const [key, value] of this.cache.entries()) {
map.set(key, value.data);
}
return map;
}
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./interfaces/ICache"), exports);
__exportStar(require("./interfaces/IAsyncCache"), exports);
__exportStar(require("./interfaces/ICacheOrAsync"), exports);
__exportStar(require("./ExpireCache"), exports);
__exportStar(require("./ExpireTimeoutCache"), exports);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiLi9zcmMvIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7O0FBQUEsc0RBQW9DO0FBQ3BDLDJEQUF5QztBQUN6Qyw2REFBMkM7QUFDM0MsZ0RBQThCO0FBQzlCLHVEQUFxQyJ9
// src/ExpireTimeoutCache.ts
import { LogLevel as LogLevel2, MapLogger as MapLogger2 } from "@avanio/logger-like";
var defaultLogMap2 = {
cleanExpired: LogLevel2.None,
clear: LogLevel2.None,
constructor: LogLevel2.None,
delete: LogLevel2.None,
expires: LogLevel2.None,
get: LogLevel2.None,
has: LogLevel2.None,
onExpire: LogLevel2.None,
set: LogLevel2.None,
size: LogLevel2.None
};
var ExpireTimeoutCache = class extends MapLogger2 {
/**
* Creates a new instance of the ExpireTimeoutCache class
* @param logger - The logger to use (optional)
* @param logMapping - The log mapping to use (optional). Default is all logging disabled
* @param defaultExpireMs - The default expiration time in milliseconds (optional)
*/
constructor(logger, logMapping, defaultExpireMs) {
super(logger, Object.assign({}, defaultLogMap2, logMapping));
this.cache = /* @__PURE__ */ new Map();
this.handleOnClear = /* @__PURE__ */ new Set();
this.logKey("constructor", `ExpireTimeoutCache created, defaultExpireMs: ${String(defaultExpireMs)}`);
this.defaultExpireMs = defaultExpireMs;
}
set(key, data, expires) {
this.clearTimeout(key);
const defaultExpireDate = this.defaultExpireMs ? new Date(Date.now() + this.defaultExpireMs) : void 0;
const expiresDate = expires != null ? expires : defaultExpireDate;
const expireTs = expiresDate && expiresDate.getTime() - Date.now();
const expireString = expireTs ? `${expireTs.toString()} ms` : "undefined";
this.logKey("set", `ExpireTimeoutCache set key: ${String(key)}, expireTs: ${expireString}`);
const timeout = expireTs ? setTimeout(() => this.delete(key), expireTs) : void 0;
this.cache.set(key, { data, timeout, expires: expiresDate });
}
get(key) {
var _a;
this.logKey("get", `ExpireTimeoutCache get key: ${String(key)}`);
return (_a = this.cache.get(key)) == null ? void 0 : _a.data;
}
has(key) {
this.logKey("has", `ExpireTimeoutCache has key: ${String(key)}`);
return this.cache.has(key);
}
expires(key) {
this.logKey("expires", `ExpireTimeoutCache get expire for key: ${String(key)}`);
const entry = this.cache.get(key);
return entry == null ? void 0 : entry.expires;
}
delete(key) {
this.logKey("delete", `ExpireTimeoutCache delete key: ${String(key)}`);
this.clearTimeout(key);
const entry = this.cache.get(key);
if (entry) {
this.notifyOnClear(/* @__PURE__ */ new Map([[key, entry.data]]));
}
return this.cache.delete(key);
}
clear() {
this.logKey("clear", `ExpireTimeoutCache clear`);
this.cache.forEach((_value, key) => this.clearTimeout(key));
this.notifyOnClear(this.cacheAsKeyPayloadMap());
this.cache.clear();
}
size() {
this.logKey("size", `ExpireTimeoutCache size: ${this.cache.size.toString()}`);
return this.cache.size;
}
onClear(callback) {
this.logKey("onExpire", `ExpireCache onExpire`);
this.handleOnClear.add(callback);
}
entries() {
return this.cacheAsKeyPayloadMap().entries();
}
keys() {
return this.cacheAsKeyPayloadMap().keys();
}
values() {
return this.cacheAsKeyPayloadMap().values();
}
setExpireMs(expireMs) {
this.defaultExpireMs = expireMs;
}
clearTimeout(key) {
const entry = this.cache.get(key);
if (entry == null ? void 0 : entry.timeout) {
clearTimeout(entry.timeout);
entry.timeout = void 0;
}
}
notifyOnClear(entries) {
this.handleOnClear.forEach((callback) => callback(entries));
}
cacheAsKeyPayloadMap() {
const map = /* @__PURE__ */ new Map();
for (const [key, value] of this.cache.entries()) {
map.set(key, value.data);
}
return map;
}
};
export {
ExpireCache,
ExpireTimeoutCache
};
//# sourceMappingURL=index.js.map

70

package.json
{
"name": "@avanio/expire-cache",
"version": "0.3.3",
"version": "0.4.0",
"description": "Typescript/Javascript cache with expiration",
"main": "./dist/index.js",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"require": "./dist/index.cjs",
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"scripts": {
"build": "tsc",
"prepublishOnly": "npm run build",
"test": "nyc mocha",
"coverage": "nyc report --reporter=lcovonly",
"lint": "eslint src"
"build": "tsup src/index.ts --sourcemap --format cjs,esm --dts --clean",
"test": "c8 mocha",
"coverage": "c8 report --reporter=lcovonly",
"lint": "eslint . --ext .ts",
"validate": "tsc --noEmit --project tsconfig.test.json"
},

@@ -18,11 +28,13 @@ "files": [

"exit": true,
"recursive": true,
"enable-source-maps": true,
"extension": [
"ts",
"js"
"test.ts",
"cjs",
"mjs"
],
"recursive": true,
"require": [
"ts-node/register",
"source-map-support/register"
"ts-node/register"
],
"loader": "ts-node/esm",
"reporters": [

@@ -56,27 +68,29 @@ "spec",

"devDependencies": {
"@types/chai": "^4.3.14",
"@stylistic/eslint-plugin": "^2.6.1",
"@types/chai": "^4.3.17",
"@types/chai-as-promised": "^7.1.8",
"@types/mocha": "^10.0.6",
"@types/node": "^16.18.96",
"@types/mocha": "^10.0.7",
"@types/node": "^18.19.43",
"@types/sinon": "^17.0.3",
"@typescript-eslint/eslint-plugin": "^7.6.0",
"@typescript-eslint/parser": "^7.6.0",
"chai": "^4.4.1",
"chai-as-promised": "^7.1.1",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
"c8": "^10.1.2",
"chai": "^5.1.1",
"chai-as-promised": "^8.0.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-deprecation": "^2.0.0",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-sonarjs": "^0.25.1",
"mocha": "^10.4.0",
"nyc": "^15.1.0",
"prettier": "^3.2.5",
"sinon": "^17.0.1",
"eslint-plugin-deprecation": "^3.0.0",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-sonarjs": "^0.23.0",
"mocha": "^10.7.0",
"prettier": "^3.3.3",
"sinon": "^18.0.0",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
"tsup": "^8.2.4",
"typescript": "^5.5.4"
},
"dependencies": {
"@avanio/logger-like": "^0.1.1"
"@avanio/logger-like": "^0.2.0"
}
}

@@ -30,3 +30,3 @@ # @avanio/expire-cache

for (const [key, value] of cleared.entries()) {
console.log(`key ${key} expired, deleted or clear with value ${value}`);
console.log(`key ${String(key)} expired, deleted or clear with value ${value}`);
}

@@ -33,0 +33,0 @@ });

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc