detritus-utils 0.5.0-beta.1 → 0.5.0-beta.3

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) 2018 Dan
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.
@@ -30,6 +30,7 @@ export interface BaseCollectionOptions {
30
30
  export declare class BaseCollection<K, V> extends BaseCollectionMixin<K, V> {
31
31
  readonly cache: Map<K, V>;
32
32
  _lastUsed?: Map<K, number>;
33
+ _order?: Map<K, true>;
33
34
  expire?: number;
34
35
  interval?: Timers.Interval;
35
36
  intervalTime: number;
@@ -38,6 +39,7 @@ export declare class BaseCollection<K, V> extends BaseCollectionMixin<K, V> {
38
39
  get lastUsed(): Map<K, number>;
39
40
  get shouldStartInterval(): boolean;
40
41
  setExpire(value: number): this;
42
+ setLimit(value: number): this;
41
43
  setIntervalTimeout(value: number): this;
42
44
  startInterval(): void;
43
45
  stopInterval(): void;
@@ -47,9 +49,20 @@ export declare class BaseCollection<K, V> extends BaseCollectionMixin<K, V> {
47
49
  delete(key: K): boolean;
48
50
  forEach(func: (v: V, k: K, map: Map<K, V>) => void, thisArg?: any): void;
49
51
  get(key: K): V | undefined;
52
+ getOrInsert(key: K, defaultValue: V): V;
53
+ getOrInsertComputed(key: K, func: (key: K) => V): V;
50
54
  has(key: K): boolean;
51
55
  keys(): IterableIterator<K>;
52
56
  set(key: K, value: V): this;
57
+ /**
58
+ * Evicts the least recently used items until there's `room` free under the limit
59
+ */
60
+ evict(room?: number): void;
61
+ /**
62
+ * The recency order (least recently used first), synced with the cache
63
+ * keys added before `limit` was set (or while it was `Infinity`) aren't tracked yet, so they count as the least recently used
64
+ */
65
+ getOrder(): Map<K, true>;
53
66
  values(): IterableIterator<V>;
54
67
  [Symbol.iterator](): IterableIterator<[K, V]>;
55
68
  get [Symbol.toStringTag](): string;
@@ -150,6 +150,7 @@ class BaseCollection extends BaseCollectionMixin {
150
150
  }
151
151
  Object.defineProperties(this, {
152
152
  _lastUsed: { enumerable: false, writable: true },
153
+ _order: { enumerable: false, writable: true },
153
154
  cache: { enumerable: false },
154
155
  expire: { configurable: true, writable: false },
155
156
  interval: { enumerable: false, writable: true },
@@ -167,20 +168,37 @@ class BaseCollection extends BaseCollectionMixin {
167
168
  return new Map();
168
169
  }
169
170
  get shouldStartInterval() {
170
- return !!this.intervalTime && (!this.interval || !!this.interval.hasStarted);
171
+ return !!this.intervalTime && (!this.interval || !this.interval.hasStarted);
171
172
  }
172
173
  setExpire(value) {
174
+ const wasExpiring = !!this.expire;
173
175
  Object.defineProperty(this, 'expire', { value });
174
176
  if (value) {
177
+ Object.defineProperty(this, 'intervalTime', { value: Math.min(value, this.intervalTime) });
178
+ const now = Date.now();
179
+ const lastUsed = this.lastUsed;
180
+ for (let key of this.cache.keys()) {
181
+ if (!wasExpiring || !lastUsed.has(key)) {
182
+ lastUsed.set(key, now);
183
+ }
184
+ }
175
185
  if (this.size) {
176
186
  this.startInterval();
177
187
  }
178
188
  }
179
189
  else {
180
190
  this.stopInterval();
191
+ if (this._lastUsed) {
192
+ this._lastUsed.clear();
193
+ }
181
194
  }
182
195
  return this;
183
196
  }
197
+ setLimit(value) {
198
+ this.limit = value;
199
+ this.evict(0);
200
+ return this;
201
+ }
184
202
  setIntervalTimeout(value) {
185
203
  Object.defineProperty(this, 'intervalTime', { value });
186
204
  if (value) {
@@ -233,11 +251,16 @@ class BaseCollection extends BaseCollectionMixin {
233
251
  if (this._lastUsed) {
234
252
  this._lastUsed.clear();
235
253
  }
254
+ if (this._order) {
255
+ this._order.clear();
256
+ }
236
257
  }
237
258
  clone() {
238
259
  const collection = new BaseCollection(this);
239
- for (let [key, value] of this) {
240
- collection.set(key, value);
260
+ // insert least recently used first so the clone keeps the same eviction order
261
+ const keys = (this.limit !== Infinity) ? this.getOrder().keys() : this.cache.keys();
262
+ for (let key of keys) {
263
+ collection.set(key, this.cache.get(key));
241
264
  }
242
265
  return collection;
243
266
  }
@@ -246,6 +269,9 @@ class BaseCollection extends BaseCollectionMixin {
246
269
  if (this._lastUsed) {
247
270
  this._lastUsed.delete(key);
248
271
  }
272
+ if (this._order) {
273
+ this._order.delete(key);
274
+ }
249
275
  if (!this.cache.size) {
250
276
  this.stopInterval();
251
277
  }
@@ -256,11 +282,32 @@ class BaseCollection extends BaseCollectionMixin {
256
282
  }
257
283
  get(key) {
258
284
  const value = this.cache.get(key);
259
- if (this.expire && value) {
285
+ if (this.limit !== Infinity && this.cache.has(key)) {
286
+ // mark it as the most recently used
287
+ const order = this.getOrder();
288
+ order.delete(key);
289
+ order.set(key, true);
290
+ }
291
+ if (this.expire && this.cache.has(key)) {
260
292
  this.lastUsed.set(key, Date.now());
261
293
  }
262
294
  return value;
263
295
  }
296
+ getOrInsert(key, defaultValue) {
297
+ if (this.has(key)) {
298
+ return this.get(key);
299
+ }
300
+ this.set(key, defaultValue);
301
+ return defaultValue;
302
+ }
303
+ getOrInsertComputed(key, func) {
304
+ if (this.has(key)) {
305
+ return this.get(key);
306
+ }
307
+ const value = func(key);
308
+ this.set(key, value);
309
+ return value;
310
+ }
264
311
  has(key) {
265
312
  return this.cache.has(key);
266
313
  }
@@ -268,6 +315,21 @@ class BaseCollection extends BaseCollectionMixin {
268
315
  return this.cache.keys();
269
316
  }
270
317
  set(key, value) {
318
+ if (this.limit !== Infinity) {
319
+ if (this.limit <= 0) {
320
+ this.evict(0);
321
+ return this;
322
+ }
323
+ const order = this.getOrder();
324
+ if (this.cache.has(key)) {
325
+ order.delete(key);
326
+ }
327
+ else {
328
+ // make room for the new key, evicting the least recently used ones
329
+ this.evict(1);
330
+ }
331
+ order.set(key, true);
332
+ }
271
333
  this.cache.set(key, value);
272
334
  if (this.expire) {
273
335
  this.lastUsed.set(key, Date.now());
@@ -275,15 +337,50 @@ class BaseCollection extends BaseCollectionMixin {
275
337
  this.startInterval();
276
338
  }
277
339
  }
278
- if (this.limit !== Infinity) {
279
- if (this.limit <= this.cache.size) {
280
- for (let [key, value] of this.cache) {
281
- this.delete(key);
282
- break;
340
+ return this;
341
+ }
342
+ /**
343
+ * Evicts the least recently used items until there's `room` free under the limit
344
+ */
345
+ evict(room = 0) {
346
+ if (this.limit === Infinity) {
347
+ return;
348
+ }
349
+ const max = Math.max(this.limit - room, 0);
350
+ if (this.cache.size <= max) {
351
+ return;
352
+ }
353
+ const order = this.getOrder();
354
+ for (let key of order.keys()) {
355
+ if (this.cache.size <= max) {
356
+ break;
357
+ }
358
+ this.delete(key);
359
+ }
360
+ }
361
+ /**
362
+ * The recency order (least recently used first), synced with the cache
363
+ * keys added before `limit` was set (or while it was `Infinity`) aren't tracked yet, so they count as the least recently used
364
+ */
365
+ getOrder() {
366
+ let order = this._order;
367
+ if (!order || order.size !== this.cache.size) {
368
+ const synced = new Map();
369
+ for (let key of this.cache.keys()) {
370
+ if (!order || !order.has(key)) {
371
+ synced.set(key, true);
283
372
  }
284
373
  }
374
+ if (order) {
375
+ for (let key of order.keys()) {
376
+ if (this.cache.has(key)) {
377
+ synced.set(key, true);
378
+ }
379
+ }
380
+ }
381
+ order = this._order = synced;
285
382
  }
286
- return this;
383
+ return order;
287
384
  }
288
385
  values() {
289
386
  return this.cache.values();
@@ -1,6 +1,6 @@
1
1
  export declare const Package: Readonly<{
2
2
  URL: "https://github.com/detritusjs/utils";
3
- VERSION: "0.5.0-beta.1";
3
+ VERSION: "0.5.0-beta.3";
4
4
  }>;
5
5
  export declare const DISCORD_SNOWFLAKE_EPOCH = 1420070400000;
6
6
  export declare const DISCORD_TOKEN_EPOCH = 1293840000000;
package/lib/constants.js CHANGED
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DISCORD_TOKEN_EPOCH = exports.DISCORD_SNOWFLAKE_EPOCH = exports.Package = void 0;
4
4
  exports.Package = Object.freeze({
5
5
  URL: 'https://github.com/detritusjs/utils',
6
- VERSION: '0.5.0-beta.1',
6
+ VERSION: '0.5.0-beta.3',
7
7
  });
8
8
  exports.DISCORD_SNOWFLAKE_EPOCH = 1420070400000;
9
9
  exports.DISCORD_TOKEN_EPOCH = 1293840000000;
@@ -15,6 +15,8 @@ export declare class EventSpewer extends Emitter implements EventEmitter {
15
15
  hasEventListener(name: string | symbol): boolean;
16
16
  subscribe(name: string | symbol, listener: (...args: any[]) => void): EventSubscription;
17
17
  removeSubscription(subscription: EventSubscription): void;
18
+ removeListener(name: string | symbol, listener: (...args: any[]) => void, ...args: Array<any>): this;
19
+ off(name: string | symbol, listener: (...args: any[]) => void, ...args: Array<any>): this;
18
20
  removeAllListeners(name?: string | symbol): this;
19
21
  removeAllSubscriptions(): this;
20
22
  }
@@ -8,10 +8,6 @@ try {
8
8
  }
9
9
  catch (e) { }
10
10
  class EventSpewer extends Emitter {
11
- /**
12
- * @ignore
13
- */
14
- _events;
15
11
  /**
16
12
  * @ignore
17
13
  */
@@ -38,12 +34,9 @@ class EventSpewer extends Emitter {
38
34
  return subscription;
39
35
  }
40
36
  removeSubscription(subscription) {
41
- if (subscription.listener) {
42
- this.removeListener(subscription.name, subscription.listener);
43
- }
44
37
  if (this._subscriptions) {
45
38
  const index = this._subscriptions.indexOf(subscription);
46
- if (index !== 1) {
39
+ if (index !== -1) {
47
40
  if (this._subscriptions.length === 1) {
48
41
  this._subscriptions.pop();
49
42
  }
@@ -55,11 +48,40 @@ class EventSpewer extends Emitter {
55
48
  this._subscriptions = undefined;
56
49
  }
57
50
  }
51
+ if (subscription.listener) {
52
+ this.removeListener(subscription.name, subscription.listener);
53
+ }
54
+ }
55
+ removeListener(name, listener, ...args) {
56
+ super.removeListener.call(this, name, listener, ...args);
57
+ if (this._subscriptions) {
58
+ let attached = this.listeners(name).filter((x) => x === listener).length;
59
+ for (let i = this._subscriptions.length - 1; 0 <= i; i--) {
60
+ const subscription = this._subscriptions[i];
61
+ if (subscription.name === name && subscription.listener === listener) {
62
+ if (attached) {
63
+ attached--;
64
+ }
65
+ else {
66
+ this._subscriptions.splice(i, 1);
67
+ subscription.listener = null;
68
+ subscription.spewer = null;
69
+ }
70
+ }
71
+ }
72
+ if (!this._subscriptions.length) {
73
+ this._subscriptions = undefined;
74
+ }
75
+ }
76
+ return this;
77
+ }
78
+ off(name, listener, ...args) {
79
+ return this.removeListener(name, listener, ...args);
58
80
  }
59
81
  removeAllListeners(name) {
60
82
  if (this._subscriptions) {
61
83
  if (name !== undefined) {
62
- for (let subscription of this._subscriptions) {
84
+ for (let subscription of this._subscriptions.slice()) {
63
85
  if (subscription.name === name) {
64
86
  subscription.remove();
65
87
  }
@@ -73,17 +95,26 @@ class EventSpewer extends Emitter {
73
95
  subscription.spewer = null;
74
96
  }
75
97
  }
98
+ this._subscriptions = undefined;
76
99
  }
77
100
  }
101
+ if (name === undefined) {
102
+ return super.removeAllListeners();
103
+ }
104
+ if (!name) {
105
+ for (let listener of this.listeners(name)) {
106
+ this.removeListener(name, listener);
107
+ }
108
+ return this;
109
+ }
78
110
  return super.removeAllListeners(name);
79
111
  }
80
112
  removeAllSubscriptions() {
81
113
  if (this._subscriptions) {
82
- while (this._subscriptions.length) {
83
- const subscription = this._subscriptions.shift();
84
- if (subscription) {
85
- subscription.remove();
86
- }
114
+ const subscriptions = this._subscriptions;
115
+ this._subscriptions = undefined;
116
+ for (let subscription of subscriptions) {
117
+ subscription.remove();
87
118
  }
88
119
  }
89
120
  return this;
package/lib/snowflake.js CHANGED
@@ -34,7 +34,11 @@ function generate(options = {}) {
34
34
  }, options);
35
35
  const epoch = BigInt(options.epoch);
36
36
  const processId = BigInt(options.processId) & max.processId;
37
- const timestamp = (BigInt(options.timestamp) - epoch) % max.timestamp;
37
+ const elapsed = BigInt(options.timestamp) - epoch;
38
+ if (elapsed < 0n) {
39
+ throw new RangeError(`Timestamp ${options.timestamp} is before the epoch ${options.epoch}`);
40
+ }
41
+ const timestamp = elapsed % max.timestamp;
38
42
  const workerId = BigInt(options.workerId) & max.workerId;
39
43
  let sequence;
40
44
  if (options.sequence === undefined) {
package/lib/tools.js CHANGED
@@ -10,7 +10,17 @@ function normalize(object) {
10
10
  return Object.freeze(object);
11
11
  }
12
12
  function guildIdToShardId(guildId, shardCount = 0) {
13
- return Math.round(+(guildId) / (1 << 22)) % shardCount;
13
+ if (shardCount < 1) {
14
+ return 0;
15
+ }
16
+ let id;
17
+ try {
18
+ id = BigInt(guildId);
19
+ }
20
+ catch (e) {
21
+ return NaN;
22
+ }
23
+ return Number((id >> 22n) % BigInt(shardCount));
14
24
  }
15
25
  const safeCharacter = '@';
16
26
  function URIEncodeWrap(unsafe) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "detritus-utils",
3
- "version": "0.5.0-beta.1",
3
+ "version": "0.5.0-beta.3",
4
4
  "description": "Detritus Utils",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -38,6 +38,7 @@
38
38
  },
39
39
  "homepage": "https://github.com/detritusjs/utils#readme",
40
40
  "devDependencies": {
41
- "@types/node": "^26.1.2"
41
+ "@types/node": "^26.1.2",
42
+ "typescript": "^7.0.2"
42
43
  }
43
44
  }
@@ -1,56 +0,0 @@
1
- import * as Timers from './timers';
2
- export declare class BaseCollectionMixin<K, V> {
3
- get length(): number;
4
- get size(): number;
5
- clear(): void;
6
- entries(): IterableIterator<[K, V]>;
7
- every(func: (v: V, k: K) => boolean): boolean;
8
- filter(func: (v: V, k: K) => boolean): Array<V>;
9
- find(func: (v: V, k: K) => boolean): V | undefined;
10
- first(): V | undefined;
11
- forEach(func: (v: V, k: K, map: Map<K, V>) => void, thisArg?: any): void;
12
- join(separator?: string): string;
13
- map(func: (v: V, k: K) => any): Array<any>;
14
- reduce(func: (intial: any, v: V) => any, initialValue?: any): any;
15
- some(func: (v: V, k: K) => boolean): boolean;
16
- sort(func?: (x: V, y: V) => number): Array<V>;
17
- toArray(): Array<V>;
18
- toJSON(): Array<V>;
19
- toString(): string;
20
- keys(): IterableIterator<K>;
21
- values(): IterableIterator<V>;
22
- [Symbol.iterator](): IterableIterator<[K, V]>;
23
- get [Symbol.toStringTag](): string;
24
- }
25
- export interface BaseCollectionOptions {
26
- expire?: number;
27
- intervalTime?: number;
28
- limit?: number;
29
- }
30
- export declare class BaseCollection<K, V> extends BaseCollectionMixin<K, V> {
31
- readonly cache: Map<K, V>;
32
- _lastUsed?: Map<K, number>;
33
- expire?: number;
34
- interval?: Timers.Interval;
35
- intervalTime: number;
36
- limit: number;
37
- constructor({ expire, intervalTime, limit }?: BaseCollectionOptions);
38
- get lastUsed(): Map<K, number>;
39
- get shouldStartInterval(): boolean;
40
- setExpire(value: number): this;
41
- setIntervalTimeout(value: number): this;
42
- startInterval(): void;
43
- stopInterval(): void;
44
- get size(): number;
45
- clear(): void;
46
- clone(): BaseCollection<K, V>;
47
- delete(key: K): boolean;
48
- forEach(func: (v: V, k: K, map: Map<K, V>) => void, thisArg?: any): void;
49
- get(key: K): V | undefined;
50
- has(key: K): boolean;
51
- keys(): IterableIterator<K>;
52
- set(key: K, value: V): this;
53
- values(): IterableIterator<V>;
54
- [Symbol.iterator](): IterableIterator<[K, V]>;
55
- get [Symbol.toStringTag](): string;
56
- }