@sapphire/ratelimits 2.1.12-next.ba37bca.0 → 2.2.0-next.53d1f86.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.
@@ -0,0 +1,1055 @@
1
+ var SapphireRatelimits = (() => {
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __reExport = (target, module, copyDefault, desc) => {
14
+ if (module && typeof module === "object" || typeof module === "function") {
15
+ for (let key of __getOwnPropNames(module))
16
+ if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
17
+ __defProp(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable });
18
+ }
19
+ return target;
20
+ };
21
+ var __toCommonJS = /* @__PURE__ */ ((cache) => {
22
+ return (module, temp) => {
23
+ return cache && cache.get(module) || (temp = __reExport(__markAsModule({}), module, 1), cache && cache.set(module, temp), temp);
24
+ };
25
+ })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
26
+ var __publicField = (obj, key, value) => {
27
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+ return value;
29
+ };
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ RateLimit: () => RateLimit,
35
+ RateLimitManager: () => RateLimitManager
36
+ });
37
+
38
+ // src/lib/RateLimit.ts
39
+ var RateLimit = class {
40
+ constructor(manager) {
41
+ __publicField(this, "remaining");
42
+ __publicField(this, "expires");
43
+ __publicField(this, "manager");
44
+ this.manager = manager;
45
+ this.reset();
46
+ }
47
+ get expired() {
48
+ return this.remainingTime === 0;
49
+ }
50
+ get limited() {
51
+ return this.remaining === 0 && !this.expired;
52
+ }
53
+ get remainingTime() {
54
+ return Math.max(this.expires - Date.now(), 0);
55
+ }
56
+ consume() {
57
+ if (this.limited)
58
+ throw new Error("Cannot consume a limited bucket");
59
+ if (this.expired)
60
+ this.reset();
61
+ this.remaining--;
62
+ return this;
63
+ }
64
+ reset() {
65
+ return this.resetRemaining().resetTime();
66
+ }
67
+ resetRemaining() {
68
+ this.remaining = this.manager.limit;
69
+ return this;
70
+ }
71
+ resetTime() {
72
+ this.expires = Date.now() + this.manager.time;
73
+ return this;
74
+ }
75
+ };
76
+ __name(RateLimit, "RateLimit");
77
+
78
+ // ../utilities/dist/index.mjs
79
+ var __defProp2 = Object.defineProperty;
80
+ var __name2 = /* @__PURE__ */ __name((target, value) => __defProp2(target, "name", { value, configurable: true }), "__name");
81
+ function arrayStrictEquals(arr1, arr2) {
82
+ if (arr1 === arr2)
83
+ return true;
84
+ if (arr1.length !== arr2.length)
85
+ return false;
86
+ for (let i = 0; i < arr1.length; i++) {
87
+ if (arr1[i] !== arr2[i] || typeof arr1[i] !== typeof arr2[i])
88
+ return false;
89
+ }
90
+ return true;
91
+ }
92
+ __name(arrayStrictEquals, "arrayStrictEquals");
93
+ __name2(arrayStrictEquals, "arrayStrictEquals");
94
+ function chunk(array, chunkSize) {
95
+ if (!Array.isArray(array))
96
+ throw new TypeError("entries must be an array.");
97
+ if (!Number.isInteger(chunkSize))
98
+ throw new TypeError("chunkSize must be an integer.");
99
+ if (chunkSize < 1)
100
+ throw new RangeError("chunkSize must be 1 or greater.");
101
+ const clone = array.slice();
102
+ const chunks = [];
103
+ while (clone.length)
104
+ chunks.push(clone.splice(0, chunkSize));
105
+ return chunks;
106
+ }
107
+ __name(chunk, "chunk");
108
+ __name2(chunk, "chunk");
109
+ function classExtends(value, base) {
110
+ let ctor = value;
111
+ while (ctor !== null) {
112
+ if (ctor === base)
113
+ return true;
114
+ ctor = Object.getPrototypeOf(ctor);
115
+ }
116
+ return false;
117
+ }
118
+ __name(classExtends, "classExtends");
119
+ __name2(classExtends, "classExtends");
120
+ var zws = String.fromCharCode(8203);
121
+ function codeBlock(language, expression) {
122
+ if (typeof expression === "string") {
123
+ if (expression.length === 0)
124
+ return `\`\`\`${zws}\`\`\``;
125
+ return `\`\`\`${language}
126
+ ${expression.replace(/```/, `\`${zws}\`\``).replace(/`$/g, `\`${zws}`)}\`\`\``;
127
+ }
128
+ return `\`\`\`${language}
129
+ ${expression || zws}\`\`\``;
130
+ }
131
+ __name(codeBlock, "codeBlock");
132
+ __name2(codeBlock, "codeBlock");
133
+ function splitText(str, length, char = " ") {
134
+ const x = str.substring(0, length).lastIndexOf(char);
135
+ const pos = x === -1 ? length : x;
136
+ return str.substring(0, pos);
137
+ }
138
+ __name(splitText, "splitText");
139
+ __name2(splitText, "splitText");
140
+ function cutText(str, length) {
141
+ if (str.length < length)
142
+ return str;
143
+ const cut = splitText(str, length - 3);
144
+ if (cut.length < length - 3)
145
+ return `${cut}...`;
146
+ return `${cut.slice(0, length - 3)}...`;
147
+ }
148
+ __name(cutText, "cutText");
149
+ __name2(cutText, "cutText");
150
+ function debounce(func, options = {}) {
151
+ var _a;
152
+ let lastArgs;
153
+ let result;
154
+ let timerId;
155
+ let lastCallTime;
156
+ let lastInvokeTime = 0;
157
+ const wait = (_a = options.wait) != null ? _a : 0;
158
+ const maxWait = typeof options.maxWait === "number" ? Math.max(options.maxWait, wait) : null;
159
+ function invokeFunc(time) {
160
+ const args = lastArgs;
161
+ lastArgs = void 0;
162
+ lastInvokeTime = time;
163
+ result = func(...args);
164
+ return result;
165
+ }
166
+ __name(invokeFunc, "invokeFunc");
167
+ __name2(invokeFunc, "invokeFunc");
168
+ function leadingEdge(time) {
169
+ lastInvokeTime = time;
170
+ timerId = setTimeout(timerExpired, wait);
171
+ return result;
172
+ }
173
+ __name(leadingEdge, "leadingEdge");
174
+ __name2(leadingEdge, "leadingEdge");
175
+ function remainingWait(time) {
176
+ const timeSinceLastCall = time - lastCallTime;
177
+ const timeSinceLastInvoke = time - lastInvokeTime;
178
+ const result2 = wait - timeSinceLastCall;
179
+ return maxWait === null ? result2 : Math.min(result2, maxWait - timeSinceLastInvoke);
180
+ }
181
+ __name(remainingWait, "remainingWait");
182
+ __name2(remainingWait, "remainingWait");
183
+ function shouldInvoke(time) {
184
+ const timeSinceLastCall = time - lastCallTime;
185
+ const timeSinceLastInvoke = time - lastInvokeTime;
186
+ return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxWait !== null && timeSinceLastInvoke >= maxWait;
187
+ }
188
+ __name(shouldInvoke, "shouldInvoke");
189
+ __name2(shouldInvoke, "shouldInvoke");
190
+ function timerExpired() {
191
+ const time = Date.now();
192
+ if (shouldInvoke(time)) {
193
+ trailingEdge(time);
194
+ return;
195
+ }
196
+ timerId = setTimeout(timerExpired, remainingWait(time));
197
+ }
198
+ __name(timerExpired, "timerExpired");
199
+ __name2(timerExpired, "timerExpired");
200
+ function trailingEdge(time) {
201
+ timerId = void 0;
202
+ return invokeFunc(time);
203
+ }
204
+ __name(trailingEdge, "trailingEdge");
205
+ __name2(trailingEdge, "trailingEdge");
206
+ function cancel() {
207
+ if (timerId !== void 0) {
208
+ clearTimeout(timerId);
209
+ }
210
+ lastInvokeTime = 0;
211
+ lastArgs = void 0;
212
+ lastCallTime = void 0;
213
+ timerId = void 0;
214
+ }
215
+ __name(cancel, "cancel");
216
+ __name2(cancel, "cancel");
217
+ function flush() {
218
+ return timerId === void 0 ? result : trailingEdge(Date.now());
219
+ }
220
+ __name(flush, "flush");
221
+ __name2(flush, "flush");
222
+ function debounced(...args) {
223
+ const time = Date.now();
224
+ const isInvoking = shouldInvoke(time);
225
+ lastArgs = args;
226
+ lastCallTime = time;
227
+ if (isInvoking) {
228
+ if (timerId === void 0) {
229
+ return leadingEdge(lastCallTime);
230
+ }
231
+ if (maxWait !== null) {
232
+ timerId = setTimeout(timerExpired, wait);
233
+ return invokeFunc(lastCallTime);
234
+ }
235
+ }
236
+ if (timerId === void 0) {
237
+ timerId = setTimeout(timerExpired, wait);
238
+ }
239
+ return result;
240
+ }
241
+ __name(debounced, "debounced");
242
+ __name2(debounced, "debounced");
243
+ debounced.cancel = cancel;
244
+ debounced.flush = flush;
245
+ return debounced;
246
+ }
247
+ __name(debounce, "debounce");
248
+ __name2(debounce, "debounce");
249
+ var primitiveTypes = ["string", "bigint", "number", "boolean"];
250
+ function isPrimitive(input) {
251
+ return primitiveTypes.includes(typeof input);
252
+ }
253
+ __name(isPrimitive, "isPrimitive");
254
+ __name2(isPrimitive, "isPrimitive");
255
+ function deepClone(source) {
256
+ if (source === null || isPrimitive(source)) {
257
+ return source;
258
+ }
259
+ if (source instanceof Date) {
260
+ const output = new source.constructor(source);
261
+ return output;
262
+ }
263
+ if (Array.isArray(source)) {
264
+ const output = new source.constructor(source.length);
265
+ for (let i = 0; i < source.length; i++) {
266
+ output[i] = deepClone(source[i]);
267
+ }
268
+ return output;
269
+ }
270
+ if (source instanceof Map) {
271
+ const output = new source.constructor();
272
+ for (const [key, value] of source.entries()) {
273
+ output.set(key, deepClone(value));
274
+ }
275
+ return output;
276
+ }
277
+ if (source instanceof Set) {
278
+ const output = new source.constructor();
279
+ for (const value of source.values()) {
280
+ output.add(deepClone(value));
281
+ }
282
+ return output;
283
+ }
284
+ if (typeof source === "object") {
285
+ const output = new source.constructor();
286
+ for (const [key, value] of Object.entries(source)) {
287
+ Object.defineProperty(output, key, {
288
+ configurable: true,
289
+ enumerable: true,
290
+ value: deepClone(value),
291
+ writable: true
292
+ });
293
+ }
294
+ return output;
295
+ }
296
+ return source;
297
+ }
298
+ __name(deepClone, "deepClone");
299
+ __name2(deepClone, "deepClone");
300
+ function isNullOrUndefined(value) {
301
+ return value === void 0 || value === null;
302
+ }
303
+ __name(isNullOrUndefined, "isNullOrUndefined");
304
+ __name2(isNullOrUndefined, "isNullOrUndefined");
305
+ function filterNullAndUndefined(value) {
306
+ return !isNullOrUndefined(value);
307
+ }
308
+ __name(filterNullAndUndefined, "filterNullAndUndefined");
309
+ __name2(filterNullAndUndefined, "filterNullAndUndefined");
310
+ function isNullOrUndefinedOrEmpty(value) {
311
+ return isNullOrUndefined(value) || value.length === 0;
312
+ }
313
+ __name(isNullOrUndefinedOrEmpty, "isNullOrUndefinedOrEmpty");
314
+ __name2(isNullOrUndefinedOrEmpty, "isNullOrUndefinedOrEmpty");
315
+ function filterNullAndUndefinedAndEmpty(value) {
316
+ return !isNullOrUndefinedOrEmpty(value);
317
+ }
318
+ __name(filterNullAndUndefinedAndEmpty, "filterNullAndUndefinedAndEmpty");
319
+ __name2(filterNullAndUndefinedAndEmpty, "filterNullAndUndefinedAndEmpty");
320
+ function isNullOrUndefinedOrZero(value) {
321
+ return value === 0 || isNullOrUndefined(value);
322
+ }
323
+ __name(isNullOrUndefinedOrZero, "isNullOrUndefinedOrZero");
324
+ __name2(isNullOrUndefinedOrZero, "isNullOrUndefinedOrZero");
325
+ function filterNullAndUndefinedAndZero(value) {
326
+ return !isNullOrUndefinedOrZero(value);
327
+ }
328
+ __name(filterNullAndUndefinedAndZero, "filterNullAndUndefinedAndZero");
329
+ __name2(filterNullAndUndefinedAndZero, "filterNullAndUndefinedAndZero");
330
+ function hasAtLeastOneKeyInMap(map, keys) {
331
+ return keys.some((key) => map.has(key));
332
+ }
333
+ __name(hasAtLeastOneKeyInMap, "hasAtLeastOneKeyInMap");
334
+ __name2(hasAtLeastOneKeyInMap, "hasAtLeastOneKeyInMap");
335
+ var zws2 = String.fromCharCode(8203);
336
+ function inlineCodeBlock(input) {
337
+ return `\`${input.replace(/ /g, "\xA0").replace(/`/g, `\`${zws2}`)}\``;
338
+ }
339
+ __name(inlineCodeBlock, "inlineCodeBlock");
340
+ __name2(inlineCodeBlock, "inlineCodeBlock");
341
+ function isClass(input) {
342
+ return typeof input === "function" && typeof input.prototype === "object";
343
+ }
344
+ __name(isClass, "isClass");
345
+ __name2(isClass, "isClass");
346
+ function isFunction(input) {
347
+ return typeof input === "function";
348
+ }
349
+ __name(isFunction, "isFunction");
350
+ __name2(isFunction, "isFunction");
351
+ function isNumber(input) {
352
+ return typeof input === "number" && !isNaN(input) && Number.isFinite(input);
353
+ }
354
+ __name(isNumber, "isNumber");
355
+ __name2(isNumber, "isNumber");
356
+ function isObject(input, constructorType) {
357
+ return typeof input === "object" && input ? input.constructor === (constructorType != null ? constructorType : Object) : false;
358
+ }
359
+ __name(isObject, "isObject");
360
+ __name2(isObject, "isObject");
361
+ function hasThen(input) {
362
+ return Reflect.has(input, "then") && isFunction(input.then);
363
+ }
364
+ __name(hasThen, "hasThen");
365
+ __name2(hasThen, "hasThen");
366
+ function hasCatch(input) {
367
+ return Reflect.has(input, "catch") && isFunction(input.catch);
368
+ }
369
+ __name(hasCatch, "hasCatch");
370
+ __name2(hasCatch, "hasCatch");
371
+ function isThenable(input) {
372
+ if (typeof input !== "object" || input === null)
373
+ return false;
374
+ return input instanceof Promise || input !== Promise.prototype && hasThen(input) && hasCatch(input);
375
+ }
376
+ __name(isThenable, "isThenable");
377
+ __name2(isThenable, "isThenable");
378
+ function makeObject(path, value, obj = {}) {
379
+ if (path.includes(".")) {
380
+ const route = path.split(".");
381
+ const lastKey = route.pop();
382
+ let reference = obj;
383
+ for (const key of route) {
384
+ if (!reference[key])
385
+ reference[key] = {};
386
+ reference = reference[key];
387
+ }
388
+ reference[lastKey] = value;
389
+ } else {
390
+ obj[path] = value;
391
+ }
392
+ return obj;
393
+ }
394
+ __name(makeObject, "makeObject");
395
+ __name2(makeObject, "makeObject");
396
+ function mergeDefault(base, overwrites) {
397
+ if (!overwrites)
398
+ return deepClone(base);
399
+ for (const [baseKey, baseValue] of Object.entries(base)) {
400
+ const overwritesValueAtBaseKey = Reflect.get(overwrites, baseKey);
401
+ if (typeof overwritesValueAtBaseKey === "undefined") {
402
+ Reflect.set(overwrites, baseKey, deepClone(baseValue));
403
+ } else if (isObject(overwritesValueAtBaseKey)) {
404
+ Reflect.set(overwrites, baseKey, mergeDefault(baseValue != null ? baseValue : {}, overwritesValueAtBaseKey));
405
+ }
406
+ }
407
+ return overwrites;
408
+ }
409
+ __name(mergeDefault, "mergeDefault");
410
+ __name2(mergeDefault, "mergeDefault");
411
+ function mergeObjects(objTarget, objSource) {
412
+ for (const [key, value] of Object.entries(objSource)) {
413
+ const targetValue = Reflect.get(objTarget, key);
414
+ if (isObject(value)) {
415
+ Reflect.set(objTarget, key, isObject(targetValue) ? mergeObjects(targetValue, value) : value);
416
+ } else if (!isObject(targetValue)) {
417
+ Reflect.set(objTarget, key, value);
418
+ }
419
+ }
420
+ return objTarget;
421
+ }
422
+ __name(mergeObjects, "mergeObjects");
423
+ __name2(mergeObjects, "mergeObjects");
424
+ function noop() {
425
+ }
426
+ __name(noop, "noop");
427
+ __name2(noop, "noop");
428
+ function objectToTuples(original, prefix = "") {
429
+ const entries = [];
430
+ for (const [key, value] of Object.entries(original)) {
431
+ if (isObject(value)) {
432
+ entries.push(...objectToTuples(value, `${prefix}${key}.`));
433
+ } else {
434
+ entries.push([`${prefix}${key}`, value]);
435
+ }
436
+ }
437
+ return entries;
438
+ }
439
+ __name(objectToTuples, "objectToTuples");
440
+ __name2(objectToTuples, "objectToTuples");
441
+ function parseURL(url) {
442
+ try {
443
+ return new URL(url);
444
+ } catch {
445
+ return null;
446
+ }
447
+ }
448
+ __name(parseURL, "parseURL");
449
+ __name2(parseURL, "parseURL");
450
+ function partition(array, predicate) {
451
+ if (!Array.isArray(array))
452
+ throw new TypeError("entries must be an array.");
453
+ if (!isFunction(predicate))
454
+ throw new TypeError("predicate must be an function that returns a boolean value.");
455
+ const partitionOne = [];
456
+ const partitionTwo = [];
457
+ for (let i = 0; i < array.length; i++) {
458
+ if (predicate(array[i], i)) {
459
+ partitionOne.push(array[i]);
460
+ } else {
461
+ partitionTwo.push(array[i]);
462
+ }
463
+ }
464
+ return [partitionOne, partitionTwo];
465
+ }
466
+ __name(partition, "partition");
467
+ __name2(partition, "partition");
468
+ function range(min, max, step) {
469
+ return new Array(Math.floor((max - min) / step) + 1).fill(0).map((_val, i) => min + i * step);
470
+ }
471
+ __name(range, "range");
472
+ __name2(range, "range");
473
+ var REGEXPESC = /[-/\\^$*+?.()|[\]{}]/g;
474
+ function regExpEsc(str) {
475
+ return str.replace(REGEXPESC, "\\$&");
476
+ }
477
+ __name(regExpEsc, "regExpEsc");
478
+ __name2(regExpEsc, "regExpEsc");
479
+ function roundNumber(num, scale = 0) {
480
+ if (!num.toString().includes("e")) {
481
+ return Number(`${Math.round(Number(`${num}e+${scale}`))}e-${scale}`);
482
+ }
483
+ const arr = `${num}`.split("e");
484
+ let sig = "";
485
+ if (Number(arr[1]) + scale > 0) {
486
+ sig = "+";
487
+ }
488
+ return Number(`${Math.round(Number(`${Number(arr[0])}e${sig}${Number(arr[1]) + scale}`))}e-${scale}`);
489
+ }
490
+ __name(roundNumber, "roundNumber");
491
+ __name2(roundNumber, "roundNumber");
492
+ var TOTITLECASE = /[A-Za-zÀ-ÖØ-öø-ÿ]\S*/g;
493
+ var titleCaseVariants = {
494
+ textchannel: "TextChannel",
495
+ voicechannel: "VoiceChannel",
496
+ categorychannel: "CategoryChannel",
497
+ guildmember: "GuildMember"
498
+ };
499
+ function toTitleCase(str) {
500
+ return str.replace(TOTITLECASE, (txt) => titleCaseVariants[txt] || txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
501
+ }
502
+ __name(toTitleCase, "toTitleCase");
503
+ __name2(toTitleCase, "toTitleCase");
504
+ function tryParse(value) {
505
+ try {
506
+ return JSON.parse(value);
507
+ } catch (err) {
508
+ return value;
509
+ }
510
+ }
511
+ __name(tryParse, "tryParse");
512
+ __name2(tryParse, "tryParse");
513
+
514
+ // ../time-utilities/dist/index.mjs
515
+ var __defProp3 = Object.defineProperty;
516
+ var __defNormalProp2 = /* @__PURE__ */ __name((obj, key, value) => key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, "__defNormalProp");
517
+ var __name3 = /* @__PURE__ */ __name((target, value) => __defProp3(target, "name", { value, configurable: true }), "__name");
518
+ var __publicField2 = /* @__PURE__ */ __name((obj, key, value) => {
519
+ __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
520
+ return value;
521
+ }, "__publicField");
522
+ var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
523
+ var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
524
+ var tokens = /* @__PURE__ */ new Map([
525
+ ["Y", 4],
526
+ ["Q", 1],
527
+ ["M", 4],
528
+ ["D", 4],
529
+ ["d", 4],
530
+ ["X", 1],
531
+ ["x", 1],
532
+ ["H", 2],
533
+ ["h", 2],
534
+ ["a", 1],
535
+ ["A", 1],
536
+ ["m", 2],
537
+ ["s", 2],
538
+ ["S", 3],
539
+ ["Z", 2],
540
+ ["l", 4],
541
+ ["L", 4],
542
+ ["T", 1],
543
+ ["t", 1]
544
+ ]);
545
+ var partRegex = /^(?:(\*)|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/;
546
+ var wildcardRegex = /\bh\b|\B\?\B/g;
547
+ var allowedNum = [
548
+ [0, 59],
549
+ [0, 23],
550
+ [1, 31],
551
+ [1, 12],
552
+ [0, 6]
553
+ ];
554
+ var predefined = {
555
+ "@annually": "0 0 1 1 *",
556
+ "@yearly": "0 0 1 1 *",
557
+ "@monthly": "0 0 1 * *",
558
+ "@weekly": "0 0 * * 0",
559
+ "@daily": "0 0 * * *",
560
+ "@hourly": "0 * * * *"
561
+ };
562
+ var cronTokens = {
563
+ jan: 1,
564
+ feb: 2,
565
+ mar: 3,
566
+ apr: 4,
567
+ may: 5,
568
+ jun: 6,
569
+ jul: 7,
570
+ aug: 8,
571
+ sep: 9,
572
+ oct: 10,
573
+ nov: 11,
574
+ dec: 12,
575
+ sun: 0,
576
+ mon: 1,
577
+ tue: 2,
578
+ wed: 3,
579
+ thu: 4,
580
+ fri: 5,
581
+ sat: 6
582
+ };
583
+ var tokensRegex = new RegExp(Object.keys(cronTokens).join("|"), "g");
584
+ var DEFAULT_UNITS = {
585
+ ["year"]: {
586
+ 1: "year",
587
+ DEFAULT: "years"
588
+ },
589
+ ["month"]: {
590
+ 1: "month",
591
+ DEFAULT: "months"
592
+ },
593
+ ["week"]: {
594
+ 1: "week",
595
+ DEFAULT: "weeks"
596
+ },
597
+ ["day"]: {
598
+ 1: "day",
599
+ DEFAULT: "days"
600
+ },
601
+ ["hour"]: {
602
+ 1: "hour",
603
+ DEFAULT: "hours"
604
+ },
605
+ ["minute"]: {
606
+ 1: "minute",
607
+ DEFAULT: "minutes"
608
+ },
609
+ ["second"]: {
610
+ 1: "second",
611
+ DEFAULT: "seconds"
612
+ }
613
+ };
614
+ var DEFAULT_SEPARATORS = {
615
+ left: " ",
616
+ right: " "
617
+ };
618
+ var Cron = /* @__PURE__ */ __name(class {
619
+ constructor(cron) {
620
+ __publicField2(this, "cron");
621
+ __publicField2(this, "normalized");
622
+ __publicField2(this, "minutes");
623
+ __publicField2(this, "hours");
624
+ __publicField2(this, "days");
625
+ __publicField2(this, "months");
626
+ __publicField2(this, "dows");
627
+ this.cron = cron.toLowerCase();
628
+ this.normalized = Cron.normalize(this.cron);
629
+ [this.minutes, this.hours, this.days, this.months, this.dows] = Cron.parseString(this.normalized);
630
+ }
631
+ next(outset = new Date(), origin = true) {
632
+ if (!this.days.includes(outset.getUTCDate()) || !this.months.includes(outset.getUTCMonth() + 1) || !this.dows.includes(outset.getUTCDay())) {
633
+ return this.next(new Date(outset.getTime() + 864e5), false);
634
+ }
635
+ if (!origin)
636
+ return new Date(Date.UTC(outset.getUTCFullYear(), outset.getUTCMonth(), outset.getUTCDate(), this.hours[0], this.minutes[0]));
637
+ const now = new Date(outset.getTime() + 6e4);
638
+ for (const hour of this.hours) {
639
+ if (hour < now.getUTCHours())
640
+ continue;
641
+ for (const minute of this.minutes) {
642
+ if (hour === now.getUTCHours() && minute < now.getUTCMinutes())
643
+ continue;
644
+ return new Date(Date.UTC(outset.getUTCFullYear(), outset.getUTCMonth(), outset.getUTCDate(), hour, minute));
645
+ }
646
+ }
647
+ return this.next(new Date(outset.getTime() + 864e5), false);
648
+ }
649
+ static normalize(cron) {
650
+ if (Reflect.has(predefined, cron))
651
+ return Reflect.get(predefined, cron);
652
+ const now = new Date();
653
+ cron = cron.split(" ").map((val, i) => val.replace(wildcardRegex, (match) => {
654
+ if (match === "h")
655
+ return (Math.floor(Math.random() * allowedNum[i][1]) + allowedNum[i][0]).toString();
656
+ if (match === "?") {
657
+ switch (i) {
658
+ case 0:
659
+ return now.getUTCMinutes().toString();
660
+ case 1:
661
+ return now.getUTCHours().toString();
662
+ case 2:
663
+ return now.getUTCDate().toString();
664
+ case 3:
665
+ return now.getUTCMonth().toString();
666
+ case 4:
667
+ return now.getUTCDay().toString();
668
+ }
669
+ }
670
+ return match;
671
+ })).join(" ");
672
+ return cron.replace(tokensRegex, (match) => String(Reflect.get(cronTokens, match)));
673
+ }
674
+ static parseString(cron) {
675
+ const parts = cron.split(" ");
676
+ if (parts.length !== 5)
677
+ throw new Error("Invalid Cron Provided");
678
+ return parts.map((part, i) => Cron.parsePart(part, i));
679
+ }
680
+ static parsePart(cronPart, id) {
681
+ if (cronPart.includes(",")) {
682
+ const res = [];
683
+ for (const part of cronPart.split(","))
684
+ res.push(...Cron.parsePart(part, id));
685
+ return [...new Set(res)].sort((a, b) => a - b);
686
+ }
687
+ const [, wild, minStr, maxStr, step] = partRegex.exec(cronPart);
688
+ let [min, max] = [parseInt(minStr, 10), parseInt(maxStr, 10)];
689
+ if (wild)
690
+ [min, max] = allowedNum[id];
691
+ else if (!max && !step)
692
+ return [min];
693
+ [min, max] = [min, max || allowedNum[id][1]].sort((a, b) => a - b);
694
+ return range(min, max, parseInt(step, 10) || 1);
695
+ }
696
+ }, "Cron");
697
+ __name3(Cron, "Cron");
698
+ var tokens2 = /* @__PURE__ */ new Map([
699
+ ["nanosecond", 1 / 1e6],
700
+ ["nanoseconds", 1 / 1e6],
701
+ ["ns", 1 / 1e6],
702
+ ["millisecond", 1],
703
+ ["milliseconds", 1],
704
+ ["ms", 1],
705
+ ["second", 1e3],
706
+ ["seconds", 1e3],
707
+ ["sec", 1e3],
708
+ ["secs", 1e3],
709
+ ["s", 1e3],
710
+ ["minute", 1e3 * 60],
711
+ ["minutes", 1e3 * 60],
712
+ ["min", 1e3 * 60],
713
+ ["mins", 1e3 * 60],
714
+ ["m", 1e3 * 60],
715
+ ["hour", 1e3 * 60 * 60],
716
+ ["hours", 1e3 * 60 * 60],
717
+ ["hr", 1e3 * 60 * 60],
718
+ ["hrs", 1e3 * 60 * 60],
719
+ ["h", 1e3 * 60 * 60],
720
+ ["day", 1e3 * 60 * 60 * 24],
721
+ ["days", 1e3 * 60 * 60 * 24],
722
+ ["d", 1e3 * 60 * 60 * 24],
723
+ ["week", 1e3 * 60 * 60 * 24 * 7],
724
+ ["weeks", 1e3 * 60 * 60 * 24 * 7],
725
+ ["wk", 1e3 * 60 * 60 * 24 * 7],
726
+ ["wks", 1e3 * 60 * 60 * 24 * 7],
727
+ ["w", 1e3 * 60 * 60 * 24 * 7],
728
+ ["month", 1e3 * 60 * 60 * 24 * (365.25 / 12)],
729
+ ["months", 1e3 * 60 * 60 * 24 * (365.25 / 12)],
730
+ ["b", 1e3 * 60 * 60 * 24 * (365.25 / 12)],
731
+ ["mo", 1e3 * 60 * 60 * 24 * (365.25 / 12)],
732
+ ["year", 1e3 * 60 * 60 * 24 * 365.25],
733
+ ["years", 1e3 * 60 * 60 * 24 * 365.25],
734
+ ["yr", 1e3 * 60 * 60 * 24 * 365.25],
735
+ ["yrs", 1e3 * 60 * 60 * 24 * 365.25],
736
+ ["y", 1e3 * 60 * 60 * 24 * 365.25]
737
+ ]);
738
+ var _Duration = /* @__PURE__ */ __name(class {
739
+ constructor(pattern) {
740
+ __publicField2(this, "offset");
741
+ this.offset = _Duration.parse(pattern.toLowerCase());
742
+ }
743
+ get fromNow() {
744
+ return this.dateFrom(new Date());
745
+ }
746
+ dateFrom(date) {
747
+ return new Date(date.getTime() + this.offset);
748
+ }
749
+ static parse(pattern) {
750
+ let result = 0;
751
+ let valid = false;
752
+ pattern.replace(_Duration.kCommaRegex, "").replace(_Duration.kAanRegex, "1").replace(_Duration.kPatternRegex, (_, i, units) => {
753
+ const token = tokens2.get(units);
754
+ if (token !== void 0) {
755
+ result += Number(i) * token;
756
+ valid = true;
757
+ }
758
+ return "";
759
+ });
760
+ return valid ? result : NaN;
761
+ }
762
+ }, "_Duration");
763
+ var Duration = _Duration;
764
+ __name3(Duration, "Duration");
765
+ __publicField2(Duration, "kPatternRegex", /(-?\d*\.?\d+(?:e[-+]?\d+)?)\s*([a-zμ]*)/gi);
766
+ __publicField2(Duration, "kCommaRegex", /,/g);
767
+ __publicField2(Duration, "kAanRegex", /\ban?\b/gi);
768
+ var kTimeDurations = [
769
+ ["year", 31536e6],
770
+ ["month", 2628e6],
771
+ ["week", 1e3 * 60 * 60 * 24 * 7],
772
+ ["day", 1e3 * 60 * 60 * 24],
773
+ ["hour", 1e3 * 60 * 60],
774
+ ["minute", 1e3 * 60],
775
+ ["second", 1e3]
776
+ ];
777
+ var DurationFormatter = /* @__PURE__ */ __name(class {
778
+ constructor(units = DEFAULT_UNITS) {
779
+ this.units = units;
780
+ }
781
+ format(duration, precision = 7, {
782
+ left: leftSeparator = DEFAULT_SEPARATORS.left,
783
+ right: rightSeparator = DEFAULT_SEPARATORS.right
784
+ } = DEFAULT_SEPARATORS) {
785
+ const output = [];
786
+ const negative = duration < 0;
787
+ if (negative)
788
+ duration *= -1;
789
+ for (const [type, timeDuration] of kTimeDurations) {
790
+ const substraction = duration / timeDuration;
791
+ if (substraction < 1)
792
+ continue;
793
+ const floored = Math.floor(substraction);
794
+ duration -= floored * timeDuration;
795
+ output.push(addUnit(floored, this.units[type], leftSeparator));
796
+ if (output.length >= precision)
797
+ break;
798
+ }
799
+ return `${negative ? "-" : ""}${output.join(rightSeparator) || addUnit(0, this.units.second, leftSeparator)}`;
800
+ }
801
+ }, "DurationFormatter");
802
+ __name3(DurationFormatter, "DurationFormatter");
803
+ function addUnit(time, unit, separator) {
804
+ if (Reflect.has(unit, time))
805
+ return `${time}${separator}${Reflect.get(unit, time)}`;
806
+ return `${time}${separator}${unit.DEFAULT}`;
807
+ }
808
+ __name(addUnit, "addUnit");
809
+ __name3(addUnit, "addUnit");
810
+ var TimerManager = /* @__PURE__ */ __name(class extends null {
811
+ static setTimeout(fn, delay, ...args) {
812
+ const timeout = setTimeout(() => {
813
+ this.storedTimeouts.delete(timeout);
814
+ fn(...args);
815
+ }, delay);
816
+ this.storedTimeouts.add(timeout);
817
+ return timeout;
818
+ }
819
+ static clearTimeout(timeout) {
820
+ clearTimeout(timeout);
821
+ this.storedTimeouts.delete(timeout);
822
+ }
823
+ static setInterval(fn, delay, ...args) {
824
+ const interval = setInterval(fn, delay, ...args);
825
+ this.storedIntervals.add(interval);
826
+ return interval;
827
+ }
828
+ static clearInterval(interval) {
829
+ clearInterval(interval);
830
+ this.storedIntervals.delete(interval);
831
+ }
832
+ static destroy() {
833
+ for (const i of this.storedTimeouts)
834
+ clearTimeout(i);
835
+ for (const i of this.storedIntervals)
836
+ clearInterval(i);
837
+ this.storedTimeouts.clear();
838
+ this.storedIntervals.clear();
839
+ }
840
+ }, "TimerManager");
841
+ __name3(TimerManager, "TimerManager");
842
+ __publicField2(TimerManager, "storedTimeouts", /* @__PURE__ */ new Set());
843
+ __publicField2(TimerManager, "storedIntervals", /* @__PURE__ */ new Set());
844
+ var tokenResolvers = /* @__PURE__ */ new Map([
845
+ ["Y", (time) => String(time.getFullYear()).slice(2)],
846
+ ["YY", (time) => String(time.getFullYear()).slice(2)],
847
+ ["YYY", (time) => String(time.getFullYear())],
848
+ ["YYYY", (time) => String(time.getFullYear())],
849
+ ["Q", (time) => String((time.getMonth() + 1) / 3)],
850
+ ["M", (time) => String(time.getMonth() + 1)],
851
+ ["MM", (time) => String(time.getMonth() + 1).padStart(2, "0")],
852
+ ["MMM", (time) => months[time.getMonth()]],
853
+ ["MMMM", (time) => months[time.getMonth()]],
854
+ ["D", (time) => String(time.getDate())],
855
+ ["DD", (time) => String(time.getDate()).padStart(2, "0")],
856
+ ["DDD", (time) => String(Math.floor((time.getTime() - new Date(time.getFullYear(), 0, 0).getTime()) / 864e5))],
857
+ ["DDDD", (time) => String(Math.floor((time.getTime() - new Date(time.getFullYear(), 0, 0).getTime()) / 864e5))],
858
+ [
859
+ "d",
860
+ (time) => {
861
+ const day = String(time.getDate());
862
+ if (day !== "11" && day.endsWith("1"))
863
+ return `${day}st`;
864
+ if (day !== "12" && day.endsWith("2"))
865
+ return `${day}nd`;
866
+ if (day !== "13" && day.endsWith("3"))
867
+ return `${day}rd`;
868
+ return `${day}th`;
869
+ }
870
+ ],
871
+ ["dd", (time) => days[time.getDay()].slice(0, 2)],
872
+ ["ddd", (time) => days[time.getDay()].slice(0, 3)],
873
+ ["dddd", (time) => days[time.getDay()]],
874
+ ["X", (time) => String(time.valueOf() / 1e3)],
875
+ ["x", (time) => String(time.valueOf())],
876
+ ["H", (time) => String(time.getHours())],
877
+ ["HH", (time) => String(time.getHours()).padStart(2, "0")],
878
+ ["h", (time) => String(time.getHours() % 12 || 12)],
879
+ ["hh", (time) => String(time.getHours() % 12 || 12).padStart(2, "0")],
880
+ ["a", (time) => time.getHours() < 12 ? "am" : "pm"],
881
+ ["A", (time) => time.getHours() < 12 ? "AM" : "PM"],
882
+ ["m", (time) => String(time.getMinutes())],
883
+ ["mm", (time) => String(time.getMinutes()).padStart(2, "0")],
884
+ ["s", (time) => String(time.getSeconds())],
885
+ ["ss", (time) => String(time.getSeconds()).padStart(2, "0")],
886
+ ["S", (time) => String(time.getMilliseconds())],
887
+ ["SS", (time) => String(time.getMilliseconds()).padStart(2, "0")],
888
+ ["SSS", (time) => String(time.getMilliseconds()).padStart(3, "0")],
889
+ ["T", (time) => `${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`],
890
+ [
891
+ "t",
892
+ (time) => `${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")}:${String(time.getSeconds()).padStart(2, "0")} ${time.getHours() < 12 ? "am" : "pm"}`
893
+ ],
894
+ ["L", (time) => `${String(time.getMonth() + 1).padStart(2, "0")}/${String(time.getDate()).padStart(2, "0")}/${String(time.getFullYear())}`],
895
+ ["l", (time) => `${String(time.getMonth() + 1)}/${String(time.getDate()).padStart(2, "0")}/${String(time.getFullYear())}`],
896
+ ["LL", (time) => `${months[time.getMonth()]} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())}`],
897
+ ["ll", (time) => `${months[time.getMonth()].slice(0, 3)} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())}`],
898
+ [
899
+ "LLL",
900
+ (time) => `${months[time.getMonth()]} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
901
+ ],
902
+ [
903
+ "lll",
904
+ (time) => `${months[time.getMonth()].slice(0, 3)} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
905
+ ],
906
+ [
907
+ "LLLL",
908
+ (time) => `${days[time.getDay()]}, ${months[time.getMonth()]} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
909
+ ],
910
+ [
911
+ "llll",
912
+ (time) => `${days[time.getDay()].slice(0, 3)} ${months[time.getMonth()].slice(0, 3)} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
913
+ ],
914
+ [
915
+ "Z",
916
+ (time) => {
917
+ const offset = time.getTimezoneOffset();
918
+ const unsigned = offset >= 0;
919
+ const absolute = Math.abs(offset);
920
+ return `${unsigned ? "+" : "-"}${String(Math.floor(absolute / 60)).padStart(2, "0")}:${String(absolute % 60).padStart(2, "0")}`;
921
+ }
922
+ ],
923
+ [
924
+ "ZZ",
925
+ (time) => {
926
+ const offset = time.getTimezoneOffset();
927
+ const unsigned = offset >= 0;
928
+ const absolute = Math.abs(offset);
929
+ return `${unsigned ? "+" : "-"}${String(Math.floor(absolute / 60)).padStart(2, "0")}:${String(absolute % 60).padStart(2, "0")}`;
930
+ }
931
+ ]
932
+ ]);
933
+ var Timestamp = /* @__PURE__ */ __name(class {
934
+ constructor(pattern) {
935
+ __publicField2(this, "pattern");
936
+ __publicField2(this, "template");
937
+ this.pattern = pattern;
938
+ this.template = Timestamp.parse(pattern);
939
+ }
940
+ display(time = new Date()) {
941
+ return Timestamp.display(this.template, time);
942
+ }
943
+ displayUTC(time) {
944
+ return Timestamp.display(this.template, Timestamp.utc(time));
945
+ }
946
+ edit(pattern) {
947
+ this.pattern = pattern;
948
+ this.template = Timestamp.parse(pattern);
949
+ return this;
950
+ }
951
+ toString() {
952
+ return this.display();
953
+ }
954
+ static displayArbitrary(pattern, time = new Date()) {
955
+ return Timestamp.display(Timestamp.parse(pattern), time);
956
+ }
957
+ static displayUTCArbitrary(pattern, time = new Date()) {
958
+ return Timestamp.display(Timestamp.parse(pattern), Timestamp.utc(time));
959
+ }
960
+ static utc(time = new Date()) {
961
+ time = Timestamp.resolveDate(time);
962
+ return new Date(time.valueOf() + time.getTimezoneOffset() * 6e4);
963
+ }
964
+ static display(template, time) {
965
+ let output = "";
966
+ const parsedTime = Timestamp.resolveDate(time);
967
+ for (const { content, type } of template)
968
+ output += content || tokenResolvers.get(type)(parsedTime);
969
+ return output;
970
+ }
971
+ static parse(pattern) {
972
+ const template = [];
973
+ for (let i = 0; i < pattern.length; i++) {
974
+ let current = "";
975
+ const currentChar = pattern[i];
976
+ const tokenMax = tokens.get(currentChar);
977
+ if (typeof tokenMax === "number") {
978
+ current += currentChar;
979
+ while (pattern[i + 1] === currentChar && current.length < tokenMax)
980
+ current += pattern[++i];
981
+ template.push({ type: current, content: null });
982
+ } else if (currentChar === "[") {
983
+ while (i + 1 < pattern.length && pattern[i + 1] !== "]")
984
+ current += pattern[++i];
985
+ i++;
986
+ template.push({ type: "literal", content: current || "[" });
987
+ } else {
988
+ current += currentChar;
989
+ while (i + 1 < pattern.length && !tokens.has(pattern[i + 1]) && pattern[i + 1] !== "[")
990
+ current += pattern[++i];
991
+ template.push({ type: "literal", content: current });
992
+ }
993
+ }
994
+ return template;
995
+ }
996
+ static resolveDate(time) {
997
+ return time instanceof Date ? time : new Date(time);
998
+ }
999
+ }, "Timestamp");
1000
+ __name3(Timestamp, "Timestamp");
1001
+
1002
+ // src/lib/RateLimitManager.ts
1003
+ var _RateLimitManager = class extends Map {
1004
+ constructor(time, limit = 1) {
1005
+ super();
1006
+ __publicField(this, "time");
1007
+ __publicField(this, "limit");
1008
+ __publicField(this, "sweepInterval");
1009
+ this.time = time;
1010
+ this.limit = limit;
1011
+ }
1012
+ acquire(id) {
1013
+ return this.get(id) ?? this.create(id);
1014
+ }
1015
+ create(id) {
1016
+ const value = new RateLimit(this);
1017
+ this.set(id, value);
1018
+ return value;
1019
+ }
1020
+ set(id, value) {
1021
+ this.sweepInterval ?? (this.sweepInterval = TimerManager.setInterval(this.sweep.bind(this), _RateLimitManager.sweepIntervalDuration));
1022
+ return super.set(id, value);
1023
+ }
1024
+ sweep() {
1025
+ for (const [id, value] of this.entries()) {
1026
+ if (value.expired)
1027
+ this.delete(id);
1028
+ }
1029
+ if (this.size === 0) {
1030
+ TimerManager.clearInterval(this.sweepInterval);
1031
+ this.sweepInterval = null;
1032
+ }
1033
+ }
1034
+ };
1035
+ var RateLimitManager = _RateLimitManager;
1036
+ __name(RateLimitManager, "RateLimitManager");
1037
+ __publicField(RateLimitManager, "sweepIntervalDuration", 3e4);
1038
+ return __toCommonJS(src_exports);
1039
+ })();
1040
+ /**
1041
+ * Split a string by its latest space character in a range from the character 0 to the selected one.
1042
+ * @param str The text to split.
1043
+ * @param length The length of the desired string.
1044
+ * @param char The character to split with
1045
+ * @copyright 2019 Antonio Román
1046
+ * @license Apache-2.0
1047
+ */
1048
+ /**
1049
+ * Split a text by its latest space character in a range from the character 0 to the selected one.
1050
+ * @param str The text to split.
1051
+ * @param length The length of the desired string.
1052
+ * @copyright 2019 Antonio Román
1053
+ * @license Apache-2.0
1054
+ */
1055
+ //# sourceMappingURL=index.global.js.map