detritus-utils 0.5.0-beta.5 → 0.5.0-beta.7

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.
@@ -26,23 +26,37 @@ export interface BaseCollectionOptions {
26
26
  expire?: number;
27
27
  intervalTime?: number;
28
28
  limit?: number;
29
+ /**
30
+ * Don't let the expiry interval keep the process alive
31
+ */
32
+ unref?: boolean;
29
33
  }
30
34
  export declare class BaseCollection<K, V> extends BaseCollectionMixin<K, V> {
31
35
  readonly cache: Map<K, V>;
32
36
  _lastUsed?: Map<K, number>;
33
37
  _order?: Map<K, true>;
34
- expire?: number;
38
+ _intervalTime: number;
39
+ readonly expire?: number;
35
40
  interval?: Timers.Interval;
36
- intervalTime: number;
41
+ readonly intervalTime: number;
37
42
  limit: number;
38
- constructor({ expire, intervalTime, limit }?: BaseCollectionOptions);
43
+ constructor({ expire, intervalTime, limit, unref }?: BaseCollectionOptions);
39
44
  get lastUsed(): Map<K, number>;
45
+ _hasExpired(key: K): boolean;
40
46
  touch(key: K): void;
41
47
  get shouldStartInterval(): boolean;
48
+ /**
49
+ * If the expiry interval is running, only while items expire and the collection isn't empty
50
+ */
51
+ get isSweeping(): boolean;
42
52
  setExpire(value: number): this;
43
53
  setLimit(value: number): this;
44
54
  setIntervalTimeout(value: number): this;
45
55
  startInterval(): void;
56
+ /**
57
+ * Deletes every expired item now, returns how many were deleted
58
+ */
59
+ sweep(): number;
46
60
  stopInterval(): void;
47
61
  get size(): number;
48
62
  clear(): void;
@@ -61,7 +75,7 @@ export declare class BaseCollection<K, V> extends BaseCollectionMixin<K, V> {
61
75
  evict(room?: number): void;
62
76
  /**
63
77
  * The recency order (least recently used first), synced with the cache
64
- * keys added before `limit` was set (or while it was `Infinity`) aren't tracked yet, so they count as the least recently used
78
+ * untracked keys (added while `limit` was `Infinity`) count as the least recently used
65
79
  */
66
80
  getOrder(): Map<K, true>;
67
81
  values(): IterableIterator<V>;
@@ -90,8 +90,17 @@ class BaseCollectionMixin {
90
90
  return map;
91
91
  }
92
92
  reduce(func, initialValue) {
93
+ const values = this.values();
93
94
  let reduced = initialValue;
94
- for (let [key, value] of this) {
95
+ // like `Array.prototype.reduce`, no initial value starts from the first item
96
+ if (arguments.length < 2) {
97
+ const first = values.next();
98
+ if (first.done) {
99
+ throw new TypeError('Reduce of empty collection with no initial value');
100
+ }
101
+ reduced = first.value;
102
+ }
103
+ for (let value of values) {
95
104
  reduced = func(reduced, value);
96
105
  }
97
106
  return reduced;
@@ -127,28 +136,39 @@ class BaseCollectionMixin {
127
136
  }
128
137
  }
129
138
  exports.BaseCollectionMixin = BaseCollectionMixin;
139
+ // a `NaN` limit would evict everything on each insert
140
+ function normalizeLimit(value) {
141
+ return (value === undefined || value === null || Number.isNaN(value)) ? Infinity : value;
142
+ }
130
143
  class BaseCollection extends BaseCollectionMixin {
131
144
  cache = new Map();
132
145
  _lastUsed;
146
+ // read only, use `setExpire()` and `setIntervalTimeout()` to change them
133
147
  expire;
134
148
  interval = undefined;
135
149
  intervalTime = 5000;
136
150
  limit = Infinity;
137
- constructor({ expire, intervalTime, limit } = {}) {
151
+ constructor({ expire, intervalTime, limit, unref } = {}) {
138
152
  super();
153
+ if (unref) {
154
+ this.interval = new Timers.Interval();
155
+ this.interval.unref();
156
+ }
139
157
  if (expire !== undefined) {
140
158
  this.expire = expire;
141
159
  }
142
160
  if (intervalTime !== undefined) {
143
161
  this.intervalTime = intervalTime;
144
162
  }
163
+ this._intervalTime = this.intervalTime;
145
164
  if (limit !== undefined) {
146
- this.limit = limit;
165
+ this.limit = normalizeLimit(limit);
147
166
  }
148
167
  if (this.expire) {
149
168
  this.intervalTime = Math.min(this.expire, this.intervalTime);
150
169
  }
151
170
  Object.defineProperties(this, {
171
+ _intervalTime: { enumerable: false, writable: true },
152
172
  _lastUsed: { enumerable: false, writable: true },
153
173
  _order: { enumerable: false, writable: true },
154
174
  cache: { enumerable: false },
@@ -167,19 +187,37 @@ class BaseCollection extends BaseCollectionMixin {
167
187
  }
168
188
  return new Map();
169
189
  }
190
+ _hasExpired(key) {
191
+ if (this.expire && this._lastUsed) {
192
+ const lastUsed = this._lastUsed.get(key);
193
+ return lastUsed !== undefined && this.expire < Date.now() - lastUsed;
194
+ }
195
+ return false;
196
+ }
170
197
  touch(key) {
198
+ if (!this.cache.has(key)) {
199
+ // a timestamp for a missing key would later be swept for nothing
200
+ return;
201
+ }
171
202
  const lastUsed = this.lastUsed;
172
203
  lastUsed.delete(key);
173
204
  lastUsed.set(key, Date.now());
174
205
  }
175
206
  get shouldStartInterval() {
176
- return !!this.intervalTime && (!this.interval || !this.interval.hasStarted);
207
+ return !!this.expire && !!this.intervalTime && (!this.interval || !this.interval.hasStarted);
208
+ }
209
+ /**
210
+ * If the expiry interval is running, only while items expire and the collection isn't empty
211
+ */
212
+ get isSweeping() {
213
+ return !!this.interval && this.interval.hasStarted;
177
214
  }
178
215
  setExpire(value) {
179
216
  const wasExpiring = !!this.expire;
180
217
  Object.defineProperty(this, 'expire', { value });
181
218
  if (value) {
182
- Object.defineProperty(this, 'intervalTime', { value: Math.min(value, this.intervalTime) });
219
+ // from the asked for interval, so raising `expire` again doesn't keep a smaller cap
220
+ Object.defineProperty(this, 'intervalTime', { value: Math.min(value, this._intervalTime) });
183
221
  const now = Date.now();
184
222
  const lastUsed = this.lastUsed;
185
223
  for (let key of this.cache.keys()) {
@@ -192,6 +230,7 @@ class BaseCollection extends BaseCollectionMixin {
192
230
  }
193
231
  }
194
232
  else {
233
+ Object.defineProperty(this, 'intervalTime', { value: this._intervalTime });
195
234
  this.stopInterval();
196
235
  if (this._lastUsed) {
197
236
  this._lastUsed.clear();
@@ -200,12 +239,14 @@ class BaseCollection extends BaseCollectionMixin {
200
239
  return this;
201
240
  }
202
241
  setLimit(value) {
203
- this.limit = value;
242
+ this.limit = normalizeLimit(value);
204
243
  this.evict(0);
205
244
  return this;
206
245
  }
207
246
  setIntervalTimeout(value) {
208
- Object.defineProperty(this, 'intervalTime', { value });
247
+ this._intervalTime = value;
248
+ // capped to `expire`, so expired items linger at most another `expire`
249
+ Object.defineProperty(this, 'intervalTime', { value: (this.expire) ? Math.min(this.expire, value) : value });
209
250
  if (value) {
210
251
  if (this.size) {
211
252
  this.startInterval();
@@ -222,15 +263,8 @@ class BaseCollection extends BaseCollectionMixin {
222
263
  this.interval = new Timers.Interval();
223
264
  }
224
265
  this.interval.start(this.intervalTime, () => {
225
- const expire = this.expire;
226
- if (expire) {
227
- const now = Date.now();
228
- for (let [key, lastUsed] of this.lastUsed) {
229
- if (now - lastUsed <= expire) {
230
- break;
231
- }
232
- this.delete(key);
233
- }
266
+ if (this.expire) {
267
+ this.sweep();
234
268
  }
235
269
  else {
236
270
  this.stopInterval();
@@ -241,11 +275,30 @@ class BaseCollection extends BaseCollectionMixin {
241
275
  this.stopInterval();
242
276
  }
243
277
  }
278
+ /**
279
+ * Deletes every expired item now, returns how many were deleted
280
+ */
281
+ sweep() {
282
+ const expire = this.expire;
283
+ let deleted = 0;
284
+ if (expire && this._lastUsed) {
285
+ const now = Date.now();
286
+ // oldest first, so everything after the first fresh item is fresh too
287
+ for (let [key, lastUsed] of this._lastUsed) {
288
+ if (now - lastUsed <= expire) {
289
+ break;
290
+ }
291
+ this.delete(key);
292
+ deleted++;
293
+ }
294
+ }
295
+ return deleted;
296
+ }
244
297
  stopInterval() {
298
+ // keep the object around so an `unref()` still applies on the next start
245
299
  if (this.interval) {
246
300
  this.interval.stop();
247
301
  }
248
- this.interval = undefined;
249
302
  }
250
303
  get size() {
251
304
  return this.cache.size;
@@ -261,12 +314,22 @@ class BaseCollection extends BaseCollectionMixin {
261
314
  }
262
315
  }
263
316
  clone() {
264
- const collection = new BaseCollection(this);
317
+ // the asked for interval, not the one capped to `expire`
318
+ const collection = new BaseCollection({
319
+ expire: this.expire,
320
+ intervalTime: this._intervalTime,
321
+ limit: this.limit,
322
+ unref: !!this.interval && !this.interval.hasRef(),
323
+ });
265
324
  // insert least recently used first so the clone keeps the same eviction order
266
325
  const keys = (this.limit !== Infinity) ? this.getOrder().keys() : this.cache.keys();
267
326
  for (let key of keys) {
268
327
  collection.set(key, this.cache.get(key));
269
328
  }
329
+ if (collection.expire && this._lastUsed) {
330
+ // `set` stamped every item as just used, keep their real ages (the map is already oldest first)
331
+ collection._lastUsed = new Map(this._lastUsed);
332
+ }
270
333
  return collection;
271
334
  }
272
335
  delete(key) {
@@ -288,8 +351,12 @@ class BaseCollection extends BaseCollectionMixin {
288
351
  get(key) {
289
352
  const value = this.cache.get(key);
290
353
  if ((this.limit !== Infinity || this.expire) && (value !== undefined || this.cache.has(key))) {
354
+ if (this._hasExpired(key)) {
355
+ // expired but not swept yet
356
+ this.delete(key);
357
+ return undefined;
358
+ }
291
359
  if (this.limit !== Infinity) {
292
- // mark it as the most recently used
293
360
  const order = this.getOrder();
294
361
  order.delete(key);
295
362
  order.set(key, true);
@@ -301,21 +368,27 @@ class BaseCollection extends BaseCollectionMixin {
301
368
  return value;
302
369
  }
303
370
  getOrInsert(key, defaultValue) {
304
- if (this.has(key)) {
305
- return this.get(key);
371
+ const value = this.get(key);
372
+ if (value !== undefined || this.cache.has(key)) {
373
+ return value;
306
374
  }
307
375
  this.set(key, defaultValue);
308
376
  return defaultValue;
309
377
  }
310
378
  getOrInsertComputed(key, func) {
311
- if (this.has(key)) {
312
- return this.get(key);
379
+ const value = this.get(key);
380
+ if (value !== undefined || this.cache.has(key)) {
381
+ return value;
313
382
  }
314
- const value = func(key);
315
- this.set(key, value);
316
- return value;
383
+ const computed = func(key);
384
+ this.set(key, computed);
385
+ return computed;
317
386
  }
318
387
  has(key) {
388
+ if (this._hasExpired(key)) {
389
+ this.delete(key);
390
+ return false;
391
+ }
319
392
  return this.cache.has(key);
320
393
  }
321
394
  keys() {
@@ -332,7 +405,6 @@ class BaseCollection extends BaseCollectionMixin {
332
405
  order.delete(key);
333
406
  }
334
407
  else {
335
- // make room for the new key, evicting the least recently used ones
336
408
  this.evict(1);
337
409
  }
338
410
  order.set(key, true);
@@ -367,7 +439,7 @@ class BaseCollection extends BaseCollectionMixin {
367
439
  }
368
440
  /**
369
441
  * The recency order (least recently used first), synced with the cache
370
- * keys added before `limit` was set (or while it was `Infinity`) aren't tracked yet, so they count as the least recently used
442
+ * untracked keys (added while `limit` was `Infinity`) count as the least recently used
371
443
  */
372
444
  getOrder() {
373
445
  let order = this._order;
package/lib/baseset.d.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  export declare class BaseSet<V> extends Set<V> {
2
2
  get length(): number;
3
3
  clone(): BaseSet<V>;
4
- every(func: any): boolean;
4
+ every(func: (v: V) => boolean): boolean;
5
5
  filter(func: (v: V) => boolean): Array<V>;
6
6
  find(func: (v: V) => boolean): undefined | V;
7
7
  first(): undefined | V;
8
8
  join(separator?: string): string;
9
9
  map(func: (v: V) => any): Array<any>;
10
- reduce(cb: any, initialValue?: any): any;
10
+ reduce(cb: (accumulator: any, v: V) => any, initialValue?: any): any;
11
11
  some(func: (v: V) => boolean): boolean;
12
12
  sort(func?: (x: V, y: V) => number): Array<V>;
13
13
  toArray(): Array<V>;
package/lib/baseset.js CHANGED
@@ -9,7 +9,12 @@ class BaseSet extends Set {
9
9
  return new BaseSet(this.values());
10
10
  }
11
11
  every(func) {
12
- return this.toArray().every(func);
12
+ for (let value of this) {
13
+ if (!func(value)) {
14
+ return false;
15
+ }
16
+ }
17
+ return true;
13
18
  }
14
19
  filter(func) {
15
20
  const map = [];
@@ -41,7 +46,20 @@ class BaseSet extends Set {
41
46
  return map;
42
47
  }
43
48
  reduce(cb, initialValue) {
44
- return this.toArray().reduce(cb, initialValue);
49
+ const values = this.values();
50
+ let reduced = initialValue;
51
+ // like `Array.prototype.reduce`, no initial value starts from the first item
52
+ if (arguments.length < 2) {
53
+ const first = values.next();
54
+ if (first.done) {
55
+ throw new TypeError('Reduce of empty set with no initial value');
56
+ }
57
+ reduced = first.value;
58
+ }
59
+ for (let value of values) {
60
+ reduced = cb(reduced, value);
61
+ }
62
+ return reduced;
45
63
  }
46
64
  some(func) {
47
65
  for (let value of this) {
@@ -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.5";
3
+ VERSION: string;
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
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DISCORD_TOKEN_EPOCH = exports.DISCORD_SNOWFLAKE_EPOCH = exports.Package = void 0;
4
+ // `require` so tsc doesn't pull it (outside rootDir) into the build
5
+ const { version } = require('../package.json');
4
6
  exports.Package = Object.freeze({
5
7
  URL: 'https://github.com/detritusjs/utils',
6
- VERSION: '0.5.0-beta.5',
8
+ VERSION: version,
7
9
  });
8
10
  exports.DISCORD_SNOWFLAKE_EPOCH = 1420070400000;
9
11
  exports.DISCORD_TOKEN_EPOCH = 1293840000000;
@@ -24,6 +24,14 @@ export declare class EventSubscription {
24
24
  listener: ((...args: any[]) => void) | null;
25
25
  name: string | symbol;
26
26
  spewer: EventSpewer | null;
27
+ /**
28
+ * What's actually attached to the spewer, a function only this subscription owns
29
+ */
30
+ wrapped: ((...args: any[]) => void) | null;
27
31
  constructor(spewer: EventSpewer, name: string | symbol, listener: (...args: any[]) => void);
32
+ /**
33
+ * If it's still attached, `false` once removed (by `remove()`, `removeListener()` or `removeAllListeners()`)
34
+ */
35
+ get active(): boolean;
28
36
  remove(): void;
29
37
  }
@@ -21,7 +21,7 @@ class EventSpewer extends events_1.EventEmitter {
21
21
  }
22
22
  subscribe(name, listener) {
23
23
  const subscription = new EventSubscription(this, name, listener);
24
- this.on(name, listener);
24
+ this.on(name, subscription.wrapped);
25
25
  if (!this._subscriptions) {
26
26
  this._subscriptions = new Map();
27
27
  }
@@ -51,33 +51,25 @@ class EventSpewer extends events_1.EventEmitter {
51
51
  this._deleteSubscriptions(subscription.name, subscriptions);
52
52
  }
53
53
  }
54
- if (subscription.listener) {
55
- const { listener, name } = subscription;
56
- const count = () => this.listeners(name).filter((x) => x === listener).length;
57
- const before = count();
58
- super.removeListener.call(this, name, listener);
59
- for (let attached = count(); attached < before - 1; attached++) {
60
- super.on.call(this, name, listener);
61
- }
54
+ if (subscription.wrapped) {
55
+ // only this subscription attached the wrapper, so this can't remove another registration of the same function
56
+ super.removeListener.call(this, subscription.name, subscription.wrapped);
62
57
  }
63
58
  }
64
59
  removeListener(name, listener, ...args) {
65
60
  super.removeListener.call(this, name, listener, ...args);
66
61
  if (this._subscriptions) {
67
62
  const subscriptions = this._subscriptions.get(name);
68
- if (subscriptions && subscriptions.some((subscription) => subscription.listener === listener)) {
69
- let attached = this.listeners(name).filter((x) => x === listener).length;
63
+ // `listener` is a wrapper when node removes it, like in `removeAllListeners()`
64
+ if (subscriptions && subscriptions.some((subscription) => subscription.listener === listener || subscription.wrapped === listener)) {
65
+ const attached = new Set(this.rawListeners(name));
70
66
  for (let i = subscriptions.length - 1; 0 <= i; i--) {
71
67
  const subscription = subscriptions[i];
72
- if (subscription.listener === listener) {
73
- if (attached) {
74
- attached--;
75
- }
76
- else {
77
- subscriptions.splice(i, 1);
78
- subscription.listener = null;
79
- subscription.spewer = null;
80
- }
68
+ if (!attached.has(subscription.wrapped)) {
69
+ subscriptions.splice(i, 1);
70
+ subscription.listener = null;
71
+ subscription.spewer = null;
72
+ subscription.wrapped = null;
81
73
  }
82
74
  }
83
75
  this._deleteSubscriptions(name, subscriptions);
@@ -103,6 +95,7 @@ class EventSpewer extends events_1.EventEmitter {
103
95
  for (let subscription of subscriptions) {
104
96
  subscription.listener = null;
105
97
  subscription.spewer = null;
98
+ subscription.wrapped = null;
106
99
  }
107
100
  }
108
101
  this._subscriptions = undefined;
@@ -135,10 +128,26 @@ class EventSubscription {
135
128
  listener;
136
129
  name;
137
130
  spewer;
131
+ /**
132
+ * What's actually attached to the spewer, a function only this subscription owns
133
+ */
134
+ wrapped;
138
135
  constructor(spewer, name, listener) {
139
136
  this.name = name;
140
137
  this.listener = listener;
141
138
  this.spewer = spewer;
139
+ const wrapped = function (...args) {
140
+ return listener.apply(this, args);
141
+ };
142
+ // like node's `once()`, so `listeners()` and `removeListener(name, listener)` still see the original function
143
+ wrapped.listener = listener;
144
+ this.wrapped = wrapped;
145
+ }
146
+ /**
147
+ * If it's still attached, `false` once removed (by `remove()`, `removeListener()` or `removeAllListeners()`)
148
+ */
149
+ get active() {
150
+ return this.spewer !== null;
142
151
  }
143
152
  remove() {
144
153
  if (this.spewer) {
@@ -146,6 +155,7 @@ class EventSubscription {
146
155
  }
147
156
  this.listener = null;
148
157
  this.spewer = null;
158
+ this.wrapped = null;
149
159
  }
150
160
  }
151
161
  exports.EventSubscription = EventSubscription;
@@ -12,6 +12,11 @@ export interface SnowflakeGenerateOptions {
12
12
  timestamp?: number;
13
13
  workerId?: number;
14
14
  }
15
+ /**
16
+ * Ids made without `timestamp` and `sequence` are unique within this process (for the same `workerId` and `processId`), whatever other calls passed
17
+ * An explicit `timestamp` before the clock's last used millisecond (or past the real clock) can collide with ids made in it
18
+ * Out of range `workerId`s and `processId`s are masked to 5 bits
19
+ */
15
20
  export declare function generate(options?: SnowflakeGenerateOptions): Snowflake;
16
21
  export interface SnowflakeDeconstructOptions {
17
22
  epoch?: number;
package/lib/snowflake.js CHANGED
@@ -22,30 +22,73 @@ const max = Object.freeze({
22
22
  sequence: -1n ^ (-1n << bits.sequence),
23
23
  workerId: -1n ^ (-1n << bits.workerId),
24
24
  });
25
- const cache = {
26
- sequence: 0n,
27
- };
25
+ // ids made from `Date.now()`, this one only ever moves forward
26
+ const clock = { start: -1n, sequence: 0n, timestamp: -1n };
27
+ // ids made from a passed in `timestamp`, kept apart so they can't rewind the clock's
28
+ const manual = { start: -1n, sequence: 0n, timestamp: -1n };
29
+ function nextSequence(state, now, isClock) {
30
+ if (now < state.timestamp && (isClock || state.start <= now)) {
31
+ // the clock went backwards, or `now` is inside a run that borrowed ahead, keep counting from the last one
32
+ now = state.timestamp;
33
+ }
34
+ let sequence = 0n;
35
+ if (now === state.timestamp) {
36
+ sequence = (state.sequence + 1n) & max.sequence;
37
+ if (!sequence) {
38
+ // every sequence in this millisecond is used, borrow the next one
39
+ now++;
40
+ }
41
+ }
42
+ else {
43
+ state.start = now;
44
+ }
45
+ state.sequence = sequence;
46
+ state.timestamp = now;
47
+ return [now, sequence];
48
+ }
28
49
  const DEFAULT_EPOCH = BigInt(constants_1.DISCORD_SNOWFLAKE_EPOCH);
50
+ const MAX_ID = 1n << 64n;
29
51
  function getEpoch(epoch) {
30
52
  return (epoch === undefined || epoch === null) ? DEFAULT_EPOCH : BigInt(epoch);
31
53
  }
54
+ function parseId(id) {
55
+ const snowflake = BigInt(id);
56
+ if (snowflake < 0n || MAX_ID <= snowflake) {
57
+ throw new RangeError(`Snowflake ${id} is not an unsigned 64 bit integer`);
58
+ }
59
+ return snowflake;
60
+ }
61
+ /**
62
+ * Ids made without `timestamp` and `sequence` are unique within this process (for the same `workerId` and `processId`), whatever other calls passed
63
+ * An explicit `timestamp` before the clock's last used millisecond (or past the real clock) can collide with ids made in it
64
+ * Out of range `workerId`s and `processId`s are masked to 5 bits
65
+ */
32
66
  function generate(options = {}) {
33
67
  const epoch = getEpoch(options.epoch);
34
68
  const processId = BigInt(options.processId ?? 0) & max.processId;
35
- const now = options.timestamp ?? Date.now();
36
- const elapsed = BigInt(now) - epoch;
37
- if (elapsed < 0n) {
69
+ let now = BigInt(options.timestamp ?? Date.now());
70
+ if (now < epoch) {
38
71
  throw new RangeError(`Timestamp ${now} is before the epoch ${epoch}`);
39
72
  }
40
- const timestamp = elapsed % max.timestamp;
41
73
  const workerId = BigInt(options.workerId ?? 0) & max.workerId;
42
74
  let sequence;
43
75
  if (options.sequence === undefined || options.sequence === null) {
44
- sequence = cache.sequence = ++cache.sequence & max.sequence;
76
+ if (options.timestamp === undefined || options.timestamp === null) {
77
+ [now, sequence] = nextSequence(clock, now, true);
78
+ }
79
+ else if (clock.start <= now && (now <= clock.timestamp || now <= BigInt(Date.now()))) {
80
+ // a millisecond the clock already made ids in (or is about to), keep counting there so they can't collide
81
+ // past the real clock stays apart, or every later id would be dated in the future
82
+ [now, sequence] = nextSequence(clock, now, false);
83
+ }
84
+ else {
85
+ [now, sequence] = nextSequence(manual, now, false);
86
+ }
45
87
  }
46
88
  else {
47
89
  sequence = BigInt(options.sequence) & max.sequence;
48
90
  }
91
+ const timestamp = (now - epoch) % max.timestamp;
49
92
  const snowflake = {
50
93
  id: '',
51
94
  processId: Number(processId),
@@ -60,8 +103,12 @@ function generate(options = {}) {
60
103
  return snowflake;
61
104
  }
62
105
  function deconstruct(id, options = {}) {
106
+ if (!id) {
107
+ // like `timestamp()`, an empty id is 0 instead of the epoch
108
+ return { id, processId: 0, sequence: 0, timestamp: 0, workerId: 0 };
109
+ }
63
110
  const epoch = getEpoch(options.epoch);
64
- const snowflake = BigInt(id);
111
+ const snowflake = parseId(id);
65
112
  return {
66
113
  id,
67
114
  processId: Number((snowflake & 0x1f000n) >> shift.processId),
@@ -73,7 +120,7 @@ function deconstruct(id, options = {}) {
73
120
  function timestamp(id, options = {}) {
74
121
  if (id) {
75
122
  const epoch = getEpoch(options.epoch);
76
- return Number((BigInt(id) >> shift.timestamp) + epoch);
123
+ return Number((parseId(id) >> shift.timestamp) + epoch);
77
124
  }
78
125
  return 0;
79
126
  }
package/lib/timers.d.ts CHANGED
@@ -6,7 +6,10 @@ export declare class Interval {
6
6
  ref(): void;
7
7
  unref(): void;
8
8
  start(milliseconds: number, handler: Function): void;
9
- stop(): void;
9
+ /**
10
+ * Returns if it was running
11
+ */
12
+ stop(): boolean;
10
13
  }
11
14
  export declare class Timeout {
12
15
  shouldRef: boolean;
@@ -15,7 +18,14 @@ export declare class Timeout {
15
18
  hasRef(): boolean;
16
19
  ref(): void;
17
20
  unref(): void;
18
- start(milliseconds: number, handler: Function, override?: boolean): void;
19
- stop(): void;
21
+ /**
22
+ * Returns if it was scheduled, `false` when it's already running and `override` is `false`
23
+ * `hasStarted` is `false` again by the time `handler` runs, so the handler can start it again
24
+ */
25
+ start(milliseconds: number, handler: Function, override?: boolean): boolean;
26
+ /**
27
+ * Returns if it was running
28
+ */
29
+ stop(): boolean;
20
30
  }
21
31
  export declare function sleep(milliseconds: number): Promise<void>;
package/lib/timers.js CHANGED
@@ -24,8 +24,10 @@ class Interval {
24
24
  }
25
25
  }
26
26
  start(milliseconds, handler) {
27
+ // schedule first, so a bad handler throws before the running interval is stopped
28
+ const reference = setInterval(handler, milliseconds);
27
29
  this.stop();
28
- this.reference = setInterval(handler, milliseconds);
30
+ this.reference = reference;
29
31
  if (this.shouldRef) {
30
32
  this.ref();
31
33
  }
@@ -33,11 +35,16 @@ class Interval {
33
35
  this.unref();
34
36
  }
35
37
  }
38
+ /**
39
+ * Returns if it was running
40
+ */
36
41
  stop() {
37
42
  if (this.hasStarted) {
38
43
  clearInterval(this.reference);
39
44
  this.reference = null;
45
+ return true;
40
46
  }
47
+ return false;
41
48
  }
42
49
  }
43
50
  exports.Interval = Interval;
@@ -62,26 +69,41 @@ class Timeout {
62
69
  this.reference.unref();
63
70
  }
64
71
  }
72
+ /**
73
+ * Returns if it was scheduled, `false` when it's already running and `override` is `false`
74
+ * `hasStarted` is `false` again by the time `handler` runs, so the handler can start it again
75
+ */
65
76
  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
- }
77
+ if (this.hasStarted && !override) {
78
+ return false;
78
79
  }
80
+ if (typeof (handler) !== 'function') {
81
+ // like `setTimeout()` would, instead of throwing later from inside the timer
82
+ throw new TypeError(`The "handler" argument must be of type function. Received ${typeof (handler)}`);
83
+ }
84
+ this.stop();
85
+ this.reference = setTimeout(() => {
86
+ this.reference = null;
87
+ handler();
88
+ }, milliseconds);
89
+ if (this.shouldRef) {
90
+ this.ref();
91
+ }
92
+ else {
93
+ this.unref();
94
+ }
95
+ return true;
79
96
  }
97
+ /**
98
+ * Returns if it was running
99
+ */
80
100
  stop() {
81
101
  if (this.hasStarted) {
82
102
  clearTimeout(this.reference);
83
103
  this.reference = null;
104
+ return true;
84
105
  }
106
+ return false;
85
107
  }
86
108
  }
87
109
  exports.Timeout = Timeout;
package/lib/tools.d.ts CHANGED
@@ -8,4 +8,16 @@ export type URIEncodeWrapFunc = (...args: Array<any>) => string;
8
8
  export type URIEncodeWrapped = {
9
9
  [key: string]: any;
10
10
  };
11
- export declare function URIEncodeWrap(unsafe: URIEncodeWrapped): URIEncodeWrapped;
11
+ /**
12
+ * What a wrapped function actually gets for an argument: truthy ones are stringified and encoded, falsy ones pass through
13
+ */
14
+ export type URIEncodedArgument<T> = string | Extract<T, '' | 0 | 0n | false | null | undefined>;
15
+ /**
16
+ * Parameters must accept strings, so a `number` or `bigint` one is a type error instead of `id + 1n` silently concatenating
17
+ */
18
+ export type URIEncodeWrapSafe<T> = {
19
+ [K in keyof T]: T[K] extends (...args: infer A) => any ? (...args: {
20
+ [I in keyof A]: URIEncodedArgument<A[I]>;
21
+ }) => any : T[K];
22
+ };
23
+ export declare function URIEncodeWrap<T extends URIEncodeWrapSafe<T>>(unsafe: T): Readonly<T>;
package/lib/tools.js CHANGED
@@ -10,7 +10,8 @@ function normalize(object) {
10
10
  return Object.freeze(object);
11
11
  }
12
12
  function guildIdToShardId(guildId, shardCount = 0) {
13
- if (shardCount < 1) {
13
+ // `BigInt()` throws on a fractional or `NaN` count
14
+ if (!Number.isInteger(shardCount) || shardCount < 1) {
14
15
  return 0;
15
16
  }
16
17
  let id;
@@ -20,9 +21,17 @@ function guildIdToShardId(guildId, shardCount = 0) {
20
21
  catch (e) {
21
22
  return NaN;
22
23
  }
24
+ // bigint `%` keeps the sign, a negative id would give a negative shard
25
+ if (id < 0n) {
26
+ return NaN;
27
+ }
23
28
  return Number((id >> 22n) % BigInt(shardCount));
24
29
  }
30
+ // `encodeURIComponent` leaves `.` alone, so a `.` or `..` argument would climb out of the url
31
+ // `%2E` is a dot to the url parser too, so the percent itself is encoded
32
+ const DotSegmentRegex = /^\.{1,2}$/;
25
33
  const safeCharacter = '@';
34
+ // generic so the wrapped route builders keep their signatures
26
35
  function URIEncodeWrap(unsafe) {
27
36
  const safe = {};
28
37
  for (let key in unsafe) {
@@ -35,8 +44,13 @@ function URIEncodeWrap(unsafe) {
35
44
  for (let i = 0; i < args.length; i++) {
36
45
  const arg = args[i];
37
46
  if (arg) {
38
- const value = String(arg);
39
- args[i] = (value.includes(safeCharacter)) ? value.split(safeCharacter).map(encodeURIComponent).join(safeCharacter) : encodeURIComponent(value);
47
+ // a lone surrogate would make `encodeURIComponent` throw
48
+ const value = String(arg).toWellFormed();
49
+ let encoded = (value.includes(safeCharacter)) ? value.split(safeCharacter).map(encodeURIComponent).join(safeCharacter) : encodeURIComponent(value);
50
+ if (DotSegmentRegex.test(encoded)) {
51
+ encoded = encoded.replace(/\./g, '%252E');
52
+ }
53
+ args[i] = encoded;
40
54
  }
41
55
  }
42
56
  return path(...args);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "detritus-utils",
3
- "version": "0.5.0-beta.5",
3
+ "version": "0.5.0-beta.7",
4
4
  "description": "Detritus Utils",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "homepage": "https://github.com/detritusjs/utils#readme",
32
32
  "devDependencies": {
33
- "@types/node": "^26.6.5",
33
+ "@types/node": "^26.6.6",
34
34
  "typescript": "^7.0.2"
35
35
  }
36
36
  }