@lp-labs/ttl-map 0.0.0-stage → 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Libin Prasanth
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 CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # @lp-labs/ttl-map
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An entry-bounded expiring Map with an indexed minimum-deadline heap and an injected clock.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @lp-labs/ttl-map
9
+ ```
10
+
11
+ Version 0.1.0. MIT. Zero runtime, peer, or sibling dependencies. Node >=18;
12
+ browser-compatible ES2022 runtime without browser-global reads. ESM and CommonJS
13
+ exports have separate matching declarations.
14
+
15
+ ## Quick start
16
+
17
+ ```js
18
+ import { TtlMap } from '@lp-labs/ttl-map';
19
+ let now = 0;
20
+ const cache = new TtlMap({ maxEntries: 2, clock: () => now, refreshOnGet: true });
21
+ cache.set('job', { ready: true }, 10);
22
+ now = 9;
23
+ if (!cache.get('job')?.ready) throw new Error('missing');
24
+ now = 19; // refresh at 9 extended the deadline to 19
25
+ if (cache.has('job')) throw new Error('expiry');
26
+ console.log(cache.size);
27
+ ```
28
+
29
+ ## Contract, customization, errors and ownership
30
+
31
+ Required `maxEntries` is a positive safe integer; required `clock()` returns a finite number in caller-chosen units. TTLs use those same units. `refreshOnGet` defaults false. No timers or Date/global-clock reads are used. Every public operation, including size/clear, samples the clock once, except set rejects a nonpositive/nonfinite TTL before sampling. Equal timestamps are accepted; a timestamp below the last accepted sample throws RangeError, rather than clamping. A successful sample advances the monotonic watermark even when a later validation/capacity error occurs. A throwing or reentrant clock callback changes no entries. Reentrant clock access throws Error.
32
+
33
+ `set(key, value, ttl)` requires positive finite TTL and a finite deadline strictly greater than now (including floating-point precision checks). It purges expired entries first and updates an existing key in place. A live-capacity overflow throws RangeError without inserting or evicting live entries; expiry purging may already have committed. Invalid deadlines are rejected before purging. There are no eviction callbacks. Clock adapters must be synchronous; nonfunctions, nonnumeric samples and thenable samples throw TypeError before purging (async rejections are observed). `get` optionally refreshes to now plus that entry's original TTL; overflow throws without changing that entry's deadline, after normal purge. `has`, `entries`, and size do not refresh.
34
+
35
+ Expiry is inclusive at the deadline: deadline <= now is absent. `purge` returns the number removed by that call. `delete` returns whether a live key was removed. `clear` removes all entries but does not reset the clock watermark. Missing get returns undefined; has distinguishes stored undefined. Entries preserve Map insertion order, with fresh tuples and shared key/value references.
36
+
37
+ The heap stores exactly one node per live entry, without tombstones: O(log n) insert/update/delete/refresh, expected O(1) non-refresh lookup plus O(k log n) expiration work per operation. Entries O(n + k log n); clear O(n); space O(maxEntries). Synchronous only; not a persistence or distributed-clock cache.
38
+
39
+ ## Complete public declaration contract
40
+
41
+ Runtime exports and all exported types are listed below. Internal storage members
42
+ are omitted. Optional settings are constructor/function options, not globals.
43
+
44
+ ```ts
45
+ export interface TtlOptions {
46
+ maxEntries: number;
47
+ clock: () => number;
48
+ refreshOnGet?: boolean;
49
+ }
50
+ /** Indexed expiry heap: no stale tombstones or background timers. */
51
+ export declare class TtlMap<K, V> {
52
+ constructor(options: TtlOptions);
53
+ get size(): number;
54
+ purge(): number;
55
+ set(key: K, value: V, ttl: number): void;
56
+ get(key: K): V | undefined;
57
+ has(key: K): boolean;
58
+ delete(key: K): boolean;
59
+ clear(): void;
60
+ entries(): [K, V][];
61
+ }
62
+ ```
63
+
64
+ ## Development
65
+
66
+ ```sh
67
+ npm ci --offline
68
+ npm run build
69
+ npm run typecheck
70
+ npm test
71
+ npm run format:check
72
+ ```
73
+
74
+ TypeScript ^5.9.3 and Prettier ^3.6.2 are development-only. Offline installation
75
+ requires their locked packages already in the local npm cache. Build emits
76
+ dist/esm and dist/cjs with separate declarations; tests exercise runtime behavior
77
+ and bare-package ESM/CommonJS type consumers with negative checks. No publish
78
+ step is needed to build or test.
79
+
80
+ ## Support
81
+
82
+ If this library is useful to you, consider supporting its maintenance with a [donation via PayPal](https://www.paypal.me/LibinPrasanth).
83
+
84
+ ## Author
85
+
86
+ Created by [Libin Prasanth](https://www.linkedin.com/in/libinprasanth/). Connect on LinkedIn for updates and discussion.
@@ -0,0 +1,30 @@
1
+ export interface TtlOptions {
2
+ maxEntries: number;
3
+ clock: () => number;
4
+ refreshOnGet?: boolean;
5
+ }
6
+ /** Indexed expiry heap: no stale tombstones or background timers. */
7
+ export declare class TtlMap<K, V> {
8
+ private readonly data;
9
+ private readonly heap;
10
+ private last;
11
+ private readingClock;
12
+ private readonly maximum;
13
+ private readonly clock;
14
+ private readonly refresh;
15
+ constructor(options: TtlOptions);
16
+ private now;
17
+ private swap;
18
+ private fix;
19
+ private remove;
20
+ private expire;
21
+ private deadline;
22
+ get size(): number;
23
+ purge(): number;
24
+ set(key: K, value: V, ttl: number): void;
25
+ get(key: K): V | undefined;
26
+ has(key: K): boolean;
27
+ delete(key: K): boolean;
28
+ clear(): void;
29
+ entries(): [K, V][];
30
+ }
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TtlMap = void 0;
4
+ /** Indexed expiry heap: no stale tombstones or background timers. */
5
+ class TtlMap {
6
+ data = new Map();
7
+ heap = [];
8
+ last = -Infinity;
9
+ readingClock = false;
10
+ maximum;
11
+ clock;
12
+ refresh;
13
+ constructor(options) {
14
+ if (typeof options.clock !== 'function')
15
+ throw new TypeError('Expected clock callback');
16
+ if (!Number.isSafeInteger(options.maxEntries) || options.maxEntries < 1)
17
+ throw new RangeError('maxEntries must be positive');
18
+ this.maximum = options.maxEntries;
19
+ this.clock = options.clock;
20
+ this.refresh = options.refreshOnGet ?? false;
21
+ }
22
+ now() {
23
+ if (this.readingClock)
24
+ throw new Error('Reentrant clock access');
25
+ let now;
26
+ this.readingClock = true;
27
+ try {
28
+ const sample = this.clock();
29
+ if (sample !== null &&
30
+ (typeof sample === 'object' || typeof sample === 'function') &&
31
+ typeof sample.then === 'function') {
32
+ void Promise.resolve(sample).catch(() => { });
33
+ throw new TypeError('Clock must be synchronous');
34
+ }
35
+ if (typeof sample !== 'number')
36
+ throw new TypeError('Clock must return a number');
37
+ now = sample;
38
+ }
39
+ finally {
40
+ this.readingClock = false;
41
+ }
42
+ if (!Number.isFinite(now) || now < this.last)
43
+ throw new RangeError('Clock must be finite and monotonic');
44
+ this.last = now;
45
+ return now;
46
+ }
47
+ swap(a, b) {
48
+ const x = this.heap[a], y = this.heap[b];
49
+ this.heap[a] = y;
50
+ this.heap[b] = x;
51
+ y.index = a;
52
+ x.index = b;
53
+ }
54
+ fix(index) {
55
+ while (index > 0) {
56
+ const parent = Math.floor((index - 1) / 2);
57
+ if (this.heap[parent].deadline <= this.heap[index].deadline)
58
+ break;
59
+ this.swap(parent, index);
60
+ index = parent;
61
+ }
62
+ while (index * 2 + 1 < this.heap.length) {
63
+ let child = index * 2 + 1;
64
+ if (child + 1 < this.heap.length &&
65
+ this.heap[child + 1].deadline < this.heap[child].deadline)
66
+ child++;
67
+ if (this.heap[index].deadline <= this.heap[child].deadline)
68
+ break;
69
+ this.swap(index, child);
70
+ index = child;
71
+ }
72
+ }
73
+ remove(entry) {
74
+ const index = entry.index, tail = this.heap.pop();
75
+ this.data.delete(entry.key);
76
+ if (index < this.heap.length) {
77
+ this.heap[index] = tail;
78
+ tail.index = index;
79
+ this.fix(index);
80
+ }
81
+ }
82
+ expire(now) {
83
+ let removed = 0;
84
+ while (this.heap.length && this.heap[0].deadline <= now) {
85
+ this.remove(this.heap[0]);
86
+ removed++;
87
+ }
88
+ return removed;
89
+ }
90
+ deadline(now, ttl) {
91
+ const end = now + ttl;
92
+ if (!Number.isFinite(ttl) || ttl <= 0 || !Number.isFinite(end) || end <= now)
93
+ throw new RangeError('TTL must produce a finite future deadline');
94
+ return end;
95
+ }
96
+ get size() {
97
+ this.expire(this.now());
98
+ return this.data.size;
99
+ }
100
+ purge() {
101
+ return this.expire(this.now());
102
+ }
103
+ set(key, value, ttl) {
104
+ if (!Number.isFinite(ttl) || ttl <= 0)
105
+ throw new RangeError('TTL must be positive and finite');
106
+ const now = this.now(), deadline = this.deadline(now, ttl);
107
+ this.expire(now);
108
+ const previous = this.data.get(key);
109
+ if (previous) {
110
+ previous.value = value;
111
+ previous.ttl = ttl;
112
+ previous.deadline = deadline;
113
+ this.fix(previous.index);
114
+ return;
115
+ }
116
+ if (this.data.size === this.maximum)
117
+ throw new RangeError('maxEntries exceeded');
118
+ const entry = { key, value, ttl, deadline, index: this.heap.length };
119
+ this.data.set(key, entry);
120
+ this.heap.push(entry);
121
+ this.fix(entry.index);
122
+ }
123
+ get(key) {
124
+ const now = this.now();
125
+ this.expire(now);
126
+ const entry = this.data.get(key);
127
+ if (!entry)
128
+ return undefined;
129
+ if (this.refresh) {
130
+ const deadline = this.deadline(now, entry.ttl);
131
+ entry.deadline = deadline;
132
+ this.fix(entry.index);
133
+ }
134
+ return entry.value;
135
+ }
136
+ has(key) {
137
+ this.expire(this.now());
138
+ return this.data.has(key);
139
+ }
140
+ delete(key) {
141
+ this.expire(this.now());
142
+ const entry = this.data.get(key);
143
+ if (!entry)
144
+ return false;
145
+ this.remove(entry);
146
+ return true;
147
+ }
148
+ clear() {
149
+ this.now();
150
+ this.data.clear();
151
+ this.heap.length = 0;
152
+ }
153
+ entries() {
154
+ this.expire(this.now());
155
+ return [...this.data.values()].map((e) => [e.key, e.value]);
156
+ }
157
+ }
158
+ exports.TtlMap = TtlMap;
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,30 @@
1
+ export interface TtlOptions {
2
+ maxEntries: number;
3
+ clock: () => number;
4
+ refreshOnGet?: boolean;
5
+ }
6
+ /** Indexed expiry heap: no stale tombstones or background timers. */
7
+ export declare class TtlMap<K, V> {
8
+ private readonly data;
9
+ private readonly heap;
10
+ private last;
11
+ private readingClock;
12
+ private readonly maximum;
13
+ private readonly clock;
14
+ private readonly refresh;
15
+ constructor(options: TtlOptions);
16
+ private now;
17
+ private swap;
18
+ private fix;
19
+ private remove;
20
+ private expire;
21
+ private deadline;
22
+ get size(): number;
23
+ purge(): number;
24
+ set(key: K, value: V, ttl: number): void;
25
+ get(key: K): V | undefined;
26
+ has(key: K): boolean;
27
+ delete(key: K): boolean;
28
+ clear(): void;
29
+ entries(): [K, V][];
30
+ }
@@ -0,0 +1,154 @@
1
+ /** Indexed expiry heap: no stale tombstones or background timers. */
2
+ export class TtlMap {
3
+ data = new Map();
4
+ heap = [];
5
+ last = -Infinity;
6
+ readingClock = false;
7
+ maximum;
8
+ clock;
9
+ refresh;
10
+ constructor(options) {
11
+ if (typeof options.clock !== 'function')
12
+ throw new TypeError('Expected clock callback');
13
+ if (!Number.isSafeInteger(options.maxEntries) || options.maxEntries < 1)
14
+ throw new RangeError('maxEntries must be positive');
15
+ this.maximum = options.maxEntries;
16
+ this.clock = options.clock;
17
+ this.refresh = options.refreshOnGet ?? false;
18
+ }
19
+ now() {
20
+ if (this.readingClock)
21
+ throw new Error('Reentrant clock access');
22
+ let now;
23
+ this.readingClock = true;
24
+ try {
25
+ const sample = this.clock();
26
+ if (sample !== null &&
27
+ (typeof sample === 'object' || typeof sample === 'function') &&
28
+ typeof sample.then === 'function') {
29
+ void Promise.resolve(sample).catch(() => { });
30
+ throw new TypeError('Clock must be synchronous');
31
+ }
32
+ if (typeof sample !== 'number')
33
+ throw new TypeError('Clock must return a number');
34
+ now = sample;
35
+ }
36
+ finally {
37
+ this.readingClock = false;
38
+ }
39
+ if (!Number.isFinite(now) || now < this.last)
40
+ throw new RangeError('Clock must be finite and monotonic');
41
+ this.last = now;
42
+ return now;
43
+ }
44
+ swap(a, b) {
45
+ const x = this.heap[a], y = this.heap[b];
46
+ this.heap[a] = y;
47
+ this.heap[b] = x;
48
+ y.index = a;
49
+ x.index = b;
50
+ }
51
+ fix(index) {
52
+ while (index > 0) {
53
+ const parent = Math.floor((index - 1) / 2);
54
+ if (this.heap[parent].deadline <= this.heap[index].deadline)
55
+ break;
56
+ this.swap(parent, index);
57
+ index = parent;
58
+ }
59
+ while (index * 2 + 1 < this.heap.length) {
60
+ let child = index * 2 + 1;
61
+ if (child + 1 < this.heap.length &&
62
+ this.heap[child + 1].deadline < this.heap[child].deadline)
63
+ child++;
64
+ if (this.heap[index].deadline <= this.heap[child].deadline)
65
+ break;
66
+ this.swap(index, child);
67
+ index = child;
68
+ }
69
+ }
70
+ remove(entry) {
71
+ const index = entry.index, tail = this.heap.pop();
72
+ this.data.delete(entry.key);
73
+ if (index < this.heap.length) {
74
+ this.heap[index] = tail;
75
+ tail.index = index;
76
+ this.fix(index);
77
+ }
78
+ }
79
+ expire(now) {
80
+ let removed = 0;
81
+ while (this.heap.length && this.heap[0].deadline <= now) {
82
+ this.remove(this.heap[0]);
83
+ removed++;
84
+ }
85
+ return removed;
86
+ }
87
+ deadline(now, ttl) {
88
+ const end = now + ttl;
89
+ if (!Number.isFinite(ttl) || ttl <= 0 || !Number.isFinite(end) || end <= now)
90
+ throw new RangeError('TTL must produce a finite future deadline');
91
+ return end;
92
+ }
93
+ get size() {
94
+ this.expire(this.now());
95
+ return this.data.size;
96
+ }
97
+ purge() {
98
+ return this.expire(this.now());
99
+ }
100
+ set(key, value, ttl) {
101
+ if (!Number.isFinite(ttl) || ttl <= 0)
102
+ throw new RangeError('TTL must be positive and finite');
103
+ const now = this.now(), deadline = this.deadline(now, ttl);
104
+ this.expire(now);
105
+ const previous = this.data.get(key);
106
+ if (previous) {
107
+ previous.value = value;
108
+ previous.ttl = ttl;
109
+ previous.deadline = deadline;
110
+ this.fix(previous.index);
111
+ return;
112
+ }
113
+ if (this.data.size === this.maximum)
114
+ throw new RangeError('maxEntries exceeded');
115
+ const entry = { key, value, ttl, deadline, index: this.heap.length };
116
+ this.data.set(key, entry);
117
+ this.heap.push(entry);
118
+ this.fix(entry.index);
119
+ }
120
+ get(key) {
121
+ const now = this.now();
122
+ this.expire(now);
123
+ const entry = this.data.get(key);
124
+ if (!entry)
125
+ return undefined;
126
+ if (this.refresh) {
127
+ const deadline = this.deadline(now, entry.ttl);
128
+ entry.deadline = deadline;
129
+ this.fix(entry.index);
130
+ }
131
+ return entry.value;
132
+ }
133
+ has(key) {
134
+ this.expire(this.now());
135
+ return this.data.has(key);
136
+ }
137
+ delete(key) {
138
+ this.expire(this.now());
139
+ const entry = this.data.get(key);
140
+ if (!entry)
141
+ return false;
142
+ this.remove(entry);
143
+ return true;
144
+ }
145
+ clear() {
146
+ this.now();
147
+ this.data.clear();
148
+ this.heap.length = 0;
149
+ }
150
+ entries() {
151
+ this.expire(this.now());
152
+ return [...this.data.values()].map((e) => [e.key, e.value]);
153
+ }
154
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@lp-labs/ttl-map",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "An entry-bounded expiring Map with an indexed minimum-deadline heap and an injected clock.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/cjs/index.js",
8
+ "module": "./dist/esm/index.js",
9
+ "types": "./dist/esm/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/esm/index.d.ts",
14
+ "default": "./dist/esm/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/cjs/index.d.ts",
18
+ "default": "./dist/cjs/index.js"
19
+ }
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "sideEffects": false,
29
+ "engines": {
30
+ "node": ">=18"
31
+ },
32
+ "scripts": {
33
+ "build": "node scripts/build.mjs",
34
+ "typecheck": "npm run build && node scripts/check-types.mjs",
35
+ "test": "npm run build && node --test tests/*.test.mjs",
36
+ "format": "prettier --write src scripts tests *.json README.md",
37
+ "format:check": "prettier --check src scripts tests *.json README.md",
38
+ "prepack": "npm run build"
39
+ },
40
+ "devDependencies": {
41
+ "typescript": "^5.9.3",
42
+ "prettier": "^3.6.2"
43
+ },
44
+ "prettier": {
45
+ "singleQuote": true,
46
+ "semi": true,
47
+ "trailingComma": "all",
48
+ "printWidth": 100,
49
+ "endOfLine": "lf"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "registry": "https://registry.npmjs.org/"
54
+ },
55
+ "author": {
56
+ "name": "Libin Prasanth",
57
+ "url": "https://www.linkedin.com/in/libinprasanth/"
58
+ },
59
+ "funding": {
60
+ "type": "paypal",
61
+ "url": "https://www.paypal.me/LibinPrasanth"
62
+ }
63
+ }