detritus-utils 0.5.0-beta.2 → 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;
@@ -52,6 +54,15 @@ export declare class BaseCollection<K, V> extends BaseCollectionMixin<K, V> {
52
54
  has(key: K): boolean;
53
55
  keys(): IterableIterator<K>;
54
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>;
55
66
  values(): IterableIterator<V>;
56
67
  [Symbol.iterator](): IterableIterator<[K, V]>;
57
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,7 +282,13 @@ 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;
@@ -283,6 +315,21 @@ class BaseCollection extends BaseCollectionMixin {
283
315
  return this.cache.keys();
284
316
  }
285
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
+ }
286
333
  this.cache.set(key, value);
287
334
  if (this.expire) {
288
335
  this.lastUsed.set(key, Date.now());
@@ -290,15 +337,50 @@ class BaseCollection extends BaseCollectionMixin {
290
337
  this.startInterval();
291
338
  }
292
339
  }
293
- if (this.limit !== Infinity) {
294
- if (this.limit <= this.cache.size) {
295
- for (let [key, value] of this.cache) {
296
- this.delete(key);
297
- 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);
372
+ }
373
+ }
374
+ if (order) {
375
+ for (let key of order.keys()) {
376
+ if (this.cache.has(key)) {
377
+ synced.set(key, true);
378
+ }
298
379
  }
299
380
  }
381
+ order = this._order = synced;
300
382
  }
301
- return this;
383
+ return order;
302
384
  }
