hcacher 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +74 -0
- package/cacher.d.ts +88 -0
- package/cacher.d.ts.map +1 -0
- package/cacher.js +2 -0
- package/cacher.js.map +7 -0
- package/index.d.ts +16 -0
- package/index.d.ts.map +1 -0
- package/index.js +2 -0
- package/index.js.map +7 -0
- package/interface/index.d.ts +16 -0
- package/interface/index.d.ts.map +1 -0
- package/interface/index.js +2 -0
- package/interface/index.js.map +7 -0
- package/miniEmitter.d.ts +7 -0
- package/miniEmitter.d.ts.map +1 -0
- package/miniEmitter.js +2 -0
- package/miniEmitter.js.map +7 -0
- package/package.json +41 -0
- package/types/index.d.ts +8 -0
- package/types/index.d.ts.map +1 -0
- package/types/index.js +2 -0
- package/types/index.js.map +7 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dirold2
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# hcacher
|
|
2
|
+
|
|
3
|
+
Flexible in-memory cache manager with TTL, LRU eviction, and event bus.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install hcacher
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { CacheManager } from "hcacher";
|
|
15
|
+
|
|
16
|
+
// Basic usage
|
|
17
|
+
const cache = new CacheManager<string>({ maxSize: 100, ttl: 60_000 });
|
|
18
|
+
cache.set("key", "value");
|
|
19
|
+
console.log(cache.get("key")); // "value"
|
|
20
|
+
|
|
21
|
+
// With factory (deduplicates concurrent requests)
|
|
22
|
+
const result = await cache.getOrSet("key", async () => {
|
|
23
|
+
const res = await fetch("https://api.example.com/data");
|
|
24
|
+
return res.json();
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// Events
|
|
28
|
+
cache.on("hit", (key, data) => console.log(`Cache hit: ${key}`));
|
|
29
|
+
cache.on("miss", (key) => console.log(`Cache miss: ${key}`));
|
|
30
|
+
cache.on("evict", (key, data) => console.log(`Evicted: ${key}`));
|
|
31
|
+
cache.on("expire", (key, data) => console.log(`Expired: ${key}`));
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## API
|
|
35
|
+
|
|
36
|
+
### `new CacheManager<T>(options?)`
|
|
37
|
+
|
|
38
|
+
| Option | Default | Description |
|
|
39
|
+
| ------------ | ------- | ------------------------------------- |
|
|
40
|
+
| `maxSize` | `1000` | Maximum number of entries |
|
|
41
|
+
| `ttl` | `60000` | Time-to-live in milliseconds |
|
|
42
|
+
| `touchOnGet` | `true` | Update access order on read (for LRU) |
|
|
43
|
+
| `enabled` | `true` | Enable/disable the cache |
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
// Positional args also supported
|
|
47
|
+
new CacheManager<string>(100, 30000, true, true);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Methods
|
|
51
|
+
|
|
52
|
+
- **`get(key)`** — Get value by key. Returns `undefined` on miss or expiration.
|
|
53
|
+
- **`getEntry(key)`** — Get full entry with `etag`/`lastModified` metadata.
|
|
54
|
+
- **`set(key, data, meta?)`** — Store value with optional `etag`/`lastModified`.
|
|
55
|
+
- **`getOrSet(key, factory, meta?)`** — Get or create via factory.
|
|
56
|
+
Deduplicates concurrent calls for the same key.
|
|
57
|
+
- **`has(key)`** — Check if key exists and is not expired.
|
|
58
|
+
- **`delete(key)`** — Remove entry (also cleans up pending factory calls).
|
|
59
|
+
- **`clear()`** — Remove all entries and pending requests.
|
|
60
|
+
- **`size`** — Current number of entries.
|
|
61
|
+
|
|
62
|
+
### Events
|
|
63
|
+
|
|
64
|
+
| Event | Payload | Description |
|
|
65
|
+
| -------- | ------------- | ------------------- |
|
|
66
|
+
| `hit` | `(key, data)` | Cache hit |
|
|
67
|
+
| `miss` | `(key)` | Cache miss |
|
|
68
|
+
| `set` | `(key, data)` | Entry stored |
|
|
69
|
+
| `evict` | `(key, data)` | Entry evicted (LRU) |
|
|
70
|
+
| `expire` | `(key, data)` | Entry expired (TTL) |
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
MIT
|
package/cacher.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { CacheEntry, CacheManagerOptions } from "./interface/index.js";
|
|
2
|
+
import { MiniEmitter } from "./miniEmitter.js";
|
|
3
|
+
import type { CacheEvents } from "./types/index.js";
|
|
4
|
+
/**
|
|
5
|
+
* @ru Менеджер кэша с поддержкой TTL, LRU-эвикции и событийной шины.
|
|
6
|
+
* @en Cache manager with TTL, LRU eviction and event bus support.
|
|
7
|
+
*/
|
|
8
|
+
export declare class CacheManager<T = unknown> extends MiniEmitter<CacheEvents<T>> {
|
|
9
|
+
private readonly storage;
|
|
10
|
+
private readonly pending;
|
|
11
|
+
private readonly maxSize;
|
|
12
|
+
private readonly ttl;
|
|
13
|
+
private readonly touchOnGet;
|
|
14
|
+
private readonly enabled;
|
|
15
|
+
/**
|
|
16
|
+
* @ru Создаёт новый экземпляр CacheManager.
|
|
17
|
+
* @en Creates a new CacheManager instance.
|
|
18
|
+
* @param maxSizeOrOptions - Maximum cache size or options object.
|
|
19
|
+
* @param ttl - Entry TTL in milliseconds.
|
|
20
|
+
* @param touchOnGet - Update order on read.
|
|
21
|
+
* @param enabled - Whether the cache is enabled.
|
|
22
|
+
*/
|
|
23
|
+
constructor(options?: CacheManagerOptions);
|
|
24
|
+
constructor(maxSize?: number, ttl?: number, touchOnGet?: boolean, enabled?: boolean);
|
|
25
|
+
/**
|
|
26
|
+
* @ru Получает значение по ключу.
|
|
27
|
+
* @en Gets a value by key.
|
|
28
|
+
* @param key - Cache key.
|
|
29
|
+
* @returns Value or undefined.
|
|
30
|
+
*/
|
|
31
|
+
get(key: string): T | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* @ru Получает запись кэша с метаданными.
|
|
34
|
+
* @en Gets a cache entry with metadata.
|
|
35
|
+
* @param key - Cache key.
|
|
36
|
+
* @returns Cache entry or undefined.
|
|
37
|
+
*/
|
|
38
|
+
getEntry(key: string): CacheEntry<T> | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* @ru Сохраняет значение в кэш.
|
|
41
|
+
* @en Stores a value in the cache.
|
|
42
|
+
* @param key - Cache key.
|
|
43
|
+
* @param data - Data.
|
|
44
|
+
* @param meta - ETag and/or LastModified.
|
|
45
|
+
*/
|
|
46
|
+
set(key: string, data: T, meta?: {
|
|
47
|
+
etag?: string;
|
|
48
|
+
lastModified?: string;
|
|
49
|
+
}): void;
|
|
50
|
+
/**
|
|
51
|
+
* @ru Получает значение из кэша или создаёт через фабрику (с дедупликацией concurrent-запросов).
|
|
52
|
+
* @en Gets from cache or creates via factory (with concurrent request deduplication).
|
|
53
|
+
* @param key - Cache key.
|
|
54
|
+
* @param factory - Factory function.
|
|
55
|
+
* @param meta - ETag and/or LastModified.
|
|
56
|
+
* @returns Cached or freshly created value.
|
|
57
|
+
*/
|
|
58
|
+
getOrSet(key: string, factory: () => Promise<T> | T, meta?: {
|
|
59
|
+
etag?: string;
|
|
60
|
+
lastModified?: string;
|
|
61
|
+
}): Promise<T>;
|
|
62
|
+
/**
|
|
63
|
+
* @ru Проверяет наличие ключа в кэше.
|
|
64
|
+
* @en Checks if a key exists in the cache.
|
|
65
|
+
* @param key - Cache key.
|
|
66
|
+
* @returns True if the key exists and is not expired.
|
|
67
|
+
*/
|
|
68
|
+
has(key: string): boolean;
|
|
69
|
+
/**
|
|
70
|
+
* @ru Удаляет запись из кэша.
|
|
71
|
+
* @en Deletes an entry from the cache.
|
|
72
|
+
* @param key - Cache key.
|
|
73
|
+
* @returns True if the entry existed and was deleted.
|
|
74
|
+
*/
|
|
75
|
+
delete(key: string): boolean;
|
|
76
|
+
/**
|
|
77
|
+
* @ru Очищает кэш и отменяет все ожидающие запросы.
|
|
78
|
+
* @en Clears the cache and cancels all pending requests.
|
|
79
|
+
*/
|
|
80
|
+
clear(): void;
|
|
81
|
+
/**
|
|
82
|
+
* @ru Текущее количество записей в кэше.
|
|
83
|
+
* @en Current number of entries in the cache.
|
|
84
|
+
*/
|
|
85
|
+
get size(): number;
|
|
86
|
+
private evict;
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=cacher.d.ts.map
|
package/cacher.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cacher.d.ts","sourceRoot":"","sources":["../src/cacher.ts"],"names":[],"mappings":"AAAA,OAAO,K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AAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,GAC9C,OAAO,CAAC,CAAC,CAAC;IAqBb;;;;;OAKG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAezB;;;;;OAKG;IACH,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAM5B;;;OAGG;IACH,KAAK,IAAI,IAAI;IAKb;;;OAGG;IACH,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,OAAO,CAAC,KAAK;CAWd"}
|
package/cacher.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";import{MiniEmitter as h}from"./miniEmitter.js";export class CacheManager extends h{storage=new Map;pending=new Map;maxSize;ttl;touchOnGet;enabled;constructor(t,e,i,s){super(),typeof t=="object"&&t!==null?(this.enabled=t.enabled??!0,this.maxSize=t.maxSize??1e3,this.ttl=t.ttl??6e4,this.touchOnGet=t.touchOnGet??!0):(this.enabled=s??!0,this.maxSize=t??1e3,this.ttl=e??6e4,this.touchOnGet=i??!0)}get(t){return this.getEntry(t)?.data}getEntry(t){if(!this.enabled)return;const e=this.storage.get(t);if(!e){this.emit("miss",t);return}if(Date.now()>e.expiresAt){this.storage.delete(t),this.emit("expire",t,e.entry.data),this.emit("miss",t);return}return this.touchOnGet&&(this.storage.delete(t),this.storage.set(t,e)),this.emit("hit",t,e.entry.data),e.entry}set(t,e,i){this.enabled&&(this.storage.has(t)?this.storage.delete(t):this.storage.size>=this.maxSize&&this.evict(),this.storage.set(t,{entry:{data:e,etag:i?.etag,lastModified:i?.lastModified},expiresAt:Date.now()+this.ttl}),this.emit("set",t,e))}async getOrSet(t,e,i){const s=this.get(t);if(s!==void 0)return s;const r=this.pending.get(t);if(r)return r;const n=(async()=>{try{const a=await e();return this.set(t,a,i),a}finally{this.pending.delete(t)}})();return this.pending.set(t,n),n}has(t){if(!this.enabled)return!1;const e=this.storage.get(t);return e?Date.now()>e.expiresAt?(this.storage.delete(t),this.emit("expire",t,e.entry.data),!1):!0:!1}delete(t){return this.enabled?(this.pending.delete(t),this.storage.delete(t)):!1}clear(){this.storage.clear(),this.pending.clear()}get size(){return this.storage.size}evict(){const t=this.storage.keys().next().value;if(t!==void 0){const e=this.storage.get(t);if(e){const i=Date.now()>e.expiresAt;this.emit(i?"expire":"evict",t,e.entry.data),this.storage.delete(t)}}}}
|
|
2
|
+
//# sourceMappingURL=cacher.js.map
|
package/cacher.js.map
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/cacher.ts"],
|
|
4
|
+
"sourcesContent": ["import type { CacheEntry, CacheManagerOptions, InternalEntry } from \"./interface/index.js\";\nimport { MiniEmitter } from \"./miniEmitter.js\";\nimport type { CacheEvents } from \"./types/index.js\";\n\n/**\n * @ru \u041C\u0435\u043D\u0435\u0434\u0436\u0435\u0440 \u043A\u044D\u0448\u0430 \u0441 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u043E\u0439 TTL, LRU-\u044D\u0432\u0438\u043A\u0446\u0438\u0438 \u0438 \u0441\u043E\u0431\u044B\u0442\u0438\u0439\u043D\u043E\u0439 \u0448\u0438\u043D\u044B.\n * @en Cache manager with TTL, LRU eviction and event bus support.\n */\nexport class CacheManager<T = unknown> extends MiniEmitter<CacheEvents<T>> {\n private readonly storage = new Map<string, InternalEntry<T>>();\n private readonly pending = new Map<string, Promise<T>>();\n private readonly maxSize: number;\n private readonly ttl: number;\n private readonly touchOnGet: boolean;\n private readonly enabled: boolean;\n\n /**\n * @ru \u0421\u043E\u0437\u0434\u0430\u0451\u0442 \u043D\u043E\u0432\u044B\u0439 \u044D\u043A\u0437\u0435\u043C\u043F\u043B\u044F\u0440 CacheManager.\n * @en Creates a new CacheManager instance.\n * @param maxSizeOrOptions - Maximum cache size or options object.\n * @param ttl - Entry TTL in milliseconds.\n * @param touchOnGet - Update order on read.\n * @param enabled - Whether the cache is enabled.\n */\n constructor(options?: CacheManagerOptions);\n constructor(maxSize?: number, ttl?: number, touchOnGet?: boolean, enabled?: boolean);\n constructor(\n maxSizeOrOptions?: number | CacheManagerOptions,\n ttl?: number,\n touchOnGet?: boolean,\n enabled?: boolean,\n ) {\n super();\n if (typeof maxSizeOrOptions === \"object\" && maxSizeOrOptions !== null) {\n this.enabled = maxSizeOrOptions.enabled ?? true;\n this.maxSize = maxSizeOrOptions.maxSize ?? 1000;\n this.ttl = maxSizeOrOptions.ttl ?? 60000;\n this.touchOnGet = maxSizeOrOptions.touchOnGet ?? true;\n } else {\n this.enabled = enabled ?? true;\n this.maxSize = maxSizeOrOptions ?? 1000;\n this.ttl = ttl ?? 60000;\n this.touchOnGet = touchOnGet ?? true;\n }\n }\n\n /**\n * @ru \u041F\u043E\u043B\u0443\u0447\u0430\u0435\u0442 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u043E \u043A\u043B\u044E\u0447\u0443.\n * @en Gets a value by key.\n * @param key - Cache key.\n * @returns Value or undefined.\n */\n get(key: string): T | undefined {\n return this.getEntry(key)?.data;\n }\n\n /**\n * @ru \u041F\u043E\u043B\u0443\u0447\u0430\u0435\u0442 \u0437\u0430\u043F\u0438\u0441\u044C \u043A\u044D\u0448\u0430 \u0441 \u043C\u0435\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u043C\u0438.\n * @en Gets a cache entry with metadata.\n * @param key - Cache key.\n * @returns Cache entry or undefined.\n */\n getEntry(key: string): CacheEntry<T> | undefined {\n if (!this.enabled) return undefined;\n\n const item = this.storage.get(key);\n if (!item) {\n this.emit(\"miss\", key);\n return undefined;\n }\n\n if (Date.now() > item.expiresAt) {\n this.storage.delete(key);\n this.emit(\"expire\", key, item.entry.data);\n this.emit(\"miss\", key);\n return undefined;\n }\n\n if (this.touchOnGet) {\n this.storage.delete(key);\n this.storage.set(key, item);\n }\n\n this.emit(\"hit\", key, item.entry.data);\n return item.entry;\n }\n\n /**\n * @ru \u0421\u043E\u0445\u0440\u0430\u043D\u044F\u0435\u0442 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 \u043A\u044D\u0448.\n * @en Stores a value in the cache.\n * @param key - Cache key.\n * @param data - Data.\n * @param meta - ETag and/or LastModified.\n */\n set(key: string, data: T, meta?: { etag?: string; lastModified?: string }): void {\n if (!this.enabled) return;\n\n if (this.storage.has(key)) {\n this.storage.delete(key);\n } else if (this.storage.size >= this.maxSize) {\n this.evict();\n }\n\n this.storage.set(key, {\n entry: {\n data,\n etag: meta?.etag,\n lastModified: meta?.lastModified,\n },\n expiresAt: Date.now() + this.ttl,\n });\n\n this.emit(\"set\", key, data);\n }\n\n /**\n * @ru \u041F\u043E\u043B\u0443\u0447\u0430\u0435\u0442 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0438\u0437 \u043A\u044D\u0448\u0430 \u0438\u043B\u0438 \u0441\u043E\u0437\u0434\u0430\u0451\u0442 \u0447\u0435\u0440\u0435\u0437 \u0444\u0430\u0431\u0440\u0438\u043A\u0443 (\u0441 \u0434\u0435\u0434\u0443\u043F\u043B\u0438\u043A\u0430\u0446\u0438\u0435\u0439 concurrent-\u0437\u0430\u043F\u0440\u043E\u0441\u043E\u0432).\n * @en Gets from cache or creates via factory (with concurrent request deduplication).\n * @param key - Cache key.\n * @param factory - Factory function.\n * @param meta - ETag and/or LastModified.\n * @returns Cached or freshly created value.\n */\n async getOrSet(\n key: string,\n factory: () => Promise<T> | T,\n meta?: { etag?: string; lastModified?: string },\n ): Promise<T> {\n const cached = this.get(key);\n if (cached !== undefined) return cached;\n\n const pendingPromise = this.pending.get(key);\n if (pendingPromise) return pendingPromise;\n\n const promise = (async () => {\n try {\n const data = await factory();\n this.set(key, data, meta);\n return data;\n } finally {\n this.pending.delete(key);\n }\n })();\n\n this.pending.set(key, promise);\n return promise;\n }\n\n /**\n * @ru \u041F\u0440\u043E\u0432\u0435\u0440\u044F\u0435\u0442 \u043D\u0430\u043B\u0438\u0447\u0438\u0435 \u043A\u043B\u044E\u0447\u0430 \u0432 \u043A\u044D\u0448\u0435.\n * @en Checks if a key exists in the cache.\n * @param key - Cache key.\n * @returns True if the key exists and is not expired.\n */\n has(key: string): boolean {\n if (!this.enabled) return false;\n\n const item = this.storage.get(key);\n if (!item) return false;\n\n if (Date.now() > item.expiresAt) {\n this.storage.delete(key);\n this.emit(\"expire\", key, item.entry.data);\n return false;\n }\n\n return true;\n }\n\n /**\n * @ru \u0423\u0434\u0430\u043B\u044F\u0435\u0442 \u0437\u0430\u043F\u0438\u0441\u044C \u0438\u0437 \u043A\u044D\u0448\u0430.\n * @en Deletes an entry from the cache.\n * @param key - Cache key.\n * @returns True if the entry existed and was deleted.\n */\n delete(key: string): boolean {\n if (!this.enabled) return false;\n this.pending.delete(key);\n return this.storage.delete(key);\n }\n\n /**\n * @ru \u041E\u0447\u0438\u0449\u0430\u0435\u0442 \u043A\u044D\u0448 \u0438 \u043E\u0442\u043C\u0435\u043D\u044F\u0435\u0442 \u0432\u0441\u0435 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0435 \u0437\u0430\u043F\u0440\u043E\u0441\u044B.\n * @en Clears the cache and cancels all pending requests.\n */\n clear(): void {\n this.storage.clear();\n this.pending.clear();\n }\n\n /**\n * @ru \u0422\u0435\u043A\u0443\u0449\u0435\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0437\u0430\u043F\u0438\u0441\u0435\u0439 \u0432 \u043A\u044D\u0448\u0435.\n * @en Current number of entries in the cache.\n */\n get size(): number {\n return this.storage.size;\n }\n\n private evict(): void {\n const oldestKey = this.storage.keys().next().value;\n if (oldestKey !== undefined) {\n const item = this.storage.get(oldestKey);\n if (item) {\n const expired = Date.now() > item.expiresAt;\n this.emit(expired ? \"expire\" : \"evict\", oldestKey, item.entry.data);\n this.storage.delete(oldestKey);\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "aAC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,EAAWP,EAAK,MAAM,IAAI,EAClE,KAAK,QAAQ,OAAOO,CAAS,CAC/B,CACF,CACF",
|
|
6
|
+
"names": ["MiniEmitter", "maxSizeOrOptions", "ttl", "touchOnGet", "enabled", "key", "item", "data", "meta", "factory", "cached", "pendingPromise", "promise", "oldestKey", "expired"]
|
|
7
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @ru hcacher — гибкий менеджер кэша с TTL, LRU-эвикцией и событийной шиной.
|
|
3
|
+
* @en hcacher — flexible cache manager with TTL, LRU eviction and event bus.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* import { CacheManager } from "hcacher";
|
|
7
|
+
*
|
|
8
|
+
* const cache = new CacheManager<string>({ maxSize: 100, ttl: 60_000 });
|
|
9
|
+
* cache.set("key", "value");
|
|
10
|
+
* console.log(cache.get("key")); // "value"
|
|
11
|
+
*/
|
|
12
|
+
export { CacheManager } from "./cacher.js";
|
|
13
|
+
export { MiniEmitter } from "./miniEmitter.js";
|
|
14
|
+
export type { CacheEntry, CacheManagerOptions } from "./interface/index.js";
|
|
15
|
+
export type { CacheEvents } from "./types/index.js";
|
|
16
|
+
//# sourceMappingURL=index.d.ts.map
|
package/index.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,YAAY,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC5E,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC"}
|
package/index.js
ADDED
package/index.js.map
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * @ru hcacher \u2014 \u0433\u0438\u0431\u043A\u0438\u0439 \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440 \u043A\u044D\u0448\u0430 \u0441 TTL, LRU-\u044D\u0432\u0438\u043A\u0446\u0438\u0435\u0439 \u0438 \u0441\u043E\u0431\u044B\u0442\u0438\u0439\u043D\u043E\u0439 \u0448\u0438\u043D\u043E\u0439.\n * @en hcacher \u2014 flexible cache manager with TTL, LRU eviction and event bus.\n *\n * @example\n * import { CacheManager } from \"hcacher\";\n *\n * const cache = new CacheManager<string>({ maxSize: 100, ttl: 60_000 });\n * cache.set(\"key\", \"value\");\n * console.log(cache.get(\"key\")); // \"value\"\n */\n\nexport { CacheManager } from \"./cacher.js\";\nexport { MiniEmitter } from \"./miniEmitter.js\";\n\nexport type { CacheEntry, CacheManagerOptions } from \"./interface/index.js\";\nexport type { CacheEvents } from \"./types/index.js\";\n"],
|
|
5
|
+
"mappings": "aAYA,OAAS,iBAAoB,cAC7B,OAAS,gBAAmB",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface CacheEntry<T> {
|
|
2
|
+
data: T;
|
|
3
|
+
etag?: string;
|
|
4
|
+
lastModified?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface CacheManagerOptions {
|
|
7
|
+
enabled?: boolean;
|
|
8
|
+
ttl?: number;
|
|
9
|
+
maxSize?: number;
|
|
10
|
+
touchOnGet?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface InternalEntry<T> {
|
|
13
|
+
entry: CacheEntry<T>;
|
|
14
|
+
expiresAt: number;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/interface/index.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU,CAAC,CAAC;IAC3B,IAAI,EAAE,CAAC,CAAC;IACR,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;CACnB"}
|
package/miniEmitter.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare class MiniEmitter<Events extends Record<string, any[]>> {
|
|
2
|
+
private readonly listeners;
|
|
3
|
+
on<K extends keyof Events>(event: K, listener: (...args: Events[K]) => void): this;
|
|
4
|
+
off<K extends keyof Events>(event: K, listener: (...args: Events[K]) => void): this;
|
|
5
|
+
protected emit<K extends keyof Events>(event: K, ...args: Events[K]): void;
|
|
6
|
+
}
|
|
7
|
+
//# sourceMappingURL=miniEmitter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"miniEmitter.d.ts","sourceRoot":"","sources":["../src/miniEmitter.ts"],"names":[],"mappings":"AAAA,qBAAa,WAAW,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC;IAC3D,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAuC;IAEjE,EAAE,CAAC,CAAC,SAAS,MAAM,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,IAAI;IAMlF,GAAG,CAAC,CAAC,SAAS,MAAM,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,IAAI;IASnF,SAAS,CAAC,IAAI,CAAC,CAAC,SAAS,MAAM,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;CAQ3E"}
|
package/miniEmitter.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";export class MiniEmitter{listeners=new Map;on(s,i){return this.listeners.has(s)||this.listeners.set(s,[]),this.listeners.get(s).push(i),this}off(s,i){const t=this.listeners.get(s);if(t){const e=t.indexOf(i);e!==-1&&t.splice(e,1)}return this}emit(s,...i){const t=this.listeners.get(s);if(!t)return;const e=[...t];for(const n of e)n(...i)}}
|
|
2
|
+
//# sourceMappingURL=miniEmitter.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/miniEmitter.ts"],
|
|
4
|
+
"sourcesContent": ["export class MiniEmitter<Events extends Record<string, any[]>> {\n private readonly listeners = new Map<keyof Events, Function[]>();\n\n on<K extends keyof Events>(event: K, listener: (...args: Events[K]) => void): this {\n if (!this.listeners.has(event)) this.listeners.set(event, []);\n this.listeners.get(event)!.push(listener);\n return this;\n }\n\n off<K extends keyof Events>(event: K, listener: (...args: Events[K]) => void): this {\n const list = this.listeners.get(event);\n if (list) {\n const index = list.indexOf(listener);\n if (index !== -1) list.splice(index, 1);\n }\n return this;\n }\n\n protected emit<K extends keyof Events>(event: K, ...args: Events[K]): void {\n const list = this.listeners.get(event);\n if (!list) return;\n const targets = [...list];\n for (const listener of targets) {\n listener(...args);\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "aAAM,aAAO,WAAW,CACL,UAAY,IAAI,IAEjC,GAA2BA,EAAUC,EAAsC,CACzE,OAAK,KAAK,UAAU,IAAID,CAAK,GAAG,KAAK,UAAU,IAAIA,EAAO,CAAA,CAAE,EAC5D,KAAK,UAAU,IAAIA,CAAK,EAAG,KAAKC,CAAQ,EACjC,IACT,CAEA,IAA4BD,EAAUC,EAAsC,CAC1E,MAAMC,EAAO,KAAK,UAAU,IAAIF,CAAK,EACrC,GAAIE,EAAM,CACR,MAAMC,EAAQD,EAAK,QAAQD,CAAQ,EAC/BE,IAAU,IAAID,EAAK,OAAOC,EAAO,CAAC,CACxC,CACA,OAAO,IACT,CAEU,KAA6BH,KAAaI,EAAe,CACjE,MAAMF,EAAO,KAAK,UAAU,IAAIF,CAAK,EACrC,GAAI,CAACE,EAAM,OACX,MAAMG,EAAU,CAAC,GAAGH,CAAI,EACxB,UAAWD,KAAYI,EACrBJ,EAAS,GAAGG,CAAI,CAEpB",
|
|
6
|
+
"names": ["event", "listener", "list", "index", "args", "targets"]
|
|
7
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "hcacher",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "In-memory cache manager with TTL, LRU eviction, and event bus",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cache",
|
|
7
|
+
"deduplication",
|
|
8
|
+
"events",
|
|
9
|
+
"in-memory",
|
|
10
|
+
"lru",
|
|
11
|
+
"ttl",
|
|
12
|
+
"typescript"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/dirold2/hcacher#readme",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/dirold2/hcacher/issues"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"author": "dirold2",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "https://github.com/dirold2/hcacher.git"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"main": "./index.js",
|
|
27
|
+
"module": "./index.ts",
|
|
28
|
+
"types": "./index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"import": {
|
|
32
|
+
"types": "./index.d.ts",
|
|
33
|
+
"default": "./index.js"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=18"
|
|
39
|
+
},
|
|
40
|
+
"private": false
|
|
41
|
+
}
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAC3B,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC5B,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACpB,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC5B,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC9B,MAAM,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;CAChC,CAAC"}
|
package/types/index.js
ADDED