303
385
  values() {
304
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.2";
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.2',
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.2",
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
- }
@@ -1,298 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.BaseCollection = exports.BaseCollectionMixin = void 0;
37
- const Timers = __importStar(require("./timers"));
38
- class BaseCollectionMixin {
39
- get length() {
40
- return this.size;
41
- }
42
- get size() {
43
- return 0;
44
- }
45
- clear() {
46
- }
47
- entries() {
48
- return this[Symbol.iterator]();
49
- }
50
- every(func) {
51
- for (let [key, value] of this) {
52
- if (!func(value, key)) {
53
- return false;
54
- }
55
- }
56
- return true;
57
- }
58
- filter(func) {
59
- const map = [];
60
- for (let [key, value] of this) {
61
- if (func(value, key)) {
62
- map.push(value);
63
- }
64
- }
65
- return map;
66
- }
67
- find(func) {
68
- for (let [key, value] of this) {
69
- if (func(value, key)) {
70
- return value;
71
- }
72
- }
73
- return undefined;
74
- }
75
- first() {
76
- for (let [key, value] of this) {
77
- return value;
78
- }
79
- }
80
- forEach(func, thisArg) {
81
- }
82
- join(separator) {
83
- return this.toArray().join(separator);
84
- }
85
- map(func) {
86
- const map = [];
87
- for (let [key, value] of this) {
88
- map.push(func(value, key));
89
- }
90
- return map;
91
- }
92
- reduce(func, initialValue) {
93
- let reduced = initialValue;
94
- for (let [key, value] of this) {
95
- reduced = func(reduced, value);
96
- }
97
- return reduced;
98
- }
99
- some(func) {
100
- for (let [key, value] of this) {
101
- if (func(value, key)) {
102
- return true;
103
- }
104
- }
105
- return false;
106
- }
107
- sort(func) {
108
- return this.toArray().sort(func);
109
- }
110
- toArray() {
111
- return Array.from(this.values());
112
- }
113
- toJSON() {
114
- return this.toArray();
115
- }
116
- toString() {
117
- return this[Symbol.toStringTag];
118
- }
119
- *keys() {
120
- }
121
- *values() {
122
- }
123
- *[Symbol.iterator]() {
124
- }
125
- get [Symbol.toStringTag]() {
126
- return 'BaseCollection';
127
- }
128
- }
129
- exports.BaseCollectionMixin = BaseCollectionMixin;
130
- class BaseCollection extends BaseCollectionMixin {
131
- cache = new Map();
132
- _lastUsed;
133
- expire;
134
- interval = undefined;
135
- intervalTime = 5000;
136
- limit = Infinity;
137
- constructor({ expire, intervalTime, limit } = {}) {
138
- super();
139
- if (expire !== undefined) {
140
- this.expire = expire;
141
- }
142
- if (intervalTime !== undefined) {
143
- this.intervalTime = intervalTime;
144
- }
145
- if (limit !== undefined) {
146
- this.limit = limit;
147
- }
148
- if (this.expire) {
149
- this.intervalTime = Math.min(this.expire, this.intervalTime);
150
- }
151
- Object.defineProperties(this, {
152
- _lastUsed: { enumerable: false, writable: true },
153
- cache: { enumerable: false },
154
- expire: { configurable: true, writable: false },
155
- interval: { enumerable: false, writeable: true },
156
- intervalTime: { configurable: true, enumerable: false, writable: false },
157
- limit: { enumerable: false },
158
- });
159
- }
160
- get lastUsed() {
161
- if (this._lastUsed) {
162
- return this._lastUsed;
163
- }
164
- if (this.expire) {
165
- return this._lastUsed = new Map();
166
- }
167
- return new Map();
168
- }
169
- get shouldStartInterval() {
170
- return !!this.intervalTime && (!this.interval || !!this.interval.hasStarted);
171
- }
172
- setExpire(value) {
173
- Object.defineProperty(this, 'expire', { value });
174
- if (value) {
175
- if (this.size) {
176
- this.startInterval();
177
- }
178
- }
179
- else {
180
- this.stopInterval();
181
- }
182
- return this;
183
- }
184
- setIntervalTimeout(value) {
185
- Object.defineProperty(this, 'intervalTime', { value });
186
- if (value) {
187
- if (this.size) {
188
- this.startInterval();
189
- }
190
- }
191
- else {
192
- this.stopInterval();
193
- }
194
- return this;
195
- }
196
- startInterval() {
197
- if (this.intervalTime && this.expire) {
198
- if (!this.interval) {
199
- this.interval = new Timers.Interval();
200
- }
201
- this.interval.start(this.intervalTime, () => {
202
- const expire = this.expire;
203
- if (expire) {
204
- const now = Date.now();
205
- for (let [key, value] of this.cache) {
206
- const lastUsed = this.lastUsed.get(key);
207
- if (lastUsed && expire < now - lastUsed) {
208
- this.delete(key);
209
- }
210
- }
211
- }
212
- else {
213
- this.stopInterval();
214
- }
215
- });
216
- }
217
- else {
218
- this.stopInterval();
219
- }
220
- }
221
- stopInterval() {
222
- if (this.interval) {
223
- this.interval.stop();
224
- }
225
- this.interval = undefined;
226
- }
227
- get size() {
228
- return this.cache.size;
229
- }
230
- clear() {
231
- this.stopInterval();
232
- this.cache.clear();
233
- if (this._lastUsed) {
234
- this._lastUsed.clear();
235
- }
236
- }
237
- clone() {
238
- const collection = new BaseCollection(this);
239
- for (let [key, value] of this) {
240
- collection.set(key, value);
241
- }
242
- return collection;
243
- }
244
- delete(key) {
245
- const deleted = this.cache.delete(key);
246
- if (this._lastUsed) {
247
- this._lastUsed.delete(key);
248
- }
249
- if (!this.cache.size) {
250
- this.stopInterval();
251
- }
252
- return deleted;
253
- }
254
- forEach(func, thisArg) {
255
- return this.cache.forEach(func, thisArg);
256
- }
257
- get(key) {
258
- const value = this.cache.get(key);
259
- if (this.expire && value) {
260
- this.lastUsed.set(key, Date.now());
261
- }
262
- return value;
263
- }
264
- has(key) {
265
- return this.cache.has(key);
266
- }
267
- keys() {
268
- return this.cache.keys();
269
- }
270
- set(key, value) {
271
- this.cache.set(key, value);
272
- if (this.expire) {
273
- this.lastUsed.set(key, Date.now());
274
- if (this.shouldStartInterval) {
275
- this.startInterval();
276
- }
277
- }
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;
283
- }
284
- }
285
- }
286
- return this;
287
- }
288
- values() {
289
- return this.cache.values();
290
- }
291
- [Symbol.iterator]() {
292
- return this.cache[Symbol.iterator]();
293
- }
294
- get [Symbol.toStringTag]() {
295
- return `BaseCollection (${this.size.toLocaleString()} items)`;
296
- }
297
- }
298
- exports.BaseCollection = BaseCollection;
@@ -1,17 +0,0 @@
1
- export declare class BaseSet<V> extends Set<V> {
2
- get length(): number;
3
- clone(): BaseSet<V>;
4
- every(func: any): boolean;
5
- filter(func: (v: V) => boolean): Array<V>;
6
- find(func: (v: V) => boolean): undefined | V;
7
- first(): undefined | V;
8
- join(separator?: string): string;
9
- map(func: (v: V) => any): Array<any>;
10
- reduce(cb: any, initialValue?: any): any;
11
- some(func: (v: V) => boolean): boolean;
12
- sort(func?: (x: V, y: V) => number): Array<V>;
13
- toArray(): Array<V>;
14
- toJSON(): Array<V>;
15
- toString(): string;
16
- get [Symbol.toStringTag](): string;
17
- }
@@ -1,70 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseSet = void 0;
4
- class BaseSet extends Set {
5
- get length() {
6
- return this.size;
7
- }
8
- clone() {
9
- return new BaseSet(this.values());
10
- }
11
- every(func) {
12
- return this.toArray().every(func);
13
- }
14
- filter(func) {
15
- const map = [];
16
- for (let value of this) {
17
- if (func(value)) {
18
- map.push(value);
19
- }
20
- }
21
- return map;
22
- }
23
- find(func) {
24
- for (let value of this) {
25
- if (func(value)) {
26
- return value;
27
- }
28
- }
29
- }
30
- first() {
31
- return this.values().next().value;
32
- }
33
- join(separator) {
34
- return this.toArray().join(separator);
35
- }
36
- map(func) {
37
- const map = [];
38
- for (let value of this) {
39
- map.push(func(value));
40
- }
41
- return map;
42
- }
43
- reduce(cb, initialValue) {
44
- return this.toArray().reduce(cb, initialValue);
45
- }
46
- some(func) {
47
- for (let value of this) {
48
- if (func(value)) {
49
- return true;
50
- }
51
- }
52
- return false;
53
- }
54
- sort(func) {
55
- return this.toArray().sort(func);
56
- }
57
- toArray() {
58
- return Array.from(this.values());
59
- }
60
- toJSON() {
61
- return this.toArray();
62
- }
63
- toString() {
64
- return this[Symbol.toStringTag];
65
- }
66
- get [Symbol.toStringTag]() {
67
- return `BaseSet (${this.size.toLocaleString()} items)`;
68
- }
69
- }
70
- exports.BaseSet = BaseSet;
@@ -1,6 +0,0 @@
1
- export declare const Package: Readonly<{
2
- URL: "https://github.com/detritusjs/utils";
3
- VERSION: "0.4.0";
4
- }>;
5
- export declare const DISCORD_SNOWFLAKE_EPOCH = 1420070400000;
6
- export declare const DISCORD_TOKEN_EPOCH = 1293840000000;
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DISCORD_TOKEN_EPOCH = exports.DISCORD_SNOWFLAKE_EPOCH = exports.Package = void 0;
4
- exports.Package = Object.freeze({
5
- URL: 'https://github.com/detritusjs/utils',
6
- VERSION: '0.4.0',
7
- });
8
- exports.DISCORD_SNOWFLAKE_EPOCH = 1420070400000;
9
- exports.DISCORD_TOKEN_EPOCH = 1293840000000;
@@ -1,28 +0,0 @@
1
- import { EventEmitter } from 'events';
2
- declare let Emitter: any;
3
- export declare class EventSpewer extends Emitter implements EventEmitter {
4
- /**
5
- * @ignore
6
- */
7
- _events: {
8
- [key: string]: any;
9
- } | undefined;
10
- /**
11
- * @ignore
12
- */
13
- _subscriptions: Array<EventSubscription> | undefined;
14
- constructor();
15
- hasEventListener(name: string | symbol): boolean;
16
- subscribe(name: string | symbol, listener: (...args: any[]) => void): EventSubscription;
17
- removeSubscription(subscription: EventSubscription): void;
18
- removeAllListeners(name?: string | symbol): this;
19
- removeAllSubscriptions(): this;
20
- }
21
- export declare class EventSubscription {
22
- listener: ((...args: any[]) => void) | null;
23
- name: string | symbol;
24
- spewer: EventSpewer | null;
25
- constructor(spewer: EventSpewer, name: string | symbol, listener: (...args: any[]) => void);
26
- remove(): void;
27
- }
28
- export {};
@@ -1,110 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EventSubscription = exports.EventSpewer = void 0;
4
- const events_1 = require("events");
5
- let Emitter = events_1.EventEmitter;
6
- try {
7
- Emitter = require('eventemitter3');
8
- }
9
- catch (e) { }
10
- class EventSpewer extends Emitter {
11
- /**
12
- * @ignore
13
- */
14
- _events;
15
- /**
16
- * @ignore
17
- */
18
- _subscriptions = undefined;
19
- constructor() {
20
- super();
21
- Object.defineProperties(this, {
22
- _events: { enumerable: false },
23
- _eventsCount: { enumerable: false },
24
- _maxListeners: { enumerable: false },
25
- _subscriptions: { enumerable: false },
26
- });
27
- }
28
- hasEventListener(name) {
29
- return !!this._events && (name in this._events);
30
- }
31
- subscribe(name, listener) {
32
- const subscription = new EventSubscription(this, name, listener);
33
- this.on(name, listener);
34
- if (!this._subscriptions) {
35
- this._subscriptions = [];
36
- }
37
- this._subscriptions.push(subscription);
38
- return subscription;
39
- }
40
- removeSubscription(subscription) {
41
- if (subscription.listener) {
42
- this.removeListener(subscription.name, subscription.listener);
43
- }
44
- if (this._subscriptions) {
45
- const index = this._subscriptions.indexOf(subscription);
46
- if (index !== 1) {
47
- if (this._subscriptions.length === 1) {
48
- this._subscriptions.pop();
49
- }
50
- else {
51
- this._subscriptions.splice(index, 1);
52
- }
53
- }
54
- if (!this._subscriptions.length) {
55
- this._subscriptions = undefined;
56
- }
57
- }
58
- }
59
- removeAllListeners(name) {
60
- if (this._subscriptions) {
61
- if (name !== undefined) {
62
- for (let subscription of this._subscriptions) {
63
- if (subscription.name === name) {
64
- subscription.remove();
65
- }
66
- }
67
- }
68
- else {
69
- while (this._subscriptions.length) {
70
- const subscription = this._subscriptions.shift();
71
- if (subscription) {
72
- subscription.listener = null;
73
- subscription.spewer = null;
74
- }
75
- }
76
- }
77
- }
78
- return super.removeAllListeners(name);
79
- }
80
- removeAllSubscriptions() {
81
- if (this._subscriptions) {
82
- while (this._subscriptions.length) {
83
- const subscription = this._subscriptions.shift();
84
- if (subscription) {
85
- subscription.remove();
86
- }
87
- }
88
- }
89
- return this;
90
- }
91
- }
92
- exports.EventSpewer = EventSpewer;
93
- class EventSubscription {
94
- listener;
95
- name;
96
- spewer;
97
- constructor(spewer, name, listener) {
98
- this.name = name;
99
- this.listener = listener;
100
- this.spewer = spewer;
101
- }
102
- remove() {
103
- if (this.spewer) {
104
- this.spewer.removeSubscription(this);
105
- }
106
- this.listener = null;
107
- this.spewer = null;
108
- }
109
- }
110
- exports.EventSubscription = EventSubscription;
@@ -1,8 +0,0 @@
1
- import * as Constants from './constants';
2
- import * as Snowflake from './snowflake';
3
- import * as Timers from './timers';
4
- import * as Tools from './tools';
5
- export { Constants, Snowflake, Timers, Tools };
6
- export * from './basecollection';
7
- export * from './baseset';
8
- export * from './eventspewer';
package/lib/src/index.js DELETED
@@ -1,50 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
36
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.Tools = exports.Timers = exports.Snowflake = exports.Constants = void 0;
40
- const Constants = __importStar(require("./constants"));
41
- exports.Constants = Constants;
42
- const Snowflake = __importStar(require("./snowflake"));
43
- exports.Snowflake = Snowflake;
44
- const Timers = __importStar(require("./timers"));
45
- exports.Timers = Timers;
46
- const Tools = __importStar(require("./tools"));
47
- exports.Tools = Tools;
48
- __exportStar(require("./basecollection"), exports);
49
- __exportStar(require("./baseset"), exports);
50
- __exportStar(require("./eventspewer"), exports);
@@ -1,20 +0,0 @@
1
- export interface Snowflake {
2
- id: string;
3
- processId: number;
4
- sequence: number;
5
- timestamp: number;
6
- workerId: number;
7
- }
8
- export interface SnowflakeGenerateOptions {
9
- epoch?: number;
10
- processId?: number;
11
- sequence?: number;
12
- timestamp?: number;
13
- workerId?: number;
14
- }
15
- export declare function generate(options?: SnowflakeGenerateOptions): Snowflake;
16
- export interface SnowflakeDeconstructOptions {
17
- epoch?: number;
18
- }
19
- export declare function deconstruct(id: string, options?: SnowflakeDeconstructOptions): Snowflake;
20
- export declare function timestamp(id: string, options?: SnowflakeDeconstructOptions): number;
@@ -1,82 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generate = generate;
4
- exports.deconstruct = deconstruct;
5
- exports.timestamp = timestamp;
6
- const constants_1 = require("./constants");
7
- const bits = Object.freeze({
8
- timestamp: 42n,
9
- workerId: 5n,
10
- processId: 5n,
11
- sequence: 12n,
12
- });
13
- const shift = Object.freeze({
14
- timestamp: bits.processId + bits.workerId + bits.sequence,
15
- workerId: bits.workerId + bits.sequence,
16
- processId: bits.sequence,
17
- sequence: 0n,
18
- });
19
- const max = Object.freeze({
20
- timestamp: 0x40000000000n,
21
- processId: -1n ^ (-1n << bits.processId),
22
- sequence: -1n ^ (-1n << bits.sequence),
23
- workerId: -1n ^ (-1n << bits.workerId),
24
- });
25
- const cache = {
26
- sequence: 0n,
27
- };
28
- function generate(options = {}) {
29
- options = Object.assign({
30
- epoch: constants_1.DISCORD_SNOWFLAKE_EPOCH,
31
- processId: 0,
32
- timestamp: Date.now(),
33
- workerId: 0,
34
- }, options);
35
- const epoch = BigInt(options.epoch);
36
- const processId = BigInt(options.processId) & max.processId;
37
- const timestamp = (BigInt(options.timestamp) - epoch) % max.timestamp;
38
- const workerId = BigInt(options.workerId) & max.workerId;
39
- let sequence;
40
- if (options.sequence === undefined) {
41
- sequence = cache.sequence = ++cache.sequence & max.sequence;
42
- }
43
- else {
44
- sequence = BigInt(options.sequence) & max.sequence;
45
- }
46
- const snowflake = {
47
- id: '',
48
- processId: Number(processId),
49
- sequence: Number(sequence),
50
- timestamp: Number(timestamp),
51
- workerId: Number(workerId),
52
- };
53
- snowflake.id = String((timestamp << shift.timestamp) |
54
- (workerId << shift.workerId) |
55
- (processId << shift.processId) |
56
- (sequence << shift.sequence));
57
- return snowflake;
58
- }
59
- function deconstruct(id, options = {}) {
60
- options = Object.assign({
61
- epoch: constants_1.DISCORD_SNOWFLAKE_EPOCH,
62
- }, options);
63
- const epoch = BigInt(options.epoch);
64
- const snowflake = BigInt(id);
65
- return {
66
- id,
67
- processId: Number((snowflake & 0x1f000n) >> shift.processId),
68
- sequence: Number(snowflake & 0xfffn),
69
- timestamp: Number((snowflake >> shift.timestamp) + epoch),
70
- workerId: Number((snowflake & 0x3e0000n) >> shift.workerId),
71
- };
72
- }
73
- function timestamp(id, options = {}) {
74
- options = Object.assign({
75
- epoch: constants_1.DISCORD_SNOWFLAKE_EPOCH,
76
- }, options);
77
- const epoch = BigInt(options.epoch);
78
- if (id) {
79
- return Number((BigInt(id) >> shift.timestamp) + epoch);
80
- }
81
- return 0;
82
- }
@@ -1,21 +0,0 @@
1
- export declare class Interval {
2
- shouldRef: boolean;
3
- reference: any;
4
- get hasStarted(): boolean;
5
- hasRef(): boolean;
6
- ref(): void;
7
- unref(): void;
8
- start(milliseconds: number, handler: Function): void;
9
- stop(): void;
10
- }
11
- export declare class Timeout {
12
- shouldRef: boolean;
13
- reference: any;
14
- get hasStarted(): boolean;
15
- hasRef(): boolean;
16
- ref(): void;
17
- unref(): void;
18
- start(milliseconds: number, handler: Function, override?: boolean): void;
19
- stop(): void;
20
- }
21
- export declare function sleep(milliseconds: number): Promise<void>;
package/lib/src/timers.js DELETED
@@ -1,92 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Timeout = exports.Interval = void 0;
4
- exports.sleep = sleep;
5
- class Interval {
6
- shouldRef = true;
7
- reference = null;
8
- get hasStarted() {
9
- return this.reference !== null;
10
- }
11
- hasRef() {
12
- return this.shouldRef;
13
- }
14
- ref() {
15
- this.shouldRef = true;
16
- if (this.reference) {
17
- this.reference.ref();
18
- }
19
- }
20
- unref() {
21
- this.shouldRef = false;
22
- if (this.reference) {
23
- this.reference.unref();
24
- }
25
- }
26
- start(milliseconds, handler) {
27
- this.stop();
28
- this.reference = setInterval(handler, milliseconds);
29
- if (this.shouldRef) {
30
- this.ref();
31
- }
32
- else {
33
- this.unref();
34
- }
35
- }
36
- stop() {
37
- if (this.hasStarted) {
38
- clearInterval(this.reference);
39
- this.reference = null;
40
- }
41
- }
42
- }
43
- exports.Interval = Interval;
44
- class Timeout {
45
- shouldRef = true;
46
- reference = null;
47
- get hasStarted() {
48
- return this.reference !== null;
49
- }
50
- hasRef() {
51
- return this.shouldRef;
52
- }
53
- ref() {
54
- this.shouldRef = true;
55
- if (this.reference) {
56
- this.reference.ref();
57
- }
58
- }
59
- unref() {
60
- this.shouldRef = false;
61
- if (this.reference) {
62
- this.reference.unref();
63
- }
64
- }
65
- start(milliseconds, handler, override = true) {
66
- if (!this.hasStarted || override) {
67
- this.stop();
68
- this.reference = setTimeout(() => {
69
- this.reference = null;
70
- handler();
71
- }, milliseconds);
72
- if (this.shouldRef) {
73
- this.ref();
74
- }
75
- else {
76
- this.unref();
77
- }
78
- }
79
- }
80
- stop() {
81
- if (this.hasStarted) {
82
- clearTimeout(this.reference);
83
- this.reference = null;
84
- }
85
- }
86
- }
87
- exports.Timeout = Timeout;
88
- function sleep(milliseconds) {
89
- return new Promise((resolve) => {
90
- setTimeout(resolve, milliseconds);
91
- });
92
- }
@@ -1,11 +0,0 @@
1
- export declare function normalize(object: {
2
- [key: string]: any;
3
- }): Readonly<{
4
- [key: string]: any;
5
- }>;
6
- export declare function guildIdToShardId(guildId: string, shardCount?: number): number;
7
- export type URIEncodeWrapFunc = (...args: Array<any>) => string;
8
- export type URIEncodeWrapped = {
9
- [key: string]: any;
10
- };
11
- export declare function URIEncodeWrap(unsafe: URIEncodeWrapped): URIEncodeWrapped;
package/lib/src/tools.js DELETED
@@ -1,41 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.normalize = normalize;
4
- exports.guildIdToShardId = guildIdToShardId;
5
- exports.URIEncodeWrap = URIEncodeWrap;
6
- function normalize(object) {
7
- for (const key in object) {
8
- object[key] = key;
9
- }
10
- return Object.freeze(object);
11
- }
12
- function guildIdToShardId(guildId, shardCount = 0) {
13
- return Math.round(+(guildId) / (1 << 22)) % shardCount;
14
- }
15
- const safeCharacter = '@';
16
- function URIEncodeWrap(unsafe) {
17
- const safe = {};
18
- for (let key in unsafe) {
19
- const path = unsafe[key];
20
- if (typeof (path) !== 'function') {
21
- safe[key] = path;
22
- continue;
23
- }
24
- safe[key] = ((...args) => {
25
- args = args.map((arg) => {
26
- if (!arg) {
27
- return arg;
28
- }
29
- const value = String(arg);
30
- if (!value.includes(safeCharacter)) {
31
- return encodeURIComponent(value);
32
- }
33
- return value.split('').map((char) => {
34
- return (char === safeCharacter) ? char : encodeURIComponent(char);
35
- }).join('');
36
- });
37
- return path(...args);
38
- });
39
- }
40
- return Object.freeze(safe);
41
- }