tinyvec, gonna revert

This commit is contained in:
mehbark 2023-06-12 11:40:38 -04:00
commit c8c12b15e9
2937 changed files with 317799 additions and 0 deletions

2
*.slimp Normal file
View file

@ -0,0 +1,2 @@
(forall (a b) (* a (succ b)) (+ a (* a b)))
(forall (a) (* a 0) 0)

3
+.slimp Normal file
View file

@ -0,0 +1,3 @@
(forall (a b) (+ a (succ b)) (succ (+ a b)))
(forall (a) (+ a 0) a)

10
1-10.slimp Normal file
View file

@ -0,0 +1,10 @@
(def 1 (succ 0))
(def 2 (succ 1))
(def 3 (succ 2))
(def 4 (succ 3))
(def 5 (succ 4))
(def 6 (succ 5))
(def 7 (succ 6))
(def 8 (succ 7))
(def 9 (succ 8))
(def 10 (succ 9))

1
100.slimp Normal file
View file

@ -0,0 +1 @@
(* 10 10)

55
Cargo.lock generated Normal file
View file

@ -0,0 +1,55 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "either"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
[[package]]
name = "intaglio"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b4f756a47a2dac507018af2d4e47988e93829f34a665da3655b23cc1d21ee47"
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "once_cell"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "slimp"
version = "0.1.0"
dependencies = [
"intaglio",
"itertools",
"once_cell",
"tinyvec",
]
[[package]]
name = "tinyvec"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"

12
Cargo.toml Normal file
View file

@ -0,0 +1,12 @@
[package]
name = "slimp"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
intaglio = "1.8.0"
itertools = "0.10.5"
once_cell = "1.18.0"
tinyvec = { version = "1.6.0", features = ["alloc"] }

27
example.slimp Normal file
View file

@ -0,0 +1,27 @@
(forall (n) (range-to n) (reverse (range-to n nil)))
(forall (xs) (range-to 0 xs) xs)
(forall (n xs) (range-to (s n) xs) (cons (s n) (range-to n xs)))
(forall (a as bs) (++ (cons a as) bs) (cons a (++ as bs)))
(forall (bs) (++ nil bs) bs)
(forall (a) (singleton a) (cons a nil))
(def (reverse nil) nil)
(forall (a as) (reverse (cons a as)) (++ (reverse as) (singleton a)))
(forall (n) (+ n 0) n)
(forall (a b) (+ a (s b)) (s (+ a b)))
(forall (n) (* n 0) 0)
(forall (a b) (* a (s b)) (+ a (* a b)))
(def 1 (s 0))
(def 2 (s 1))
(def 3 (s 2))
(def 4 (s 3))
(def 5 (s 4))
(def 6 (s 5))
(def 7 (s 6))
(def 8 (s 7))
(def 9 (s 8))
(def 10 (s 9))
(def 20 (+ 10 10))
; i need to do comments
(range-to 5)

491
flamegraph.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.1 MiB

40
main.js Normal file
View file

@ -0,0 +1,40 @@
const { Client, Events, GatewayIntentBits } = require("discord.js");
const { token, id } = require("./config.json");
const { spawn } = require("child_process");
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
client.once(Events.ClientReady, c => {
console.log(`okay cool, ${c.user.tag}`);
console.log(
`Invite link: https://discord.com/oauth2/authorize?client_id=${id}&permissions=3072&scope=bot`
);
});
client.login(token);
client.on("messageCreate", message => {
if (message.author.id == id || !message.mentions.has(id)) return;
try {
let process = spawn("./target/release/slimp", [message.content], {
stdio: "pipe",
});
process.stdout.on("data", data =>
message.reply(mk_message(data.toString()))
);
process.stderr.on("data", data => console.error(data.toString()));
} catch (e) {
console.error(e);
message.reply(":(");
}
});
function mk_message(str) {
return "```lisp\n" + str.slice(0, 1975) + "```";
}

395
node_modules/.package-lock.json generated vendored Normal file
View file

@ -0,0 +1,395 @@
{
"name": "slimp",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/@discordjs/builders": {
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.6.3.tgz",
"integrity": "sha512-CTCh8NqED3iecTNuiz49mwSsrc2iQb4d0MjMdmS/8pb69Y4IlzJ/DIy/p5GFlgOrFbNO2WzMHkWKQSiJ3VNXaw==",
"dependencies": {
"@discordjs/formatters": "^0.3.1",
"@discordjs/util": "^0.3.1",
"@sapphire/shapeshift": "^3.8.2",
"discord-api-types": "^0.37.41",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.3",
"tslib": "^2.5.0"
},
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@discordjs/collection": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.1.tgz",
"integrity": "sha512-aWEc9DCf3TMDe9iaJoOnO2+JVAjeRNuRxPZQA6GVvBf+Z3gqUuWYBy2NWh4+5CLYq5uoc3MOvUQ5H5m8CJBqOA==",
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@discordjs/formatters": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.1.tgz",
"integrity": "sha512-M7X4IGiSeh4znwcRGcs+49B5tBkNDn4k5bmhxJDAUhRxRHTiFAOTVUNQ6yAKySu5jZTnCbSvTYHW3w0rAzV1MA==",
"dependencies": {
"discord-api-types": "^0.37.41"
},
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@discordjs/rest": {
"version": "1.7.1",
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.7.1.tgz",
"integrity": "sha512-Ofa9UqT0U45G/eX86cURQnX7gzOJLG2oC28VhIk/G6IliYgQF7jFByBJEykPSHE4MxPhqCleYvmsrtfKh1nYmQ==",
"dependencies": {
"@discordjs/collection": "^1.5.1",
"@discordjs/util": "^0.3.0",
"@sapphire/async-queue": "^1.5.0",
"@sapphire/snowflake": "^3.4.2",
"discord-api-types": "^0.37.41",
"file-type": "^18.3.0",
"tslib": "^2.5.0",
"undici": "^5.22.0"
},
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@discordjs/util": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.3.1.tgz",
"integrity": "sha512-HxXKYKg7vohx2/OupUN/4Sd02Ev3PBJ5q0gtjdcvXb0ErCva8jNHWfe/v5sU3UKjIB/uxOhc+TDOnhqffj9pRA==",
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@discordjs/ws": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-0.8.3.tgz",
"integrity": "sha512-hcYtppanjHecbdNyCKQNH2I4RP9UrphDgmRgLYrATEQF1oo4sYSve7ZmGsBEXSzH72MO2tBPdWSThunbxUVk0g==",
"dependencies": {
"@discordjs/collection": "^1.5.1",
"@discordjs/rest": "^1.7.1",
"@discordjs/util": "^0.3.1",
"@sapphire/async-queue": "^1.5.0",
"@types/ws": "^8.5.4",
"@vladfrangu/async_event_emitter": "^2.2.1",
"discord-api-types": "^0.37.41",
"tslib": "^2.5.0",
"ws": "^8.13.0"
},
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@sapphire/async-queue": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.0.tgz",
"integrity": "sha512-JkLdIsP8fPAdh9ZZjrbHWR/+mZj0wvKS5ICibcLrRI1j84UmLMshx5n9QmL8b95d4onJ2xxiyugTgSAX7AalmA==",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@sapphire/shapeshift": {
"version": "3.9.2",
"resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.2.tgz",
"integrity": "sha512-YRbCXWy969oGIdqR/wha62eX8GNHsvyYi0Rfd4rNW6tSVVa8p0ELiMEuOH/k8rgtvRoM+EMV7Csqz77YdwiDpA==",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"lodash": "^4.17.21"
},
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@sapphire/snowflake": {
"version": "3.5.1",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.1.tgz",
"integrity": "sha512-BxcYGzgEsdlG0dKAyOm0ehLGm2CafIrfQTZGWgkfKYbj+pNNsorZ7EotuZukc2MT70E0UbppVbtpBrqpzVzjNA==",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@tokenizer/token": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",
"integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="
},
"node_modules/@types/node": {
"version": "20.3.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz",
"integrity": "sha512-cumHmIAf6On83X7yP+LrsEyUOf/YlociZelmpRYaGFydoaPdxdt80MAbu6vWerQT2COCp2nPvHdsbD7tHn/YlQ=="
},
"node_modules/@types/ws": {
"version": "8.5.5",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz",
"integrity": "sha512-lwhs8hktwxSjf9UaZ9tG5M03PGogvFaH8gUgLNbN9HKIg0dvv6q+gkSuJ8HN4/VbyxkuLzCjlN7GquQ0gUJfIg==",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@vladfrangu/async_event_emitter": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.2.2.tgz",
"integrity": "sha512-HIzRG7sy88UZjBJamssEczH5q7t5+axva19UbZLO6u0ySbYPrwzWiXBcC0WuHyhKKoeCyneH+FvYzKQq/zTtkQ==",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/discord-api-types": {
"version": "0.37.43",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.43.tgz",
"integrity": "sha512-bBhDWU3TF9KADxR/mHp1K4Bvu/LRtFQdGyBjADu4e66F3ZnD4kp12W/SJCttIaCcMXzPV3sfty6eDGRNRph51Q=="
},
"node_modules/discord.js": {
"version": "14.11.0",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.11.0.tgz",
"integrity": "sha512-CkueWYFQ28U38YPR8HgsBR/QT35oPpMbEsTNM30Fs8loBIhnA4s70AwQEoy6JvLcpWWJO7GY0y2BUzZmuBMepQ==",
"dependencies": {
"@discordjs/builders": "^1.6.3",
"@discordjs/collection": "^1.5.1",
"@discordjs/formatters": "^0.3.1",
"@discordjs/rest": "^1.7.1",
"@discordjs/util": "^0.3.1",
"@discordjs/ws": "^0.8.3",
"@sapphire/snowflake": "^3.4.2",
"@types/ws": "^8.5.4",
"discord-api-types": "^0.37.41",
"fast-deep-equal": "^3.1.3",
"lodash.snakecase": "^4.1.1",
"tslib": "^2.5.0",
"undici": "^5.22.0",
"ws": "^8.13.0"
},
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
},
"node_modules/file-type": {
"version": "18.5.0",
"resolved": "https://registry.npmjs.org/file-type/-/file-type-18.5.0.tgz",
"integrity": "sha512-yvpl5U868+V6PqXHMmsESpg6unQ5GfnPssl4dxdJudBrr9qy7Fddt7EVX1VLlddFfe8Gj9N7goCZH22FXuSQXQ==",
"dependencies": {
"readable-web-to-node-stream": "^3.0.2",
"strtok3": "^7.0.0",
"token-types": "^5.0.1"
},
"engines": {
"node": ">=14.16"
},
"funding": {
"url": "https://github.com/sindresorhus/file-type?sponsor=1"
}
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
},
"node_modules/lodash.snakecase": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="
},
"node_modules/peek-readable": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-5.0.0.tgz",
"integrity": "sha512-YtCKvLUOvwtMGmrniQPdO7MwPjgkFBtFIrmfSbYmYuq3tKDV/mcfAhBth1+C3ru7uXIZasc/pHnb+YDYNkkj4A==",
"engines": {
"node": ">=14.16"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Borewit"
}
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/readable-web-to-node-stream": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/readable-web-to-node-stream/-/readable-web-to-node-stream-3.0.2.tgz",
"integrity": "sha512-ePeK6cc1EcKLEhJFt/AebMCLL+GgSKhuygrZ/GLaKZYEecIgIECf4UaUuaByiGtzckwR4ain9VzUh95T1exYGw==",
"dependencies": {
"readable-stream": "^3.6.0"
},
"engines": {
"node": ">=8"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Borewit"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/strtok3": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/strtok3/-/strtok3-7.0.0.tgz",
"integrity": "sha512-pQ+V+nYQdC5H3Q7qBZAz/MO6lwGhoC2gOAjuouGf/VO0m7vQRh8QNMl2Uf6SwAtzZ9bOw3UIeBukEGNJl5dtXQ==",
"dependencies": {
"@tokenizer/token": "^0.3.0",
"peek-readable": "^5.0.0"
},
"engines": {
"node": ">=14.16"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Borewit"
}
},
"node_modules/token-types": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/token-types/-/token-types-5.0.1.tgz",
"integrity": "sha512-Y2fmSnZjQdDb9W4w4r1tswlMHylzWIeOKpx0aZH9BgGtACHhrk3OkT52AzwcuqTRBZtvvnTjDBh8eynMulu8Vg==",
"dependencies": {
"@tokenizer/token": "^0.3.0",
"ieee754": "^1.2.1"
},
"engines": {
"node": ">=14.16"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Borewit"
}
},
"node_modules/ts-mixer": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.3.tgz",
"integrity": "sha512-k43M7uCG1AkTyxgnmI5MPwKoUvS/bRvLvUb7+Pgpdlmok8AoqmUaZxUUw8zKM5B1lqZrt41GjYgnvAi0fppqgQ=="
},
"node_modules/tslib": {
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz",
"integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w=="
},
"node_modules/undici": {
"version": "5.22.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-5.22.1.tgz",
"integrity": "sha512-Ji2IJhFXZY0x/0tVBXeQwgPlLWw13GVzpsWPQ3rV50IFMMof2I55PZZxtm4P6iNq+L5znYN9nSTAq0ZyE6lSJw==",
"dependencies": {
"busboy": "^1.6.0"
},
"engines": {
"node": ">=14.0"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
},
"node_modules/ws": {
"version": "8.13.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz",
"integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}

279
node_modules/@discordjs/builders/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,279 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@discordjs/builders@1.6.3](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.2...@discordjs/builders@1.6.3) - (2023-05-01)
## Refactor
- Remove `@discordjs/util` re-export (#9488) ([54ceedf](https://github.com/discordjs/discord.js/commit/54ceedf6c535d4641643d4106b6286cbef09de4a))
# [@discordjs/builders@1.6.2](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.1...@discordjs/builders@1.6.2) - (2023-05-01)
## Bug Fixes
- **BaseSelectMenuBuilder:** Modify class to be `abstract` (#9358) ([ca4de2d](https://github.com/discordjs/discord.js/commit/ca4de2d9c6bc204e85d1b7eae7eabd23dbeb4475))
- Correct `@link` tags that involve parents (#9351) ([fbbce3e](https://github.com/discordjs/discord.js/commit/fbbce3eb4ba20bc0c4806ca2259d1f86001594be))
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Documentation
- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef))
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
- **builders:** Add some basic documentation (#9359) ([8073561](https://github.com/discordjs/discord.js/commit/8073561824f911d1a18d0b4f1de39f452bc69fa9))
- Use `@link` in `@see` (#9348) ([d66d113](https://github.com/discordjs/discord.js/commit/d66d1133331b81563588db4500c63a18c3c3dfae))
# [@discordjs/builders@1.6.2](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.1...@discordjs/builders@1.6.2) - (2023-05-01)
## Bug Fixes
- **BaseSelectMenuBuilder:** Modify class to be `abstract` (#9358) ([ca4de2d](https://github.com/discordjs/discord.js/commit/ca4de2d9c6bc204e85d1b7eae7eabd23dbeb4475))
- Correct `@link` tags that involve parents (#9351) ([fbbce3e](https://github.com/discordjs/discord.js/commit/fbbce3eb4ba20bc0c4806ca2259d1f86001594be))
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Documentation
- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef))
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
- **builders:** Add some basic documentation (#9359) ([8073561](https://github.com/discordjs/discord.js/commit/8073561824f911d1a18d0b4f1de39f452bc69fa9))
- Use `@link` in `@see` (#9348) ([d66d113](https://github.com/discordjs/discord.js/commit/d66d1133331b81563588db4500c63a18c3c3dfae))
# [@discordjs/builders@1.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.5.0...@discordjs/builders@1.6.0) - (2023-04-01)
## Bug Fixes
- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b))
## Features
- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b))
# [@discordjs/builders@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.4.0...@discordjs/builders@1.5.0) - (2023-03-12)
## Documentation
- **EmbedBuilder#spliceFields:** Fix a typo (#9159) ([4367ab9](https://github.com/discordjs/discord.js/commit/4367ab930227048868db3ed8437f6c4507ff32e1))
- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28))
## Features
- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38))
- **StringSelectMenu:** Add `spliceOptions()` (#8937) ([a6941d5](https://github.com/discordjs/discord.js/commit/a6941d536ce24ed2b5446a154cbc886b2b97c63a))
- Add support for nsfw commands (#7976) ([7a51344](https://github.com/discordjs/discord.js/commit/7a5134459c5f06864bf74631d83b96d9c21b72d8))
- Add `@discordjs/formatters` (#8889) ([3fca638](https://github.com/discordjs/discord.js/commit/3fca638a8470dcea2f79ddb9f18526dbc0017c88))
## Styling
- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b))
# [@discordjs/builders@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.3.0...@discordjs/builders@1.4.0) - (2022-11-28)
## Bug Fixes
- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4))
## Features
- New select menus (#8793) ([5152abf](https://github.com/discordjs/discord.js/commit/5152abf7285581abf7689e9050fdc56c4abb1e2b))
- Allow punctuation characters in context menus (#8783) ([b521366](https://github.com/discordjs/discord.js/commit/b5213664fa66746daab1673ebe2adf2db3d1522c))
## Typings
- **Formatters:** Allow boolean in `formatEmoji` (#8823) ([ec37f13](https://github.com/discordjs/discord.js/commit/ec37f137fd4fca0fdbdb8a5c83abf32362a8f285))
# [@discordjs/builders@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.2.0...@discordjs/builders@1.3.0) - (2022-10-08)
## Bug Fixes
- Allow adding forums to `channelTypes` (#8658) ([b1e190c](https://github.com/discordjs/discord.js/commit/b1e190c4f0773a1a739625f5b41026f593515370))
- **SlashCommandBuilder:** Missing methods in subcommand builder (#8583) ([1c5b78f](https://github.com/discordjs/discord.js/commit/1c5b78fd2130f09c951459cf4c2d637f46c3c2c9))
- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9))
## Documentation
- **builders/components:** Document constructors (#8636) ([8444576](https://github.com/discordjs/discord.js/commit/8444576f45da5fdddbf8ba2d91b4cb31a3b51c04))
- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0))
- Use remarks instead of `Note` in descriptions (#8597) ([f3ce4a7](https://github.com/discordjs/discord.js/commit/f3ce4a75d0c4eafc89a1f0ce9f4964bcbcdae6da))
## Features
- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2))
- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3))
- Add `chatInputApplicationCommandMention` formatter (#8546) ([d08a57c](https://github.com/discordjs/discord.js/commit/d08a57cadd9d69a734077cc1902d931ab10336db))
## Refactor
- Replace usage of deprecated `ChannelType`s (#8625) ([669c3cd](https://github.com/discordjs/discord.js/commit/669c3cd2566eac68ef38ab522dd6378ba761e8b3))
- Website components (#8600) ([c334157](https://github.com/discordjs/discord.js/commit/c3341570d983aea9ecc419979d5a01de658c9d67))
- Use `eslint-config-neon` for packages. (#8579) ([edadb9f](https://github.com/discordjs/discord.js/commit/edadb9fe5dfd9ff51a3cfc9b25cb242d3f9f5241))
## Testing
- Rename incorrect test (#8596) ([ce991dd](https://github.com/discordjs/discord.js/commit/ce991dd1d883f6785b5f4b4b3ac80ef21cb304e7))
## Typings
- **interactions:** Fix `{Slash,ContextMenu}CommandBuilder#toJSON` (#8568) ([b7eb96d](https://github.com/discordjs/discord.js/commit/b7eb96d45670616521fbcca28a657793d91605c7))
# [@discordjs/builders@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.1.0...@discordjs/builders@1.2.0) - (2022-08-22)
## Features
- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007))
- **website:** Show descriptions for `@typeParam` blocks (#8523) ([e475b63](https://github.com/discordjs/discord.js/commit/e475b63f257f6261d73cb89fee9ecbcdd84e2a6b))
- **website:** Show parameter descriptions (#8519) ([7f415a2](https://github.com/discordjs/discord.js/commit/7f415a2502bf7ce2025dbcfed9017b0635a19966))
- **WebSocketShard:** Support new resume url (#8480) ([bc06cc6](https://github.com/discordjs/discord.js/commit/bc06cc638d2f57ab5c600e8cdb6afc8eb2180166))
## Refactor
- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e))
# [@discordjs/builders@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.16.0...@discordjs/builders@1.1.0) - (2022-07-29)
## Bug Fixes
- Use proper format for `@link` text (#8384) ([2655639](https://github.com/discordjs/discord.js/commit/26556390a3800e954974a00c1328ff47d3e67e9a))
- **Formatters:** Add newline in `codeBlock` (#8369) ([5d8bd03](https://github.com/discordjs/discord.js/commit/5d8bd030d60ef364de3ef5f9963da8bda5c4efd4))
- **selectMenu:** Allow json to be used for select menu options (#8322) ([6a2d0d8](https://github.com/discordjs/discord.js/commit/6a2d0d8e96d157d5b85cee7f17bffdfff4240074))
## Documentation
- Use link tags (#8382) ([5494791](https://github.com/discordjs/discord.js/commit/549479131318c659f86f0eb18578d597e22522d3))
## Features
- Add channel & message URL formatters (#8371) ([a7deb8f](https://github.com/discordjs/discord.js/commit/a7deb8f89830ead6185c5fb46a49688b6d209ed1))
## Testing
- **builders:** Improve coverage (#8274) ([b7e6238](https://github.com/discordjs/discord.js/commit/b7e62380f2e6b9324d6bba9b9eaa5315080bf66a))
# [@discordjs/builders@0.16.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.15.0...@discordjs/builders@0.16.0) - (2022-07-17)
## Bug Fixes
- Slash command name regex (#8265) ([32f9056](https://github.com/discordjs/discord.js/commit/32f9056b15edede3bab07de96afb4b56d3a9ecca))
- **TextInputBuilder:** Parse `custom_id`, `label`, and `style` (#8216) ([2d9dfa3](https://github.com/discordjs/discord.js/commit/2d9dfa3c6ea4bb972da2f7e088d148b798c866d9))
## Documentation
- Add codecov coverage badge to readmes (#8226) ([f6db285](https://github.com/discordjs/discord.js/commit/f6db285c073898a749fe4591cbd4463d1896daf5))
## Features
- **builder:** Add max min length in string option (#8214) ([96c8d21](https://github.com/discordjs/discord.js/commit/96c8d21f95eb366c46ae23505ba9054f44821b25))
- Codecov (#8219) ([f10f4cd](https://github.com/discordjs/discord.js/commit/f10f4cdcd88ca6be7ec735ed3a415ba13da83db0))
- **docgen:** Update typedoc ([b3346f4](https://github.com/discordjs/discord.js/commit/b3346f4b9b3d4f96443506643d4631dc1c6d7b21))
- Website (#8043) ([127931d](https://github.com/discordjs/discord.js/commit/127931d1df7a2a5c27923c2f2151dbf3824e50cc))
- **docgen:** Typescript support ([3279b40](https://github.com/discordjs/discord.js/commit/3279b40912e6aa61507bedb7db15a2b8668de44b))
- Docgen package (#8029) ([8b979c0](https://github.com/discordjs/discord.js/commit/8b979c0245c42fd824d8e98745ee869f5360fc86))
## Refactor
- **builder:** Remove `unsafe*Builder`s (#8074) ([a4d1862](https://github.com/discordjs/discord.js/commit/a4d18629828234f43f03d1bd4851d4b727c6903b))
- Remove @sindresorhus/is as it's now esm only (#8133) ([c6f285b](https://github.com/discordjs/discord.js/commit/c6f285b7b089b004776fbeb444fe973a68d158d8))
- Move all the config files to root (#8033) ([769ea0b](https://github.com/discordjs/discord.js/commit/769ea0bfe78c4f1d413c6b397c604ffe91e39c6a))
## Typings
- Remove expect error (#8242) ([7e6dbaa](https://github.com/discordjs/discord.js/commit/7e6dbaaed900c07d1a04e23bbbf9cd0d1b0501c5))
- **builder:** Remove casting (#8241) ([8198da5](https://github.com/discordjs/discord.js/commit/8198da5cd0898e06954615a2287853321e7ebbd4))
# [@discordjs/builders@0.15.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.14.0...@discordjs/builders@0.15.0) - (2022-06-06)
## Features
- Allow builders to accept rest params and arrays (#7874) ([ad75be9](https://github.com/discordjs/discord.js/commit/ad75be9a9cf90c8624495df99b75177e6c24022f))
- Use vitest instead of jest for more speed ([8d8e6c0](https://github.com/discordjs/discord.js/commit/8d8e6c03decd7352a2aa180f6e5bc1a13602539b))
- Add scripts package for locally used scripts ([f2ae1f9](https://github.com/discordjs/discord.js/commit/f2ae1f9348bfd893332a9060f71a8a5f272a1b8b))
# [@discordjs/builders@0.14.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.13.0...@discordjs/builders@0.14.0) - (2022-06-04)
## Bug Fixes
- **builders:** Leftover invalid null type ([8a7cd10](https://github.com/discordjs/discord.js/commit/8a7cd10554a2a71cd2fe7f6a177b5f4f43464348))
- **SlashCommandBuilder:** Import `Permissions` correctly (#7921) ([7ce641d](https://github.com/discordjs/discord.js/commit/7ce641d33a4af6586d5e7beffbe7d38619dcf1a2))
- Add localizations for subcommand builders and option choices (#7862) ([c1b5e73](https://github.com/discordjs/discord.js/commit/c1b5e731daa9cbbfca03a046e47cb1221ee1ed7c))
## Features
- Export types from `interactions/slashCommands/mixins` (#7942) ([68d5169](https://github.com/discordjs/discord.js/commit/68d5169f66c96f8fe5be17a1c01cdd5155607ab2))
- **builders:** Add new command permissions v2 (#7861) ([de3f157](https://github.com/discordjs/discord.js/commit/de3f1573f07dda294cc0fbb1ca4b659eb2388a12))
- **builders:** Improve embed errors and predicates (#7795) ([ec8d87f](https://github.com/discordjs/discord.js/commit/ec8d87f93272cc9987f9613735c0361680c4ed1e))
## Refactor
- Use arrays instead of rest parameters for builders (#7759) ([29293d7](https://github.com/discordjs/discord.js/commit/29293d7bbb5ed463e52e5a5853817e5a09cf265b))
## Styling
- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629))
# [@discordjs/builders@0.13.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.12.0...@discordjs/builders@0.13.0) - (2022-04-17)
## Bug Fixes
- Validate select menu options (#7566) ([b1d63d9](https://github.com/discordjs/discord.js/commit/b1d63d919a61f309ac89f27016b0f148678dac2b))
- **SelectMenu:** Set `placeholder` max to 150 (#7538) ([dcd4797](https://github.com/discordjs/discord.js/commit/dcd479767b6ec980a373f2ea1f22754f41661c1e))
- Only check `instanceof Component` once (#7546) ([0aa4851](https://github.com/discordjs/discord.js/commit/0aa48516a4e33497e8e8dc50da164a57cdee09d3))
- **builders:** Allow negative min/max value of number/integer option (#7484) ([3baa340](https://github.com/discordjs/discord.js/commit/3baa340821b8ecf8a16253bc0917a1033250d7c9))
- **components:** SetX should take rest parameters (#7461) ([3617359](https://github.com/discordjs/discord.js/commit/36173590a712f041b087b7882054805a8bd42dae))
- Unsafe embed builder field normalization (#7418) ([b936103](https://github.com/discordjs/discord.js/commit/b936103395121cb21a8c616f669ddab1d2efb0f1))
- Fix some typos (#7393) ([92a04f4](https://github.com/discordjs/discord.js/commit/92a04f4d98f6c6760214034cc8f5a1eaa78893c7))
- **builders:** Make type optional in constructor (#7391) ([4abb28c](https://github.com/discordjs/discord.js/commit/4abb28c0a1256c57a60369a6b8ec9e98c265b489))
- Don't create new instances of builders classes (#7343) ([d6b56d0](https://github.com/discordjs/discord.js/commit/d6b56d0080c4c5f8ace731f1e8bcae0c9d3fb5a5))
## Documentation
- Completely fix builders example link (#7543) ([1a14c0c](https://github.com/discordjs/discord.js/commit/1a14c0ca562ea173d363a770a0437209f461fd23))
- Add slash command builders example, fixes #7338 (#7339) ([3ae6f3c](https://github.com/discordjs/discord.js/commit/3ae6f3c313091151245d6e6b52337b459ecfc765))
## Features
- Slash command localization for builders (#7683) ([40b9a1d](https://github.com/discordjs/discord.js/commit/40b9a1d67d0b508ec593e030913acd8161cd17f8))
- Add API v10 support (#7477) ([72577c4](https://github.com/discordjs/discord.js/commit/72577c4bfd02524a27afb6ff4aebba9301a690d3))
- Add support for module: NodeNext in TS and ESM (#7598) ([8f1986a](https://github.com/discordjs/discord.js/commit/8f1986a6aa98365e09b00e84ad5f9f354ab61f3d))
- Add Modals and Text Inputs (#7023) ([ed92015](https://github.com/discordjs/discord.js/commit/ed920156344233241a21b0c0b99736a3a855c23c))
- Add missing `v13` component methods (#7466) ([f7257f0](https://github.com/discordjs/discord.js/commit/f7257f07655076eabfe355cb6a53260b39ca9670))
- **builders:** Add attachment command option type (#7203) ([ae0f35f](https://github.com/discordjs/discord.js/commit/ae0f35f51d68dfa5a7dc43d161ef9365171debdb))
- **components:** Add unsafe message component builders (#7387) ([6b6222b](https://github.com/discordjs/discord.js/commit/6b6222bf513d1ee8cd98fba0ad313def560b864f))
- **embed:** Add setFields (#7322) ([bcc5cda](https://github.com/discordjs/discord.js/commit/bcc5cda8a902ddb28c7e3578e0f29b4272832624))
## Refactor
- Remove nickname parsing (#7736) ([78a3afc](https://github.com/discordjs/discord.js/commit/78a3afcd7fdac358e06764cc0d675e1215c785f3))
- Replace zod with shapeshift (#7547) ([3c0bbac](https://github.com/discordjs/discord.js/commit/3c0bbac82fa9988af4a62ff00c66d149fbe6b921))
- Remove store channels (#7634) ([aedddb8](https://github.com/discordjs/discord.js/commit/aedddb875e740e1f1bd77f06ce1b361fd3b7bc36))
- Allow builders to accept emoji strings (#7616) ([fb9a9c2](https://github.com/discordjs/discord.js/commit/fb9a9c221121ee1c7986f9c775b77b9691a0ae15))
- Don't return builders from API data (#7584) ([549716e](https://github.com/discordjs/discord.js/commit/549716e4fcec89ca81216a6d22aa8e623175e37a))
- Remove obsolete builder methods (#7590) ([10607db](https://github.com/discordjs/discord.js/commit/10607dbdafe257c5cbf5b952b7eecec4919e8b4a))
- **Embed:** Remove add field (#7522) ([8478d2f](https://github.com/discordjs/discord.js/commit/8478d2f4de9ac013733850cbbc67902f7c5abc55))
- Make `data` public in builders (#7486) ([ba31203](https://github.com/discordjs/discord.js/commit/ba31203a0ad96e0a00f8312c397889351e4c5cfd))
- **embed:** Remove array support in favor of rest params (#7498) ([b3fa2ec](https://github.com/discordjs/discord.js/commit/b3fa2ece402839008738ad3adce3db958445838d))
- **components:** Default set boolean methods to true (#7502) ([b122149](https://github.com/discordjs/discord.js/commit/b12214922cea2f43afbe6b1555a74a3c8e16f798))
- Make public builder props getters (#7422) ([e8252ed](https://github.com/discordjs/discord.js/commit/e8252ed3b981a4b7e4013f12efadd2f5d9318d3e))
- **builders-methods:** Make methods consistent (#7395) ([f495364](https://github.com/discordjs/discord.js/commit/f4953647ff9f39127978c73bf8a62c08462802ca))
- Remove conditional autocomplete option return types (#7396) ([0909824](https://github.com/discordjs/discord.js/commit/09098240bfb13b8afafa4ab549f06d236e0ff1c9))
- **embed:** Mark properties as readonly (#7332) ([31768fc](https://github.com/discordjs/discord.js/commit/31768fcd69ed5b4566a340bda89ce881418e8272))
## Typings
- Fix regressions (#7649) ([5748dbe](https://github.com/discordjs/discord.js/commit/5748dbe08783beb80c526de38ccd105eb0e82664))
# [@discordjs/builders@0.12.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.11.0...@discordjs/builders@0.12.0) - (2022-01-24)
## Bug Fixes
- **builders:** Dont export `Button` component stuff twice (#7289) ([86d9d06](https://github.com/discordjs/discord.js/commit/86d9d0674347c08d056cd054cb4ce4253195bf94))
## Documentation
- **SlashCommandSubcommands:** Updating old links from Discord developer portal (#7224) ([bd7a6f2](https://github.com/discordjs/discord.js/commit/bd7a6f265212624199fb0b2ddc8ece39759c63de))
## Features
- Add components to /builders (#7195) ([2bb40fd](https://github.com/discordjs/discord.js/commit/2bb40fd767cf5918e3ba422ff73082734bfa05b0))
## Typings
- Make `required` a boolean (#7307) ([c10afea](https://github.com/discordjs/discord.js/commit/c10afeadc702ab98bec5e077b3b92494a9596f9c))

191
node_modules/@discordjs/builders/LICENSE generated vendored Normal file
View file

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler
Copyright 2021 Vlad Frangu
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

71
node_modules/@discordjs/builders/README.md generated vendored Normal file
View file

@ -0,0 +1,71 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://www.npmjs.com/package/@discordjs/builders"><img src="https://img.shields.io/npm/v/@discordjs/builders.svg?maxAge=3600" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/@discordjs/builders"><img src="https://img.shields.io/npm/dt/@discordjs/builders.svg?maxAge=3600" alt="npm downloads" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=builders" alt="Code coverage" /></a>
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
</p>
</div>
## About
`@discordjs/builders` is a utility package for easily building Discord API payloads.
## Installation
**Node.js 16.9.0 or newer is required.**
```sh
npm install @discordjs/builders
yarn add @discordjs/builders
pnpm add @discordjs/builders
```
## Examples
You can find examples of how to use the builders in the [Slash Command Builders][example] examples.
## Links
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library.
- [discord.js Discord server][discord]
- [Discord API Discord server][discord-api]
- [GitHub][source]
- [npm][npm]
- [Related libraries][related-libs]
## Contributing
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
[documentation][documentation].
See [the contribution guide][contributing] if you'd like to submit a PR.
## Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord].
[example]: https://github.com/discordjs/discord.js/blob/main/packages/builders/docs/examples/Slash%20Command%20Builders.md
[website]: https://discord.js.org
[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website
[documentation]: https://discord.js.org/docs/packages/builders/stable
[guide]: https://discordjs.guide/
[guide-source]: https://github.com/discordjs/guide
[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html
[discord]: https://discord.gg/djs
[discord-api]: https://discord.gg/discord-api
[source]: https://github.com/discordjs/discord.js/tree/main/packages/builders
[npm]: https://www.npmjs.com/package/@discordjs/builders
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md

1948
node_modules/@discordjs/builders/dist/index.d.ts generated vendored Normal file

File diff suppressed because it is too large Load diff

2562
node_modules/@discordjs/builders/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/builders/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2490
node_modules/@discordjs/builders/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/builders/dist/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

89
node_modules/@discordjs/builders/package.json generated vendored Normal file
View file

@ -0,0 +1,89 @@
{
"name": "@discordjs/builders",
"version": "1.6.3",
"description": "A set of builders that you can use when creating your bot",
"scripts": {
"test": "vitest run",
"build": "tsup",
"build:docs": "tsc -p tsconfig.docs.json && yarn downlevel-dts ./dist-docs ./dist-docs",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"fmt": "yarn format",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/builders/*'",
"release": "cliff-jumper"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"directories": {
"lib": "src",
"test": "__tests__"
},
"files": [
"dist"
],
"contributors": [
"Vlad Frangu <kingdgrizzle@gmail.com>",
"Crawl <icrawltogo@gmail.com>",
"Amish Shah <amishshah.2k@gmail.com>",
"SpaceEEC <spaceeec@yahoo.com>",
"Aura Román <kyradiscord@gmail.com>"
],
"license": "Apache-2.0",
"keywords": [
"discord",
"api",
"bot",
"client",
"node",
"discordapp",
"discordjs"
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/builders"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/formatters": "^0.3.1",
"@discordjs/util": "^0.3.1",
"@sapphire/shapeshift": "^3.8.2",
"discord-api-types": "^0.37.41",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.3",
"tslib": "^2.5.0"
},
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.6",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"downlevel-dts": "^0.11.0",
"esbuild-plugin-version-injector": "^1.1.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

152
node_modules/@discordjs/collection/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,152 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@discordjs/collection@1.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.0...@discordjs/collection@1.5.1) - (2023-05-01)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Documentation
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
# [@discordjs/collection@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.4.0...@discordjs/collection@1.5.0) - (2023-04-01)
## Bug Fixes
- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b))
## Features
- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b))
## Refactor
- **collection:** Fix/silence linter warnings (#9266) ([d6f4e60](https://github.com/discordjs/discord.js/commit/d6f4e60efd1a1796fc84dbbfbac4f9790e480a1c))
# [@discordjs/collection@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.3.0...@discordjs/collection@1.4.0) - (2023-03-12)
## Documentation
- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28))
## Features
- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38))
## Refactor
- Compare with `undefined` directly (#9191) ([869153c](https://github.com/discordjs/discord.js/commit/869153c3fdf155783e7c0ecebd3627b087c3a026))
# [@discordjs/collection@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.2.0...@discordjs/collection@1.3.0) - (2022-11-28)
## Bug Fixes
- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4))
## Features
- Add `Collection#subtract()` (#8393) ([291f36c](https://github.com/discordjs/discord.js/commit/291f36cd736b5dea058145a1335bf7c78ec1d81d))
# [@discordjs/collection@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.1.0...@discordjs/collection@1.2.0) - (2022-10-08)
## Bug Fixes
- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9))
## Documentation
- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0))
- Remove xml tag from collection#find (#8550) ([4032457](https://github.com/discordjs/discord.js/commit/40324574ebea9894cadcc967e0db0e4e21d62768))
## Features
- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2))
## Refactor
- Website components (#8600) ([c334157](https://github.com/discordjs/discord.js/commit/c3341570d983aea9ecc419979d5a01de658c9d67))
- Use `eslint-config-neon` for packages. (#8579) ([edadb9f](https://github.com/discordjs/discord.js/commit/edadb9fe5dfd9ff51a3cfc9b25cb242d3f9f5241))
## Typings
- **Collection:** Make fn return type unknown (#8676) ([822b7f2](https://github.com/discordjs/discord.js/commit/822b7f234af053c8f917b0a998b82abfccd33801))
# [@discordjs/collection@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.0.1...@discordjs/collection@1.1.0) - (2022-08-22)
## Bug Fixes
- Use proper format for `@link` text (#8384) ([2655639](https://github.com/discordjs/discord.js/commit/26556390a3800e954974a00c1328ff47d3e67e9a))
## Documentation
- Fence examples in codeblocks ([193b252](https://github.com/discordjs/discord.js/commit/193b252672440a860318d3c2968aedd9cb88e0ce))
- Use link tags (#8382) ([5494791](https://github.com/discordjs/discord.js/commit/549479131318c659f86f0eb18578d597e22522d3))
## Features
- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007))
- **website:** Show descriptions for `@typeParam` blocks (#8523) ([e475b63](https://github.com/discordjs/discord.js/commit/e475b63f257f6261d73cb89fee9ecbcdd84e2a6b))
## Refactor
- **website:** Adjust typography (#8503) ([0f83402](https://github.com/discordjs/discord.js/commit/0f834029850d2448981596cf082ff59917018d66))
- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e))
# [@discordjs/collection@0.8.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.7.0...@discordjs/collection@0.8.0) - (2022-07-17)
## Bug Fixes
- **Collection:** Make error messages consistent (#8224) ([5bd6b28](https://github.com/discordjs/discord.js/commit/5bd6b28b3ebfced1cb9d23e83bd7c0def7a12404))
- Check for function type (#8064) ([3bb9c0e](https://github.com/discordjs/discord.js/commit/3bb9c0e5c37311044ff41761b572ac4f91cda57c))
## Documentation
- Add codecov coverage badge to readmes (#8226) ([f6db285](https://github.com/discordjs/discord.js/commit/f6db285c073898a749fe4591cbd4463d1896daf5))
## Features
- Codecov (#8219) ([f10f4cd](https://github.com/discordjs/discord.js/commit/f10f4cdcd88ca6be7ec735ed3a415ba13da83db0))
- **docgen:** Update typedoc ([b3346f4](https://github.com/discordjs/discord.js/commit/b3346f4b9b3d4f96443506643d4631dc1c6d7b21))
- Website (#8043) ([127931d](https://github.com/discordjs/discord.js/commit/127931d1df7a2a5c27923c2f2151dbf3824e50cc))
- **docgen:** Typescript support ([3279b40](https://github.com/discordjs/discord.js/commit/3279b40912e6aa61507bedb7db15a2b8668de44b))
- Docgen package (#8029) ([8b979c0](https://github.com/discordjs/discord.js/commit/8b979c0245c42fd824d8e98745ee869f5360fc86))
- Use vitest instead of jest for more speed ([8d8e6c0](https://github.com/discordjs/discord.js/commit/8d8e6c03decd7352a2aa180f6e5bc1a13602539b))
- Add scripts package for locally used scripts ([f2ae1f9](https://github.com/discordjs/discord.js/commit/f2ae1f9348bfd893332a9060f71a8a5f272a1b8b))
## Refactor
- **collection:** Remove `default` property (#8055) ([c8f1690](https://github.com/discordjs/discord.js/commit/c8f1690896f55f06e05a83704262783cfc2bb91d))
- **collection:** Remove default export (#8053) ([16810f3](https://github.com/discordjs/discord.js/commit/16810f3e410bf35ed7e6e7412d517ea74c792c5d))
- Move all the config files to root (#8033) ([769ea0b](https://github.com/discordjs/discord.js/commit/769ea0bfe78c4f1d413c6b397c604ffe91e39c6a))
## Testing
- **collection:** Improve coverage (#8222) ([a51f721](https://github.com/discordjs/discord.js/commit/a51f7215eca67a0f46fba8b2d706f7ec6f6dc228))
# [@discordjs/collection@0.7.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.6.0...@discordjs/collection@0.7.0) - (2022-06-04)
## Styling
- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629))
# [@discordjs/collection@0.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.5.0...@discordjs/collection@0.6.0) - (2022-04-17)
## Features
- Add support for module: NodeNext in TS and ESM (#7598) ([8f1986a](https://github.com/discordjs/discord.js/commit/8f1986a6aa98365e09b00e84ad5f9f354ab61f3d))
- **builders:** Add attachment command option type (#7203) ([ae0f35f](https://github.com/discordjs/discord.js/commit/ae0f35f51d68dfa5a7dc43d161ef9365171debdb))
- **Collection:** Add merging functions (#7299) ([e4bd07b](https://github.com/discordjs/discord.js/commit/e4bd07b2394f227ea06b72eb6999de9ab3127b25))
# [@discordjs/collection@0.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.4.0...@discordjs/collection@0.5.0) - (2022-01-24)
## Refactor
- Make `intersect` perform a true intersection (#7211) ([d8efba2](https://github.com/discordjs/discord.js/commit/d8efba24e09aa2a8dbf028fc57a561a56e7833fd))
## Typings
- Add `ReadonlyCollection` (#7245) ([db25f52](https://github.com/discordjs/discord.js/commit/db25f529b26d7c819c1c42ad3e26c2263ea2da0e))
- **Collection:** Union types on `intersect` and `difference` (#7196) ([1f9b922](https://github.com/discordjs/discord.js/commit/1f9b9225f2066e9cc66c3355417139fd25cc403c))

191
node_modules/@discordjs/collection/LICENSE generated vendored Normal file
View file

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler
Copyright 2015 Amish Shah
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

66
node_modules/@discordjs/collection/README.md generated vendored Normal file
View file

@ -0,0 +1,66 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://www.npmjs.com/package/@discordjs/collection"><img src="https://img.shields.io/npm/v/@discordjs/collection.svg?maxAge=3600" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/@discordjs/collection"><img src="https://img.shields.io/npm/dt/@discordjs/collection.svg?maxAge=3600" alt="npm downloads" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=collection" alt="Code coverage" /></a>
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
</p>
</div>
## About
`@discordjs/collection` is a powerful utility data structure used in discord.js.
## Installation
**Node.js 16.9.0 or newer is required.**
```sh
npm install @discordjs/collection
yarn add @discordjs/collection
pnpm add @discordjs/collection
```
## Links
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library.
- [discord.js Discord server][discord]
- [Discord API Discord server][discord-api]
- [GitHub][source]
- [npm][npm]
- [Related libraries][related-libs]
## Contributing
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
[documentation][documentation].
See [the contribution guide][contributing] if you'd like to submit a PR.
## Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord].
[website]: https://discord.js.org
[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website
[documentation]: https://discord.js.org/docs/packages/collection/stable
[guide]: https://discordjs.guide/
[guide-source]: https://github.com/discordjs/guide
[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html
[discord]: https://discord.gg/djs
[discord-api]: https://discord.gg/discord-api
[source]: https://github.com/discordjs/discord.js/tree/main/packages/collection
[npm]: https://www.npmjs.com/package/@discordjs/collection
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md

457
node_modules/@discordjs/collection/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,457 @@
/**
* @internal
*/
interface CollectionConstructor {
new (): Collection<unknown, unknown>;
new <K, V>(entries?: readonly (readonly [K, V])[] | null): Collection<K, V>;
new <K, V>(iterable: Iterable<readonly [K, V]>): Collection<K, V>;
readonly prototype: Collection<unknown, unknown>;
readonly [Symbol.species]: CollectionConstructor;
}
/**
* Represents an immutable version of a collection
*/
type ReadonlyCollection<K, V> = Omit<Collection<K, V>, 'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'> & ReadonlyMap<K, V>;
/**
* Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself
*
* @internal
*/
interface Collection<K, V> extends Map<K, V> {
constructor: CollectionConstructor;
}
/**
* A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has
* an ID, for significantly improved performance and ease-of-use.
*
* @typeParam K - The key type this collection holds
* @typeParam V - The value type this collection holds
*/
declare class Collection<K, V> extends Map<K, V> {
/**
* Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
*
* @param key - The key to get if it exists, or set otherwise
* @param defaultValueGenerator - A function that generates the default value
* @example
* ```ts
* collection.ensure(guildId, () => defaultGuildConfig);
* ```
*/
ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V;
/**
* Checks if all of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if all of the elements exist, `false` if at least one does not exist.
*/
hasAll(...keys: K[]): boolean;
/**
* Checks if any of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if any of the elements exist, `false` if none exist.
*/
hasAny(...keys: K[]): boolean;
/**
* Obtains the first value(s) in this collection.
*
* @param amount - Amount of values to obtain from the beginning
* @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative
*/
first(): V | undefined;
first(amount: number): V[];
/**
* Obtains the first key(s) in this collection.
*
* @param amount - Amount of keys to obtain from the beginning
* @returns A single key if no amount is provided or an array of keys, starting from the end if
* amount is negative
*/
firstKey(): K | undefined;
firstKey(amount: number): K[];
/**
* Obtains the last value(s) in this collection.
*
* @param amount - Amount of values to obtain from the end
* @returns A single value if no amount is provided or an array of values, starting from the start if
* amount is negative
*/
last(): V | undefined;
last(amount: number): V[];
/**
* Obtains the last key(s) in this collection.
*
* @param amount - Amount of keys to obtain from the end
* @returns A single key if no amount is provided or an array of keys, starting from the start if
* amount is negative
*/
lastKey(): K | undefined;
lastKey(amount: number): K[];
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the item at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the element to obtain
*/
at(index: number): V | undefined;
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the key at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the key to obtain
*/
keyAt(index: number): K | undefined;
/**
* Obtains unique random value(s) from this collection.
*
* @param amount - Amount of values to obtain randomly
* @returns A single value if no amount is provided or an array of values
*/
random(): V | undefined;
random(amount: number): V[];
/**
* Obtains unique random key(s) from this collection.
*
* @param amount - Amount of keys to obtain randomly
* @returns A single key if no amount is provided or an array
*/
randomKey(): K | undefined;
randomKey(amount: number): K[];
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}
* but returns a Collection instead of an Array.
*/
reverse(): this;
/**
* Searches for a single item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.
* All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you
* should use the `get` method. See
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.
*
* @param fn - The function to test with (should return boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.find(user => user.username === 'Bob');
* ```
*/
find<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;
find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;
find<This, V2 extends V>(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): V2 | undefined;
find<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;
/**
* Searches for the key of a single item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},
* but returns the key rather than the positional index.
*
* @param fn - The function to test with (should return boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.findKey(user => user.username === 'Bob');
* ```
*/
findKey<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;
findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;
findKey<This, K2 extends K>(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): K2 | undefined;
findKey<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;
/**
* Removes items that satisfy the provided filter function.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing function
* @returns The number of removed entries
*/
sweep(fn: (value: V, key: K, collection: this) => unknown): number;
sweep<T>(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;
/**
* Identical to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},
* but returns a Collection instead of an Array.
*
* @param fn - The function to test with (should return boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.filter(user => user.username === 'Bob');
* ```
*/
filter<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): Collection<K2, V>;
filter<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): Collection<K, V2>;
filter(fn: (value: V, key: K, collection: this) => unknown): Collection<K, V>;
filter<This, K2 extends K>(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): Collection<K2, V>;
filter<This, V2 extends V>(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): Collection<K, V2>;
filter<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection<K, V>;
/**
* Partitions the collection into two collections where the first collection
* contains the items that passed and the second contains the items that failed.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* const [big, small] = collection.partition(guild => guild.memberCount > 250);
* ```
*/
partition<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): [Collection<K2, V>, Collection<Exclude<K, K2>, V>];
partition<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): [Collection<K, V2>, Collection<K, Exclude<V, V2>>];
partition(fn: (value: V, key: K, collection: this) => unknown): [Collection<K, V>, Collection<K, V>];
partition<This, K2 extends K>(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): [Collection<K2, V>, Collection<Exclude<K, K2>, V>];
partition<This, V2 extends V>(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): [Collection<K, V2>, Collection<K, Exclude<V, V2>>];
partition<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): [Collection<K, V>, Collection<K, V>];
/**
* Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.
*
* @param fn - Function that produces a new Collection
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.flatMap(guild => guild.members.cache);
* ```
*/
flatMap<T>(fn: (value: V, key: K, collection: this) => Collection<K, T>): Collection<K, T>;
flatMap<T, This>(fn: (this: This, value: V, key: K, collection: this) => Collection<K, T>, thisArg: This): Collection<K, T>;
/**
* Maps each item to another value into an array. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.
*
* @param fn - Function that produces an element of the new array, taking three arguments
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.map(user => user.tag);
* ```
*/
map<T>(fn: (value: V, key: K, collection: this) => T): T[];
map<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];
/**
* Maps each item to another value into a collection. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.
*
* @param fn - Function that produces an element of the new collection, taking three arguments
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.mapValues(user => user.tag);
* ```
*/
mapValues<T>(fn: (value: V, key: K, collection: this) => T): Collection<K, T>;
mapValues<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection<K, T>;
/**
* Checks if there exists an item that passes a test. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.some(user => user.discriminator === '0000');
* ```
*/
some(fn: (value: V, key: K, collection: this) => unknown): boolean;
some<T>(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;
/**
* Checks if all items passes a test. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.every(user => !user.bot);
* ```
*/
every<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): this is Collection<K2, V>;
every<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): this is Collection<K, V2>;
every(fn: (value: V, key: K, collection: this) => unknown): boolean;
every<This, K2 extends K>(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): this is Collection<K2, V>;
every<This, V2 extends V>(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): this is Collection<K, V2>;
every<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;
/**
* Applies a function to produce a single value. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
* and `collection`
* @param initialValue - Starting value for the accumulator
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
reduce<T>(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T;
/**
* Identical to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},
* but returns the collection instead of undefined.
*
* @param fn - Function to execute for each element
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection
* .each(user => console.log(user.username))
* .filter(user => user.bot)
* .each(user => console.log(user.username));
* ```
*/
each(fn: (value: V, key: K, collection: this) => void): this;
each<T>(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;
/**
* Runs a function on the collection and returns the collection.
*
* @param fn - Function to execute
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection
* .tap(coll => console.log(coll.size))
* .filter(user => user.bot)
* .tap(coll => console.log(coll.size))
* ```
*/
tap(fn: (collection: this) => void): this;
tap<T>(fn: (this: T, collection: this) => void, thisArg: T): this;
/**
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
clone(): Collection<K, V>;
/**
* Combines this collection with others into a new collection. None of the source collections are modified.
*
* @param collections - Collections to merge
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
concat(...collections: ReadonlyCollection<K, V>[]): Collection<K, V>;
/**
* Checks if this collection shares identical items with another.
* This is different to checking for equality using equal-signs, because
* the collections may be different objects, but contain the same data.
*
* @param collection - Collection to compare with
* @returns Whether the collections have identical contents
*/
equals(collection: ReadonlyCollection<K, V>): boolean;
/**
* The sort method sorts the items of a collection in place and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sort(compareFunction?: Comparator<K, V>): this;
/**
* The intersect method returns a new structure containing items where the keys and values are present in both original structures.
*
* @param other - The other Collection to filter against
*/
intersect<T>(other: ReadonlyCollection<K, T>): Collection<K, T>;
/**
* The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.
*
* @param other - The other Collection to filter against
*/
subtract<T>(other: ReadonlyCollection<K, T>): Collection<K, V>;
/**
* The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.
*
* @param other - The other Collection to filter against
*/
difference<T>(other: ReadonlyCollection<K, T>): Collection<K, T | V>;
/**
* Merges two Collections together into a new Collection.
*
* @param other - The other Collection to merge with
* @param whenInSelf - Function getting the result if the entry only exists in this Collection
* @param whenInOther - Function getting the result if the entry only exists in the other Collection
* @param whenInBoth - Function getting the result if the entry exists in both Collections
* @example
* ```ts
* // Sums up the entries in two collections.
* coll.merge(
* other,
* x => ({ keep: true, value: x }),
* y => ({ keep: true, value: y }),
* (x, y) => ({ keep: true, value: x + y }),
* );
* ```
* @example
* ```ts
* // Intersects two collections in a left-biased manner.
* coll.merge(
* other,
* x => ({ keep: false }),
* y => ({ keep: false }),
* (x, _) => ({ keep: true, value: x }),
* );
* ```
*/
merge<T, R>(other: ReadonlyCollection<K, T>, whenInSelf: (value: V, key: K) => Keep<R>, whenInOther: (valueOther: T, key: K) => Keep<R>, whenInBoth: (value: V, valueOther: T, key: K) => Keep<R>): Collection<K, R>;
/**
* The sorted method sorts the items of a collection and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value,
* according to the string conversion of each element.
* @example
* ```ts
* collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sorted(compareFunction?: Comparator<K, V>): Collection<K, V>;
toJSON(): V[];
private static defaultSort;
/**
* Creates a Collection from a list of entries.
*
* @param entries - The list of entries
* @param combine - Function to combine an existing entry with a new one
* @example
* ```ts
* Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
* // returns Collection { "a" => 3, "b" => 2 }
* ```
*/
static combineEntries<K, V>(entries: Iterable<[K, V]>, combine: (firstValue: V, secondValue: V, key: K) => V): Collection<K, V>;
}
/**
* @internal
*/
type Keep<V> = {
keep: false;
} | {
keep: true;
value: V;
};
/**
* @internal
*/
type Comparator<K, V> = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;
/**
* The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version
* that you are currently using.
*/
declare const version: string;
export { Collection, CollectionConstructor, Comparator, Keep, ReadonlyCollection, version };

548
node_modules/@discordjs/collection/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,548 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
Collection: () => Collection,
version: () => version
});
module.exports = __toCommonJS(src_exports);
// src/collection.ts
var Collection = class extends Map {
/**
* Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
*
* @param key - The key to get if it exists, or set otherwise
* @param defaultValueGenerator - A function that generates the default value
* @example
* ```ts
* collection.ensure(guildId, () => defaultGuildConfig);
* ```
*/
ensure(key, defaultValueGenerator) {
if (this.has(key))
return this.get(key);
if (typeof defaultValueGenerator !== "function")
throw new TypeError(`${defaultValueGenerator} is not a function`);
const defaultValue = defaultValueGenerator(key, this);
this.set(key, defaultValue);
return defaultValue;
}
/**
* Checks if all of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if all of the elements exist, `false` if at least one does not exist.
*/
hasAll(...keys) {
return keys.every((key) => super.has(key));
}
/**
* Checks if any of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if any of the elements exist, `false` if none exist.
*/
hasAny(...keys) {
return keys.some((key) => super.has(key));
}
first(amount) {
if (amount === void 0)
return this.values().next().value;
if (amount < 0)
return this.last(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.values();
return Array.from({ length: amount }, () => iter.next().value);
}
firstKey(amount) {
if (amount === void 0)
return this.keys().next().value;
if (amount < 0)
return this.lastKey(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.keys();
return Array.from({ length: amount }, () => iter.next().value);
}
last(amount) {
const arr = [...this.values()];
if (amount === void 0)
return arr[arr.length - 1];
if (amount < 0)
return this.first(amount * -1);
if (!amount)
return [];
return arr.slice(-amount);
}
lastKey(amount) {
const arr = [...this.keys()];
if (amount === void 0)
return arr[arr.length - 1];
if (amount < 0)
return this.firstKey(amount * -1);
if (!amount)
return [];
return arr.slice(-amount);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the item at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the element to obtain
*/
at(index) {
index = Math.floor(index);
const arr = [...this.values()];
return arr.at(index);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the key at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the key to obtain
*/
keyAt(index) {
index = Math.floor(index);
const arr = [...this.keys()];
return arr.at(index);
}
random(amount) {
const arr = [...this.values()];
if (amount === void 0)
return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount)
return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
() => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
);
}
randomKey(amount) {
const arr = [...this.keys()];
if (amount === void 0)
return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount)
return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
() => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}
* but returns a Collection instead of an Array.
*/
reverse() {
const entries = [...this.entries()].reverse();
this.clear();
for (const [key, value] of entries)
this.set(key, value);
return this;
}
find(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return val;
}
return void 0;
}
findKey(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return key;
}
return void 0;
}
sweep(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const previousSize = this.size;
for (const [key, val] of this) {
if (fn(val, key, this))
this.delete(key);
}
return previousSize - this.size;
}
filter(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const results = new this.constructor[Symbol.species]();
for (const [key, val] of this) {
if (fn(val, key, this))
results.set(key, val);
}
return results;
}
partition(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const results = [
new this.constructor[Symbol.species](),
new this.constructor[Symbol.species]()
];
for (const [key, val] of this) {
if (fn(val, key, this)) {
results[0].set(key, val);
} else {
results[1].set(key, val);
}
}
return results;
}
flatMap(fn, thisArg) {
const collections = this.map(fn, thisArg);
return new this.constructor[Symbol.species]().concat(...collections);
}
map(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const iter = this.entries();
return Array.from({ length: this.size }, () => {
const [key, value] = iter.next().value;
return fn(value, key, this);
});
}
mapValues(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const coll = new this.constructor[Symbol.species]();
for (const [key, val] of this)
coll.set(key, fn(val, key, this));
return coll;
}
some(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return true;
}
return false;
}
every(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (!fn(val, key, this))
return false;
}
return true;
}
/**
* Applies a function to produce a single value. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
* and `collection`
* @param initialValue - Starting value for the accumulator
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
reduce(fn, initialValue) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
let accumulator;
if (initialValue !== void 0) {
accumulator = initialValue;
for (const [key, val] of this)
accumulator = fn(accumulator, val, key, this);
return accumulator;
}
let first = true;
for (const [key, val] of this) {
if (first) {
accumulator = val;
first = false;
continue;
}
accumulator = fn(accumulator, val, key, this);
}
if (first) {
throw new TypeError("Reduce of empty collection with no initial value");
}
return accumulator;
}
each(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, value] of this) {
fn(value, key, this);
}
return this;
}
tap(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
fn(this);
return this;
}
/**
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
clone() {
return new this.constructor[Symbol.species](this);
}
/**
* Combines this collection with others into a new collection. None of the source collections are modified.
*
* @param collections - Collections to merge
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
concat(...collections) {
const newColl = this.clone();
for (const coll of collections) {
for (const [key, val] of coll)
newColl.set(key, val);
}
return newColl;
}
/**
* Checks if this collection shares identical items with another.
* This is different to checking for equality using equal-signs, because
* the collections may be different objects, but contain the same data.
*
* @param collection - Collection to compare with
* @returns Whether the collections have identical contents
*/
equals(collection) {
if (!collection)
return false;
if (this === collection)
return true;
if (this.size !== collection.size)
return false;
for (const [key, value] of this) {
if (!collection.has(key) || value !== collection.get(key)) {
return false;
}
}
return true;
}
/**
* The sort method sorts the items of a collection in place and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sort(compareFunction = Collection.defaultSort) {
const entries = [...this.entries()];
entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0]));
super.clear();
for (const [key, value] of entries) {
super.set(key, value);
}
return this;
}
/**
* The intersect method returns a new structure containing items where the keys and values are present in both original structures.
*
* @param other - The other Collection to filter against
*/
intersect(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of other) {
if (this.has(key) && Object.is(value, this.get(key))) {
coll.set(key, value);
}
}
return coll;
}
/**
* The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.
*
* @param other - The other Collection to filter against
*/
subtract(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of this) {
if (!other.has(key) || !Object.is(value, other.get(key))) {
coll.set(key, value);
}
}
return coll;
}
/**
* The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.
*
* @param other - The other Collection to filter against
*/
difference(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of other) {
if (!this.has(key))
coll.set(key, value);
}
for (const [key, value] of this) {
if (!other.has(key))
coll.set(key, value);
}
return coll;
}
/**
* Merges two Collections together into a new Collection.
*
* @param other - The other Collection to merge with
* @param whenInSelf - Function getting the result if the entry only exists in this Collection
* @param whenInOther - Function getting the result if the entry only exists in the other Collection
* @param whenInBoth - Function getting the result if the entry exists in both Collections
* @example
* ```ts
* // Sums up the entries in two collections.
* coll.merge(
* other,
* x => ({ keep: true, value: x }),
* y => ({ keep: true, value: y }),
* (x, y) => ({ keep: true, value: x + y }),
* );
* ```
* @example
* ```ts
* // Intersects two collections in a left-biased manner.
* coll.merge(
* other,
* x => ({ keep: false }),
* y => ({ keep: false }),
* (x, _) => ({ keep: true, value: x }),
* );
* ```
*/
merge(other, whenInSelf, whenInOther, whenInBoth) {
const coll = new this.constructor[Symbol.species]();
const keys = /* @__PURE__ */ new Set([...this.keys(), ...other.keys()]);
for (const key of keys) {
const hasInSelf = this.has(key);
const hasInOther = other.has(key);
if (hasInSelf && hasInOther) {
const result = whenInBoth(this.get(key), other.get(key), key);
if (result.keep)
coll.set(key, result.value);
} else if (hasInSelf) {
const result = whenInSelf(this.get(key), key);
if (result.keep)
coll.set(key, result.value);
} else if (hasInOther) {
const result = whenInOther(other.get(key), key);
if (result.keep)
coll.set(key, result.value);
}
}
return coll;
}
/**
* The sorted method sorts the items of a collection and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value,
* according to the string conversion of each element.
* @example
* ```ts
* collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sorted(compareFunction = Collection.defaultSort) {
return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));
}
toJSON() {
return [...this.values()];
}
static defaultSort(firstValue, secondValue) {
return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;
}
/**
* Creates a Collection from a list of entries.
*
* @param entries - The list of entries
* @param combine - Function to combine an existing entry with a new one
* @example
* ```ts
* Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
* // returns Collection { "a" => 3, "b" => 2 }
* ```
*/
static combineEntries(entries, combine) {
const coll = new Collection();
for (const [key, value] of entries) {
if (coll.has(key)) {
coll.set(key, combine(coll.get(key), value, key));
} else {
coll.set(key, value);
}
}
return coll;
}
};
__name(Collection, "Collection");
// src/index.ts
var version = "1.5.1";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Collection,
version
});
//# sourceMappingURL=index.js.map

1
node_modules/@discordjs/collection/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

522
node_modules/@discordjs/collection/dist/index.mjs generated vendored Normal file
View file

@ -0,0 +1,522 @@
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/collection.ts
var Collection = class extends Map {
/**
* Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
*
* @param key - The key to get if it exists, or set otherwise
* @param defaultValueGenerator - A function that generates the default value
* @example
* ```ts
* collection.ensure(guildId, () => defaultGuildConfig);
* ```
*/
ensure(key, defaultValueGenerator) {
if (this.has(key))
return this.get(key);
if (typeof defaultValueGenerator !== "function")
throw new TypeError(`${defaultValueGenerator} is not a function`);
const defaultValue = defaultValueGenerator(key, this);
this.set(key, defaultValue);
return defaultValue;
}
/**
* Checks if all of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if all of the elements exist, `false` if at least one does not exist.
*/
hasAll(...keys) {
return keys.every((key) => super.has(key));
}
/**
* Checks if any of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if any of the elements exist, `false` if none exist.
*/
hasAny(...keys) {
return keys.some((key) => super.has(key));
}
first(amount) {
if (amount === void 0)
return this.values().next().value;
if (amount < 0)
return this.last(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.values();
return Array.from({ length: amount }, () => iter.next().value);
}
firstKey(amount) {
if (amount === void 0)
return this.keys().next().value;
if (amount < 0)
return this.lastKey(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.keys();
return Array.from({ length: amount }, () => iter.next().value);
}
last(amount) {
const arr = [...this.values()];
if (amount === void 0)
return arr[arr.length - 1];
if (amount < 0)
return this.first(amount * -1);
if (!amount)
return [];
return arr.slice(-amount);
}
lastKey(amount) {
const arr = [...this.keys()];
if (amount === void 0)
return arr[arr.length - 1];
if (amount < 0)
return this.firstKey(amount * -1);
if (!amount)
return [];
return arr.slice(-amount);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the item at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the element to obtain
*/
at(index) {
index = Math.floor(index);
const arr = [...this.values()];
return arr.at(index);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the key at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the key to obtain
*/
keyAt(index) {
index = Math.floor(index);
const arr = [...this.keys()];
return arr.at(index);
}
random(amount) {
const arr = [...this.values()];
if (amount === void 0)
return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount)
return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
() => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
);
}
randomKey(amount) {
const arr = [...this.keys()];
if (amount === void 0)
return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount)
return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
() => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}
* but returns a Collection instead of an Array.
*/
reverse() {
const entries = [...this.entries()].reverse();
this.clear();
for (const [key, value] of entries)
this.set(key, value);
return this;
}
find(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return val;
}
return void 0;
}
findKey(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return key;
}
return void 0;
}
sweep(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const previousSize = this.size;
for (const [key, val] of this) {
if (fn(val, key, this))
this.delete(key);
}
return previousSize - this.size;
}
filter(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const results = new this.constructor[Symbol.species]();
for (const [key, val] of this) {
if (fn(val, key, this))
results.set(key, val);
}
return results;
}
partition(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const results = [
new this.constructor[Symbol.species](),
new this.constructor[Symbol.species]()
];
for (const [key, val] of this) {
if (fn(val, key, this)) {
results[0].set(key, val);
} else {
results[1].set(key, val);
}
}
return results;
}
flatMap(fn, thisArg) {
const collections = this.map(fn, thisArg);
return new this.constructor[Symbol.species]().concat(...collections);
}
map(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const iter = this.entries();
return Array.from({ length: this.size }, () => {
const [key, value] = iter.next().value;
return fn(value, key, this);
});
}
mapValues(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
const coll = new this.constructor[Symbol.species]();
for (const [key, val] of this)
coll.set(key, fn(val, key, this));
return coll;
}
some(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this))
return true;
}
return false;
}
every(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (!fn(val, key, this))
return false;
}
return true;
}
/**
* Applies a function to produce a single value. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
* and `collection`
* @param initialValue - Starting value for the accumulator
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
reduce(fn, initialValue) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
let accumulator;
if (initialValue !== void 0) {
accumulator = initialValue;
for (const [key, val] of this)
accumulator = fn(accumulator, val, key, this);
return accumulator;
}
let first = true;
for (const [key, val] of this) {
if (first) {
accumulator = val;
first = false;
continue;
}
accumulator = fn(accumulator, val, key, this);
}
if (first) {
throw new TypeError("Reduce of empty collection with no initial value");
}
return accumulator;
}
each(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
for (const [key, value] of this) {
fn(value, key, this);
}
return this;
}
tap(fn, thisArg) {
if (typeof fn !== "function")
throw new TypeError(`${fn} is not a function`);
if (thisArg !== void 0)
fn = fn.bind(thisArg);
fn(this);
return this;
}
/**
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
clone() {
return new this.constructor[Symbol.species](this);
}
/**
* Combines this collection with others into a new collection. None of the source collections are modified.
*
* @param collections - Collections to merge
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
concat(...collections) {
const newColl = this.clone();
for (const coll of collections) {
for (const [key, val] of coll)
newColl.set(key, val);
}
return newColl;
}
/**
* Checks if this collection shares identical items with another.
* This is different to checking for equality using equal-signs, because
* the collections may be different objects, but contain the same data.
*
* @param collection - Collection to compare with
* @returns Whether the collections have identical contents
*/
equals(collection) {
if (!collection)
return false;
if (this === collection)
return true;
if (this.size !== collection.size)
return false;
for (const [key, value] of this) {
if (!collection.has(key) || value !== collection.get(key)) {
return false;
}
}
return true;
}
/**
* The sort method sorts the items of a collection in place and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sort(compareFunction = Collection.defaultSort) {
const entries = [...this.entries()];
entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0]));
super.clear();
for (const [key, value] of entries) {
super.set(key, value);
}
return this;
}
/**
* The intersect method returns a new structure containing items where the keys and values are present in both original structures.
*
* @param other - The other Collection to filter against
*/
intersect(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of other) {
if (this.has(key) && Object.is(value, this.get(key))) {
coll.set(key, value);
}
}
return coll;
}
/**
* The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.
*
* @param other - The other Collection to filter against
*/
subtract(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of this) {
if (!other.has(key) || !Object.is(value, other.get(key))) {
coll.set(key, value);
}
}
return coll;
}
/**
* The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.
*
* @param other - The other Collection to filter against
*/
difference(other) {
const coll = new this.constructor[Symbol.species]();
for (const [key, value] of other) {
if (!this.has(key))
coll.set(key, value);
}
for (const [key, value] of this) {
if (!other.has(key))
coll.set(key, value);
}
return coll;
}
/**
* Merges two Collections together into a new Collection.
*
* @param other - The other Collection to merge with
* @param whenInSelf - Function getting the result if the entry only exists in this Collection
* @param whenInOther - Function getting the result if the entry only exists in the other Collection
* @param whenInBoth - Function getting the result if the entry exists in both Collections
* @example
* ```ts
* // Sums up the entries in two collections.
* coll.merge(
* other,
* x => ({ keep: true, value: x }),
* y => ({ keep: true, value: y }),
* (x, y) => ({ keep: true, value: x + y }),
* );
* ```
* @example
* ```ts
* // Intersects two collections in a left-biased manner.
* coll.merge(
* other,
* x => ({ keep: false }),
* y => ({ keep: false }),
* (x, _) => ({ keep: true, value: x }),
* );
* ```
*/
merge(other, whenInSelf, whenInOther, whenInBoth) {
const coll = new this.constructor[Symbol.species]();
const keys = /* @__PURE__ */ new Set([...this.keys(), ...other.keys()]);
for (const key of keys) {
const hasInSelf = this.has(key);
const hasInOther = other.has(key);
if (hasInSelf && hasInOther) {
const result = whenInBoth(this.get(key), other.get(key), key);
if (result.keep)
coll.set(key, result.value);
} else if (hasInSelf) {
const result = whenInSelf(this.get(key), key);
if (result.keep)
coll.set(key, result.value);
} else if (hasInOther) {
const result = whenInOther(other.get(key), key);
if (result.keep)
coll.set(key, result.value);
}
}
return coll;
}
/**
* The sorted method sorts the items of a collection and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value,
* according to the string conversion of each element.
* @example
* ```ts
* collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
sorted(compareFunction = Collection.defaultSort) {
return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));
}
toJSON() {
return [...this.values()];
}
static defaultSort(firstValue, secondValue) {
return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;
}
/**
* Creates a Collection from a list of entries.
*
* @param entries - The list of entries
* @param combine - Function to combine an existing entry with a new one
* @example
* ```ts
* Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
* // returns Collection { "a" => 3, "b" => 2 }
* ```
*/
static combineEntries(entries, combine) {
const coll = new Collection();
for (const [key, value] of entries) {
if (coll.has(key)) {
coll.set(key, combine(coll.get(key), value, key));
} else {
coll.set(key, value);
}
}
return coll;
}
};
__name(Collection, "Collection");
// src/index.ts
var version = "1.5.1";
export {
Collection,
version
};
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

75
node_modules/@discordjs/collection/package.json generated vendored Normal file
View file

@ -0,0 +1,75 @@
{
"name": "@discordjs/collection",
"version": "1.5.1",
"description": "Utility data structure used in discord.js",
"scripts": {
"test": "vitest run",
"build": "tsup",
"build:docs": "tsc -p tsconfig.docs.json",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"fmt": "yarn format",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/collection/*'",
"release": "cliff-jumper"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"directories": {
"lib": "src",
"test": "__tests__"
},
"files": [
"dist"
],
"contributors": [
"Crawl <icrawltogo@gmail.com>",
"Amish Shah <amishshah.2k@gmail.com>",
"SpaceEEC <spaceeec@yahoo.com>",
"Vlad Frangu <kingdgrizzle@gmail.com>",
"Aura Román <kyradiscord@gmail.com>"
],
"license": "Apache-2.0",
"keywords": [
"map",
"collection",
"utility"
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/collection"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.6",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"esbuild-plugin-version-injector": "^1.1.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

42
node_modules/@discordjs/formatters/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,42 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@discordjs/formatters@0.3.1](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.3.0...@discordjs/formatters@0.3.1) - (2023-05-01)
## Documentation
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
- **formatters:** Enhance the documentation (#9364) ([23e0ac5](https://github.com/discordjs/discord.js/commit/23e0ac56f456c39d925e2644ec3ca209d4410a99))
# [@discordjs/formatters@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.2.0...@discordjs/formatters@0.3.0) - (2023-04-01)
## Bug Fixes
- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b))
## Features
- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b))
# [@discordjs/formatters@0.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.1.0...@discordjs/formatters@0.2.0) - (2023-03-12)
## Features
- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38))
## Refactor
- Compare with `undefined` directly (#9191) ([869153c](https://github.com/discordjs/discord.js/commit/869153c3fdf155783e7c0ecebd3627b087c3a026))
- Moved the escapeX functions from discord.js to @discord.js/formatters (#8957) ([13ce78a](https://github.com/discordjs/discord.js/commit/13ce78af6e3aedc793f53a099a6a615df44311f7))
## Styling
- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b))
# [@discordjs/formatters@0.1.0](https://github.com/discordjs/discord.js/tree/@discordjs/formatters@0.1.0) - (2022-12-16)
## Features
- Add `@discordjs/formatters` (#8889) ([3fca638](https://github.com/discordjs/discord.js/commit/3fca638a8470dcea2f79ddb9f18526dbc0017c88))

191
node_modules/@discordjs/formatters/LICENSE generated vendored Normal file
View file

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler
Copyright 2021 Vlad Frangu
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

80
node_modules/@discordjs/formatters/README.md generated vendored Normal file
View file

@ -0,0 +1,80 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://www.npmjs.com/package/@discordjs/formatters"><img src="https://img.shields.io/npm/v/@discordjs/formatters.svg?maxAge=3600" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/@discordjs/formatters"><img src="https://img.shields.io/npm/dt/@discordjs/formatters.svg?maxAge=3600" alt="npm downloads" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=formatters" alt="Code coverage" /></a>
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
</p>
</div>
## About
`@discordjs/formatters` is a collection of functions for formatting strings to be used on Discord.
## Installation
**Node.js 16.9.0 or newer is required.**
```sh
npm install @discordjs/formatters
yarn add @discordjs/formatters
pnpm add @discordjs/formatters
```
## Example usage
````ts
import { codeBlock } from '@discordjs/formatters';
const formattedCode = codeBlock('hello world!');
console.log(formattedCode);
// Prints:
// ```
// hello world!
// ```
````
## Links
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library.
- [discord.js Discord server][discord]
- [Discord API Discord server][discord-api]
- [GitHub][source]
- [npm][npm]
- [Related libraries][related-libs]
## Contributing
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
[documentation][documentation].
See [the contribution guide][contributing] if you'd like to submit a PR.
## Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord].
[website]: https://discord.js.org
[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website
[documentation]: https://discord.js.org/docs/packages/formatters/stable
[guide]: https://discordjs.guide/
[guide-source]: https://github.com/discordjs/guide
[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html
[discord]: https://discord.gg/djs
[discord-api]: https://discord.gg/discord-api
[source]: https://github.com/discordjs/discord.js/tree/main/packages/formatters
[npm]: https://www.npmjs.com/package/@discordjs/formatters
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md

511
node_modules/@discordjs/formatters/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,511 @@
import { URL } from 'node:url';
import { Snowflake } from 'discord-api-types/globals';
/**
* The options that affect what will be escaped.
*/
interface EscapeMarkdownOptions {
/**
* Whether to escape bold text.
*
* @defaultValue `true`
*/
bold?: boolean;
/**
* Whether to escape bulleted lists.
*
* @defaultValue `false`
*/
bulletedList?: boolean;
/**
* Whether to escape code blocks.
*
* @defaultValue `true`
*/
codeBlock?: boolean;
/**
* Whether to escape text inside code blocks.
*
* @defaultValue `true`
*/
codeBlockContent?: boolean;
/**
* Whether to escape `\`.
*
* @defaultValue `true`
*/
escape?: boolean;
/**
* Whether to escape headings.
*
* @defaultValue `false`
*/
heading?: boolean;
/**
* Whether to escape inline code.
*
* @defaultValue `true`
*/
inlineCode?: boolean;
/**
* Whether to escape text inside inline code.
*
* @defaultValue `true`
*/
inlineCodeContent?: boolean;
/**
* Whether to escape italics.
*
* @defaultValue `true`
*/
italic?: boolean;
/**
* Whether to escape masked links.
*
* @defaultValue `false`
*/
maskedLink?: boolean;
/**
* Whether to escape numbered lists.
*
* @defaultValue `false`
*/
numberedList?: boolean;
/**
* Whether to escape spoilers.
*
* @defaultValue `true`
*/
spoiler?: boolean;
/**
* Whether to escape strikethroughs.
*
* @defaultValue `true`
*/
strikethrough?: boolean;
/**
* Whether to escape underlines.
*
* @defaultValue `true`
*/
underline?: boolean;
}
/**
* Escapes any Discord-flavored markdown in a string.
*
* @param text - Content to escape
* @param options - Options for escaping the markdown
*/
declare function escapeMarkdown(text: string, options?: EscapeMarkdownOptions): string;
/**
* Escapes code block markdown in a string.
*
* @param text - Content to escape
*/
declare function escapeCodeBlock(text: string): string;
/**
* Escapes inline code markdown in a string.
*
* @param text - Content to escape
*/
declare function escapeInlineCode(text: string): string;
/**
* Escapes italic markdown in a string.
*
* @param text - Content to escape
*/
declare function escapeItalic(text: string): string;
/**
* Escapes bold markdown in a string.
*
* @param text - Content to escape
*/
declare function escapeBold(text: string): string;
/**
* Escapes underline markdown in a string.
*
* @param text - Content to escape
*/
declare function escapeUnderline(text: string): string;
/**
* Escapes strikethrough markdown in a string.
*
* @param text - Content to escape
*/
declare function escapeStrikethrough(text: string): string;
/**
* Escapes spoiler markdown in a string.
*
* @param text - Content to escape
*/
declare function escapeSpoiler(text: string): string;
/**
* Escapes escape characters in a string.
*
* @param text - Content to escape
*/
declare function escapeEscape(text: string): string;
/**
* Escapes heading characters in a string.
*
* @param text - Content to escape
*/
declare function escapeHeading(text: string): string;
/**
* Escapes bulleted list characters in a string.
*
* @param text - Content to escape
*/
declare function escapeBulletedList(text: string): string;
/**
* Escapes numbered list characters in a string.
*
* @param text - Content to escape
*/
declare function escapeNumberedList(text: string): string;
/**
* Escapes masked link characters in a string.
*
* @param text - Content to escape
*/
declare function escapeMaskedLink(text: string): string;
/**
* Wraps the content inside a code block with no language.
*
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function codeBlock<C extends string>(content: C): `\`\`\`\n${C}\n\`\`\``;
/**
* Wraps the content inside a code block with the specified language.
*
* @typeParam L - This is inferred by the supplied language
* @typeParam C - This is inferred by the supplied content
* @param language - The language for the code block
* @param content - The content to wrap
*/
declare function codeBlock<L extends string, C extends string>(language: L, content: C): `\`\`\`${L}\n${C}\n\`\`\``;
/**
* Wraps the content inside \`backticks\` which formats it as inline code.
*
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function inlineCode<C extends string>(content: C): `\`${C}\``;
/**
* Formats the content into italic text.
*
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function italic<C extends string>(content: C): `_${C}_`;
/**
* Formats the content into bold text.
*
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function bold<C extends string>(content: C): `**${C}**`;
/**
* Formats the content into underscored text.
*
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function underscore<C extends string>(content: C): `__${C}__`;
/**
* Formats the content into strike-through text.
*
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function strikethrough<C extends string>(content: C): `~~${C}~~`;
/**
* Formats the content into a quote.
*
* @remarks This needs to be at the start of the line for Discord to format it.
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function quote<C extends string>(content: C): `> ${C}`;
/**
* Formats the content into a block quote.
*
* @remarks This needs to be at the start of the line for Discord to format it.
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function blockQuote<C extends string>(content: C): `>>> ${C}`;
/**
* Wraps the URL into `<>` which stops it from embedding.
*
* @typeParam C - This is inferred by the supplied content
* @param url - The URL to wrap
*/
declare function hideLinkEmbed<C extends string>(url: C): `<${C}>`;
/**
* Wraps the URL into `<>` which stops it from embedding.
*
* @param url - The URL to wrap
*/
declare function hideLinkEmbed(url: URL): `<${string}>`;
/**
* Formats the content and the URL into a masked URL.
*
* @typeParam C - This is inferred by the supplied content
* @param content - The content to display
* @param url - The URL the content links to
*/
declare function hyperlink<C extends string>(content: C, url: URL): `[${C}](${string})`;
/**
* Formats the content and the URL into a masked URL.
*
* @typeParam C - This is inferred by the supplied content
* @typeParam U - This is inferred by the supplied URL
* @param content - The content to display
* @param url - The URL the content links to
*/
declare function hyperlink<C extends string, U extends string>(content: C, url: U): `[${C}](${U})`;
/**
* Formats the content and the URL into a masked URL with a custom tooltip.
*
* @typeParam C - This is inferred by the supplied content
* @typeParam T - This is inferred by the supplied title
* @param content - The content to display
* @param url - The URL the content links to
* @param title - The title shown when hovering on the masked link
*/
declare function hyperlink<C extends string, T extends string>(content: C, url: URL, title: T): `[${C}](${string} "${T}")`;
/**
* Formats the content and the URL into a masked URL with a custom tooltip.
*
* @typeParam C - This is inferred by the supplied content
* @typeParam U - This is inferred by the supplied URL
* @typeParam T - This is inferred by the supplied title
* @param content - The content to display
* @param url - The URL the content links to
* @param title - The title shown when hovering on the masked link
*/
declare function hyperlink<C extends string, U extends string, T extends string>(content: C, url: U, title: T): `[${C}](${U} "${T}")`;
/**
* Formats the content into a spoiler.
*
* @typeParam C - This is inferred by the supplied content
* @param content - The content to wrap
*/
declare function spoiler<C extends string>(content: C): `||${C}||`;
/**
* Formats a user id into a user mention.
*
* @typeParam C - This is inferred by the supplied user id
* @param userId - The user id to format
*/
declare function userMention<C extends Snowflake>(userId: C): `<@${C}>`;
/**
* Formats a channel id into a channel mention.
*
* @typeParam C - This is inferred by the supplied channel id
* @param channelId - The channel id to format
*/
declare function channelMention<C extends Snowflake>(channelId: C): `<#${C}>`;
/**
* Formats a role id into a role mention.
*
* @typeParam C - This is inferred by the supplied role id
* @param roleId - The role id to format
*/
declare function roleMention<C extends Snowflake>(roleId: C): `<@&${C}>`;
/**
* Formats an application command name, subcommand group name, subcommand name, and id into an application command mention.
*
* @typeParam N - This is inferred by the supplied command name
* @typeParam G - This is inferred by the supplied subcommand group name
* @typeParam S - This is inferred by the supplied subcommand name
* @typeParam I - This is inferred by the supplied command id
* @param commandName - The application command name to format
* @param subcommandGroupName - The subcommand group name to format
* @param subcommandName - The subcommand name to format
* @param commandId - The application command id to format
*/
declare function chatInputApplicationCommandMention<N extends string, G extends string, S extends string, I extends Snowflake>(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): `</${N} ${G} ${S}:${I}>`;
/**
* Formats an application command name, subcommand name, and id into an application command mention.
*
* @typeParam N - This is inferred by the supplied command name
* @typeParam S - This is inferred by the supplied subcommand name
* @typeParam I - This is inferred by the supplied command id
* @param commandName - The application command name to format
* @param subcommandName - The subcommand name to format
* @param commandId - The application command id to format
*/
declare function chatInputApplicationCommandMention<N extends string, S extends string, I extends Snowflake>(commandName: N, subcommandName: S, commandId: I): `</${N} ${S}:${I}>`;
/**
* Formats an application command name and id into an application command mention.
*
* @typeParam N - This is inferred by the supplied command name
* @typeParam I - This is inferred by the supplied command id
* @param commandName - The application command name to format
* @param commandId - The application command id to format
*/
declare function chatInputApplicationCommandMention<N extends string, I extends Snowflake>(commandName: N, commandId: I): `</${N}:${I}>`;
/**
* Formats a non-animated emoji id into a fully qualified emoji identifier.
*
* @typeParam C - This is inferred by the supplied emoji id
* @param emojiId - The emoji id to format
*/
declare function formatEmoji<C extends Snowflake>(emojiId: C, animated?: false): `<:_:${C}>`;
/**
* Formats an animated emoji id into a fully qualified emoji identifier.
*
* @typeParam C - This is inferred by the supplied emoji id
* @param emojiId - The emoji id to format
* @param animated - Whether the emoji is animated
*/
declare function formatEmoji<C extends Snowflake>(emojiId: C, animated?: true): `<a:_:${C}>`;
/**
* Formats an emoji id into a fully qualified emoji identifier.
*
* @typeParam C - This is inferred by the supplied emoji id
* @param emojiId - The emoji id to format
* @param animated - Whether the emoji is animated
*/
declare function formatEmoji<C extends Snowflake>(emojiId: C, animated?: boolean): `<:_:${C}>` | `<a:_:${C}>`;
/**
* Formats a channel link for a direct message channel.
*
* @typeParam C - This is inferred by the supplied channel id
* @param channelId - The channel's id
*/
declare function channelLink<C extends Snowflake>(channelId: C): `https://discord.com/channels/@me/${C}`;
/**
* Formats a channel link for a guild channel.
*
* @typeParam C - This is inferred by the supplied channel id
* @typeParam G - This is inferred by the supplied guild id
* @param channelId - The channel's id
* @param guildId - The guild's id
*/
declare function channelLink<C extends Snowflake, G extends Snowflake>(channelId: C, guildId: G): `https://discord.com/channels/${G}/${C}`;
/**
* Formats a message link for a direct message channel.
*
* @typeParam C - This is inferred by the supplied channel id
* @typeParam M - This is inferred by the supplied message id
* @param channelId - The channel's id
* @param messageId - The message's id
*/
declare function messageLink<C extends Snowflake, M extends Snowflake>(channelId: C, messageId: M): `https://discord.com/channels/@me/${C}/${M}`;
/**
* Formats a message link for a guild channel.
*
* @typeParam C - This is inferred by the supplied channel id
* @typeParam M - This is inferred by the supplied message id
* @typeParam G - This is inferred by the supplied guild id
* @param channelId - The channel's id
* @param messageId - The message's id
* @param guildId - The guild's id
*/
declare function messageLink<C extends Snowflake, M extends Snowflake, G extends Snowflake>(channelId: C, messageId: M, guildId: G): `https://discord.com/channels/${G}/${C}/${M}`;
/**
* Formats a date into a short date-time string.
*
* @param date - The date to format. Defaults to the current time
*/
declare function time(date?: Date): `<t:${bigint}>`;
/**
* Formats a date given a format style.
*
* @typeParam S - This is inferred by the supplied {@link TimestampStylesString}
* @param date - The date to format
* @param style - The style to use
*/
declare function time<S extends TimestampStylesString>(date: Date, style: S): `<t:${bigint}:${S}>`;
/**
* Formats the given timestamp into a short date-time string.
*
* @typeParam C - This is inferred by the supplied timestamp
* @param seconds - A Unix timestamp in seconds
*/
declare function time<C extends number>(seconds: C): `<t:${C}>`;
/**
* Formats the given timestamp into a short date-time string.
*
* @typeParam C - This is inferred by the supplied timestamp
* @typeParam S - This is inferred by the supplied {@link TimestampStylesString}
* @param seconds - A Unix timestamp in seconds
* @param style - The style to use
*/
declare function time<C extends number, S extends TimestampStylesString>(seconds: C, style: S): `<t:${C}:${S}>`;
/**
* The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles}
* supported by Discord.
*/
declare const TimestampStyles: {
/**
* Short time format, consisting of hours and minutes.
*
* @example `16:20`
*/
readonly ShortTime: "t";
/**
* Long time format, consisting of hours, minutes, and seconds.
*
* @example `16:20:30`
*/
readonly LongTime: "T";
/**
* Short date format, consisting of day, month, and year.
*
* @example `20/04/2021`
*/
readonly ShortDate: "d";
/**
* Long date format, consisting of day, month, and year.
*
* @example `20 April 2021`
*/
readonly LongDate: "D";
/**
* Short date-time format, consisting of short date and short time formats.
*
* @example `20 April 2021 16:20`
*/
readonly ShortDateTime: "f";
/**
* Long date-time format, consisting of long date and short time formats.
*
* @example `Tuesday, 20 April 2021 16:20`
*/
readonly LongDateTime: "F";
/**
* Relative time format, consisting of a relative duration format.
*
* @example `2 months ago`
*/
readonly RelativeTime: "R";
};
/**
* The possible {@link TimestampStyles} values.
*/
type TimestampStylesString = (typeof TimestampStyles)[keyof typeof TimestampStyles];
/**
* All the available faces from Discord's native slash commands.
*/
declare enum Faces {
/**
* `¯\_(ツ)_/¯`
*/
Shrug = "\u00AF_(\u30C4)_/\u00AF",
/**
* `(╯°□°)╯︵ ┻━┻`
*/
Tableflip = "(\u256F\u00B0\u25A1\u00B0)\u256F\uFE35 \u253B\u2501\u253B",
/**
* `┬─┬ノ( º _ ºノ)`
*/
Unflip = "\u252C\u2500\u252C\u30CE( \u00BA _ \u00BA\u30CE)"
}
export { EscapeMarkdownOptions, Faces, TimestampStyles, TimestampStylesString, blockQuote, bold, channelLink, channelMention, chatInputApplicationCommandMention, codeBlock, escapeBold, escapeBulletedList, escapeCodeBlock, escapeEscape, escapeHeading, escapeInlineCode, escapeItalic, escapeMarkdown, escapeMaskedLink, escapeNumberedList, escapeSpoiler, escapeStrikethrough, escapeUnderline, formatEmoji, hideLinkEmbed, hyperlink, inlineCode, italic, messageLink, quote, roleMention, spoiler, strikethrough, time, underscore, userMention };

393
node_modules/@discordjs/formatters/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,393 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
Faces: () => Faces,
TimestampStyles: () => TimestampStyles,
blockQuote: () => blockQuote,
bold: () => bold,
channelLink: () => channelLink,
channelMention: () => channelMention,
chatInputApplicationCommandMention: () => chatInputApplicationCommandMention,
codeBlock: () => codeBlock,
escapeBold: () => escapeBold,
escapeBulletedList: () => escapeBulletedList,
escapeCodeBlock: () => escapeCodeBlock,
escapeEscape: () => escapeEscape,
escapeHeading: () => escapeHeading,
escapeInlineCode: () => escapeInlineCode,
escapeItalic: () => escapeItalic,
escapeMarkdown: () => escapeMarkdown,
escapeMaskedLink: () => escapeMaskedLink,
escapeNumberedList: () => escapeNumberedList,
escapeSpoiler: () => escapeSpoiler,
escapeStrikethrough: () => escapeStrikethrough,
escapeUnderline: () => escapeUnderline,
formatEmoji: () => formatEmoji,
hideLinkEmbed: () => hideLinkEmbed,
hyperlink: () => hyperlink,
inlineCode: () => inlineCode,
italic: () => italic,
messageLink: () => messageLink,
quote: () => quote,
roleMention: () => roleMention,
spoiler: () => spoiler,
strikethrough: () => strikethrough,
time: () => time,
underscore: () => underscore,
userMention: () => userMention
});
module.exports = __toCommonJS(src_exports);
// src/escapers.ts
function escapeMarkdown(text, options = {}) {
const {
codeBlock: codeBlock2 = true,
inlineCode: inlineCode2 = true,
bold: bold2 = true,
italic: italic2 = true,
underline = true,
strikethrough: strikethrough2 = true,
spoiler: spoiler2 = true,
codeBlockContent = true,
inlineCodeContent = true,
escape = true,
heading = false,
bulletedList = false,
numberedList = false,
maskedLink = false
} = options;
if (!codeBlockContent) {
return text.split("```").map((subString, index, array) => {
if (index % 2 && index !== array.length - 1)
return subString;
return escapeMarkdown(subString, {
inlineCode: inlineCode2,
bold: bold2,
italic: italic2,
underline,
strikethrough: strikethrough2,
spoiler: spoiler2,
inlineCodeContent,
escape,
heading,
bulletedList,
numberedList,
maskedLink
});
}).join(codeBlock2 ? "\\`\\`\\`" : "```");
}
if (!inlineCodeContent) {
return text.split(/(?<=^|[^`])`(?=[^`]|$)/g).map((subString, index, array) => {
if (index % 2 && index !== array.length - 1)
return subString;
return escapeMarkdown(subString, {
codeBlock: codeBlock2,
bold: bold2,
italic: italic2,
underline,
strikethrough: strikethrough2,
spoiler: spoiler2,
escape,
heading,
bulletedList,
numberedList,
maskedLink
});
}).join(inlineCode2 ? "\\`" : "`");
}
let res = text;
if (escape)
res = escapeEscape(res);
if (inlineCode2)
res = escapeInlineCode(res);
if (codeBlock2)
res = escapeCodeBlock(res);
if (italic2)
res = escapeItalic(res);
if (bold2)
res = escapeBold(res);
if (underline)
res = escapeUnderline(res);
if (strikethrough2)
res = escapeStrikethrough(res);
if (spoiler2)
res = escapeSpoiler(res);
if (heading)
res = escapeHeading(res);
if (bulletedList)
res = escapeBulletedList(res);
if (numberedList)
res = escapeNumberedList(res);
if (maskedLink)
res = escapeMaskedLink(res);
return res;
}
__name(escapeMarkdown, "escapeMarkdown");
function escapeCodeBlock(text) {
return text.replaceAll("```", "\\`\\`\\`");
}
__name(escapeCodeBlock, "escapeCodeBlock");
function escapeInlineCode(text) {
return text.replaceAll(/(?<=^|[^`])``?(?=[^`]|$)/g, (match) => match.length === 2 ? "\\`\\`" : "\\`");
}
__name(escapeInlineCode, "escapeInlineCode");
function escapeItalic(text) {
let idx = 0;
const newText = text.replaceAll(/(?<=^|[^*])\*([^*]|\*\*|$)/g, (_, match) => {
if (match === "**")
return ++idx % 2 ? `\\*${match}` : `${match}\\*`;
return `\\*${match}`;
});
idx = 0;
return newText.replaceAll(/(?<=^|[^_])(?<!<a?:.+)_(?!:\d+>)([^_]|__|$)/g, (_, match) => {
if (match === "__")
return ++idx % 2 ? `\\_${match}` : `${match}\\_`;
return `\\_${match}`;
});
}
__name(escapeItalic, "escapeItalic");
function escapeBold(text) {
let idx = 0;
return text.replaceAll(/\*\*(\*)?/g, (_, match) => {
if (match)
return ++idx % 2 ? `${match}\\*\\*` : `\\*\\*${match}`;
return "\\*\\*";
});
}
__name(escapeBold, "escapeBold");
function escapeUnderline(text) {
let idx = 0;
return text.replaceAll(/(?<!<a?:.+)__(_)?(?!:\d+>)/g, (_, match) => {
if (match)
return ++idx % 2 ? `${match}\\_\\_` : `\\_\\_${match}`;
return "\\_\\_";
});
}
__name(escapeUnderline, "escapeUnderline");
function escapeStrikethrough(text) {
return text.replaceAll("~~", "\\~\\~");
}
__name(escapeStrikethrough, "escapeStrikethrough");
function escapeSpoiler(text) {
return text.replaceAll("||", "\\|\\|");
}
__name(escapeSpoiler, "escapeSpoiler");
function escapeEscape(text) {
return text.replaceAll("\\", "\\\\");
}
__name(escapeEscape, "escapeEscape");
function escapeHeading(text) {
return text.replaceAll(/^( {0,2})([*-] )?( *)(#{1,3} )/gm, "$1$2$3\\$4");
}
__name(escapeHeading, "escapeHeading");
function escapeBulletedList(text) {
return text.replaceAll(/^( *)([*-])( +)/gm, "$1\\$2$3");
}
__name(escapeBulletedList, "escapeBulletedList");
function escapeNumberedList(text) {
return text.replaceAll(/^( *\d+)\./gm, "$1\\.");
}
__name(escapeNumberedList, "escapeNumberedList");
function escapeMaskedLink(text) {
return text.replaceAll(/\[.+]\(.+\)/gm, "\\$&");
}
__name(escapeMaskedLink, "escapeMaskedLink");
// src/formatters.ts
function codeBlock(language, content) {
return content === void 0 ? `\`\`\`
${language}
\`\`\`` : `\`\`\`${language}
${content}
\`\`\``;
}
__name(codeBlock, "codeBlock");
function inlineCode(content) {
return `\`${content}\``;
}
__name(inlineCode, "inlineCode");
function italic(content) {
return `_${content}_`;
}
__name(italic, "italic");
function bold(content) {
return `**${content}**`;
}
__name(bold, "bold");
function underscore(content) {
return `__${content}__`;
}
__name(underscore, "underscore");
function strikethrough(content) {
return `~~${content}~~`;
}
__name(strikethrough, "strikethrough");
function quote(content) {
return `> ${content}`;
}
__name(quote, "quote");
function blockQuote(content) {
return `>>> ${content}`;
}
__name(blockQuote, "blockQuote");
function hideLinkEmbed(url) {
return `<${url}>`;
}
__name(hideLinkEmbed, "hideLinkEmbed");
function hyperlink(content, url, title) {
return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`;
}
__name(hyperlink, "hyperlink");
function spoiler(content) {
return `||${content}||`;
}
__name(spoiler, "spoiler");
function userMention(userId) {
return `<@${userId}>`;
}
__name(userMention, "userMention");
function channelMention(channelId) {
return `<#${channelId}>`;
}
__name(channelMention, "channelMention");
function roleMention(roleId) {
return `<@&${roleId}>`;
}
__name(roleMention, "roleMention");
function chatInputApplicationCommandMention(commandName, subcommandGroupName, subcommandName, commandId) {
if (commandId !== void 0) {
return `</${commandName} ${subcommandGroupName} ${subcommandName}:${commandId}>`;
}
if (subcommandName !== void 0) {
return `</${commandName} ${subcommandGroupName}:${subcommandName}>`;
}
return `</${commandName}:${subcommandGroupName}>`;
}
__name(chatInputApplicationCommandMention, "chatInputApplicationCommandMention");
function formatEmoji(emojiId, animated = false) {
return `<${animated ? "a" : ""}:_:${emojiId}>`;
}
__name(formatEmoji, "formatEmoji");
function channelLink(channelId, guildId) {
return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}`;
}
__name(channelLink, "channelLink");
function messageLink(channelId, messageId, guildId) {
return `${guildId === void 0 ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;
}
__name(messageLink, "messageLink");
function time(timeOrSeconds, style) {
if (typeof timeOrSeconds !== "number") {
timeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1e3);
}
return typeof style === "string" ? `<t:${timeOrSeconds}:${style}>` : `<t:${timeOrSeconds}>`;
}
__name(time, "time");
var TimestampStyles = {
/**
* Short time format, consisting of hours and minutes.
*
* @example `16:20`
*/
ShortTime: "t",
/**
* Long time format, consisting of hours, minutes, and seconds.
*
* @example `16:20:30`
*/
LongTime: "T",
/**
* Short date format, consisting of day, month, and year.
*
* @example `20/04/2021`
*/
ShortDate: "d",
/**
* Long date format, consisting of day, month, and year.
*
* @example `20 April 2021`
*/
LongDate: "D",
/**
* Short date-time format, consisting of short date and short time formats.
*
* @example `20 April 2021 16:20`
*/
ShortDateTime: "f",
/**
* Long date-time format, consisting of long date and short time formats.
*
* @example `Tuesday, 20 April 2021 16:20`
*/
LongDateTime: "F",
/**
* Relative time format, consisting of a relative duration format.
*
* @example `2 months ago`
*/
RelativeTime: "R"
};
var Faces = /* @__PURE__ */ ((Faces2) => {
Faces2["Shrug"] = "\xAF_(\u30C4)_/\xAF";
Faces2["Tableflip"] = "(\u256F\xB0\u25A1\xB0)\u256F\uFE35 \u253B\u2501\u253B";
Faces2["Unflip"] = "\u252C\u2500\u252C\u30CE( \xBA _ \xBA\u30CE)";
return Faces2;
})(Faces || {});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Faces,
TimestampStyles,
blockQuote,
bold,
channelLink,
channelMention,
chatInputApplicationCommandMention,
codeBlock,
escapeBold,
escapeBulletedList,
escapeCodeBlock,
escapeEscape,
escapeHeading,
escapeInlineCode,
escapeItalic,
escapeMarkdown,
escapeMaskedLink,
escapeNumberedList,
escapeSpoiler,
escapeStrikethrough,
escapeUnderline,
formatEmoji,
hideLinkEmbed,
hyperlink,
inlineCode,
italic,
messageLink,
quote,
roleMention,
spoiler,
strikethrough,
time,
underscore,
userMention
});
//# sourceMappingURL=index.js.map

1
node_modules/@discordjs/formatters/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

335
node_modules/@discordjs/formatters/dist/index.mjs generated vendored Normal file
View file

@ -0,0 +1,335 @@
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/escapers.ts
function escapeMarkdown(text, options = {}) {
const {
codeBlock: codeBlock2 = true,
inlineCode: inlineCode2 = true,
bold: bold2 = true,
italic: italic2 = true,
underline = true,
strikethrough: strikethrough2 = true,
spoiler: spoiler2 = true,
codeBlockContent = true,
inlineCodeContent = true,
escape = true,
heading = false,
bulletedList = false,
numberedList = false,
maskedLink = false
} = options;
if (!codeBlockContent) {
return text.split("```").map((subString, index, array) => {
if (index % 2 && index !== array.length - 1)
return subString;
return escapeMarkdown(subString, {
inlineCode: inlineCode2,
bold: bold2,
italic: italic2,
underline,
strikethrough: strikethrough2,
spoiler: spoiler2,
inlineCodeContent,
escape,
heading,
bulletedList,
numberedList,
maskedLink
});
}).join(codeBlock2 ? "\\`\\`\\`" : "```");
}
if (!inlineCodeContent) {
return text.split(/(?<=^|[^`])`(?=[^`]|$)/g).map((subString, index, array) => {
if (index % 2 && index !== array.length - 1)
return subString;
return escapeMarkdown(subString, {
codeBlock: codeBlock2,
bold: bold2,
italic: italic2,
underline,
strikethrough: strikethrough2,
spoiler: spoiler2,
escape,
heading,
bulletedList,
numberedList,
maskedLink
});
}).join(inlineCode2 ? "\\`" : "`");
}
let res = text;
if (escape)
res = escapeEscape(res);
if (inlineCode2)
res = escapeInlineCode(res);
if (codeBlock2)
res = escapeCodeBlock(res);
if (italic2)
res = escapeItalic(res);
if (bold2)
res = escapeBold(res);
if (underline)
res = escapeUnderline(res);
if (strikethrough2)
res = escapeStrikethrough(res);
if (spoiler2)
res = escapeSpoiler(res);
if (heading)
res = escapeHeading(res);
if (bulletedList)
res = escapeBulletedList(res);
if (numberedList)
res = escapeNumberedList(res);
if (maskedLink)
res = escapeMaskedLink(res);
return res;
}
__name(escapeMarkdown, "escapeMarkdown");
function escapeCodeBlock(text) {
return text.replaceAll("```", "\\`\\`\\`");
}
__name(escapeCodeBlock, "escapeCodeBlock");
function escapeInlineCode(text) {
return text.replaceAll(/(?<=^|[^`])``?(?=[^`]|$)/g, (match) => match.length === 2 ? "\\`\\`" : "\\`");
}
__name(escapeInlineCode, "escapeInlineCode");
function escapeItalic(text) {
let idx = 0;
const newText = text.replaceAll(/(?<=^|[^*])\*([^*]|\*\*|$)/g, (_, match) => {
if (match === "**")
return ++idx % 2 ? `\\*${match}` : `${match}\\*`;
return `\\*${match}`;
});
idx = 0;
return newText.replaceAll(/(?<=^|[^_])(?<!<a?:.+)_(?!:\d+>)([^_]|__|$)/g, (_, match) => {
if (match === "__")
return ++idx % 2 ? `\\_${match}` : `${match}\\_`;
return `\\_${match}`;
});
}
__name(escapeItalic, "escapeItalic");
function escapeBold(text) {
let idx = 0;
return text.replaceAll(/\*\*(\*)?/g, (_, match) => {
if (match)
return ++idx % 2 ? `${match}\\*\\*` : `\\*\\*${match}`;
return "\\*\\*";
});
}
__name(escapeBold, "escapeBold");
function escapeUnderline(text) {
let idx = 0;
return text.replaceAll(/(?<!<a?:.+)__(_)?(?!:\d+>)/g, (_, match) => {
if (match)
return ++idx % 2 ? `${match}\\_\\_` : `\\_\\_${match}`;
return "\\_\\_";
});
}
__name(escapeUnderline, "escapeUnderline");
function escapeStrikethrough(text) {
return text.replaceAll("~~", "\\~\\~");
}
__name(escapeStrikethrough, "escapeStrikethrough");
function escapeSpoiler(text) {
return text.replaceAll("||", "\\|\\|");
}
__name(escapeSpoiler, "escapeSpoiler");
function escapeEscape(text) {
return text.replaceAll("\\", "\\\\");
}
__name(escapeEscape, "escapeEscape");
function escapeHeading(text) {
return text.replaceAll(/^( {0,2})([*-] )?( *)(#{1,3} )/gm, "$1$2$3\\$4");
}
__name(escapeHeading, "escapeHeading");
function escapeBulletedList(text) {
return text.replaceAll(/^( *)([*-])( +)/gm, "$1\\$2$3");
}
__name(escapeBulletedList, "escapeBulletedList");
function escapeNumberedList(text) {
return text.replaceAll(/^( *\d+)\./gm, "$1\\.");
}
__name(escapeNumberedList, "escapeNumberedList");
function escapeMaskedLink(text) {
return text.replaceAll(/\[.+]\(.+\)/gm, "\\$&");
}
__name(escapeMaskedLink, "escapeMaskedLink");
// src/formatters.ts
function codeBlock(language, content) {
return content === void 0 ? `\`\`\`
${language}
\`\`\`` : `\`\`\`${language}
${content}
\`\`\``;
}
__name(codeBlock, "codeBlock");
function inlineCode(content) {
return `\`${content}\``;
}
__name(inlineCode, "inlineCode");
function italic(content) {
return `_${content}_`;
}
__name(italic, "italic");
function bold(content) {
return `**${content}**`;
}
__name(bold, "bold");
function underscore(content) {
return `__${content}__`;
}
__name(underscore, "underscore");
function strikethrough(content) {
return `~~${content}~~`;
}
__name(strikethrough, "strikethrough");
function quote(content) {
return `> ${content}`;
}
__name(quote, "quote");
function blockQuote(content) {
return `>>> ${content}`;
}
__name(blockQuote, "blockQuote");
function hideLinkEmbed(url) {
return `<${url}>`;
}
__name(hideLinkEmbed, "hideLinkEmbed");
function hyperlink(content, url, title) {
return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`;
}
__name(hyperlink, "hyperlink");
function spoiler(content) {
return `||${content}||`;
}
__name(spoiler, "spoiler");
function userMention(userId) {
return `<@${userId}>`;
}
__name(userMention, "userMention");
function channelMention(channelId) {
return `<#${channelId}>`;
}
__name(channelMention, "channelMention");
function roleMention(roleId) {
return `<@&${roleId}>`;
}
__name(roleMention, "roleMention");
function chatInputApplicationCommandMention(commandName, subcommandGroupName, subcommandName, commandId) {
if (commandId !== void 0) {
return `</${commandName} ${subcommandGroupName} ${subcommandName}:${commandId}>`;
}
if (subcommandName !== void 0) {
return `</${commandName} ${subcommandGroupName}:${subcommandName}>`;
}
return `</${commandName}:${subcommandGroupName}>`;
}
__name(chatInputApplicationCommandMention, "chatInputApplicationCommandMention");
function formatEmoji(emojiId, animated = false) {
return `<${animated ? "a" : ""}:_:${emojiId}>`;
}
__name(formatEmoji, "formatEmoji");
function channelLink(channelId, guildId) {
return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}`;
}
__name(channelLink, "channelLink");
function messageLink(channelId, messageId, guildId) {
return `${guildId === void 0 ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;
}
__name(messageLink, "messageLink");
function time(timeOrSeconds, style) {
if (typeof timeOrSeconds !== "number") {
timeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1e3);
}
return typeof style === "string" ? `<t:${timeOrSeconds}:${style}>` : `<t:${timeOrSeconds}>`;
}
__name(time, "time");
var TimestampStyles = {
/**
* Short time format, consisting of hours and minutes.
*
* @example `16:20`
*/
ShortTime: "t",
/**
* Long time format, consisting of hours, minutes, and seconds.
*
* @example `16:20:30`
*/
LongTime: "T",
/**
* Short date format, consisting of day, month, and year.
*
* @example `20/04/2021`
*/
ShortDate: "d",
/**
* Long date format, consisting of day, month, and year.
*
* @example `20 April 2021`
*/
LongDate: "D",
/**
* Short date-time format, consisting of short date and short time formats.
*
* @example `20 April 2021 16:20`
*/
ShortDateTime: "f",
/**
* Long date-time format, consisting of long date and short time formats.
*
* @example `Tuesday, 20 April 2021 16:20`
*/
LongDateTime: "F",
/**
* Relative time format, consisting of a relative duration format.
*
* @example `2 months ago`
*/
RelativeTime: "R"
};
var Faces = /* @__PURE__ */ ((Faces2) => {
Faces2["Shrug"] = "\xAF_(\u30C4)_/\xAF";
Faces2["Tableflip"] = "(\u256F\xB0\u25A1\xB0)\u256F\uFE35 \u253B\u2501\u253B";
Faces2["Unflip"] = "\u252C\u2500\u252C\u30CE( \xBA _ \xBA\u30CE)";
return Faces2;
})(Faces || {});
export {
Faces,
TimestampStyles,
blockQuote,
bold,
channelLink,
channelMention,
chatInputApplicationCommandMention,
codeBlock,
escapeBold,
escapeBulletedList,
escapeCodeBlock,
escapeEscape,
escapeHeading,
escapeInlineCode,
escapeItalic,
escapeMarkdown,
escapeMaskedLink,
escapeNumberedList,
escapeSpoiler,
escapeStrikethrough,
escapeUnderline,
formatEmoji,
hideLinkEmbed,
hyperlink,
inlineCode,
italic,
messageLink,
quote,
roleMention,
spoiler,
strikethrough,
time,
underscore,
userMention
};
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

71
node_modules/@discordjs/formatters/package.json generated vendored Normal file
View file

@ -0,0 +1,71 @@
{
"name": "@discordjs/formatters",
"version": "0.3.1",
"description": "A set of functions to format strings for Discord.",
"scripts": {
"test": "vitest run",
"build": "tsup",
"build:docs": "tsc -p tsconfig.docs.json",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn build && yarn lint",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/formatters/*'",
"release": "cliff-jumper"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"typings": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"directories": {
"lib": "src",
"test": "__tests__"
},
"files": [
"dist"
],
"contributors": [
"Crawl <icrawltogo@gmail.com>",
"SpaceEEC <spaceeec@yahoo.com>",
"Vlad Frangu <kingdgrizzle@gmail.com>",
"Aura Román <kyradiscord@gmail.com>"
],
"license": "Apache-2.0",
"keywords": [],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/formatters"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"discord-api-types": "^0.37.41"
},
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.6",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

208
node_modules/@discordjs/rest/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,208 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@discordjs/rest@1.7.1](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.7.0...@discordjs/rest@1.7.1) - (2023-05-01)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Documentation
- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef))
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
# [@discordjs/rest@1.7.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.6.0...@discordjs/rest@1.7.0) - (2023-04-01)
## Bug Fixes
- **handlers:** Create burst handler for interaction callbacks (#8996) ([db8df10](https://github.com/discordjs/discord.js/commit/db8df104c5e70a12f35b54e5f3f7c897068dde6f))
- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b))
- **rest:** Remove `const enum`s in favour of regular enums (#9243) ([229ad07](https://github.com/discordjs/discord.js/commit/229ad077ff52d8706d68ed4d31983619a32eba45))
## Features
- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b))
# [@discordjs/rest@1.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.5.0...@discordjs/rest@1.6.0) - (2023-03-12)
## Bug Fixes
- **snowflake:** Snowflakes length (#9144) ([955e8fe](https://github.com/discordjs/discord.js/commit/955e8fe312c42ad4937cc1994d1d81e517c413c8))
- **RequestManager:** Inference of image/apng (#9014) ([ecb4281](https://github.com/discordjs/discord.js/commit/ecb4281d1e2d9a0a427605f75352cbf74ffb2d7c))
## Documentation
- Fix typos (#9127) ([1ba1f23](https://github.com/discordjs/discord.js/commit/1ba1f238f04221ec890fc921678909b5b7d92c26))
- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28))
## Features
- **Sticker:** Add support for gif stickers (#9038) ([6a9875d](https://github.com/discordjs/discord.js/commit/6a9875da054a875a4711394547d47439bbe66fb6))
- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38))
## Styling
- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b))
# [@discordjs/rest@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.4.0...@discordjs/rest@1.5.0) - (2022-12-16)
## Features
- **core:** Add support for role connections (#8930) ([3d6fa24](https://github.com/discordjs/discord.js/commit/3d6fa248c07b2278504bbe8bafa17a3294971fd9))
# [@discordjs/rest@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.3.0...@discordjs/rest@1.4.0) - (2022-11-28)
## Bug Fixes
- **SequentialHandler:** Downlevel ECONNRESET errors (#8785) ([5a70057](https://github.com/discordjs/discord.js/commit/5a70057826b47fb8251f3d836a536de689444ca1))
- Make ratelimit timeout require event loop to be active (#8779) ([68d5712](https://github.com/discordjs/discord.js/commit/68d5712deae85532604d93b4505f0953d664cde7))
- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4))
## Features
- Add `@discordjs/core` (#8736) ([2127b32](https://github.com/discordjs/discord.js/commit/2127b32d26dedeb44ec43d16ec2e2046919f9bb0))
- New select menus (#8793) ([5152abf](https://github.com/discordjs/discord.js/commit/5152abf7285581abf7689e9050fdc56c4abb1e2b))
## Refactor
- Update `makeURLSearchParams` to accept readonly non-`Record`s (#8868) ([8376e2d](https://github.com/discordjs/discord.js/commit/8376e2dbcd38697ce62615d9a539fd198fbc4713))
# [@discordjs/rest@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.2.0...@discordjs/rest@1.3.0) - (2022-10-08)
## Bug Fixes
- **SequentialHandler:** Throw http error with proper name and more useful message (#8694) ([3f86561](https://github.com/discordjs/discord.js/commit/3f8656115bf9df0dbf8391de68a3401535325895))
## Features
- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2))
- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3))
- Add `AbortSignal` support (#8672) ([3c231ae](https://github.com/discordjs/discord.js/commit/3c231ae81a52b66940ba495f35fd59a76c65e306))
# [@discordjs/rest@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.1.0...@discordjs/rest@1.2.0) - (2022-09-25)
## Bug Fixes
- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9))
## Documentation
- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0))
## Features
- **rest:** Use Agent with higher connect timeout (#8679) ([64cd53c](https://github.com/discordjs/discord.js/commit/64cd53c4c23dd9c9503fd0887ac5c542137c57e8))
## Refactor
- Website components (#8600) ([c334157](https://github.com/discordjs/discord.js/commit/c3341570d983aea9ecc419979d5a01de658c9d67))
- Use `eslint-config-neon` for packages. (#8579) ([edadb9f](https://github.com/discordjs/discord.js/commit/edadb9fe5dfd9ff51a3cfc9b25cb242d3f9f5241))
# [@discordjs/rest@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.0.1...@discordjs/rest@1.1.0) - (2022-08-22)
## Features
- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007))
- **website:** Render `@defaultValue` blocks (#8527) ([8028813](https://github.com/discordjs/discord.js/commit/8028813825e7708915ea892760c1003afd60df2f))
- **WebSocketShard:** Support new resume url (#8480) ([bc06cc6](https://github.com/discordjs/discord.js/commit/bc06cc638d2f57ab5c600e8cdb6afc8eb2180166))
## Refactor
- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e))
# [@discordjs/rest@0.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.5.0...@discordjs/rest@0.6.0) - (2022-07-17)
## Documentation
- Add codecov coverage badge to readmes (#8226) ([f6db285](https://github.com/discordjs/discord.js/commit/f6db285c073898a749fe4591cbd4463d1896daf5))
## Features
- **builder:** Add max min length in string option (#8214) ([96c8d21](https://github.com/discordjs/discord.js/commit/96c8d21f95eb366c46ae23505ba9054f44821b25))
- Codecov (#8219) ([f10f4cd](https://github.com/discordjs/discord.js/commit/f10f4cdcd88ca6be7ec735ed3a415ba13da83db0))
- **docgen:** Update typedoc ([b3346f4](https://github.com/discordjs/discord.js/commit/b3346f4b9b3d4f96443506643d4631dc1c6d7b21))
- Website (#8043) ([127931d](https://github.com/discordjs/discord.js/commit/127931d1df7a2a5c27923c2f2151dbf3824e50cc))
- **docgen:** Typescript support ([3279b40](https://github.com/discordjs/discord.js/commit/3279b40912e6aa61507bedb7db15a2b8668de44b))
- Docgen package (#8029) ([8b979c0](https://github.com/discordjs/discord.js/commit/8b979c0245c42fd824d8e98745ee869f5360fc86))
- Use vitest instead of jest for more speed ([8d8e6c0](https://github.com/discordjs/discord.js/commit/8d8e6c03decd7352a2aa180f6e5bc1a13602539b))
- Add scripts package for locally used scripts ([f2ae1f9](https://github.com/discordjs/discord.js/commit/f2ae1f9348bfd893332a9060f71a8a5f272a1b8b))
## Refactor
- **rest:** Add content-type(s) to uploads (#8290) ([103a358](https://github.com/discordjs/discord.js/commit/103a3584c95a7b7f57fa62d47b86520d5ec32303))
- **collection:** Remove default export (#8053) ([16810f3](https://github.com/discordjs/discord.js/commit/16810f3e410bf35ed7e6e7412d517ea74c792c5d))
- Move all the config files to root (#8033) ([769ea0b](https://github.com/discordjs/discord.js/commit/769ea0bfe78c4f1d413c6b397c604ffe91e39c6a))
# [@discordjs/rest@0.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.4.0...@discordjs/rest@0.5.0) - (2022-06-04)
## Bug Fixes
- **REST:** Remove dom types (#7922) ([e92b17d](https://github.com/discordjs/discord.js/commit/e92b17d8555164ff259e524efc6a26675660e5c2))
- Ok statusCode can be 200..299 (#7919) ([d1504f2](https://github.com/discordjs/discord.js/commit/d1504f2ae19816b3fadcdb3ad17facc863ed7529))
## Features
- **rest:** Add guild member banner cdn url (#7973) ([97eaab3](https://github.com/discordjs/discord.js/commit/97eaab35d7383ecbbd93dc623ceda969286c1554))
- REST#raw (#7929) ([dfe449c](https://github.com/discordjs/discord.js/commit/dfe449c253b617e8f92c720a2f71135aa1601a65))
- **rest:** Use undici (#7747) ([d1ec8c3](https://github.com/discordjs/discord.js/commit/d1ec8c37ffb7fe3b63eaa8c382f22ca1fb348c9b))
- **REST:** Enable setting default authPrefix (#7853) ([679dcda](https://github.com/discordjs/discord.js/commit/679dcda9709376f37cc58a60f74d12d324d93e4e))
## Styling
- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629))
# [@discordjs/rest@0.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.3.0...@discordjs/rest@0.4.0) - (2022-04-17)
## Bug Fixes
- **gateway:** Use version 10 (#7689) ([8880de0](https://github.com/discordjs/discord.js/commit/8880de0cecdf273fd6df23988e4cb77774a75390))
- **RequestHandler:** Only reset tokens for authenticated 401s (#7508) ([b9ff7b0](https://github.com/discordjs/discord.js/commit/b9ff7b057379a47ce13265f78e21bf0d55feaf0a))
- **ci:** Ci error (#7454) ([0af9bc8](https://github.com/discordjs/discord.js/commit/0af9bc841ffe1a297d308500d696bad4b85abda9))
- Use png as extension for defaultAvatarURL (#7414) ([538e9ce](https://github.com/discordjs/discord.js/commit/538e9cef459d00d74b9bd6852da3ce2acac9bae5))
- **rest:** Sublimit all requests on unhandled routes (#7366) ([733ac82](https://github.com/discordjs/discord.js/commit/733ac82d5dffabc622fb59e06d06e83396734dc6))
- Fix some typos (#7393) ([92a04f4](https://github.com/discordjs/discord.js/commit/92a04f4d98f6c6760214034cc8f5a1eaa78893c7))
## Documentation
- Enhance /rest README (#7757) ([a1329bd](https://github.com/discordjs/discord.js/commit/a1329bd3ebafc6d5b5e2788ff082674f01b726f3))
## Features
- Add `makeURLSearchParams` utility function (#7744) ([8eaec11](https://github.com/discordjs/discord.js/commit/8eaec114a98026024c21545988860c123948c55d))
- Add API v10 support (#7477) ([72577c4](https://github.com/discordjs/discord.js/commit/72577c4bfd02524a27afb6ff4aebba9301a690d3))
- Add support for module: NodeNext in TS and ESM (#7598) ([8f1986a](https://github.com/discordjs/discord.js/commit/8f1986a6aa98365e09b00e84ad5f9f354ab61f3d))
- **builders:** Add attachment command option type (#7203) ([ae0f35f](https://github.com/discordjs/discord.js/commit/ae0f35f51d68dfa5a7dc43d161ef9365171debdb))
- **cdn:** Add support for scheduled event image covers (#7335) ([ac26d9b](https://github.com/discordjs/discord.js/commit/ac26d9b1307d63e116b043505e5f925db7ed01aa))
## Refactor
- **requestmanager:** Use timestampfrom (#7459) ([3298510](https://github.com/discordjs/discord.js/commit/32985109c3b7614d364007608f8c5af4bed753ae))
- **files:** Remove redundant file property names (#7340) ([6725038](https://github.com/discordjs/discord.js/commit/67250382f99872a9edff99ebaa482ffa895b0c37))
# [@discordjs/rest@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.2.0...@discordjs/rest@0.3.0) - (2022-01-24)
## Bug Fixes
- **rest:** Don't add empty query (#7308) ([d0fa5aa](https://github.com/discordjs/discord.js/commit/d0fa5aaa26d316608120bca3050e14eefbe2f93b))
- **rest:** Use http agent when protocol is not https (#7309) ([d8ea572](https://github.com/discordjs/discord.js/commit/d8ea572fb8a51f2f6a902c4926e814017d115708))
- `ref` delay for rate limited requests (#7239) ([ed0cfd9](https://github.com/discordjs/discord.js/commit/ed0cfd91edc3a2b23a34a8ecd9db38baa12b52fa))
## Documentation
- Fix a typo and use milliseconds instead of ms (#7251) ([0dd56af](https://github.com/discordjs/discord.js/commit/0dd56afe1cdf16f1e7d9afe1f8c29c31d1833a25))
## Features
- Rest hash and handler sweeping (#7255) ([3bb4829](https://github.com/discordjs/discord.js/commit/3bb48298004d292214c6cb8f927c2fea78a42952))
- Rest docs (#7281) ([9054f2f](https://github.com/discordjs/discord.js/commit/9054f2f7ad7f246431e5f53403535bf301c27a80))
## Refactor
- **files:** File data can be much more than buffer (#7238) ([86ab526](https://github.com/discordjs/discord.js/commit/86ab526d493415b14b79b51d08c3677897d219ee))
- **rest:** Rename attachment to file (#7199) ([c969cbf](https://github.com/discordjs/discord.js/commit/c969cbf6524093757d47108b6a55e62dcb210e8b))
## Testing
- **voice:** Fix tests ([62c74b8](https://github.com/discordjs/discord.js/commit/62c74b8333066465e5bd295b8b102b35a506751d))

192
node_modules/@discordjs/rest/LICENSE generated vendored Normal file
View file

@ -0,0 +1,192 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler
Copyright 2021 Vlad Frangu
Copyright 2021 Aura Román
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

115
node_modules/@discordjs/rest/README.md generated vendored Normal file
View file

@ -0,0 +1,115 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://www.npmjs.com/package/@discordjs/rest"><img src="https://img.shields.io/npm/v/@discordjs/rest.svg?maxAge=3600" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/@discordjs/rest"><img src="https://img.shields.io/npm/dt/@discordjs/rest.svg?maxAge=3600" alt="npm downloads" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Tests status" /></a>
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=rest" alt="Code coverage" /></a>
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
</p>
</div>
## About
`@discordjs/rest` is a module that allows you to easily make REST requests to the Discord API.
## Installation
**Node.js 16.9.0 or newer is required.**
```sh
npm install @discordjs/rest
yarn add @discordjs/rest
pnpm add @discordjs/rest
```
## Examples
Install all required dependencies:
```sh
npm install @discordjs/rest discord-api-types
yarn add @discordjs/rest discord-api-types
pnpm add @discordjs/rest discord-api-types
```
Send a basic message:
```js
import { REST } from '@discordjs/rest';
import { Routes } from 'discord-api-types/v10';
const rest = new REST({ version: '10' }).setToken(TOKEN);
try {
await rest.post(Routes.channelMessages(CHANNEL_ID), {
body: {
content: 'A message via REST!',
},
});
} catch (error) {
console.error(error);
}
```
Create a thread from an existing message to be archived after 60 minutes of inactivity:
```js
import { REST } from '@discordjs/rest';
import { Routes } from 'discord-api-types/v10';
const rest = new REST({ version: '10' }).setToken(TOKEN);
try {
await rest.post(Routes.threads(CHANNEL_ID, MESSAGE_ID), {
body: {
name: 'Thread',
auto_archive_duration: 60,
},
});
} catch (error) {
console.error(error);
}
```
## Links
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library.
- [discord.js Discord server][discord]
- [Discord API Discord server][discord-api]
- [GitHub][source]
- [npm][npm]
- [Related libraries][related-libs]
## Contributing
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
[documentation][documentation].
See [the contribution guide][contributing] if you'd like to submit a PR.
## Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord].
[website]: https://discord.js.org
[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website
[documentation]: https://discord.js.org/docs/packages/rest/stable
[guide]: https://discordjs.guide/
[guide-source]: https://github.com/discordjs/guide
[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html
[discord]: https://discord.gg/djs
[discord-api]: https://discord.gg/discord-api
[source]: https://github.com/discordjs/discord.js/tree/main/packages/rest
[npm]: https://www.npmjs.com/package/@discordjs/rest
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md

875
node_modules/@discordjs/rest/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,875 @@
import { Agent, Dispatcher, request, BodyInit } from 'undici';
import { Buffer } from 'node:buffer';
import { EventEmitter } from 'node:events';
import { URLSearchParams } from 'node:url';
import { Collection } from '@discordjs/collection';
declare const DefaultUserAgent: `DiscordBot (https://discord.js.org, ${string})`;
/**
* The default string to append onto the user agent.
*/
declare const DefaultUserAgentAppendix: string;
declare const DefaultRestOptions: {
readonly agent: Agent;
readonly api: "https://discord.com/api";
readonly authPrefix: "Bot";
readonly cdn: "https://cdn.discordapp.com";
readonly headers: {};
readonly invalidRequestWarningInterval: 0;
readonly globalRequestsPerSecond: 50;
readonly offset: 50;
readonly rejectOnRateLimit: null;
readonly retries: 3;
readonly timeout: 15000;
readonly userAgentAppendix: string;
readonly version: "10";
readonly hashSweepInterval: 14400000;
readonly hashLifetime: 86400000;
readonly handlerSweepInterval: 3600000;
};
/**
* The events that the REST manager emits
*/
declare enum RESTEvents {
Debug = "restDebug",
HandlerSweep = "handlerSweep",
HashSweep = "hashSweep",
InvalidRequestWarning = "invalidRequestWarning",
RateLimited = "rateLimited",
Response = "response"
}
declare const ALLOWED_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif"];
declare const ALLOWED_STICKER_EXTENSIONS: readonly ["png", "json", "gif"];
declare const ALLOWED_SIZES: readonly [16, 32, 64, 128, 256, 512, 1024, 2048, 4096];
type ImageExtension = (typeof ALLOWED_EXTENSIONS)[number];
type StickerExtension = (typeof ALLOWED_STICKER_EXTENSIONS)[number];
type ImageSize = (typeof ALLOWED_SIZES)[number];
declare const OverwrittenMimeTypes: {
readonly 'image/apng': "image/png";
};
declare const BurstHandlerMajorIdKey = "burst";
/**
* The options used for image URLs
*/
interface BaseImageURLOptions {
/**
* The extension to use for the image URL
*
* @defaultValue `'webp'`
*/
extension?: ImageExtension;
/**
* The size specified in the image URL
*/
size?: ImageSize;
}
/**
* The options used for image URLs with animated content
*/
interface ImageURLOptions extends BaseImageURLOptions {
/**
* Whether or not to prefer the static version of an image asset.
*/
forceStatic?: boolean;
}
/**
* The options to use when making a CDN URL
*/
interface MakeURLOptions {
/**
* The allowed extensions that can be used
*/
allowedExtensions?: readonly string[];
/**
* The extension to use for the image URL
*
* @defaultValue `'webp'`
*/
extension?: string | undefined;
/**
* The size specified in the image URL
*/
size?: ImageSize;
}
/**
* The CDN link builder
*/
declare class CDN {
private readonly base;
constructor(base?: string);
/**
* Generates an app asset URL for a client's asset.
*
* @param clientId - The client id that has the asset
* @param assetHash - The hash provided by Discord for this asset
* @param options - Optional options for the asset
*/
appAsset(clientId: string, assetHash: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Generates an app icon URL for a client's icon.
*
* @param clientId - The client id that has the icon
* @param iconHash - The hash provided by Discord for this icon
* @param options - Optional options for the icon
*/
appIcon(clientId: string, iconHash: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Generates an avatar URL, e.g. for a user or a webhook.
*
* @param id - The id that has the icon
* @param avatarHash - The hash provided by Discord for this avatar
* @param options - Optional options for the avatar
*/
avatar(id: string, avatarHash: string, options?: Readonly<ImageURLOptions>): string;
/**
* Generates a banner URL, e.g. for a user or a guild.
*
* @param id - The id that has the banner splash
* @param bannerHash - The hash provided by Discord for this banner
* @param options - Optional options for the banner
*/
banner(id: string, bannerHash: string, options?: Readonly<ImageURLOptions>): string;
/**
* Generates an icon URL for a channel, e.g. a group DM.
*
* @param channelId - The channel id that has the icon
* @param iconHash - The hash provided by Discord for this channel
* @param options - Optional options for the icon
*/
channelIcon(channelId: string, iconHash: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Generates the default avatar URL for a discriminator.
*
* @param discriminator - The discriminator modulo 5
*/
defaultAvatar(discriminator: number): string;
/**
* Generates a discovery splash URL for a guild's discovery splash.
*
* @param guildId - The guild id that has the discovery splash
* @param splashHash - The hash provided by Discord for this splash
* @param options - Optional options for the splash
*/
discoverySplash(guildId: string, splashHash: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Generates an emoji's URL for an emoji.
*
* @param emojiId - The emoji id
* @param extension - The extension of the emoji
*/
emoji(emojiId: string, extension?: ImageExtension): string;
/**
* Generates a guild member avatar URL.
*
* @param guildId - The id of the guild
* @param userId - The id of the user
* @param avatarHash - The hash provided by Discord for this avatar
* @param options - Optional options for the avatar
*/
guildMemberAvatar(guildId: string, userId: string, avatarHash: string, options?: Readonly<ImageURLOptions>): string;
/**
* Generates a guild member banner URL.
*
* @param guildId - The id of the guild
* @param userId - The id of the user
* @param bannerHash - The hash provided by Discord for this banner
* @param options - Optional options for the banner
*/
guildMemberBanner(guildId: string, userId: string, bannerHash: string, options?: Readonly<ImageURLOptions>): string;
/**
* Generates an icon URL, e.g. for a guild.
*
* @param id - The id that has the icon splash
* @param iconHash - The hash provided by Discord for this icon
* @param options - Optional options for the icon
*/
icon(id: string, iconHash: string, options?: Readonly<ImageURLOptions>): string;
/**
* Generates a URL for the icon of a role
*
* @param roleId - The id of the role that has the icon
* @param roleIconHash - The hash provided by Discord for this role icon
* @param options - Optional options for the role icon
*/
roleIcon(roleId: string, roleIconHash: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Generates a guild invite splash URL for a guild's invite splash.
*
* @param guildId - The guild id that has the invite splash
* @param splashHash - The hash provided by Discord for this splash
* @param options - Optional options for the splash
*/
splash(guildId: string, splashHash: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Generates a sticker URL.
*
* @param stickerId - The sticker id
* @param extension - The extension of the sticker
* @privateRemarks
* Stickers cannot have a `.webp` extension, so we default to a `.png`
*/
sticker(stickerId: string, extension?: StickerExtension): string;
/**
* Generates a sticker pack banner URL.
*
* @param bannerId - The banner id
* @param options - Optional options for the banner
*/
stickerPackBanner(bannerId: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Generates a team icon URL for a team's icon.
*
* @param teamId - The team id that has the icon
* @param iconHash - The hash provided by Discord for this icon
* @param options - Optional options for the icon
*/
teamIcon(teamId: string, iconHash: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Generates a cover image for a guild scheduled event.
*
* @param scheduledEventId - The scheduled event id
* @param coverHash - The hash provided by discord for this cover image
* @param options - Optional options for the cover image
*/
guildScheduledEventCover(scheduledEventId: string, coverHash: string, options?: Readonly<BaseImageURLOptions>): string;
/**
* Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.
*
* @param route - The base cdn route
* @param hash - The hash provided by Discord for this icon
* @param options - Optional options for the link
*/
private dynamicMakeURL;
/**
* Constructs the URL for the resource
*
* @param route - The base cdn route
* @param options - The extension/size options for the link
*/
private makeURL;
}
interface IHandler {
/**
* The unique id of the handler
*/
readonly id: string;
/**
* If the bucket is currently inactive (no pending requests)
*/
get inactive(): boolean;
/**
* Queues a request to be sent
*
* @param routeId - The generalized api route with literal ids for major parameters
* @param url - The url to do the request on
* @param options - All the information needed to make a request
* @param requestData - Extra data from the user's request needed for errors and additional processing
*/
queueRequest(routeId: RouteData, url: string, options: RequestOptions, requestData: HandlerRequestData): Promise<Dispatcher.ResponseData>;
}
/**
* Options to be passed when creating the REST instance
*/
interface RESTOptions {
/**
* The agent to set globally
*/
agent: Dispatcher;
/**
* The base api path, without version
*
* @defaultValue `'https://discord.com/api'`
*/
api: string;
/**
* The authorization prefix to use for requests, useful if you want to use
* bearer tokens
*
* @defaultValue `'Bot'`
*/
authPrefix: 'Bearer' | 'Bot';
/**
* The cdn path
*
* @defaultValue 'https://cdn.discordapp.com'
*/
cdn: string;
/**
* How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)
*
* @defaultValue `50`
*/
globalRequestsPerSecond: number;
/**
* The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)
*
* @defaultValue `3_600_000`
*/
handlerSweepInterval: number;
/**
* The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)
*
* @defaultValue `86_400_000`
*/
hashLifetime: number;
/**
* The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)
*
* @defaultValue `14_400_000`
*/
hashSweepInterval: number;
/**
* Additional headers to send for all API requests
*
* @defaultValue `{}`
*/
headers: Record<string, string>;
/**
* The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).
* That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.
*
* @defaultValue `0`
*/
invalidRequestWarningInterval: number;
/**
* The extra offset to add to rate limits in milliseconds
*
* @defaultValue `50`
*/
offset: number;
/**
* Determines how rate limiting and pre-emptive throttling should be handled.
* When an array of strings, each element is treated as a prefix for the request route
* (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)
* for which to throw {@link RateLimitError}s. All other request routes will be queued normally
*
* @defaultValue `null`
*/
rejectOnRateLimit: RateLimitQueueFilter | string[] | null;
/**
* The number of retries for errors with the 500 code, or errors
* that timeout
*
* @defaultValue `3`
*/
retries: number;
/**
* The time to wait in milliseconds before a request is aborted
*
* @defaultValue `15_000`
*/
timeout: number;
/**
* Extra information to add to the user agent
*
* @defaultValue DefaultUserAgentAppendix
*/
userAgentAppendix: string;
/**
* The version of the API to use
*
* @defaultValue `'10'`
*/
version: string;
}
/**
* Data emitted on `RESTEvents.RateLimited`
*/
interface RateLimitData {
/**
* Whether the rate limit that was reached was the global limit
*/
global: boolean;
/**
* The bucket hash for this request
*/
hash: string;
/**
* The amount of requests we can perform before locking requests
*/
limit: number;
/**
* The major parameter of the route
*
* For example, in `/channels/x`, this will be `x`.
* If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.
*/
majorParameter: string;
/**
* The HTTP method being performed
*/
method: string;
/**
* The route being hit in this request
*/
route: string;
/**
* The time, in milliseconds, until the request-lock is reset
*/
timeToReset: number;
/**
* The full URL for this request
*/
url: string;
}
/**
* A function that determines whether the rate limit hit should throw an Error
*/
type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise<boolean> | boolean;
interface APIRequest {
/**
* The data that was used to form the body of this request
*/
data: HandlerRequestData;
/**
* The HTTP method used in this request
*/
method: string;
/**
* Additional HTTP options for this request
*/
options: RequestOptions;
/**
* The full path used to make the request
*/
path: RouteLike;
/**
* The number of times this request has been attempted
*/
retries: number;
/**
* The API route identifying the ratelimit for this request
*/
route: string;
}
interface InvalidRequestWarningData {
/**
* Number of invalid requests that have been made in the window
*/
count: number;
/**
* Time in milliseconds remaining before the count resets
*/
remainingTime: number;
}
interface RestEvents {
handlerSweep: [sweptHandlers: Collection<string, IHandler>];
hashSweep: [sweptHashes: Collection<string, HashData>];
invalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];
newListener: [name: string, listener: (...args: any) => void];
rateLimited: [rateLimitInfo: RateLimitData];
removeListener: [name: string, listener: (...args: any) => void];
response: [request: APIRequest, response: Dispatcher.ResponseData];
restDebug: [info: string];
}
type RequestOptions = Exclude<Parameters<typeof request>[1], undefined>;
interface REST {
emit: (<K extends keyof RestEvents>(event: K, ...args: RestEvents[K]) => boolean) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, ...args: any[]) => boolean);
off: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
on: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
once: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
removeAllListeners: (<K extends keyof RestEvents>(event?: K) => this) & (<S extends string | symbol>(event?: Exclude<S, keyof RestEvents>) => this);
}
declare class REST extends EventEmitter {
readonly cdn: CDN;
readonly requestManager: RequestManager;
constructor(options?: Partial<RESTOptions>);
/**
* Gets the agent set for this instance
*/
getAgent(): Dispatcher | null;
/**
* Sets the default agent to use for requests performed by this instance
*
* @param agent - Sets the agent to use
*/
setAgent(agent: Dispatcher): this;
/**
* Sets the authorization token that should be used for requests
*
* @param token - The authorization token to use
*/
setToken(token: string): this;
/**
* Runs a get request from the api
*
* @param fullRoute - The full route to query
* @param options - Optional request options
*/
get(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
/**
* Runs a delete request from the api
*
* @param fullRoute - The full route to query
* @param options - Optional request options
*/
delete(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
/**
* Runs a post request from the api
*
* @param fullRoute - The full route to query
* @param options - Optional request options
*/
post(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
/**
* Runs a put request from the api
*
* @param fullRoute - The full route to query
* @param options - Optional request options
*/
put(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
/**
* Runs a patch request from the api
*
* @param fullRoute - The full route to query
* @param options - Optional request options
*/
patch(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
/**
* Runs a request from the api
*
* @param options - Request options
*/
request(options: InternalRequest): Promise<unknown>;
/**
* Runs a request from the API, yielding the raw Response object
*
* @param options - Request options
*/
raw(options: InternalRequest): Promise<Dispatcher.ResponseData>;
}
/**
* Represents a file to be added to the request
*/
interface RawFile {
/**
* Content-Type of the file
*/
contentType?: string;
/**
* The actual data for the file
*/
data: Buffer | boolean | number | string;
/**
* An explicit key to use for key of the formdata field for this file.
* When not provided, the index of the file in the files array is used in the form `files[${index}]`.
* If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)
*/
key?: string;
/**
* The name of the file
*/
name: string;
}
/**
* Represents possible data to be given to an endpoint
*/
interface RequestData {
/**
* Whether to append JSON data to form data instead of `payload_json` when sending files
*/
appendToFormData?: boolean;
/**
* If this request needs the `Authorization` header
*
* @defaultValue `true`
*/
auth?: boolean;
/**
* The authorization prefix to use for this request, useful if you use this with bearer tokens
*
* @defaultValue `'Bot'`
*/
authPrefix?: 'Bearer' | 'Bot';
/**
* The body to send to this request.
* If providing as BodyInit, set `passThroughBody: true`
*/
body?: BodyInit | unknown;
/**
* The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.
*/
dispatcher?: Agent;
/**
* Files to be attached to this request
*/
files?: RawFile[] | undefined;
/**
* Additional headers to add to this request
*/
headers?: Record<string, string>;
/**
* Whether to pass-through the body property directly to `fetch()`.
* <warn>This only applies when files is NOT present</warn>
*/
passThroughBody?: boolean;
/**
* Query string parameters to append to the called endpoint
*/
query?: URLSearchParams;
/**
* Reason to show in the audit logs
*/
reason?: string | undefined;
/**
* The signal to abort the queue entry or the REST call, where applicable
*/
signal?: AbortSignal | undefined;
/**
* If this request should be versioned
*
* @defaultValue `true`
*/
versioned?: boolean;
}
/**
* Possible headers for an API call
*/
interface RequestHeaders {
Authorization?: string;
'User-Agent': string;
'X-Audit-Log-Reason'?: string;
}
/**
* Possible API methods to be used when doing requests
*/
declare enum RequestMethod {
Delete = "DELETE",
Get = "GET",
Patch = "PATCH",
Post = "POST",
Put = "PUT"
}
type RouteLike = `/${string}`;
/**
* Internal request options
*
* @internal
*/
interface InternalRequest extends RequestData {
fullRoute: RouteLike;
method: RequestMethod;
}
type HandlerRequestData = Pick<InternalRequest, 'auth' | 'body' | 'files' | 'signal'>;
/**
* Parsed route data for an endpoint
*
* @internal
*/
interface RouteData {
bucketRoute: string;
majorParameter: string;
original: RouteLike;
}
/**
* Represents a hash and its associated fields
*
* @internal
*/
interface HashData {
lastAccess: number;
value: string;
}
interface RequestManager {
emit: (<K extends keyof RestEvents>(event: K, ...args: RestEvents[K]) => boolean) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, ...args: any[]) => boolean);
off: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
on: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
once: (<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void) => this) & (<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void) => this);
removeAllListeners: (<K extends keyof RestEvents>(event?: K) => this) & (<S extends string | symbol>(event?: Exclude<S, keyof RestEvents>) => this);
}
/**
* Represents the class that manages handlers for endpoints
*/
declare class RequestManager extends EventEmitter {
#private;
/**
* The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests
* performed by this manager.
*/
agent: Dispatcher | null;
/**
* The number of requests remaining in the global bucket
*/
globalRemaining: number;
/**
* The promise used to wait out the global rate limit
*/
globalDelay: Promise<void> | null;
/**
* The timestamp at which the global bucket resets
*/
globalReset: number;
/**
* API bucket hashes that are cached from provided routes
*/
readonly hashes: Collection<string, HashData>;
/**
* Request handlers created from the bucket hash and the major parameters
*/
readonly handlers: Collection<string, IHandler>;
private hashTimer;
private handlerTimer;
readonly options: RESTOptions;
constructor(options: Partial<RESTOptions>);
private setupSweepers;
/**
* Sets the default agent to use for requests performed by this manager
*
* @param agent - The agent to use
*/
setAgent(agent: Dispatcher): this;
/**
* Sets the authorization token that should be used for requests
*
* @param token - The authorization token to use
*/
setToken(token: string): this;
/**
* Queues a request to be sent
*
* @param request - All the information needed to make a request
* @returns The response from the api request
*/
queueRequest(request: InternalRequest): Promise<Dispatcher.ResponseData>;
/**
* Creates a new rate limit handler from a hash, based on the hash and the major parameter
*
* @param hash - The hash for the route
* @param majorParameter - The major parameter for this handler
* @internal
*/
private createHandler;
/**
* Formats the request data to a usable format for fetch
*
* @param request - The request data
*/
private resolveRequest;
/**
* Stops the hash sweeping interval
*/
clearHashSweeper(): void;
/**
* Stops the request handler sweeping interval
*/
clearHandlerSweeper(): void;
/**
* Generates route data for an endpoint:method
*
* @param endpoint - The raw endpoint to generalize
* @param method - The HTTP method this endpoint is called without
* @internal
*/
private static generateRouteData;
}
interface DiscordErrorFieldInformation {
code: string;
message: string;
}
interface DiscordErrorGroupWrapper {
_errors: DiscordError[];
}
type DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | {
[k: string]: DiscordError;
};
interface DiscordErrorData {
code: number;
errors?: DiscordError;
message: string;
}
interface OAuthErrorData {
error: string;
error_description?: string;
}
interface RequestBody {
files: RawFile[] | undefined;
json: unknown | undefined;
}
/**
* Represents an API error returned by Discord
*/
declare class DiscordAPIError extends Error {
rawError: DiscordErrorData | OAuthErrorData;
code: number | string;
status: number;
method: string;
url: string;
requestBody: RequestBody;
/**
* @param rawError - The error reported by Discord
* @param code - The error code reported by Discord
* @param status - The status code of the response
* @param method - The method of the request that erred
* @param url - The url of the request that erred
* @param bodyData - The unparsed data for the request that errored
*/
constructor(rawError: DiscordErrorData | OAuthErrorData, code: number | string, status: number, method: string, url: string, bodyData: Pick<InternalRequest, 'body' | 'files'>);
/**
* The name of the error
*/
get name(): string;
private static getMessage;
private static flattenDiscordError;
}
/**
* Represents a HTTP error
*/
declare class HTTPError extends Error {
status: number;
method: string;
url: string;
requestBody: RequestBody;
name: string;
/**
* @param status - The status code of the response
* @param method - The method of the request that erred
* @param url - The url of the request that erred
* @param bodyData - The unparsed data for the request that errored
*/
constructor(status: number, method: string, url: string, bodyData: Pick<InternalRequest, 'body' | 'files'>);
}
declare class RateLimitError extends Error implements RateLimitData {
timeToReset: number;
limit: number;
method: string;
hash: string;
url: string;
route: string;
majorParameter: string;
global: boolean;
constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData);
/**
* The name of the error
*/
get name(): string;
}
/**
* Creates and populates an URLSearchParams instance from an object, stripping
* out null and undefined values, while also coercing non-strings to strings.
*
* @param options - The options to use
* @returns A populated URLSearchParams instance
*/
declare function makeURLSearchParams<T extends object>(options?: Readonly<T>): URLSearchParams;
/**
* Converts the response to usable data
*
* @param res - The fetch response
*/
declare function parseResponse(res: Dispatcher.ResponseData): Promise<unknown>;
/**
* The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version
* that you are currently using.
*/
declare const version: string;
export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, APIRequest, BaseImageURLOptions, BurstHandlerMajorIdKey, CDN, DefaultRestOptions, DefaultUserAgent, DefaultUserAgentAppendix, DiscordAPIError, DiscordErrorData, HTTPError, HandlerRequestData, HashData, ImageExtension, ImageSize, ImageURLOptions, InternalRequest, InvalidRequestWarningData, MakeURLOptions, OAuthErrorData, OverwrittenMimeTypes, REST, RESTEvents, RESTOptions, RateLimitData, RateLimitError, RateLimitQueueFilter, RawFile, RequestBody, RequestData, RequestHeaders, RequestManager, RequestMethod, RequestOptions, RestEvents, RouteData, RouteLike, StickerExtension, makeURLSearchParams, parseResponse, version };

1425
node_modules/@discordjs/rest/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/rest/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

1372
node_modules/@discordjs/rest/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/rest/dist/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

87
node_modules/@discordjs/rest/package.json generated vendored Normal file
View file

@ -0,0 +1,87 @@
{
"name": "@discordjs/rest",
"version": "1.7.1",
"description": "The REST API for discord.js",
"scripts": {
"test": "vitest run",
"build": "tsup",
"build:docs": "tsc -p tsconfig.docs.json",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"fmt": "yarn format",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/rest/*'",
"release": "cliff-jumper"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"typings": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"directories": {
"lib": "src",
"test": "__tests__"
},
"files": [
"dist"
],
"contributors": [
"Crawl <icrawltogo@gmail.com>",
"Amish Shah <amishshah.2k@gmail.com>",
"SpaceEEC <spaceeec@yahoo.com>",
"Vlad Frangu <kingdgrizzle@gmail.com>",
"Aura Román <kyradiscord@gmail.com>"
],
"license": "Apache-2.0",
"keywords": [
"discord",
"api",
"rest",
"discordapp",
"discordjs"
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/rest"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/collection": "^1.5.1",
"@discordjs/util": "^0.3.0",
"@sapphire/async-queue": "^1.5.0",
"@sapphire/snowflake": "^3.4.2",
"discord-api-types": "^0.37.41",
"file-type": "^18.3.0",
"tslib": "^2.5.0",
"undici": "^5.22.0"
},
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.6",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"esbuild-plugin-version-injector": "^1.1.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

57
node_modules/@discordjs/util/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,57 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@discordjs/util@0.3.1](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.3.0...@discordjs/util@0.3.1) - (2023-05-01)
## Refactor
- **ShardClientUtil:** Logic de-duplication (#9491) ([a9f2bff](https://github.com/discordjs/discord.js/commit/a9f2bff82a18c6a3afdee99e5830e1d7b4da65dc))
# [@discordjs/util@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.2.0...@discordjs/util@0.3.0) - (2023-05-01)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b))
## Documentation
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
## Features
- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b))
# [@discordjs/util@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.2.0...@discordjs/util@0.3.0) - (2023-05-01)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b))
## Documentation
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
## Features
- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b))
# [@discordjs/util@0.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.1.0...@discordjs/util@0.2.0) - (2023-03-12)
## Bug Fixes
- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4))
## Features
- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38))
- **core:** Implement some ws send events (#8941) ([816aed4](https://github.com/discordjs/discord.js/commit/816aed478e3035060697092d52ad2b58106be0ee))
- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2))
# [@discordjs/util@0.1.0](https://github.com/discordjs/discord.js/tree/@discordjs/util@0.1.0) - (2022-10-03)
## Features
- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3))

190
node_modules/@discordjs/util/LICENSE generated vendored Normal file
View file

@ -0,0 +1,190 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2022 Noel Buechler
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

63
node_modules/@discordjs/util/README.md generated vendored Normal file
View file

@ -0,0 +1,63 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
</p>
</div>
## About
`@discordjs/util` is a collection of utility functions for use with discord.js.
## Installation
**Node.js 16.9.0 or newer is required.**
```sh
npm install @discordjs/util
yarn add @discordjs/util
pnpm add @discordjs/util
```
## Links
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library.
- [discord.js Discord server][discord]
- [Discord API Discord server][discord-api]
- [GitHub][source]
- [npm][npm]
- [Related libraries][related-libs]
## Contributing
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
[documentation][documentation].
See [the contribution guide][contributing] if you'd like to submit a PR.
## Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord].
[website]: https://discord.js.org
[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website
[documentation]: https://discord.js.org/docs/packages/util/stable
[guide]: https://discordjs.guide/
[guide-source]: https://github.com/discordjs/guide
[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html
[discord]: https://discord.gg/djs
[discord-api]: https://discord.gg/discord-api
[source]: https://github.com/discordjs/discord.js/tree/main/packages/util
[npm]: https://www.npmjs.com/package/@discordjs/util
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md

110
node_modules/@discordjs/util/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,110 @@
/**
* Represents a type that may or may not be a promise
*/
type Awaitable<T> = PromiseLike<T> | T;
/**
* Lazy is a wrapper around a value that is computed lazily. It is useful for
* cases where the value is expensive to compute and the computation may not
* be needed at all.
*
* @param cb - The callback to lazily evaluate
* @typeParam T - The type of the value
* @example
* ```ts
* const value = lazy(() => computeExpensiveValue());
* ```
*/
declare function lazy<T>(cb: () => T): () => T;
/**
* Options for creating a range
*/
interface RangeOptions {
/**
* The end of the range (exclusive)
*/
end: number;
/**
* The start of the range (inclusive)
*/
start: number;
/**
* The amount to increment by
*
* @defaultValue `1`
*/
step?: number;
}
/**
* A generator to yield numbers in a given range
*
* @remarks
* This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you
* prefer for the end to be included add 1 to the range or `end` option.
* @param range - A number representing the the range to yield (exclusive) or an object with start, end and step
* @example
* Basic range
* ```ts
* for (const number of range(5)) {
* console.log(number);
* }
* // Prints 0, 1, 2, 3, 4
* ```
* @example
* Range with a step
* ```ts
* for (const number of range({ start: 3, end: 10, step: 2 })) {
* console.log(number);
* }
* // Prints 3, 5, 7, 9
* ```
*/
declare function range(range: RangeOptions | number): Generator<number, void, unknown>;
/**
* Calculates the shard id for a given guild id.
*
* @param guildId - The guild id to calculate the shard id for
* @param shardCount - The total number of shards
*/
declare function calculateShardId(guildId: string, shardCount: number): number;
/**
* Represents an object capable of representing itself as a JSON object
*
* @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.
*/
interface JSONEncodable<T> {
/**
* Transforms this object to its JSON format
*/
toJSON(): T;
}
/**
* Indicates if an object is encodable or not.
*
* @param maybeEncodable - The object to check against
*/
declare function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable<unknown>;
/**
* Represents a structure that can be checked against another
* given structure for equality
*
* @typeParam T - The type of object to compare the current object to
*/
interface Equatable<T> {
/**
* Whether or not this is equal to another structure
*/
equals(other: T): boolean;
}
/**
* Indicates if an object is equatable or not.
*
* @param maybeEquatable - The object to check against
*/
declare function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable<unknown>;
export { Awaitable, Equatable, JSONEncodable, RangeOptions, calculateShardId, isEquatable, isJSONEncodable, lazy, range };

82
node_modules/@discordjs/util/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,82 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
calculateShardId: () => calculateShardId,
isEquatable: () => isEquatable,
isJSONEncodable: () => isJSONEncodable,
lazy: () => lazy,
range: () => range
});
module.exports = __toCommonJS(src_exports);
// src/functions/lazy.ts
function lazy(cb) {
let defaultValue;
return () => defaultValue ??= cb();
}
__name(lazy, "lazy");
// src/functions/range.ts
function* range(range2) {
let rangeEnd;
let start = 0;
let step = 1;
if (typeof range2 === "number") {
rangeEnd = range2;
} else {
start = range2.start;
rangeEnd = range2.end;
step = range2.step ?? 1;
}
for (let index = start; index < rangeEnd; index += step) {
yield index;
}
}
__name(range, "range");
// src/functions/calculateShardId.ts
function calculateShardId(guildId, shardCount) {
return Number(BigInt(guildId) >> 22n) % shardCount;
}
__name(calculateShardId, "calculateShardId");
// src/JSONEncodable.ts
function isJSONEncodable(maybeEncodable) {
return maybeEncodable !== null && typeof maybeEncodable === "object" && "toJSON" in maybeEncodable;
}
__name(isJSONEncodable, "isJSONEncodable");
// src/Equatable.ts
function isEquatable(maybeEquatable) {
return maybeEquatable !== null && typeof maybeEquatable === "object" && "equals" in maybeEquatable;
}
__name(isEquatable, "isEquatable");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
calculateShardId,
isEquatable,
isJSONEncodable,
lazy,
range
});
//# sourceMappingURL=index.js.map

1
node_modules/@discordjs/util/dist/index.js.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"sources":["../src/index.ts","../src/functions/lazy.ts","../src/functions/range.ts","../src/functions/calculateShardId.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["export * from './types.js';\nexport * from './functions/index.js';\nexport * from './JSONEncodable.js';\nexport * from './Equatable.js';\n","/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy<T>(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Options for creating a range\n */\nexport interface RangeOptions {\n\t/**\n\t * The end of the range (exclusive)\n\t */\n\tend: number;\n\t/**\n\t * The start of the range (inclusive)\n\t */\n\tstart: number;\n\t/**\n\t * The amount to increment by\n\t *\n\t * @defaultValue `1`\n\t */\n\tstep?: number;\n}\n\n/**\n * A generator to yield numbers in a given range\n *\n * @remarks\n * This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you\n * prefer for the end to be included add 1 to the range or `end` option.\n * @param range - A number representing the the range to yield (exclusive) or an object with start, end and step\n * @example\n * Basic range\n * ```ts\n * for (const number of range(5)) {\n * console.log(number);\n * }\n * // Prints 0, 1, 2, 3, 4\n * ```\n * @example\n * Range with a step\n * ```ts\n * for (const number of range({ start: 3, end: 10, step: 2 })) {\n * \tconsole.log(number);\n * }\n * // Prints 3, 5, 7, 9\n * ```\n */\nexport function* range(range: RangeOptions | number) {\n\tlet rangeEnd: number;\n\tlet start = 0;\n\tlet step = 1;\n\n\tif (typeof range === 'number') {\n\t\trangeEnd = range;\n\t} else {\n\t\tstart = range.start;\n\t\trangeEnd = range.end;\n\t\tstep = range.step ?? 1;\n\t}\n\n\tfor (let index = start; index < rangeEnd; index += step) {\n\t\tyield index;\n\t}\n}\n","/**\n * Calculates the shard id for a given guild id.\n *\n * @param guildId - The guild id to calculate the shard id for\n * @param shardCount - The total number of shards\n */\nexport function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number(BigInt(guildId) >> 22n) % shardCount;\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable<T> {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable<unknown> {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable<T> {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable<unknown> {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;AC+BT,UAAU,MAAMA,QAA8B;AACpD,MAAI;AACJ,MAAI,QAAQ;AACZ,MAAI,OAAO;AAEX,MAAI,OAAOA,WAAU,UAAU;AAC9B,eAAWA;AAAA,EACZ,OAAO;AACN,YAAQA,OAAM;AACd,eAAWA,OAAM;AACjB,WAAOA,OAAM,QAAQ;AAAA,EACtB;AAEA,WAAS,QAAQ,OAAO,QAAQ,UAAU,SAAS,MAAM;AACxD,UAAM;AAAA,EACP;AACD;AAhBiB;;;ACtCV,SAAS,iBAAiB,SAAiB,YAAoB;AACrE,SAAO,OAAO,OAAO,OAAO,KAAK,GAAG,IAAI;AACzC;AAFgB;;;ACWT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":["range"]}

53
node_modules/@discordjs/util/dist/index.mjs generated vendored Normal file
View file

@ -0,0 +1,53 @@
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/functions/lazy.ts
function lazy(cb) {
let defaultValue;
return () => defaultValue ??= cb();
}
__name(lazy, "lazy");
// src/functions/range.ts
function* range(range2) {
let rangeEnd;
let start = 0;
let step = 1;
if (typeof range2 === "number") {
rangeEnd = range2;
} else {
start = range2.start;
rangeEnd = range2.end;
step = range2.step ?? 1;
}
for (let index = start; index < rangeEnd; index += step) {
yield index;
}
}
__name(range, "range");
// src/functions/calculateShardId.ts
function calculateShardId(guildId, shardCount) {
return Number(BigInt(guildId) >> 22n) % shardCount;
}
__name(calculateShardId, "calculateShardId");
// src/JSONEncodable.ts
function isJSONEncodable(maybeEncodable) {
return maybeEncodable !== null && typeof maybeEncodable === "object" && "toJSON" in maybeEncodable;
}
__name(isJSONEncodable, "isJSONEncodable");
// src/Equatable.ts
function isEquatable(maybeEquatable) {
return maybeEquatable !== null && typeof maybeEquatable === "object" && "equals" in maybeEquatable;
}
__name(isEquatable, "isEquatable");
export {
calculateShardId,
isEquatable,
isJSONEncodable,
lazy,
range
};
//# sourceMappingURL=index.mjs.map

1
node_modules/@discordjs/util/dist/index.mjs.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"sources":["../src/functions/lazy.ts","../src/functions/range.ts","../src/functions/calculateShardId.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy<T>(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Options for creating a range\n */\nexport interface RangeOptions {\n\t/**\n\t * The end of the range (exclusive)\n\t */\n\tend: number;\n\t/**\n\t * The start of the range (inclusive)\n\t */\n\tstart: number;\n\t/**\n\t * The amount to increment by\n\t *\n\t * @defaultValue `1`\n\t */\n\tstep?: number;\n}\n\n/**\n * A generator to yield numbers in a given range\n *\n * @remarks\n * This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you\n * prefer for the end to be included add 1 to the range or `end` option.\n * @param range - A number representing the the range to yield (exclusive) or an object with start, end and step\n * @example\n * Basic range\n * ```ts\n * for (const number of range(5)) {\n * console.log(number);\n * }\n * // Prints 0, 1, 2, 3, 4\n * ```\n * @example\n * Range with a step\n * ```ts\n * for (const number of range({ start: 3, end: 10, step: 2 })) {\n * \tconsole.log(number);\n * }\n * // Prints 3, 5, 7, 9\n * ```\n */\nexport function* range(range: RangeOptions | number) {\n\tlet rangeEnd: number;\n\tlet start = 0;\n\tlet step = 1;\n\n\tif (typeof range === 'number') {\n\t\trangeEnd = range;\n\t} else {\n\t\tstart = range.start;\n\t\trangeEnd = range.end;\n\t\tstep = range.step ?? 1;\n\t}\n\n\tfor (let index = start; index < rangeEnd; index += step) {\n\t\tyield index;\n\t}\n}\n","/**\n * Calculates the shard id for a given guild id.\n *\n * @param guildId - The guild id to calculate the shard id for\n * @param shardCount - The total number of shards\n */\nexport function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number(BigInt(guildId) >> 22n) % shardCount;\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable<T> {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable<unknown> {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable<T> {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable<unknown> {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;AAaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;AC+BT,UAAU,MAAMA,QAA8B;AACpD,MAAI;AACJ,MAAI,QAAQ;AACZ,MAAI,OAAO;AAEX,MAAI,OAAOA,WAAU,UAAU;AAC9B,eAAWA;AAAA,EACZ,OAAO;AACN,YAAQA,OAAM;AACd,eAAWA,OAAM;AACjB,WAAOA,OAAM,QAAQ;AAAA,EACtB;AAEA,WAAS,QAAQ,OAAO,QAAQ,UAAU,SAAS,MAAM;AACxD,UAAM;AAAA,EACP;AACD;AAhBiB;;;ACtCV,SAAS,iBAAiB,SAAiB,YAAoB;AACrE,SAAO,OAAO,OAAO,OAAO,KAAK,GAAG,IAAI;AACzC;AAFgB;;;ACWT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":["range"]}

79
node_modules/@discordjs/util/package.json generated vendored Normal file
View file

@ -0,0 +1,79 @@
{
"name": "@discordjs/util",
"version": "0.3.1",
"description": "Utilities shared across Discord.js packages",
"scripts": {
"build": "tsup",
"build:docs": "tsc -p tsconfig.docs.json",
"test": "vitest run && tsd",
"lint": "prettier --check . && TIMING=1 eslint src --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && TIMING=1 eslint src --ext .mjs,.js,.ts --fix --format=pretty",
"fmt": "yarn format",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/util/*'",
"release": "cliff-jumper"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"directories": {
"lib": "src"
},
"files": [
"dist"
],
"contributors": [
"Crawl <icrawltogo@gmail.com>",
"Amish Shah <amishshah.2k@gmail.com>",
"Vlad Frangu <kingdgrizzle@gmail.com>",
"SpaceEEC <spaceeec@yahoo.com>",
"Aura Román <kyradiscord@gmail.com>"
],
"license": "Apache-2.0",
"keywords": [
"api",
"bot",
"client",
"node",
"discordjs"
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/util"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.6",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.8",
"tsd": "^0.28.1",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
},
"tsd": {
"directory": "__tests__/types"
}
}

193
node_modules/@discordjs/ws/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,193 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@discordjs/ws@0.8.3](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.2...@discordjs/ws@0.8.3) - (2023-05-06)
## Bug Fixes
- **WebSocketShard:** Wait a little before reconnecting (#9517) ([00da44a](https://github.com/discordjs/discord.js/commit/00da44a120fb0eeb2bdc3a03670836a544dc5418))
## Testing
- **ws:** Fix tests (#9520) ([3e80f0b](https://github.com/discordjs/discord.js/commit/3e80f0b384ea2dc14c1b60b5897e90040cab9a24))
# [@discordjs/ws@0.8.2](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.1...@discordjs/ws@0.8.2) - (2023-05-01)
## Documentation
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
# [@discordjs/ws@0.8.1](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.0...@discordjs/ws@0.8.1) - (2023-04-16)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Refactor
- Abstract identify throttling and correct max_concurrency handling (#9375) ([02dfaf1](https://github.com/discordjs/discord.js/commit/02dfaf1aa2c798315d0dd7f809cc469771b36ffc))
- **WebSocketShard:** WaitForEvent and its error handling (#9282) ([dcf58d8](https://github.com/discordjs/discord.js/commit/dcf58d81401387a5e157b20829aa56638e106e9d))
# [@discordjs/ws@0.8.2](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.1...@discordjs/ws@0.8.2) - (2023-05-01)
## Documentation
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
# [@discordjs/ws@0.8.1](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.0...@discordjs/ws@0.8.1) - (2023-04-16)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Refactor
- Abstract identify throttling and correct max_concurrency handling (#9375) ([02dfaf1](https://github.com/discordjs/discord.js/commit/02dfaf1aa2c798315d0dd7f809cc469771b36ffc))
- **WebSocketShard:** WaitForEvent and its error handling (#9282) ([dcf58d8](https://github.com/discordjs/discord.js/commit/dcf58d81401387a5e157b20829aa56638e106e9d))
# [@discordjs/ws@0.8.1](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.8.0...@discordjs/ws@0.8.1) - (2023-04-16)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Refactor
- Abstract identify throttling and correct max_concurrency handling (#9375) ([02dfaf1](https://github.com/discordjs/discord.js/commit/02dfaf1aa2c798315d0dd7f809cc469771b36ffc))
- **WebSocketShard:** WaitForEvent and its error handling (#9282) ([dcf58d8](https://github.com/discordjs/discord.js/commit/dcf58d81401387a5e157b20829aa56638e106e9d))
# [@discordjs/ws@0.8.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.7.0...@discordjs/ws@0.8.0) - (2023-04-01)
## Bug Fixes
- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b))
- **WebSocketShard:** Don't await #destroy in error bubbling logic (#9276) ([519825a](https://github.com/discordjs/discord.js/commit/519825a651fe22042a73046824d12f03f56ca9e2))
- **WebSocketShard:** Don't close in #destroy when status is connecting (#9254) ([c76b17d](https://github.com/discordjs/discord.js/commit/c76b17d3b327fb55ef76770d4825e02ab8f26ad1))
- **WebSocketShard:** Cancel initial heartbeat in destroy (#9244) ([9842082](https://github.com/discordjs/discord.js/commit/98420826bc2296fc392f17e8254cf4ad743ff5af))
## Features
- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b))
# [@discordjs/ws@0.7.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.6.0...@discordjs/ws@0.7.0) - (2023-03-12)
## Bug Fixes
- **WebSocketShard:** #send race condition due to ready state (#9226) ([a99fc64](https://github.com/discordjs/discord.js/commit/a99fc64e3f73c3976617a7ed825fa7d6e9fb3b53))
- **WebSocketShard:** Wait for hello rather than ready in connect (#9178) ([27e0b32](https://github.com/discordjs/discord.js/commit/27e0b32c5f0fe605f152e6ba67ce3f596137ff01))
- **WebSocketShard:** Proper error bubbling (#9119) ([9681f34](https://github.com/discordjs/discord.js/commit/9681f348770b0e2ff9b7c96b1c30575dd950e2ed))
- Ws typo (#9056) ([05a1cbf](https://github.com/discordjs/discord.js/commit/05a1cbfe5479195b0bc9b6f0971fe39f6af6fd77))
## Documentation
- Fix typos (#9127) ([1ba1f23](https://github.com/discordjs/discord.js/commit/1ba1f238f04221ec890fc921678909b5b7d92c26))
- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28))
- Updated @discordjs/ws README.md to include optional packages (#8973) ([4ee00b6](https://github.com/discordjs/discord.js/commit/4ee00b6534fad39da1fe54fb2c1766b264a020ca))
## Features
- **WebSocketShard:** Heartbeat jitter (#9223) ([6ecff26](https://github.com/discordjs/discord.js/commit/6ecff26ec65ce1d559a3406b396b3190868b1961))
- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38))
- **ws:** Custom workers (#9004) ([828a13b](https://github.com/discordjs/discord.js/commit/828a13b526dde1334e8879e76e664584bdb5db73))
- **ws:** Metrics (#9005) ([0ff67d8](https://github.com/discordjs/discord.js/commit/0ff67d8e7adee43ff82bbf072dac9a4c7c9fe8c2))
## Refactor
- **WebSocketManager:** Passing in strategy (#9122) ([5c5a583](https://github.com/discordjs/discord.js/commit/5c5a5832b94cd4d371cc99c4f9c3384523dabeeb))
## Styling
- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b))
# [@discordjs/ws@0.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.5.0...@discordjs/ws@0.6.0) - (2022-12-16)
## Bug Fixes
- **WebSocketShard:** Send ratelimit handling (#8887) ([40b504a](https://github.com/discordjs/discord.js/commit/40b504a2088effc6a467f40ac3cf2a6d736ab209))
## Features
- **core:** Add support for role connections (#8930) ([3d6fa24](https://github.com/discordjs/discord.js/commit/3d6fa248c07b2278504bbe8bafa17a3294971fd9))
## Refactor
- **WebSocketShard:** Identify throttling (#8888) ([8f552a0](https://github.com/discordjs/discord.js/commit/8f552a0e17c0eca71063e7a4353b9b351bcdf9fd))
# [@discordjs/ws@0.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.4.1...@discordjs/ws@0.5.0) - (2022-11-28)
## Bug Fixes
- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4))
## Documentation
- Remove unused imports (#8744) ([179392d](https://github.com/discordjs/discord.js/commit/179392d6d7d634c6d10f6abb20c072516c1c1d43))
## Features
- New select menus (#8793) ([5152abf](https://github.com/discordjs/discord.js/commit/5152abf7285581abf7689e9050fdc56c4abb1e2b))
# [@discordjs/ws@0.4.1](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.4.0...@discordjs/ws@0.4.1) - (2022-10-10)
## Bug Fixes
- **WebSocketShard:** Dispatch race condition (#8731) ([c2b6777](https://github.com/discordjs/discord.js/commit/c2b677759b905d6eb3ebcefcec2cb04eb38436bb))
# [@discordjs/ws@0.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.3.0...@discordjs/ws@0.4.0) - (2022-10-08)
## Bug Fixes
- Ws package.json path (#8720) ([7af3c3b](https://github.com/discordjs/discord.js/commit/7af3c3b6f1517a5d14372b5aa0ef3a2ed8633f6f))
- **WebSocketShard:** Add ready data parameter to ready event (#8705) ([a7eab50](https://github.com/discordjs/discord.js/commit/a7eab50ee3e286ca10e37107d695385251bd044d))
- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9))
## Documentation
- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0))
## Features
- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2))
- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3))
## Refactor
- Website components (#8600) ([c334157](https://github.com/discordjs/discord.js/commit/c3341570d983aea9ecc419979d5a01de658c9d67))
- Use `eslint-config-neon` for packages. (#8579) ([edadb9f](https://github.com/discordjs/discord.js/commit/edadb9fe5dfd9ff51a3cfc9b25cb242d3f9f5241))
# [@discordjs/ws@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/ws@0.2.0...@discordjs/ws@0.3.0) - (2022-08-22)
## Bug Fixes
- **WebSocketShard#destroy:** Wait for close and cleanup listeners (#8479) ([acdafe6](https://github.com/discordjs/discord.js/commit/acdafe60c7aa1ac5a3d358934c055c297080a944))
- **WebSocketManager#connect:** Check if we have enough sessions (#8481) ([4fd4252](https://github.com/discordjs/discord.js/commit/4fd42528fea6127e6468a651f9544913c19ade4d))
- **WebSocketShard:** Always reconnect on disconnected with 1000 (#8405) ([359f688](https://github.com/discordjs/discord.js/commit/359f6885558fcfb3151971ab589077a89ee71a01))
- **WebSocketShard:** Emit errors directly instead of objects (#8406) ([3161e1a](https://github.com/discordjs/discord.js/commit/3161e1a1acfbf929ecf33958fa1657553dd9bc1e))
## Documentation
- Fence examples in codeblocks ([193b252](https://github.com/discordjs/discord.js/commit/193b252672440a860318d3c2968aedd9cb88e0ce))
## Features
- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007))
- **website:** Render `@defaultValue` blocks (#8527) ([8028813](https://github.com/discordjs/discord.js/commit/8028813825e7708915ea892760c1003afd60df2f))
- **website:** Render tsdoc examples (#8494) ([7116647](https://github.com/discordjs/discord.js/commit/7116647947e413da59fbf493ed5251ddcd710ce7))
- **WebSocketShard:** Support new resume url (#8480) ([bc06cc6](https://github.com/discordjs/discord.js/commit/bc06cc638d2f57ab5c600e8cdb6afc8eb2180166))
## Refactor
- **website:** Adjust typography (#8503) ([0f83402](https://github.com/discordjs/discord.js/commit/0f834029850d2448981596cf082ff59917018d66))
- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e))
# [@discordjs/ws@0.2.0](https://github.com/discordjs/discord.js/tree/@discordjs/ws@0.2.0) - (2022-07-30)
## Bug Fixes
- **WebSocketShard:** Account code 1000 with no prior indication (#8399) ([5137bfc](https://github.com/discordjs/discord.js/commit/5137bfc17d763488083b76ee9008611df333272a))
- **WebSocketShard:** Use correct import (#8357) ([78d4295](https://github.com/discordjs/discord.js/commit/78d4295a40b83ea4f7cc830ff81927cba2d1d3f0))
## Features
- @discordjs/ws (#8260) ([748d727](https://github.com/discordjs/discord.js/commit/748d7271c45796479a29d8ed3101421de09ef867))

191
node_modules/@discordjs/ws/LICENSE generated vendored Normal file
View file

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2022 Noel Buechler
Copyright 2022 Charlotte Cristea
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

196
node_modules/@discordjs/ws/README.md generated vendored Normal file
View file

@ -0,0 +1,196 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://www.npmjs.com/package/@discordjs/ws"><img src="https://img.shields.io/npm/v/@discordjs/ws.svg?maxAge=3600" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/@discordjs/ws"><img src="https://img.shields.io/npm/dt/@discordjs/ws.svg?maxAge=3600" alt="npm downloads" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=ws" alt="Code coverage" /></a>
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
<a href="https://www.cloudflare.com"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-workers.png" alt="Cloudflare Workers" height="44" /></a>
</p>
</div>
## About
`@discordjs/ws` is a powerful wrapper around Discord's gateway.
## Installation
**Node.js 16.9.0 or newer is required.**
```sh
npm install @discordjs/ws
yarn add @discordjs/ws
pnpm add @discordjs/ws
```
### Optional packages
- [zlib-sync](https://www.npmjs.com/package/zlib-sync) for WebSocket data compression and inflation (`npm install zlib-sync`)
- [bufferutil](https://www.npmjs.com/package/bufferutil) for a much faster WebSocket connection (`npm install bufferutil`)
- [utf-8-validate](https://www.npmjs.com/package/utf-8-validate) in combination with `bufferutil` for much faster WebSocket processing (`npm install utf-8-validate`)
## Example usage
```ts
import { WebSocketManager, WebSocketShardEvents, CompressionMethod } from '@discordjs/ws';
import { REST } from '@discordjs/rest';
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
// This example will spawn Discord's recommended shard count, all under the current process.
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0, // for no intents
rest,
// uncomment if you have zlib-sync installed and want to use compression
// compression: CompressionMethod.ZlibStream,
});
manager.on(WebSocketShardEvents.Dispatch, (event) => {
// Process gateway events here.
});
await manager.connect();
```
### Specify shards
```ts
// Spawn 4 shards
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0,
rest,
shardCount: 4,
});
// The manager also supports being responsible for only a subset of your shards:
// Your bot will run 8 shards overall
// This manager will only take care of 0, 2, 4, and 6
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0,
rest,
shardCount: 8,
shardIds: [0, 2, 4, 6],
});
// Alternatively, if your shards are consecutive, you can pass in a range
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0,
rest,
shardCount: 8,
shardIds: {
start: 0,
end: 4,
},
});
```
### Specify `worker_threads`
You can also have the shards spawn in worker threads:
```ts
import { WebSocketManager, WorkerShardingStrategy } from '@discordjs/ws';
import { REST } from '@discordjs/rest';
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0,
rest,
shardCount: 6,
// This will cause 3 workers to spawn, 2 shards per each
buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 2 }),
// Or maybe you want all your shards under a single worker
buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 'all' }),
});
```
**Note**: By default, this will cause the workers to effectively only be responsible for the WebSocket connection, they simply pass up all the events back to the main process for the manager to emit. If you want to have the workers handle events as well, you can pass in a `workerPath` option to the `WorkerShardingStrategy` constructor:
```ts
import { WebSocketManager, WorkerShardingStrategy } from '@discordjs/ws';
import { REST } from '@discordjs/rest';
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0,
rest,
buildStrategy: (manager) =>
new WorkerShardingStrategy(manager, {
shardsPerWorker: 2,
workerPath: './worker.js',
}),
});
```
And your `worker.ts` file:
```ts
import { WorkerBootstrapper, WebSocketShardEvents } from '@discordjs/ws';
const bootstrapper = new WorkerBootstrapper();
void bootstrapper.bootstrap({
// Those will be sent to the main thread for the manager to emit
forwardEvents: [
WebSocketShardEvents.Closed,
WebSocketShardEvents.Debug,
WebSocketShardEvents.Hello,
WebSocketShardEvents.Ready,
WebSocketShardEvents.Resumed,
],
shardCallback: (shard) => {
shard.on(WebSocketShardEvents.Dispatch, (event) => {
// Process gateway events here however you want (e.g. send them through a message broker)
// You also have access to shard.id if you need it
});
},
});
```
## Links
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library.
- [discord.js Discord server][discord]
- [Discord API Discord server][discord-api]
- [GitHub][source]
- [npm][npm]
- [Related libraries][related-libs]
## Contributing
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
[documentation][documentation].
See [the contribution guide][contributing] if you'd like to submit a PR.
## Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord].
[website]: https://discord.js.org
[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website
[documentation]: https://discord.js.org/docs/packages/ws/stable
[guide]: https://discordjs.guide/
[guide-source]: https://github.com/discordjs/guide
[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html
[discord]: https://discord.gg/djs
[discord-api]: https://discord.gg/discord-api
[source]: https://github.com/discordjs/discord.js/tree/main/packages/ws
[npm]: https://www.npmjs.com/package/@discordjs/ws
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md

2
node_modules/@discordjs/ws/dist/defaultWorker.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
export { }

982
node_modules/@discordjs/ws/dist/defaultWorker.js generated vendored Normal file
View file

@ -0,0 +1,982 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/utils/WorkerBootstrapper.ts
var import_node_worker_threads3 = require("worker_threads");
var import_collection7 = require("@discordjs/collection");
// src/strategies/context/WorkerContextFetchingStrategy.ts
var import_node_worker_threads2 = require("worker_threads");
var import_collection2 = require("@discordjs/collection");
// src/strategies/sharding/WorkerShardingStrategy.ts
var import_node_events = require("events");
var import_node_path = require("path");
var import_node_worker_threads = require("worker_threads");
var import_collection = require("@discordjs/collection");
// src/strategies/context/IContextFetchingStrategy.ts
async function managerToFetchingStrategyOptions(manager) {
const {
buildIdentifyThrottler,
buildStrategy,
retrieveSessionInfo,
updateSessionInfo,
shardCount,
shardIds,
rest,
...managerOptions
} = manager.options;
return {
...managerOptions,
gatewayInformation: await manager.fetchGatewayInformation(),
shardCount: await manager.getShardCount()
};
}
__name(managerToFetchingStrategyOptions, "managerToFetchingStrategyOptions");
// src/strategies/context/WorkerContextFetchingStrategy.ts
var WorkerContextFetchingStrategy = class {
constructor(options) {
this.options = options;
if (import_node_worker_threads2.isMainThread) {
throw new Error("Cannot instantiate WorkerContextFetchingStrategy on the main thread");
}
import_node_worker_threads2.parentPort.on("message", (payload) => {
if (payload.op === 3 /* SessionInfoResponse */) {
this.sessionPromises.get(payload.nonce)?.(payload.session);
this.sessionPromises.delete(payload.nonce);
}
if (payload.op === 4 /* ShardIdentifyResponse */) {
const promise = this.waitForIdentifyPromises.get(payload.nonce);
if (payload.ok) {
promise?.resolve();
} else {
promise?.reject();
}
this.waitForIdentifyPromises.delete(payload.nonce);
}
});
}
sessionPromises = new import_collection2.Collection();
waitForIdentifyPromises = new import_collection2.Collection();
async retrieveSessionInfo(shardId) {
const nonce = Math.random();
const payload = {
op: 3 /* RetrieveSessionInfo */,
shardId,
nonce
};
const promise = new Promise((resolve2) => this.sessionPromises.set(nonce, resolve2));
import_node_worker_threads2.parentPort.postMessage(payload);
return promise;
}
updateSessionInfo(shardId, sessionInfo) {
const payload = {
op: 4 /* UpdateSessionInfo */,
shardId,
session: sessionInfo
};
import_node_worker_threads2.parentPort.postMessage(payload);
}
async waitForIdentify(shardId, signal) {
const nonce = Math.random();
const payload = {
op: 5 /* WaitForIdentify */,
nonce,
shardId
};
const promise = new Promise(
(resolve2, reject) => (
// eslint-disable-next-line no-promise-executor-return
this.waitForIdentifyPromises.set(nonce, { resolve: resolve2, reject })
)
);
import_node_worker_threads2.parentPort.postMessage(payload);
const listener = /* @__PURE__ */ __name(() => {
const payload2 = {
op: 8 /* CancelIdentify */,
nonce
};
import_node_worker_threads2.parentPort.postMessage(payload2);
}, "listener");
signal.addEventListener("abort", listener);
try {
await promise;
} finally {
signal.removeEventListener("abort", listener);
}
}
};
__name(WorkerContextFetchingStrategy, "WorkerContextFetchingStrategy");
// src/ws/WebSocketShard.ts
var import_node_buffer = require("buffer");
var import_node_events2 = require("events");
var import_node_timers = require("timers");
var import_promises2 = require("timers/promises");
var import_node_url = require("url");
var import_node_util = require("util");
var import_node_zlib = require("zlib");
var import_collection6 = require("@discordjs/collection");
var import_util2 = require("@discordjs/util");
var import_async_queue2 = require("@sapphire/async-queue");
var import_async_event_emitter = require("@vladfrangu/async_event_emitter");
var import_v102 = require("discord-api-types/v10");
var import_ws = require("ws");
// src/utils/constants.ts
var import_node_process = __toESM(require("process"));
var import_collection5 = require("@discordjs/collection");
var import_util = require("@discordjs/util");
var import_v10 = require("discord-api-types/v10");
// src/strategies/sharding/SimpleShardingStrategy.ts
var import_collection3 = require("@discordjs/collection");
// src/strategies/context/SimpleContextFetchingStrategy.ts
var _SimpleContextFetchingStrategy = class {
constructor(manager, options) {
this.manager = manager;
this.options = options;
}
static async ensureThrottler(manager) {
const throttler = _SimpleContextFetchingStrategy.throttlerCache.get(manager);
if (throttler) {
return throttler;
}
const newThrottler = await manager.options.buildIdentifyThrottler(manager);
_SimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler);
return newThrottler;
}
async retrieveSessionInfo(shardId) {
return this.manager.options.retrieveSessionInfo(shardId);
}
updateSessionInfo(shardId, sessionInfo) {
return this.manager.options.updateSessionInfo(shardId, sessionInfo);
}
async waitForIdentify(shardId, signal) {
const throttler = await _SimpleContextFetchingStrategy.ensureThrottler(this.manager);
await throttler.waitForIdentify(shardId, signal);
}
};
var SimpleContextFetchingStrategy = _SimpleContextFetchingStrategy;
__name(SimpleContextFetchingStrategy, "SimpleContextFetchingStrategy");
// This strategy assumes every shard is running under the same process - therefore we need a single
// IdentifyThrottler per manager.
__publicField(SimpleContextFetchingStrategy, "throttlerCache", /* @__PURE__ */ new WeakMap());
// src/strategies/sharding/SimpleShardingStrategy.ts
var SimpleShardingStrategy = class {
manager;
shards = new import_collection3.Collection();
constructor(manager) {
this.manager = manager;
}
/**
* {@inheritDoc IShardingStrategy.spawn}
*/
async spawn(shardIds) {
const strategyOptions = await managerToFetchingStrategyOptions(this.manager);
for (const shardId of shardIds) {
const strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions);
const shard = new WebSocketShard(strategy, shardId);
for (const event of Object.values(WebSocketShardEvents)) {
shard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId }));
}
this.shards.set(shardId, shard);
}
}
/**
* {@inheritDoc IShardingStrategy.connect}
*/
async connect() {
const promises = [];
for (const shard of this.shards.values()) {
promises.push(shard.connect());
}
await Promise.all(promises);
}
/**
* {@inheritDoc IShardingStrategy.destroy}
*/
async destroy(options) {
const promises = [];
for (const shard of this.shards.values()) {
promises.push(shard.destroy(options));
}
await Promise.all(promises);
this.shards.clear();
}
/**
* {@inheritDoc IShardingStrategy.send}
*/
async send(shardId, payload) {
const shard = this.shards.get(shardId);
if (!shard) {
throw new RangeError(`Shard ${shardId} not found`);
}
return shard.send(payload);
}
/**
* {@inheritDoc IShardingStrategy.fetchStatus}
*/
async fetchStatus() {
return this.shards.mapValues((shard) => shard.status);
}
};
__name(SimpleShardingStrategy, "SimpleShardingStrategy");
// src/throttling/SimpleIdentifyThrottler.ts
var import_promises = require("timers/promises");
var import_collection4 = require("@discordjs/collection");
var import_async_queue = require("@sapphire/async-queue");
var SimpleIdentifyThrottler = class {
constructor(maxConcurrency) {
this.maxConcurrency = maxConcurrency;
}
states = new import_collection4.Collection();
/**
* {@inheritDoc IIdentifyThrottler.waitForIdentify}
*/
async waitForIdentify(shardId, signal) {
const key = shardId % this.maxConcurrency;
const state = this.states.ensure(key, () => {
return {
queue: new import_async_queue.AsyncQueue(),
resetsAt: Number.POSITIVE_INFINITY
};
});
await state.queue.wait({ signal });
try {
const diff = state.resetsAt - Date.now();
if (diff <= 5e3) {
const time = diff + Math.random() * 1500;
await (0, import_promises.setTimeout)(time);
}
state.resetsAt = Date.now() + 5e3;
} finally {
state.queue.shift();
}
}
};
__name(SimpleIdentifyThrottler, "SimpleIdentifyThrottler");
// src/utils/constants.ts
var DefaultDeviceProperty = `@discordjs/ws 0.8.3`;
var getDefaultSessionStore = (0, import_util.lazy)(() => new import_collection5.Collection());
var DefaultWebSocketManagerOptions = {
async buildIdentifyThrottler(manager) {
const info = await manager.fetchGatewayInformation();
return new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency);
},
buildStrategy: (manager) => new SimpleShardingStrategy(manager),
shardCount: null,
shardIds: null,
largeThreshold: null,
initialPresence: null,
identifyProperties: {
browser: DefaultDeviceProperty,
device: DefaultDeviceProperty,
os: import_node_process.default.platform
},
version: import_v10.APIVersion,
encoding: "json" /* JSON */,
compression: null,
retrieveSessionInfo(shardId) {
const store = getDefaultSessionStore();
return store.get(shardId) ?? null;
},
updateSessionInfo(shardId, info) {
const store = getDefaultSessionStore();
if (info) {
store.set(shardId, info);
} else {
store.delete(shardId);
}
},
handshakeTimeout: 3e4,
helloTimeout: 6e4,
readyTimeout: 15e3
};
var ImportantGatewayOpcodes = /* @__PURE__ */ new Set([
import_v10.GatewayOpcodes.Heartbeat,
import_v10.GatewayOpcodes.Identify,
import_v10.GatewayOpcodes.Resume
]);
function getInitialSendRateLimitState() {
return {
remaining: 120,
resetAt: Date.now() + 6e4
};
}
__name(getInitialSendRateLimitState, "getInitialSendRateLimitState");
// src/ws/WebSocketShard.ts
var getZlibSync = (0, import_util2.lazy)(async () => import("zlib-sync").then((mod) => mod.default).catch(() => null));
var WebSocketShardEvents = /* @__PURE__ */ ((WebSocketShardEvents2) => {
WebSocketShardEvents2["Closed"] = "closed";
WebSocketShardEvents2["Debug"] = "debug";
WebSocketShardEvents2["Dispatch"] = "dispatch";
WebSocketShardEvents2["Error"] = "error";
WebSocketShardEvents2["HeartbeatComplete"] = "heartbeat";
WebSocketShardEvents2["Hello"] = "hello";
WebSocketShardEvents2["Ready"] = "ready";
WebSocketShardEvents2["Resumed"] = "resumed";
return WebSocketShardEvents2;
})(WebSocketShardEvents || {});
var WebSocketShardDestroyRecovery = /* @__PURE__ */ ((WebSocketShardDestroyRecovery2) => {
WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Reconnect"] = 0] = "Reconnect";
WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Resume"] = 1] = "Resume";
return WebSocketShardDestroyRecovery2;
})(WebSocketShardDestroyRecovery || {});
var WebSocketShard = class extends import_async_event_emitter.AsyncEventEmitter {
connection = null;
useIdentifyCompress = false;
inflate = null;
textDecoder = new import_node_util.TextDecoder();
replayedEvents = 0;
isAck = true;
sendRateLimitState = getInitialSendRateLimitState();
initialHeartbeatTimeoutController = null;
heartbeatInterval = null;
lastHeartbeatAt = -1;
// Indicates whether the shard has already resolved its original connect() call
initialConnectResolved = false;
// Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET)
failedToConnectDueToNetworkError = false;
sendQueue = new import_async_queue2.AsyncQueue();
timeoutAbortControllers = new import_collection6.Collection();
strategy;
id;
#status = 0 /* Idle */;
get status() {
return this.#status;
}
constructor(strategy, id) {
super();
this.strategy = strategy;
this.id = id;
}
async connect() {
const promise = this.initialConnectResolved ? Promise.resolve() : (0, import_node_events2.once)(this, "ready" /* Ready */);
void this.internalConnect();
await promise;
this.initialConnectResolved = true;
}
async internalConnect() {
if (this.#status !== 0 /* Idle */) {
throw new Error("Tried to connect a shard that wasn't idle");
}
const { version, encoding, compression } = this.strategy.options;
const params = new import_node_url.URLSearchParams({ v: version, encoding });
if (compression) {
const zlib = await getZlibSync();
if (zlib) {
params.append("compress", compression);
this.inflate = new zlib.Inflate({
chunkSize: 65535,
to: "string"
});
} else if (!this.useIdentifyCompress) {
this.useIdentifyCompress = true;
console.warn(
"WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress"
);
}
}
const session = await this.strategy.retrieveSessionInfo(this.id);
const url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`;
this.debug([`Connecting to ${url}`]);
const connection = new import_ws.WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? void 0 }).on("message", this.onMessage.bind(this)).on("error", this.onError.bind(this)).on("close", this.onClose.bind(this));
connection.binaryType = "arraybuffer";
this.connection = connection;
this.#status = 1 /* Connecting */;
this.sendRateLimitState = getInitialSendRateLimitState();
const { ok } = await this.waitForEvent("hello" /* Hello */, this.strategy.options.helloTimeout);
if (!ok) {
return;
}
if (session?.shardCount === this.strategy.options.shardCount) {
await this.resume(session);
} else {
await this.identify();
}
}
async destroy(options = {}) {
if (this.#status === 0 /* Idle */) {
this.debug(["Tried to destroy a shard that was idle"]);
return;
}
if (!options.code) {
options.code = options.recover === 1 /* Resume */ ? 4200 /* Resuming */ : 1e3 /* Normal */;
}
this.debug([
"Destroying shard",
`Reason: ${options.reason ?? "none"}`,
`Code: ${options.code}`,
`Recover: ${options.recover === void 0 ? "none" : WebSocketShardDestroyRecovery[options.recover]}`
]);
this.isAck = true;
if (this.heartbeatInterval) {
(0, import_node_timers.clearInterval)(this.heartbeatInterval);
}
if (this.initialHeartbeatTimeoutController) {
this.initialHeartbeatTimeoutController.abort();
this.initialHeartbeatTimeoutController = null;
}
this.lastHeartbeatAt = -1;
for (const controller of this.timeoutAbortControllers.values()) {
controller.abort();
}
this.timeoutAbortControllers.clear();
this.failedToConnectDueToNetworkError = false;
if (options.recover !== 1 /* Resume */) {
await this.strategy.updateSessionInfo(this.id, null);
}
if (this.connection) {
this.connection.removeAllListeners("message");
this.connection.removeAllListeners("close");
const shouldClose = this.connection.readyState === import_ws.WebSocket.OPEN;
this.debug([
"Connection status during destroy",
`Needs closing: ${shouldClose}`,
`Ready state: ${this.connection.readyState}`
]);
if (shouldClose) {
this.connection.close(options.code, options.reason);
await (0, import_node_events2.once)(this.connection, "close");
this.emit("closed" /* Closed */, { code: options.code });
}
this.connection.removeAllListeners("error");
} else {
this.debug(["Destroying a shard that has no connection; please open an issue on GitHub"]);
}
this.#status = 0 /* Idle */;
if (options.recover !== void 0) {
await (0, import_promises2.setTimeout)(500);
return this.internalConnect();
}
}
async waitForEvent(event, timeoutDuration) {
this.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : "indefinitely"}`]);
const timeoutController = new AbortController();
const timeout = timeoutDuration ? (0, import_node_timers.setTimeout)(() => timeoutController.abort(), timeoutDuration).unref() : null;
this.timeoutAbortControllers.set(event, timeoutController);
const closeController = new AbortController();
try {
const closed = await Promise.race([
(0, import_node_events2.once)(this, event, { signal: timeoutController.signal }).then(() => false),
(0, import_node_events2.once)(this, "closed" /* Closed */, { signal: closeController.signal }).then(() => true)
]);
return { ok: !closed };
} catch {
void this.destroy({
code: 1e3 /* Normal */,
reason: "Something timed out or went wrong while waiting for an event",
recover: 0 /* Reconnect */
});
return { ok: false };
} finally {
if (timeout) {
(0, import_node_timers.clearTimeout)(timeout);
}
this.timeoutAbortControllers.delete(event);
if (!closeController.signal.aborted) {
closeController.abort();
}
}
}
async send(payload) {
if (!this.connection) {
throw new Error("WebSocketShard wasn't connected");
}
if (this.#status !== 3 /* Ready */ && !ImportantGatewayOpcodes.has(payload.op)) {
this.debug(["Tried to send a non-crucial payload before the shard was ready, waiting"]);
try {
await (0, import_node_events2.once)(this, "ready" /* Ready */);
} catch {
return this.send(payload);
}
}
await this.sendQueue.wait();
if (--this.sendRateLimitState.remaining <= 0) {
const now = Date.now();
if (this.sendRateLimitState.resetAt > now) {
const sleepFor = this.sendRateLimitState.resetAt - now;
this.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]);
const controller = new AbortController();
const interrupted = await Promise.race([
(0, import_promises2.setTimeout)(sleepFor).then(() => false),
(0, import_node_events2.once)(this, "closed" /* Closed */, { signal: controller.signal }).then(() => true)
]);
if (interrupted) {
this.debug(["Connection closed while waiting for the send rate limit to reset, re-queueing payload"]);
this.sendQueue.shift();
return this.send(payload);
}
controller.abort();
}
this.sendRateLimitState = getInitialSendRateLimitState();
}
this.sendQueue.shift();
this.connection.send(JSON.stringify(payload));
}
async identify() {
this.debug(["Waiting for identify throttle"]);
const controller = new AbortController();
const closeHandler = /* @__PURE__ */ __name(() => {
controller.abort();
}, "closeHandler");
this.on("closed" /* Closed */, closeHandler);
try {
await this.strategy.waitForIdentify(this.id, controller.signal);
} catch {
this.debug(["Was waiting for an identify, but the shard closed in the meantime"]);
return;
} finally {
this.off("closed" /* Closed */, closeHandler);
}
this.debug([
"Identifying",
`shard id: ${this.id.toString()}`,
`shard count: ${this.strategy.options.shardCount}`,
`intents: ${this.strategy.options.intents}`,
`compression: ${this.inflate ? "zlib-stream" : this.useIdentifyCompress ? "identify" : "none"}`
]);
const d = {
token: this.strategy.options.token,
properties: this.strategy.options.identifyProperties,
intents: this.strategy.options.intents,
compress: this.useIdentifyCompress,
shard: [this.id, this.strategy.options.shardCount]
};
if (this.strategy.options.largeThreshold) {
d.large_threshold = this.strategy.options.largeThreshold;
}
if (this.strategy.options.initialPresence) {
d.presence = this.strategy.options.initialPresence;
}
await this.send({
op: import_v102.GatewayOpcodes.Identify,
d
});
await this.waitForEvent("ready" /* Ready */, this.strategy.options.readyTimeout);
}
async resume(session) {
this.debug([
"Resuming session",
`resume url: ${session.resumeURL}`,
`sequence: ${session.sequence}`,
`shard id: ${this.id.toString()}`
]);
this.#status = 2 /* Resuming */;
this.replayedEvents = 0;
return this.send({
op: import_v102.GatewayOpcodes.Resume,
d: {
token: this.strategy.options.token,
seq: session.sequence,
session_id: session.sessionId
}
});
}
async heartbeat(requested = false) {
if (!this.isAck && !requested) {
return this.destroy({ reason: "Zombie connection", recover: 1 /* Resume */ });
}
const session = await this.strategy.retrieveSessionInfo(this.id);
await this.send({
op: import_v102.GatewayOpcodes.Heartbeat,
d: session?.sequence ?? null
});
this.lastHeartbeatAt = Date.now();
this.isAck = false;
}
async unpackMessage(data, isBinary) {
const decompressable = new Uint8Array(data);
if (!isBinary) {
return JSON.parse(this.textDecoder.decode(decompressable));
}
if (this.useIdentifyCompress) {
return new Promise((resolve2, reject) => {
(0, import_node_zlib.inflate)(decompressable, { chunkSize: 65535 }, (err, result) => {
if (err) {
reject(err);
return;
}
resolve2(JSON.parse(this.textDecoder.decode(result)));
});
});
}
if (this.inflate) {
const l = decompressable.length;
const flush = l >= 4 && decompressable[l - 4] === 0 && decompressable[l - 3] === 0 && decompressable[l - 2] === 255 && decompressable[l - 1] === 255;
const zlib = await getZlibSync();
this.inflate.push(import_node_buffer.Buffer.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH);
if (this.inflate.err) {
this.emit("error" /* Error */, {
error: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ""}`)
});
}
if (!flush) {
return null;
}
const { result } = this.inflate;
if (!result) {
return null;
}
return JSON.parse(typeof result === "string" ? result : this.textDecoder.decode(result));
}
this.debug([
"Received a message we were unable to decompress",
`isBinary: ${isBinary.toString()}`,
`useIdentifyCompress: ${this.useIdentifyCompress.toString()}`,
`inflate: ${Boolean(this.inflate).toString()}`
]);
return null;
}
async onMessage(data, isBinary) {
const payload = await this.unpackMessage(data, isBinary);
if (!payload) {
return;
}
switch (payload.op) {
case import_v102.GatewayOpcodes.Dispatch: {
if (this.#status === 2 /* Resuming */) {
this.replayedEvents++;
}
switch (payload.t) {
case import_v102.GatewayDispatchEvents.Ready: {
this.#status = 3 /* Ready */;
const session2 = {
sequence: payload.s,
sessionId: payload.d.session_id,
shardId: this.id,
shardCount: this.strategy.options.shardCount,
resumeURL: payload.d.resume_gateway_url
};
await this.strategy.updateSessionInfo(this.id, session2);
this.emit("ready" /* Ready */, { data: payload.d });
break;
}
case import_v102.GatewayDispatchEvents.Resumed: {
this.#status = 3 /* Ready */;
this.debug([`Resumed and replayed ${this.replayedEvents} events`]);
this.emit("resumed" /* Resumed */);
break;
}
default: {
break;
}
}
const session = await this.strategy.retrieveSessionInfo(this.id);
if (session) {
if (payload.s > session.sequence) {
await this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s });
}
} else {
this.debug([
`Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect`
]);
}
this.emit("dispatch" /* Dispatch */, { data: payload });
break;
}
case import_v102.GatewayOpcodes.Heartbeat: {
await this.heartbeat(true);
break;
}
case import_v102.GatewayOpcodes.Reconnect: {
await this.destroy({
reason: "Told to reconnect by Discord",
recover: 1 /* Resume */
});
break;
}
case import_v102.GatewayOpcodes.InvalidSession: {
this.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]);
const session = await this.strategy.retrieveSessionInfo(this.id);
if (payload.d && session) {
await this.resume(session);
} else {
await this.destroy({
reason: "Invalid session",
recover: 0 /* Reconnect */
});
}
break;
}
case import_v102.GatewayOpcodes.Hello: {
this.emit("hello" /* Hello */);
const jitter = Math.random();
const firstWait = Math.floor(payload.d.heartbeat_interval * jitter);
this.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]);
try {
const controller = new AbortController();
this.initialHeartbeatTimeoutController = controller;
await (0, import_promises2.setTimeout)(firstWait, void 0, { signal: controller.signal });
} catch {
this.debug(["Cancelled initial heartbeat due to #destroy being called"]);
return;
} finally {
this.initialHeartbeatTimeoutController = null;
}
await this.heartbeat();
this.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]);
this.heartbeatInterval = (0, import_node_timers.setInterval)(() => void this.heartbeat(), payload.d.heartbeat_interval);
break;
}
case import_v102.GatewayOpcodes.HeartbeatAck: {
this.isAck = true;
const ackAt = Date.now();
this.emit("heartbeat" /* HeartbeatComplete */, {
ackAt,
heartbeatAt: this.lastHeartbeatAt,
latency: ackAt - this.lastHeartbeatAt
});
break;
}
}
}
onError(error) {
if ("code" in error && ["ECONNRESET", "ECONNREFUSED"].includes(error.code)) {
this.debug(["Failed to connect to the gateway URL specified due to a network error"]);
this.failedToConnectDueToNetworkError = true;
return;
}
this.emit("error" /* Error */, { error });
}
async onClose(code) {
this.emit("closed" /* Closed */, { code });
switch (code) {
case 1e3 /* Normal */: {
return this.destroy({
code,
reason: "Got disconnected by Discord",
recover: 0 /* Reconnect */
});
}
case 4200 /* Resuming */: {
break;
}
case import_v102.GatewayCloseCodes.UnknownError: {
this.debug([`An unknown error occurred: ${code}`]);
return this.destroy({ code, recover: 1 /* Resume */ });
}
case import_v102.GatewayCloseCodes.UnknownOpcode: {
this.debug(["An invalid opcode was sent to Discord."]);
return this.destroy({ code, recover: 1 /* Resume */ });
}
case import_v102.GatewayCloseCodes.DecodeError: {
this.debug(["An invalid payload was sent to Discord."]);
return this.destroy({ code, recover: 1 /* Resume */ });
}
case import_v102.GatewayCloseCodes.NotAuthenticated: {
this.debug(["A request was somehow sent before the identify/resume payload."]);
return this.destroy({ code, recover: 0 /* Reconnect */ });
}
case import_v102.GatewayCloseCodes.AuthenticationFailed: {
throw new Error("Authentication failed");
}
case import_v102.GatewayCloseCodes.AlreadyAuthenticated: {
this.debug(["More than one auth payload was sent."]);
return this.destroy({ code, recover: 0 /* Reconnect */ });
}
case import_v102.GatewayCloseCodes.InvalidSeq: {
this.debug(["An invalid sequence was sent."]);
return this.destroy({ code, recover: 0 /* Reconnect */ });
}
case import_v102.GatewayCloseCodes.RateLimited: {
this.debug(["The WebSocket rate limit has been hit, this should never happen"]);
return this.destroy({ code, recover: 0 /* Reconnect */ });
}
case import_v102.GatewayCloseCodes.SessionTimedOut: {
this.debug(["Session timed out."]);
return this.destroy({ code, recover: 1 /* Resume */ });
}
case import_v102.GatewayCloseCodes.InvalidShard: {
throw new Error("Invalid shard");
}
case import_v102.GatewayCloseCodes.ShardingRequired: {
throw new Error("Sharding is required");
}
case import_v102.GatewayCloseCodes.InvalidAPIVersion: {
throw new Error("Used an invalid API version");
}
case import_v102.GatewayCloseCodes.InvalidIntents: {
throw new Error("Used invalid intents");
}
case import_v102.GatewayCloseCodes.DisallowedIntents: {
throw new Error("Used disallowed intents");
}
default: {
this.debug([
`The gateway closed with an unexpected code ${code}, attempting to ${this.failedToConnectDueToNetworkError ? "reconnect" : "resume"}.`
]);
return this.destroy({
code,
recover: this.failedToConnectDueToNetworkError ? 0 /* Reconnect */ : 1 /* Resume */
});
}
}
}
debug(messages) {
const message = `${messages[0]}${messages.length > 1 ? `
${messages.slice(1).map((m) => ` ${m}`).join("\n")}` : ""}`;
this.emit("debug" /* Debug */, { message });
}
};
__name(WebSocketShard, "WebSocketShard");
// src/utils/WorkerBootstrapper.ts
var WorkerBootstrapper = class {
/**
* The data passed to the worker thread
*/
data = import_node_worker_threads3.workerData;
/**
* The shards that are managed by this worker
*/
shards = new import_collection7.Collection();
constructor() {
if (import_node_worker_threads3.isMainThread) {
throw new Error("Expected WorkerBootstrap to not be used within the main thread");
}
}
/**
* Helper method to initiate a shard's connection process
*/
async connect(shardId) {
const shard = this.shards.get(shardId);
if (!shard) {
throw new RangeError(`Shard ${shardId} does not exist`);
}
await shard.connect();
}
/**
* Helper method to destroy a shard
*/
async destroy(shardId, options) {
const shard = this.shards.get(shardId);
if (!shard) {
throw new RangeError(`Shard ${shardId} does not exist`);
}
await shard.destroy(options);
}
/**
* Helper method to attach event listeners to the parentPort
*/
setupThreadEvents() {
import_node_worker_threads3.parentPort.on("messageerror", (err) => {
throw err;
}).on("message", async (payload) => {
switch (payload.op) {
case 0 /* Connect */: {
await this.connect(payload.shardId);
const response = {
op: 0 /* Connected */,
shardId: payload.shardId
};
import_node_worker_threads3.parentPort.postMessage(response);
break;
}
case 1 /* Destroy */: {
await this.destroy(payload.shardId, payload.options);
const response = {
op: 1 /* Destroyed */,
shardId: payload.shardId
};
import_node_worker_threads3.parentPort.postMessage(response);
break;
}
case 2 /* Send */: {
const shard = this.shards.get(payload.shardId);
if (!shard) {
throw new RangeError(`Shard ${payload.shardId} does not exist`);
}
await shard.send(payload.payload);
break;
}
case 3 /* SessionInfoResponse */: {
break;
}
case 4 /* ShardIdentifyResponse */: {
break;
}
case 5 /* FetchStatus */: {
const shard = this.shards.get(payload.shardId);
if (!shard) {
throw new Error(`Shard ${payload.shardId} does not exist`);
}
const response = {
op: 6 /* FetchStatusResponse */,
status: shard.status,
nonce: payload.nonce
};
import_node_worker_threads3.parentPort.postMessage(response);
break;
}
}
});
}
/**
* Bootstraps the worker thread with the provided options
*/
async bootstrap(options = {}) {
for (const shardId of this.data.shardIds) {
const shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId);
for (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) {
shard.on(event, (data) => {
const payload = {
op: 2 /* Event */,
event,
data,
shardId
};
import_node_worker_threads3.parentPort.postMessage(payload);
});
}
await options.shardCallback?.(shard);
this.shards.set(shardId, shard);
}
this.setupThreadEvents();
const message = {
op: 7 /* WorkerReady */
};
import_node_worker_threads3.parentPort.postMessage(message);
}
};
__name(WorkerBootstrapper, "WorkerBootstrapper");
// src/strategies/sharding/defaultWorker.ts
var bootstrapper = new WorkerBootstrapper();
void bootstrapper.bootstrap();
//# sourceMappingURL=defaultWorker.js.map

1
node_modules/@discordjs/ws/dist/defaultWorker.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

964
node_modules/@discordjs/ws/dist/defaultWorker.mjs generated vendored Normal file
View file

@ -0,0 +1,964 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/utils/WorkerBootstrapper.ts
import { isMainThread as isMainThread2, parentPort as parentPort2, workerData } from "node:worker_threads";
import { Collection as Collection7 } from "@discordjs/collection";
// src/strategies/context/WorkerContextFetchingStrategy.ts
import { isMainThread, parentPort } from "node:worker_threads";
import { Collection as Collection2 } from "@discordjs/collection";
// src/strategies/sharding/WorkerShardingStrategy.ts
import { once } from "node:events";
import { join, isAbsolute, resolve } from "node:path";
import { Worker } from "node:worker_threads";
import { Collection } from "@discordjs/collection";
// src/strategies/context/IContextFetchingStrategy.ts
async function managerToFetchingStrategyOptions(manager) {
const {
buildIdentifyThrottler,
buildStrategy,
retrieveSessionInfo,
updateSessionInfo,
shardCount,
shardIds,
rest,
...managerOptions
} = manager.options;
return {
...managerOptions,
gatewayInformation: await manager.fetchGatewayInformation(),
shardCount: await manager.getShardCount()
};
}
__name(managerToFetchingStrategyOptions, "managerToFetchingStrategyOptions");
// src/strategies/context/WorkerContextFetchingStrategy.ts
var WorkerContextFetchingStrategy = class {
constructor(options) {
this.options = options;
if (isMainThread) {
throw new Error("Cannot instantiate WorkerContextFetchingStrategy on the main thread");
}
parentPort.on("message", (payload) => {
if (payload.op === 3 /* SessionInfoResponse */) {
this.sessionPromises.get(payload.nonce)?.(payload.session);
this.sessionPromises.delete(payload.nonce);
}
if (payload.op === 4 /* ShardIdentifyResponse */) {
const promise = this.waitForIdentifyPromises.get(payload.nonce);
if (payload.ok) {
promise?.resolve();
} else {
promise?.reject();
}
this.waitForIdentifyPromises.delete(payload.nonce);
}
});
}
sessionPromises = new Collection2();
waitForIdentifyPromises = new Collection2();
async retrieveSessionInfo(shardId) {
const nonce = Math.random();
const payload = {
op: 3 /* RetrieveSessionInfo */,
shardId,
nonce
};
const promise = new Promise((resolve2) => this.sessionPromises.set(nonce, resolve2));
parentPort.postMessage(payload);
return promise;
}
updateSessionInfo(shardId, sessionInfo) {
const payload = {
op: 4 /* UpdateSessionInfo */,
shardId,
session: sessionInfo
};
parentPort.postMessage(payload);
}
async waitForIdentify(shardId, signal) {
const nonce = Math.random();
const payload = {
op: 5 /* WaitForIdentify */,
nonce,
shardId
};
const promise = new Promise(
(resolve2, reject) => (
// eslint-disable-next-line no-promise-executor-return
this.waitForIdentifyPromises.set(nonce, { resolve: resolve2, reject })
)
);
parentPort.postMessage(payload);
const listener = /* @__PURE__ */ __name(() => {
const payload2 = {
op: 8 /* CancelIdentify */,
nonce
};
parentPort.postMessage(payload2);
}, "listener");
signal.addEventListener("abort", listener);
try {
await promise;
} finally {
signal.removeEventListener("abort", listener);
}
}
};
__name(WorkerContextFetchingStrategy, "WorkerContextFetchingStrategy");
// src/ws/WebSocketShard.ts
import { Buffer as Buffer2 } from "node:buffer";
import { once as once2 } from "node:events";
import { clearInterval, clearTimeout, setInterval, setTimeout } from "node:timers";
import { setTimeout as sleep2 } from "node:timers/promises";
import { URLSearchParams } from "node:url";
import { TextDecoder } from "node:util";
import { inflate } from "node:zlib";
import { Collection as Collection6 } from "@discordjs/collection";
import { lazy as lazy2 } from "@discordjs/util";
import { AsyncQueue as AsyncQueue2 } from "@sapphire/async-queue";
import { AsyncEventEmitter } from "@vladfrangu/async_event_emitter";
import {
GatewayCloseCodes,
GatewayDispatchEvents,
GatewayOpcodes as GatewayOpcodes2
} from "discord-api-types/v10";
import { WebSocket } from "ws";
// src/utils/constants.ts
import process from "node:process";
import { Collection as Collection5 } from "@discordjs/collection";
import { lazy } from "@discordjs/util";
import { APIVersion, GatewayOpcodes } from "discord-api-types/v10";
// src/strategies/sharding/SimpleShardingStrategy.ts
import { Collection as Collection3 } from "@discordjs/collection";
// src/strategies/context/SimpleContextFetchingStrategy.ts
var _SimpleContextFetchingStrategy = class {
constructor(manager, options) {
this.manager = manager;
this.options = options;
}
static async ensureThrottler(manager) {
const throttler = _SimpleContextFetchingStrategy.throttlerCache.get(manager);
if (throttler) {
return throttler;
}
const newThrottler = await manager.options.buildIdentifyThrottler(manager);
_SimpleContextFetchingStrategy.throttlerCache.set(manager, newThrottler);
return newThrottler;
}
async retrieveSessionInfo(shardId) {
return this.manager.options.retrieveSessionInfo(shardId);
}
updateSessionInfo(shardId, sessionInfo) {
return this.manager.options.updateSessionInfo(shardId, sessionInfo);
}
async waitForIdentify(shardId, signal) {
const throttler = await _SimpleContextFetchingStrategy.ensureThrottler(this.manager);
await throttler.waitForIdentify(shardId, signal);
}
};
var SimpleContextFetchingStrategy = _SimpleContextFetchingStrategy;
__name(SimpleContextFetchingStrategy, "SimpleContextFetchingStrategy");
// This strategy assumes every shard is running under the same process - therefore we need a single
// IdentifyThrottler per manager.
__publicField(SimpleContextFetchingStrategy, "throttlerCache", /* @__PURE__ */ new WeakMap());
// src/strategies/sharding/SimpleShardingStrategy.ts
var SimpleShardingStrategy = class {
manager;
shards = new Collection3();
constructor(manager) {
this.manager = manager;
}
/**
* {@inheritDoc IShardingStrategy.spawn}
*/
async spawn(shardIds) {
const strategyOptions = await managerToFetchingStrategyOptions(this.manager);
for (const shardId of shardIds) {
const strategy = new SimpleContextFetchingStrategy(this.manager, strategyOptions);
const shard = new WebSocketShard(strategy, shardId);
for (const event of Object.values(WebSocketShardEvents)) {
shard.on(event, (payload) => this.manager.emit(event, { ...payload, shardId }));
}
this.shards.set(shardId, shard);
}
}
/**
* {@inheritDoc IShardingStrategy.connect}
*/
async connect() {
const promises = [];
for (const shard of this.shards.values()) {
promises.push(shard.connect());
}
await Promise.all(promises);
}
/**
* {@inheritDoc IShardingStrategy.destroy}
*/
async destroy(options) {
const promises = [];
for (const shard of this.shards.values()) {
promises.push(shard.destroy(options));
}
await Promise.all(promises);
this.shards.clear();
}
/**
* {@inheritDoc IShardingStrategy.send}
*/
async send(shardId, payload) {
const shard = this.shards.get(shardId);
if (!shard) {
throw new RangeError(`Shard ${shardId} not found`);
}
return shard.send(payload);
}
/**
* {@inheritDoc IShardingStrategy.fetchStatus}
*/
async fetchStatus() {
return this.shards.mapValues((shard) => shard.status);
}
};
__name(SimpleShardingStrategy, "SimpleShardingStrategy");
// src/throttling/SimpleIdentifyThrottler.ts
import { setTimeout as sleep } from "node:timers/promises";
import { Collection as Collection4 } from "@discordjs/collection";
import { AsyncQueue } from "@sapphire/async-queue";
var SimpleIdentifyThrottler = class {
constructor(maxConcurrency) {
this.maxConcurrency = maxConcurrency;
}
states = new Collection4();
/**
* {@inheritDoc IIdentifyThrottler.waitForIdentify}
*/
async waitForIdentify(shardId, signal) {
const key = shardId % this.maxConcurrency;
const state = this.states.ensure(key, () => {
return {
queue: new AsyncQueue(),
resetsAt: Number.POSITIVE_INFINITY
};
});
await state.queue.wait({ signal });
try {
const diff = state.resetsAt - Date.now();
if (diff <= 5e3) {
const time = diff + Math.random() * 1500;
await sleep(time);
}
state.resetsAt = Date.now() + 5e3;
} finally {
state.queue.shift();
}
}
};
__name(SimpleIdentifyThrottler, "SimpleIdentifyThrottler");
// src/utils/constants.ts
var DefaultDeviceProperty = `@discordjs/ws 0.8.3`;
var getDefaultSessionStore = lazy(() => new Collection5());
var DefaultWebSocketManagerOptions = {
async buildIdentifyThrottler(manager) {
const info = await manager.fetchGatewayInformation();
return new SimpleIdentifyThrottler(info.session_start_limit.max_concurrency);
},
buildStrategy: (manager) => new SimpleShardingStrategy(manager),
shardCount: null,
shardIds: null,
largeThreshold: null,
initialPresence: null,
identifyProperties: {
browser: DefaultDeviceProperty,
device: DefaultDeviceProperty,
os: process.platform
},
version: APIVersion,
encoding: "json" /* JSON */,
compression: null,
retrieveSessionInfo(shardId) {
const store = getDefaultSessionStore();
return store.get(shardId) ?? null;
},
updateSessionInfo(shardId, info) {
const store = getDefaultSessionStore();
if (info) {
store.set(shardId, info);
} else {
store.delete(shardId);
}
},
handshakeTimeout: 3e4,
helloTimeout: 6e4,
readyTimeout: 15e3
};
var ImportantGatewayOpcodes = /* @__PURE__ */ new Set([
GatewayOpcodes.Heartbeat,
GatewayOpcodes.Identify,
GatewayOpcodes.Resume
]);
function getInitialSendRateLimitState() {
return {
remaining: 120,
resetAt: Date.now() + 6e4
};
}
__name(getInitialSendRateLimitState, "getInitialSendRateLimitState");
// src/ws/WebSocketShard.ts
var getZlibSync = lazy2(async () => import("zlib-sync").then((mod) => mod.default).catch(() => null));
var WebSocketShardEvents = /* @__PURE__ */ ((WebSocketShardEvents2) => {
WebSocketShardEvents2["Closed"] = "closed";
WebSocketShardEvents2["Debug"] = "debug";
WebSocketShardEvents2["Dispatch"] = "dispatch";
WebSocketShardEvents2["Error"] = "error";
WebSocketShardEvents2["HeartbeatComplete"] = "heartbeat";
WebSocketShardEvents2["Hello"] = "hello";
WebSocketShardEvents2["Ready"] = "ready";
WebSocketShardEvents2["Resumed"] = "resumed";
return WebSocketShardEvents2;
})(WebSocketShardEvents || {});
var WebSocketShardDestroyRecovery = /* @__PURE__ */ ((WebSocketShardDestroyRecovery2) => {
WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Reconnect"] = 0] = "Reconnect";
WebSocketShardDestroyRecovery2[WebSocketShardDestroyRecovery2["Resume"] = 1] = "Resume";
return WebSocketShardDestroyRecovery2;
})(WebSocketShardDestroyRecovery || {});
var WebSocketShard = class extends AsyncEventEmitter {
connection = null;
useIdentifyCompress = false;
inflate = null;
textDecoder = new TextDecoder();
replayedEvents = 0;
isAck = true;
sendRateLimitState = getInitialSendRateLimitState();
initialHeartbeatTimeoutController = null;
heartbeatInterval = null;
lastHeartbeatAt = -1;
// Indicates whether the shard has already resolved its original connect() call
initialConnectResolved = false;
// Indicates if we failed to connect to the ws url (ECONNREFUSED/ECONNRESET)
failedToConnectDueToNetworkError = false;
sendQueue = new AsyncQueue2();
timeoutAbortControllers = new Collection6();
strategy;
id;
#status = 0 /* Idle */;
get status() {
return this.#status;
}
constructor(strategy, id) {
super();
this.strategy = strategy;
this.id = id;
}
async connect() {
const promise = this.initialConnectResolved ? Promise.resolve() : once2(this, "ready" /* Ready */);
void this.internalConnect();
await promise;
this.initialConnectResolved = true;
}
async internalConnect() {
if (this.#status !== 0 /* Idle */) {
throw new Error("Tried to connect a shard that wasn't idle");
}
const { version, encoding, compression } = this.strategy.options;
const params = new URLSearchParams({ v: version, encoding });
if (compression) {
const zlib = await getZlibSync();
if (zlib) {
params.append("compress", compression);
this.inflate = new zlib.Inflate({
chunkSize: 65535,
to: "string"
});
} else if (!this.useIdentifyCompress) {
this.useIdentifyCompress = true;
console.warn(
"WebSocketShard: Compression is enabled but zlib-sync is not installed, falling back to identify compress"
);
}
}
const session = await this.strategy.retrieveSessionInfo(this.id);
const url = `${session?.resumeURL ?? this.strategy.options.gatewayInformation.url}?${params.toString()}`;
this.debug([`Connecting to ${url}`]);
const connection = new WebSocket(url, { handshakeTimeout: this.strategy.options.handshakeTimeout ?? void 0 }).on("message", this.onMessage.bind(this)).on("error", this.onError.bind(this)).on("close", this.onClose.bind(this));
connection.binaryType = "arraybuffer";
this.connection = connection;
this.#status = 1 /* Connecting */;
this.sendRateLimitState = getInitialSendRateLimitState();
const { ok } = await this.waitForEvent("hello" /* Hello */, this.strategy.options.helloTimeout);
if (!ok) {
return;
}
if (session?.shardCount === this.strategy.options.shardCount) {
await this.resume(session);
} else {
await this.identify();
}
}
async destroy(options = {}) {
if (this.#status === 0 /* Idle */) {
this.debug(["Tried to destroy a shard that was idle"]);
return;
}
if (!options.code) {
options.code = options.recover === 1 /* Resume */ ? 4200 /* Resuming */ : 1e3 /* Normal */;
}
this.debug([
"Destroying shard",
`Reason: ${options.reason ?? "none"}`,
`Code: ${options.code}`,
`Recover: ${options.recover === void 0 ? "none" : WebSocketShardDestroyRecovery[options.recover]}`
]);
this.isAck = true;
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
}
if (this.initialHeartbeatTimeoutController) {
this.initialHeartbeatTimeoutController.abort();
this.initialHeartbeatTimeoutController = null;
}
this.lastHeartbeatAt = -1;
for (const controller of this.timeoutAbortControllers.values()) {
controller.abort();
}
this.timeoutAbortControllers.clear();
this.failedToConnectDueToNetworkError = false;
if (options.recover !== 1 /* Resume */) {
await this.strategy.updateSessionInfo(this.id, null);
}
if (this.connection) {
this.connection.removeAllListeners("message");
this.connection.removeAllListeners("close");
const shouldClose = this.connection.readyState === WebSocket.OPEN;
this.debug([
"Connection status during destroy",
`Needs closing: ${shouldClose}`,
`Ready state: ${this.connection.readyState}`
]);
if (shouldClose) {
this.connection.close(options.code, options.reason);
await once2(this.connection, "close");
this.emit("closed" /* Closed */, { code: options.code });
}
this.connection.removeAllListeners("error");
} else {
this.debug(["Destroying a shard that has no connection; please open an issue on GitHub"]);
}
this.#status = 0 /* Idle */;
if (options.recover !== void 0) {
await sleep2(500);
return this.internalConnect();
}
}
async waitForEvent(event, timeoutDuration) {
this.debug([`Waiting for event ${event} ${timeoutDuration ? `for ${timeoutDuration}ms` : "indefinitely"}`]);
const timeoutController = new AbortController();
const timeout = timeoutDuration ? setTimeout(() => timeoutController.abort(), timeoutDuration).unref() : null;
this.timeoutAbortControllers.set(event, timeoutController);
const closeController = new AbortController();
try {
const closed = await Promise.race([
once2(this, event, { signal: timeoutController.signal }).then(() => false),
once2(this, "closed" /* Closed */, { signal: closeController.signal }).then(() => true)
]);
return { ok: !closed };
} catch {
void this.destroy({
code: 1e3 /* Normal */,
reason: "Something timed out or went wrong while waiting for an event",
recover: 0 /* Reconnect */
});
return { ok: false };
} finally {
if (timeout) {
clearTimeout(timeout);
}
this.timeoutAbortControllers.delete(event);
if (!closeController.signal.aborted) {
closeController.abort();
}
}
}
async send(payload) {
if (!this.connection) {
throw new Error("WebSocketShard wasn't connected");
}
if (this.#status !== 3 /* Ready */ && !ImportantGatewayOpcodes.has(payload.op)) {
this.debug(["Tried to send a non-crucial payload before the shard was ready, waiting"]);
try {
await once2(this, "ready" /* Ready */);
} catch {
return this.send(payload);
}
}
await this.sendQueue.wait();
if (--this.sendRateLimitState.remaining <= 0) {
const now = Date.now();
if (this.sendRateLimitState.resetAt > now) {
const sleepFor = this.sendRateLimitState.resetAt - now;
this.debug([`Was about to hit the send rate limit, sleeping for ${sleepFor}ms`]);
const controller = new AbortController();
const interrupted = await Promise.race([
sleep2(sleepFor).then(() => false),
once2(this, "closed" /* Closed */, { signal: controller.signal }).then(() => true)
]);
if (interrupted) {
this.debug(["Connection closed while waiting for the send rate limit to reset, re-queueing payload"]);
this.sendQueue.shift();
return this.send(payload);
}
controller.abort();
}
this.sendRateLimitState = getInitialSendRateLimitState();
}
this.sendQueue.shift();
this.connection.send(JSON.stringify(payload));
}
async identify() {
this.debug(["Waiting for identify throttle"]);
const controller = new AbortController();
const closeHandler = /* @__PURE__ */ __name(() => {
controller.abort();
}, "closeHandler");
this.on("closed" /* Closed */, closeHandler);
try {
await this.strategy.waitForIdentify(this.id, controller.signal);
} catch {
this.debug(["Was waiting for an identify, but the shard closed in the meantime"]);
return;
} finally {
this.off("closed" /* Closed */, closeHandler);
}
this.debug([
"Identifying",
`shard id: ${this.id.toString()}`,
`shard count: ${this.strategy.options.shardCount}`,
`intents: ${this.strategy.options.intents}`,
`compression: ${this.inflate ? "zlib-stream" : this.useIdentifyCompress ? "identify" : "none"}`
]);
const d = {
token: this.strategy.options.token,
properties: this.strategy.options.identifyProperties,
intents: this.strategy.options.intents,
compress: this.useIdentifyCompress,
shard: [this.id, this.strategy.options.shardCount]
};
if (this.strategy.options.largeThreshold) {
d.large_threshold = this.strategy.options.largeThreshold;
}
if (this.strategy.options.initialPresence) {
d.presence = this.strategy.options.initialPresence;
}
await this.send({
op: GatewayOpcodes2.Identify,
d
});
await this.waitForEvent("ready" /* Ready */, this.strategy.options.readyTimeout);
}
async resume(session) {
this.debug([
"Resuming session",
`resume url: ${session.resumeURL}`,
`sequence: ${session.sequence}`,
`shard id: ${this.id.toString()}`
]);
this.#status = 2 /* Resuming */;
this.replayedEvents = 0;
return this.send({
op: GatewayOpcodes2.Resume,
d: {
token: this.strategy.options.token,
seq: session.sequence,
session_id: session.sessionId
}
});
}
async heartbeat(requested = false) {
if (!this.isAck && !requested) {
return this.destroy({ reason: "Zombie connection", recover: 1 /* Resume */ });
}
const session = await this.strategy.retrieveSessionInfo(this.id);
await this.send({
op: GatewayOpcodes2.Heartbeat,
d: session?.sequence ?? null
});
this.lastHeartbeatAt = Date.now();
this.isAck = false;
}
async unpackMessage(data, isBinary) {
const decompressable = new Uint8Array(data);
if (!isBinary) {
return JSON.parse(this.textDecoder.decode(decompressable));
}
if (this.useIdentifyCompress) {
return new Promise((resolve2, reject) => {
inflate(decompressable, { chunkSize: 65535 }, (err, result) => {
if (err) {
reject(err);
return;
}
resolve2(JSON.parse(this.textDecoder.decode(result)));
});
});
}
if (this.inflate) {
const l = decompressable.length;
const flush = l >= 4 && decompressable[l - 4] === 0 && decompressable[l - 3] === 0 && decompressable[l - 2] === 255 && decompressable[l - 1] === 255;
const zlib = await getZlibSync();
this.inflate.push(Buffer2.from(decompressable), flush ? zlib.Z_SYNC_FLUSH : zlib.Z_NO_FLUSH);
if (this.inflate.err) {
this.emit("error" /* Error */, {
error: new Error(`${this.inflate.err}${this.inflate.msg ? `: ${this.inflate.msg}` : ""}`)
});
}
if (!flush) {
return null;
}
const { result } = this.inflate;
if (!result) {
return null;
}
return JSON.parse(typeof result === "string" ? result : this.textDecoder.decode(result));
}
this.debug([
"Received a message we were unable to decompress",
`isBinary: ${isBinary.toString()}`,
`useIdentifyCompress: ${this.useIdentifyCompress.toString()}`,
`inflate: ${Boolean(this.inflate).toString()}`
]);
return null;
}
async onMessage(data, isBinary) {
const payload = await this.unpackMessage(data, isBinary);
if (!payload) {
return;
}
switch (payload.op) {
case GatewayOpcodes2.Dispatch: {
if (this.#status === 2 /* Resuming */) {
this.replayedEvents++;
}
switch (payload.t) {
case GatewayDispatchEvents.Ready: {
this.#status = 3 /* Ready */;
const session2 = {
sequence: payload.s,
sessionId: payload.d.session_id,
shardId: this.id,
shardCount: this.strategy.options.shardCount,
resumeURL: payload.d.resume_gateway_url
};
await this.strategy.updateSessionInfo(this.id, session2);
this.emit("ready" /* Ready */, { data: payload.d });
break;
}
case GatewayDispatchEvents.Resumed: {
this.#status = 3 /* Ready */;
this.debug([`Resumed and replayed ${this.replayedEvents} events`]);
this.emit("resumed" /* Resumed */);
break;
}
default: {
break;
}
}
const session = await this.strategy.retrieveSessionInfo(this.id);
if (session) {
if (payload.s > session.sequence) {
await this.strategy.updateSessionInfo(this.id, { ...session, sequence: payload.s });
}
} else {
this.debug([
`Received a ${payload.t} event but no session is available. Session information cannot be re-constructed in this state without a full reconnect`
]);
}
this.emit("dispatch" /* Dispatch */, { data: payload });
break;
}
case GatewayOpcodes2.Heartbeat: {
await this.heartbeat(true);
break;
}
case GatewayOpcodes2.Reconnect: {
await this.destroy({
reason: "Told to reconnect by Discord",
recover: 1 /* Resume */
});
break;
}
case GatewayOpcodes2.InvalidSession: {
this.debug([`Invalid session; will attempt to resume: ${payload.d.toString()}`]);
const session = await this.strategy.retrieveSessionInfo(this.id);
if (payload.d && session) {
await this.resume(session);
} else {
await this.destroy({
reason: "Invalid session",
recover: 0 /* Reconnect */
});
}
break;
}
case GatewayOpcodes2.Hello: {
this.emit("hello" /* Hello */);
const jitter = Math.random();
const firstWait = Math.floor(payload.d.heartbeat_interval * jitter);
this.debug([`Preparing first heartbeat of the connection with a jitter of ${jitter}; waiting ${firstWait}ms`]);
try {
const controller = new AbortController();
this.initialHeartbeatTimeoutController = controller;
await sleep2(firstWait, void 0, { signal: controller.signal });
} catch {
this.debug(["Cancelled initial heartbeat due to #destroy being called"]);
return;
} finally {
this.initialHeartbeatTimeoutController = null;
}
await this.heartbeat();
this.debug([`First heartbeat sent, starting to beat every ${payload.d.heartbeat_interval}ms`]);
this.heartbeatInterval = setInterval(() => void this.heartbeat(), payload.d.heartbeat_interval);
break;
}
case GatewayOpcodes2.HeartbeatAck: {
this.isAck = true;
const ackAt = Date.now();
this.emit("heartbeat" /* HeartbeatComplete */, {
ackAt,
heartbeatAt: this.lastHeartbeatAt,
latency: ackAt - this.lastHeartbeatAt
});
break;
}
}
}
onError(error) {
if ("code" in error && ["ECONNRESET", "ECONNREFUSED"].includes(error.code)) {
this.debug(["Failed to connect to the gateway URL specified due to a network error"]);
this.failedToConnectDueToNetworkError = true;
return;
}
this.emit("error" /* Error */, { error });
}
async onClose(code) {
this.emit("closed" /* Closed */, { code });
switch (code) {
case 1e3 /* Normal */: {
return this.destroy({
code,
reason: "Got disconnected by Discord",
recover: 0 /* Reconnect */
});
}
case 4200 /* Resuming */: {
break;
}
case GatewayCloseCodes.UnknownError: {
this.debug([`An unknown error occurred: ${code}`]);
return this.destroy({ code, recover: 1 /* Resume */ });
}
case GatewayCloseCodes.UnknownOpcode: {
this.debug(["An invalid opcode was sent to Discord."]);
return this.destroy({ code, recover: 1 /* Resume */ });
}
case GatewayCloseCodes.DecodeError: {
this.debug(["An invalid payload was sent to Discord."]);
return this.destroy({ code, recover: 1 /* Resume */ });
}
case GatewayCloseCodes.NotAuthenticated: {
this.debug(["A request was somehow sent before the identify/resume payload."]);
return this.destroy({ code, recover: 0 /* Reconnect */ });
}
case GatewayCloseCodes.AuthenticationFailed: {
throw new Error("Authentication failed");
}
case GatewayCloseCodes.AlreadyAuthenticated: {
this.debug(["More than one auth payload was sent."]);
return this.destroy({ code, recover: 0 /* Reconnect */ });
}
case GatewayCloseCodes.InvalidSeq: {
this.debug(["An invalid sequence was sent."]);
return this.destroy({ code, recover: 0 /* Reconnect */ });
}
case GatewayCloseCodes.RateLimited: {
this.debug(["The WebSocket rate limit has been hit, this should never happen"]);
return this.destroy({ code, recover: 0 /* Reconnect */ });
}
case GatewayCloseCodes.SessionTimedOut: {
this.debug(["Session timed out."]);
return this.destroy({ code, recover: 1 /* Resume */ });
}
case GatewayCloseCodes.InvalidShard: {
throw new Error("Invalid shard");
}
case GatewayCloseCodes.ShardingRequired: {
throw new Error("Sharding is required");
}
case GatewayCloseCodes.InvalidAPIVersion: {
throw new Error("Used an invalid API version");
}
case GatewayCloseCodes.InvalidIntents: {
throw new Error("Used invalid intents");
}
case GatewayCloseCodes.DisallowedIntents: {
throw new Error("Used disallowed intents");
}
default: {
this.debug([
`The gateway closed with an unexpected code ${code}, attempting to ${this.failedToConnectDueToNetworkError ? "reconnect" : "resume"}.`
]);
return this.destroy({
code,
recover: this.failedToConnectDueToNetworkError ? 0 /* Reconnect */ : 1 /* Resume */
});
}
}
}
debug(messages) {
const message = `${messages[0]}${messages.length > 1 ? `
${messages.slice(1).map((m) => ` ${m}`).join("\n")}` : ""}`;
this.emit("debug" /* Debug */, { message });
}
};
__name(WebSocketShard, "WebSocketShard");
// src/utils/WorkerBootstrapper.ts
var WorkerBootstrapper = class {
/**
* The data passed to the worker thread
*/
data = workerData;
/**
* The shards that are managed by this worker
*/
shards = new Collection7();
constructor() {
if (isMainThread2) {
throw new Error("Expected WorkerBootstrap to not be used within the main thread");
}
}
/**
* Helper method to initiate a shard's connection process
*/
async connect(shardId) {
const shard = this.shards.get(shardId);
if (!shard) {
throw new RangeError(`Shard ${shardId} does not exist`);
}
await shard.connect();
}
/**
* Helper method to destroy a shard
*/
async destroy(shardId, options) {
const shard = this.shards.get(shardId);
if (!shard) {
throw new RangeError(`Shard ${shardId} does not exist`);
}
await shard.destroy(options);
}
/**
* Helper method to attach event listeners to the parentPort
*/
setupThreadEvents() {
parentPort2.on("messageerror", (err) => {
throw err;
}).on("message", async (payload) => {
switch (payload.op) {
case 0 /* Connect */: {
await this.connect(payload.shardId);
const response = {
op: 0 /* Connected */,
shardId: payload.shardId
};
parentPort2.postMessage(response);
break;
}
case 1 /* Destroy */: {
await this.destroy(payload.shardId, payload.options);
const response = {
op: 1 /* Destroyed */,
shardId: payload.shardId
};
parentPort2.postMessage(response);
break;
}
case 2 /* Send */: {
const shard = this.shards.get(payload.shardId);
if (!shard) {
throw new RangeError(`Shard ${payload.shardId} does not exist`);
}
await shard.send(payload.payload);
break;
}
case 3 /* SessionInfoResponse */: {
break;
}
case 4 /* ShardIdentifyResponse */: {
break;
}
case 5 /* FetchStatus */: {
const shard = this.shards.get(payload.shardId);
if (!shard) {
throw new Error(`Shard ${payload.shardId} does not exist`);
}
const response = {
op: 6 /* FetchStatusResponse */,
status: shard.status,
nonce: payload.nonce
};
parentPort2.postMessage(response);
break;
}
}
});
}
/**
* Bootstraps the worker thread with the provided options
*/
async bootstrap(options = {}) {
for (const shardId of this.data.shardIds) {
const shard = new WebSocketShard(new WorkerContextFetchingStrategy(this.data), shardId);
for (const event of options.forwardEvents ?? Object.values(WebSocketShardEvents)) {
shard.on(event, (data) => {
const payload = {
op: 2 /* Event */,
event,
data,
shardId
};
parentPort2.postMessage(payload);
});
}
await options.shardCallback?.(shard);
this.shards.set(shardId, shard);
}
this.setupThreadEvents();
const message = {
op: 7 /* WorkerReady */
};
parentPort2.postMessage(message);
}
};
__name(WorkerBootstrapper, "WorkerBootstrapper");
// src/strategies/sharding/defaultWorker.ts
var bootstrapper = new WorkerBootstrapper();
void bootstrapper.bootstrap();
//# sourceMappingURL=defaultWorker.mjs.map

File diff suppressed because one or more lines are too long

667
node_modules/@discordjs/ws/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,667 @@
import * as _discordjs_util from '@discordjs/util';
import { Awaitable } from '@discordjs/util';
import { GatewayDispatchPayload, GatewayReadyDispatchData, GatewaySendPayload, GatewayOpcodes, GatewayIntentBits, GatewayIdentifyProperties, GatewayPresenceUpdateData, APIGatewayBotInfo } from 'discord-api-types/v10';
import * as _discordjs_collection from '@discordjs/collection';
import { Collection } from '@discordjs/collection';
import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
import { REST } from '@discordjs/rest';
import { AsyncQueue } from '@sapphire/async-queue';
declare enum WebSocketShardEvents {
Closed = "closed",
Debug = "debug",
Dispatch = "dispatch",
Error = "error",
HeartbeatComplete = "heartbeat",
Hello = "hello",
Ready = "ready",
Resumed = "resumed"
}
declare enum WebSocketShardStatus {
Idle = 0,
Connecting = 1,
Resuming = 2,
Ready = 3
}
declare enum WebSocketShardDestroyRecovery {
Reconnect = 0,
Resume = 1
}
type WebSocketShardEventsMap = {
[WebSocketShardEvents.Closed]: [{
code: number;
}];
[WebSocketShardEvents.Debug]: [payload: {
message: string;
}];
[WebSocketShardEvents.Dispatch]: [payload: {
data: GatewayDispatchPayload;
}];
[WebSocketShardEvents.Error]: [payload: {
error: Error;
}];
[WebSocketShardEvents.Hello]: [];
[WebSocketShardEvents.Ready]: [payload: {
data: GatewayReadyDispatchData;
}];
[WebSocketShardEvents.Resumed]: [];
[WebSocketShardEvents.HeartbeatComplete]: [payload: {
ackAt: number;
heartbeatAt: number;
latency: number;
}];
};
interface WebSocketShardDestroyOptions {
code?: number;
reason?: string;
recover?: WebSocketShardDestroyRecovery;
}
declare enum CloseCodes {
Normal = 1000,
Resuming = 4200
}
interface SendRateLimitState {
remaining: number;
resetAt: number;
}
declare class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
#private;
private connection;
private useIdentifyCompress;
private inflate;
private readonly textDecoder;
private replayedEvents;
private isAck;
private sendRateLimitState;
private initialHeartbeatTimeoutController;
private heartbeatInterval;
private lastHeartbeatAt;
private initialConnectResolved;
private failedToConnectDueToNetworkError;
private readonly sendQueue;
private readonly timeoutAbortControllers;
private readonly strategy;
readonly id: number;
get status(): WebSocketShardStatus;
constructor(strategy: IContextFetchingStrategy, id: number);
connect(): Promise<void>;
private internalConnect;
destroy(options?: WebSocketShardDestroyOptions): Promise<void>;
private waitForEvent;
send(payload: GatewaySendPayload): Promise<void>;
private identify;
private resume;
private heartbeat;
private unpackMessage;
private onMessage;
private onError;
private onClose;
private debug;
}
/**
* Strategies responsible for spawning, initializing connections, destroying shards, and relaying events
*/
interface IShardingStrategy {
/**
* Initializes all the shards
*/
connect(): Awaitable<void>;
/**
* Destroys all the shards
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Awaitable<void>;
/**
* Fetches the status of all the shards
*/
fetchStatus(): Awaitable<Collection<number, WebSocketShardStatus>>;
/**
* Sends a payload to a shard
*/
send(shardId: number, payload: GatewaySendPayload): Awaitable<void>;
/**
* Spawns all the shards
*/
spawn(shardIds: number[]): Awaitable<void>;
}
/**
* IdentifyThrottlers are responsible for dictating when a shard is allowed to identify.
*
* @see {@link https://discord.com/developers/docs/topics/gateway#sharding-max-concurrency}
*/
interface IIdentifyThrottler {
/**
* Resolves once the given shard should be allowed to identify, or rejects if the operation was aborted.
*/
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
/**
* Simple strategy that just spawns shards in the current process
*/
declare class SimpleShardingStrategy implements IShardingStrategy {
private readonly manager;
private readonly shards;
constructor(manager: WebSocketManager);
/**
* {@inheritDoc IShardingStrategy.spawn}
*/
spawn(shardIds: number[]): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.connect}
*/
connect(): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.destroy}
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.send}
*/
send(shardId: number, payload: GatewaySendPayload): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.fetchStatus}
*/
fetchStatus(): Promise<Collection<number, WebSocketShardStatus>>;
}
/**
* The state of a rate limit key's identify queue.
*/
interface IdentifyState {
queue: AsyncQueue;
resetsAt: number;
}
/**
* Local, in-memory identify throttler.
*/
declare class SimpleIdentifyThrottler implements IIdentifyThrottler {
private readonly maxConcurrency;
private readonly states;
constructor(maxConcurrency: number);
/**
* {@inheritDoc IIdentifyThrottler.waitForIdentify}
*/
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
/**
* Valid encoding types
*/
declare enum Encoding {
JSON = "json"
}
/**
* Valid compression methods
*/
declare enum CompressionMethod {
ZlibStream = "zlib-stream"
}
declare const DefaultDeviceProperty: `@discordjs/ws ${string}`;
/**
* Default options used by the manager
*/
declare const DefaultWebSocketManagerOptions: {
readonly buildIdentifyThrottler: (manager: WebSocketManager) => Promise<SimpleIdentifyThrottler>;
readonly buildStrategy: (manager: WebSocketManager) => SimpleShardingStrategy;
readonly shardCount: null;
readonly shardIds: null;
readonly largeThreshold: null;
readonly initialPresence: null;
readonly identifyProperties: {
readonly browser: `@discordjs/ws ${string}`;
readonly device: `@discordjs/ws ${string}`;
readonly os: NodeJS.Platform;
};
readonly version: "10";
readonly encoding: Encoding;
readonly compression: null;
readonly retrieveSessionInfo: (shardId: number) => SessionInfo | null;
readonly updateSessionInfo: (shardId: number, info: SessionInfo | null) => void;
readonly handshakeTimeout: 30000;
readonly helloTimeout: 60000;
readonly readyTimeout: 15000;
};
declare const ImportantGatewayOpcodes: Set<GatewayOpcodes>;
declare function getInitialSendRateLimitState(): SendRateLimitState;
/**
* Represents a range of shard ids
*/
interface ShardRange {
end: number;
start: number;
}
/**
* Session information for a given shard, used to resume a session
*/
interface SessionInfo {
/**
* URL to use when resuming
*/
resumeURL: string;
/**
* The sequence number of the last message sent by the shard
*/
sequence: number;
/**
* Session id for this shard
*/
sessionId: string;
/**
* The total number of shards at the time of this shard identifying
*/
shardCount: number;
/**
* The id of the shard
*/
shardId: number;
}
/**
* Required options for the WebSocketManager
*/
interface RequiredWebSocketManagerOptions {
/**
* The intents to request
*/
intents: GatewayIntentBits | 0;
/**
* The REST instance to use for fetching gateway information
*/
rest: REST;
/**
* The token to use for identifying with the gateway
*/
token: string;
}
/**
* Optional additional configuration for the WebSocketManager
*/
interface OptionalWebSocketManagerOptions {
/**
* Builds an identify throttler to use for this manager's shards
*/
buildIdentifyThrottler(manager: WebSocketManager): Awaitable<IIdentifyThrottler>;
/**
* Builds the strategy to use for sharding
*
* @example
* ```ts
* const manager = new WebSocketManager({
* token: process.env.DISCORD_TOKEN,
* intents: 0, // for no intents
* rest,
* buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 2 }),
* });
* ```
*/
buildStrategy(manager: WebSocketManager): IShardingStrategy;
/**
* The compression method to use
*
* @defaultValue `null` (no compression)
*/
compression: CompressionMethod | null;
/**
* The encoding to use
*
* @defaultValue `'json'`
*/
encoding: Encoding;
/**
* How long to wait for a shard to connect before giving up
*/
handshakeTimeout: number | null;
/**
* How long to wait for a shard's HELLO packet before giving up
*/
helloTimeout: number | null;
/**
* Properties to send to the gateway when identifying
*/
identifyProperties: GatewayIdentifyProperties;
/**
* Initial presence data to send to the gateway when identifying
*/
initialPresence: GatewayPresenceUpdateData | null;
/**
* Value between 50 and 250, total number of members where the gateway will stop sending offline members in the guild member list
*/
largeThreshold: number | null;
/**
* How long to wait for a shard's READY packet before giving up
*/
readyTimeout: number | null;
/**
* Function used to retrieve session information (and attempt to resume) for a given shard
*
* @example
* ```ts
* const manager = new WebSocketManager({
* async retrieveSessionInfo(shardId): Awaitable<SessionInfo | null> {
* // Fetch this info from redis or similar
* return { sessionId: string, sequence: number };
* // Return null if no information is found
* },
* });
* ```
*/
retrieveSessionInfo(shardId: number): Awaitable<SessionInfo | null>;
/**
* The total number of shards across all WebsocketManagers you intend to instantiate.
* Use `null` to use Discord's recommended shard count
*/
shardCount: number | null;
/**
* The ids of the shards this WebSocketManager should manage.
* Use `null` to simply spawn 0 through `shardCount - 1`
*
* @example
* ```ts
* const manager = new WebSocketManager({
* shardIds: [1, 3, 7], // spawns shard 1, 3, and 7, nothing else
* });
* ```
* @example
* ```ts
* const manager = new WebSocketManager({
* shardIds: {
* start: 3,
* end: 6,
* }, // spawns shards 3, 4, 5, and 6
* });
* ```
*/
shardIds: number[] | ShardRange | null;
/**
* Function used to store session information for a given shard
*/
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable<void>;
/**
* The gateway version to use
*
* @defaultValue `'10'`
*/
version: string;
}
type WebSocketManagerOptions = OptionalWebSocketManagerOptions & RequiredWebSocketManagerOptions;
type ManagerShardEventsMap = {
[K in keyof WebSocketShardEventsMap]: [
WebSocketShardEventsMap[K] extends [] ? {
shardId: number;
} : WebSocketShardEventsMap[K][0] & {
shardId: number;
}
];
};
declare class WebSocketManager extends AsyncEventEmitter<ManagerShardEventsMap> {
/**
* The options being used by this manager
*/
readonly options: WebSocketManagerOptions;
/**
* Internal cache for a GET /gateway/bot result
*/
private gatewayInformation;
/**
* Internal cache for the shard ids
*/
private shardIds;
/**
* Strategy used to manage shards
*
* @defaultValue `SimpleShardingStrategy`
*/
private readonly strategy;
constructor(options: Partial<OptionalWebSocketManagerOptions> & RequiredWebSocketManagerOptions);
/**
* Fetches the gateway information from Discord - or returns it from cache if available
*
* @param force - Whether to ignore the cache and force a fresh fetch
*/
fetchGatewayInformation(force?: boolean): Promise<APIGatewayBotInfo>;
/**
* Updates your total shard count on-the-fly, spawning shards as needed
*
* @param shardCount - The new shard count to use
*/
updateShardCount(shardCount: number | null): Promise<this>;
/**
* Yields the total number of shards across for your bot, accounting for Discord recommendations
*/
getShardCount(): Promise<number>;
/**
* Yields the ids of the shards this manager should manage
*/
getShardIds(force?: boolean): Promise<number[]>;
connect(): Promise<void>;
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Awaitable<void>;
send(shardId: number, payload: GatewaySendPayload): Awaitable<void>;
fetchStatus(): Awaitable<_discordjs_collection.Collection<number, WebSocketShardStatus>>;
}
interface FetchingStrategyOptions extends Omit<WebSocketManagerOptions, 'buildIdentifyThrottler' | 'buildStrategy' | 'rest' | 'retrieveSessionInfo' | 'shardCount' | 'shardIds' | 'updateSessionInfo'> {
readonly gatewayInformation: APIGatewayBotInfo;
readonly shardCount: number;
}
/**
* Strategies responsible solely for making manager information accessible
*/
interface IContextFetchingStrategy {
readonly options: FetchingStrategyOptions;
retrieveSessionInfo(shardId: number): Awaitable<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): Awaitable<void>;
/**
* Resolves once the given shard should be allowed to identify, or rejects if the operation was aborted
*/
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
declare function managerToFetchingStrategyOptions(manager: WebSocketManager): Promise<FetchingStrategyOptions>;
declare class SimpleContextFetchingStrategy implements IContextFetchingStrategy {
private readonly manager;
readonly options: FetchingStrategyOptions;
private static throttlerCache;
private static ensureThrottler;
constructor(manager: WebSocketManager, options: FetchingStrategyOptions);
retrieveSessionInfo(shardId: number): Promise<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): _discordjs_util.Awaitable<void>;
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
declare class WorkerContextFetchingStrategy implements IContextFetchingStrategy {
readonly options: FetchingStrategyOptions;
private readonly sessionPromises;
private readonly waitForIdentifyPromises;
constructor(options: FetchingStrategyOptions);
retrieveSessionInfo(shardId: number): Promise<SessionInfo | null>;
updateSessionInfo(shardId: number, sessionInfo: SessionInfo | null): void;
waitForIdentify(shardId: number, signal: AbortSignal): Promise<void>;
}
interface WorkerData extends FetchingStrategyOptions {
shardIds: number[];
}
declare enum WorkerSendPayloadOp {
Connect = 0,
Destroy = 1,
Send = 2,
SessionInfoResponse = 3,
ShardIdentifyResponse = 4,
FetchStatus = 5
}
type WorkerSendPayload = {
nonce: number;
ok: boolean;
op: WorkerSendPayloadOp.ShardIdentifyResponse;
} | {
nonce: number;
op: WorkerSendPayloadOp.FetchStatus;
shardId: number;
} | {
nonce: number;
op: WorkerSendPayloadOp.SessionInfoResponse;
session: SessionInfo | null;
} | {
op: WorkerSendPayloadOp.Connect;
shardId: number;
} | {
op: WorkerSendPayloadOp.Destroy;
options?: WebSocketShardDestroyOptions;
shardId: number;
} | {
op: WorkerSendPayloadOp.Send;
payload: GatewaySendPayload;
shardId: number;
};
declare enum WorkerReceivePayloadOp {
Connected = 0,
Destroyed = 1,
Event = 2,
RetrieveSessionInfo = 3,
UpdateSessionInfo = 4,
WaitForIdentify = 5,
FetchStatusResponse = 6,
WorkerReady = 7,
CancelIdentify = 8
}
type WorkerReceivePayload = {
data: any;
event: WebSocketShardEvents;
op: WorkerReceivePayloadOp.Event;
shardId: number;
} | {
nonce: number;
op: WorkerReceivePayloadOp.CancelIdentify;
} | {
nonce: number;
op: WorkerReceivePayloadOp.FetchStatusResponse;
status: WebSocketShardStatus;
} | {
nonce: number;
op: WorkerReceivePayloadOp.RetrieveSessionInfo;
shardId: number;
} | {
nonce: number;
op: WorkerReceivePayloadOp.WaitForIdentify;
shardId: number;
} | {
op: WorkerReceivePayloadOp.Connected;
shardId: number;
} | {
op: WorkerReceivePayloadOp.Destroyed;
shardId: number;
} | {
op: WorkerReceivePayloadOp.UpdateSessionInfo;
session: SessionInfo | null;
shardId: number;
} | {
op: WorkerReceivePayloadOp.WorkerReady;
};
/**
* Options for a {@link WorkerShardingStrategy}
*/
interface WorkerShardingStrategyOptions {
/**
* Dictates how many shards should be spawned per worker thread.
*/
shardsPerWorker: number | 'all';
/**
* Path to the worker file to use. The worker requires quite a bit of setup, it is recommended you leverage the {@link WorkerBootstrapper} class.
*/
workerPath?: string;
}
/**
* Strategy used to spawn threads in worker_threads
*/
declare class WorkerShardingStrategy implements IShardingStrategy {
#private;
private readonly manager;
private readonly options;
private readonly connectPromises;
private readonly destroyPromises;
private readonly fetchStatusPromises;
private readonly waitForIdentifyControllers;
private throttler?;
constructor(manager: WebSocketManager, options: WorkerShardingStrategyOptions);
/**
* {@inheritDoc IShardingStrategy.spawn}
*/
spawn(shardIds: number[]): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.connect}
*/
connect(): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.destroy}
*/
destroy(options?: Omit<WebSocketShardDestroyOptions, 'recover'>): Promise<void>;
/**
* {@inheritDoc IShardingStrategy.send}
*/
send(shardId: number, data: GatewaySendPayload): void;
/**
* {@inheritDoc IShardingStrategy.fetchStatus}
*/
fetchStatus(): Promise<Collection<number, WebSocketShardStatus>>;
private setupWorker;
private resolveWorkerPath;
private waitForWorkerReady;
private onMessage;
private ensureThrottler;
}
/**
* Options for bootstrapping the worker
*/
interface BootstrapOptions {
/**
* Shard events to just arbitrarily forward to the parent thread for the manager to emit
* Note: By default, this will include ALL events
* you most likely want to handle dispatch within the worker itself
*/
forwardEvents?: WebSocketShardEvents[];
/**
* Function to call when a shard is created for additional setup
*/
shardCallback?(shard: WebSocketShard): Awaitable<void>;
}
/**
* Utility class for bootstrapping a worker thread to be used for sharding
*/
declare class WorkerBootstrapper {
/**
* The data passed to the worker thread
*/
protected readonly data: WorkerData;
/**
* The shards that are managed by this worker
*/
protected readonly shards: Collection<number, WebSocketShard>;
constructor();
/**
* Helper method to initiate a shard's connection process
*/
protected connect(shardId: number): Promise<void>;
/**
* Helper method to destroy a shard
*/
protected destroy(shardId: number, options?: WebSocketShardDestroyOptions): Promise<void>;
/**
* Helper method to attach event listeners to the parentPort
*/
protected setupThreadEvents(): void;
/**
* Bootstraps the worker thread with the provided options
*/
bootstrap(options?: Readonly<BootstrapOptions>): Promise<void>;
}
/**
* The {@link https://github.com/discordjs/discord.js/blob/main/packages/ws/#readme | @discordjs/ws} version
* that you are currently using.
*/
declare const version: string;
export { BootstrapOptions, CloseCodes, CompressionMethod, DefaultDeviceProperty, DefaultWebSocketManagerOptions, Encoding, FetchingStrategyOptions, IContextFetchingStrategy, IIdentifyThrottler, IShardingStrategy, IdentifyState, ImportantGatewayOpcodes, ManagerShardEventsMap, OptionalWebSocketManagerOptions, RequiredWebSocketManagerOptions, SendRateLimitState, SessionInfo, ShardRange, SimpleContextFetchingStrategy, SimpleIdentifyThrottler, SimpleShardingStrategy, WebSocketManager, WebSocketManagerOptions, WebSocketShard, WebSocketShardDestroyOptions, WebSocketShardDestroyRecovery, WebSocketShardEvents, WebSocketShardEventsMap, WebSocketShardStatus, WorkerBootstrapper, WorkerContextFetchingStrategy, WorkerData, WorkerReceivePayload, WorkerReceivePayloadOp, WorkerSendPayload, WorkerSendPayloadOp, WorkerShardingStrategy, WorkerShardingStrategyOptions, getInitialSendRateLimitState, managerToFetchingStrategyOptions, version };

1409
node_modules/@discordjs/ws/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/ws/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

1373
node_modules/@discordjs/ws/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@discordjs/ws/dist/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

99
node_modules/@discordjs/ws/package.json generated vendored Normal file
View file

@ -0,0 +1,99 @@
{
"name": "@discordjs/ws",
"version": "0.8.3",
"description": "Wrapper around Discord's gateway",
"scripts": {
"test": "vitest run",
"build": "tsup",
"build:docs": "tsc -p tsconfig.docs.json",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn build && yarn lint",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/ws/*'",
"release": "cliff-jumper"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"typings": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./defaultWorker": {
"types": null,
"import": "./dist/defaultWorker.mjs",
"require": "./dist/defaultWorker.js"
}
},
"directories": {
"lib": "src",
"test": "__tests__"
},
"files": [
"dist"
],
"contributors": [
"Crawl <icrawltogo@gmail.com>",
"Amish Shah <amishshah.2k@gmail.com>",
"SpaceEEC <spaceeec@yahoo.com>",
"Vlad Frangu <kingdgrizzle@gmail.com>",
"Aura Román <kyradiscord@gmail.com>",
"DD <didinele.dev@gmail.com>"
],
"license": "Apache-2.0",
"keywords": [
"discord",
"api",
"gateway",
"discordapp",
"discordjs"
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/ws"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/collection": "^1.5.1",
"@discordjs/rest": "^1.7.1",
"@discordjs/util": "^0.3.1",
"@sapphire/async-queue": "^1.5.0",
"@types/ws": "^8.5.4",
"@vladfrangu/async_event_emitter": "^2.2.1",
"discord-api-types": "^0.37.41",
"tslib": "^2.5.0",
"ws": "^8.13.0"
},
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.8",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.31.0",
"cross-env": "^7.0.3",
"esbuild-plugin-version-injector": "^1.1.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.46",
"eslint-formatter-pretty": "^5.0.0",
"mock-socket": "^9.2.1",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"turbo": "^1.9.4-canary.9",
"typescript": "^5.0.4",
"undici": "^5.22.0",
"vitest": "^0.31.0",
"zlib-sync": "^0.1.8"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

148
node_modules/@sapphire/async-queue/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,148 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@sapphire/async-queue@1.5.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.4.0...@sapphire/async-queue@1.5.0) - (2022-08-16)
## 🐛 Bug Fixes
- **deps:** Update all non-major dependencies ([2308bd7](https://github.com/sapphiredev/utilities/commit/2308bd74356b6b2e0c12995b25f4d8ade4803fe9))
## 🚀 Features
- Add `AsyncQueue#abortAll` (#429) ([b351e70](https://github.com/sapphiredev/utilities/commit/b351e70ebef329009daaebba89729ee84bb5704c))
# [@sapphire/async-queue@1.4.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.3.1...@sapphire/async-queue@1.4.0) - (2022-08-07)
## 🐛 Bug Fixes
- **deps:** Update all non-major dependencies ([84af0db](https://github.com/sapphiredev/utilities/commit/84af0db2db749223b036aa99fe19a2e9af5681c6))
- **deps:** Update all non-major dependencies ([50cd8de](https://github.com/sapphiredev/utilities/commit/50cd8dea593b6f5ae75571209456b3421e2ca59a))
## 📝 Documentation
- Add @muchnameless as a contributor ([a1221fe](https://github.com/sapphiredev/utilities/commit/a1221fea68506e99591d5d00ec552a07c26833f9))
- Add @enxg as a contributor ([d2382f0](https://github.com/sapphiredev/utilities/commit/d2382f04e3909cb4ad11798a0a10e683f6cf5383))
- Add @EvolutionX-10 as a contributor ([efc3a32](https://github.com/sapphiredev/utilities/commit/efc3a320a72ae258996dd62866d206c33f8d4961))
- Add @MajesticString as a contributor ([295b3e9](https://github.com/sapphiredev/utilities/commit/295b3e9849a4b0fe64074bae02f6426378a303c3))
- Add @Mzato0001 as a contributor ([c790ef2](https://github.com/sapphiredev/utilities/commit/c790ef25df2d7e22888fa9f8169167aa555e9e19))
- Add @NotKaskus as a contributor ([00da8f1](https://github.com/sapphiredev/utilities/commit/00da8f199137b9277119823f322d1f2d168d928a))
- Add @imranbarbhuiya as a contributor ([fb674c2](https://github.com/sapphiredev/utilities/commit/fb674c2c5594d41e71662263553dcb4bac9e37f4))
- Add @axisiscool as a contributor ([ce1aa31](https://github.com/sapphiredev/utilities/commit/ce1aa316871a88d3663efbdf2a42d3d8dfe6a27f))
- Add @dhruv-kaushikk as a contributor ([ebbf43f](https://github.com/sapphiredev/utilities/commit/ebbf43f63617daba96e72c50a234bf8b64f6ddc4))
- Add @Commandtechno as a contributor ([f1d69fa](https://github.com/sapphiredev/utilities/commit/f1d69fabe1ee0abe4be08b19e63dbec03102f7ce))
- Fix typedoc causing OOM crashes ([63ba41c](https://github.com/sapphiredev/utilities/commit/63ba41c4b6678554b1c7043a22d3296db4f59360))
## 🚀 Features
- **AsyncQueue:** Add AbortSignal support (#417) ([c0629e7](https://github.com/sapphiredev/utilities/commit/c0629e781ebc3f48e496a0851191b32e91f62fe9))
## 🧪 Testing
- Migrate to vitest (#380) ([075ec73](https://github.com/sapphiredev/utilities/commit/075ec73c7a8e3374fad3ada612d37eb4ac36ec8d))
## [1.3.1](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.3.0...@sapphire/async-queue@1.3.1) (2022-04-01)
**Note:** Version bump only for package @sapphire/async-queue
# [1.3.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.2.0...@sapphire/async-queue@1.3.0) (2022-03-06)
### Features
- allow module: NodeNext ([#306](https://github.com/sapphiredev/utilities/issues/306)) ([9dc6dd6](https://github.com/sapphiredev/utilities/commit/9dc6dd619efab879bb2b0b3c9e64304e10a67ed6))
- **ts-config:** add multi-config structure ([#281](https://github.com/sapphiredev/utilities/issues/281)) ([b5191d7](https://github.com/sapphiredev/utilities/commit/b5191d7f2416dc5838590c4ff221454925553e37))
# [1.2.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.9...@sapphire/async-queue@1.2.0) (2022-01-28)
### Features
- change build system to tsup ([#270](https://github.com/sapphiredev/utilities/issues/270)) ([365a53a](https://github.com/sapphiredev/utilities/commit/365a53a5517a01a0926cf28a83c96b63f32ed9f8))
## [1.1.9](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.8...@sapphire/async-queue@1.1.9) (2021-11-06)
**Note:** Version bump only for package @sapphire/async-queue
## [1.1.8](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.7...@sapphire/async-queue@1.1.8) (2021-10-26)
**Note:** Version bump only for package @sapphire/async-queue
## [1.1.7](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.6...@sapphire/async-queue@1.1.7) (2021-10-17)
### Bug Fixes
- allow more node & npm versions in engines field ([5977d2a](https://github.com/sapphiredev/utilities/commit/5977d2a30a4b2cfdf84aff3f33af03ffde1bbec5))
## [1.1.6](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.5...@sapphire/async-queue@1.1.6) (2021-10-11)
**Note:** Version bump only for package @sapphire/async-queue
## [1.1.5](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.4...@sapphire/async-queue@1.1.5) (2021-10-04)
**Note:** Version bump only for package @sapphire/async-queue
## [1.1.4](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.3...@sapphire/async-queue@1.1.4) (2021-06-27)
**Note:** Version bump only for package @sapphire/async-queue
## [1.1.3](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.2...@sapphire/async-queue@1.1.3) (2021-06-06)
### Bug Fixes
- remove peer deps, update dev deps, update READMEs ([#124](https://github.com/sapphiredev/utilities/issues/124)) ([67256ed](https://github.com/sapphiredev/utilities/commit/67256ed43b915b02a8b5c68230ba82d6210c5032))
## [1.1.2](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.1...@sapphire/async-queue@1.1.2) (2021-05-20)
### Bug Fixes
- **async-queue:** mark package as side effect free ([1c4b901](https://github.com/sapphiredev/utilities/commit/1c4b901cda3d14bd085c35cc74e160f844567ba7))
## [1.1.1](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.0...@sapphire/async-queue@1.1.1) (2021-05-02)
### Bug Fixes
- drop the `www.` from the SapphireJS URL ([494d89f](https://github.com/sapphiredev/utilities/commit/494d89ffa04f78c195b93d7905b3232884f7d7e2))
- update all the SapphireJS URLs from `.com` to `.dev` ([f59b46d](https://github.com/sapphiredev/utilities/commit/f59b46d1a0ebd39cad17b17d71cd3b9da808d5fd))
# [1.1.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.7...@sapphire/async-queue@1.1.0) (2021-04-21)
### Features
- add @sapphire/embed-jsx ([#100](https://github.com/sapphiredev/utilities/issues/100)) ([7277a23](https://github.com/sapphiredev/utilities/commit/7277a236015236ed8e81b7882875410facc4ce17))
## [1.0.7](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.6...@sapphire/async-queue@1.0.7) (2021-04-19)
### Bug Fixes
- change all Sapphire URLs from "project"->"community" & use our domain where applicable 👨‍🌾🚜 ([#102](https://github.com/sapphiredev/utilities/issues/102)) ([835b408](https://github.com/sapphiredev/utilities/commit/835b408e8e57130c3787aca2e32613346ff23e4d))
## [1.0.6](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.5...@sapphire/async-queue@1.0.6) (2021-04-03)
**Note:** Version bump only for package @sapphire/async-queue
## [1.0.5](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.4...@sapphire/async-queue@1.0.5) (2021-03-16)
### Bug Fixes
- remove terser from all packages ([#79](https://github.com/sapphiredev/utilities/issues/79)) ([1cfe4e7](https://github.com/sapphiredev/utilities/commit/1cfe4e7c804e62c142495686d2b83b81d0026c02))
## [1.0.4](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.3...@sapphire/async-queue@1.0.4) (2021-02-16)
**Note:** Version bump only for package @sapphire/async-queue
## [1.0.3](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.2...@sapphire/async-queue@1.0.3) (2021-02-13)
**Note:** Version bump only for package @sapphire/async-queue
## [1.0.2](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.1...@sapphire/async-queue@1.0.2) (2021-01-25)
**Note:** Version bump only for package @sapphire/async-queue
## [1.0.1](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.0...@sapphire/async-queue@1.0.1) (2021-01-16)
**Note:** Version bump only for package @sapphire/async-queue
# 1.0.0 (2021-01-13)
### Features
- **async-queue:** add async-queue package ([#56](https://github.com/sapphiredev/utilities/issues/56)) ([ba81832](https://github.com/sapphiredev/utilities/commit/ba8183287dbbc3f3d7d79af6d5a2d3dd8d62f63e))

116
node_modules/@sapphire/async-queue/README.md generated vendored Normal file
View file

@ -0,0 +1,116 @@
<div align="center">
![Sapphire Logo](https://cdn.skyra.pw/gh-assets/sapphire-banner.png)
# @sapphire/async-queue
**Sequential asynchronous lock-based queue for promises.**
[![GitHub](https://img.shields.io/github/license/sapphiredev/utilities)](https://github.com/sapphiredev/utilities/blob/main/LICENSE.md)
[![codecov](https://codecov.io/gh/sapphiredev/utilities/branch/main/graph/badge.svg?token=OEGIV6RFDO)](https://codecov.io/gh/sapphiredev/utilities)
[![npm bundle size](https://img.shields.io/bundlephobia/min/@sapphire/async-queue?logo=webpack&style=flat-square)](https://bundlephobia.com/result?p=@sapphire/async-queue)
[![npm](https://img.shields.io/npm/v/@sapphire/async-queue?color=crimson&logo=npm&style=flat-square)](https://www.npmjs.com/package/@sapphire/async-queue)
</div>
## Description
Ever needed a queue for a set of promises? This is the package for you.
## Features
- Written in TypeScript
- Bundled with esbuild so it can be used in NodeJS and browsers
- Offers CommonJS, ESM and UMD bundles
- Fully tested
## Installation
You can use the following command to install this package, or replace `npm install` with your package manager of choice.
```sh
npm install @sapphire/async-queue
```
---
## Buy us some doughnuts
Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are amazing people who may still want to donate just to show their appreciation. Thank you very much in advance!
We accept donations through Open Collective, Ko-fi, PayPal, Patreon and GitHub Sponsorships. You can use the buttons below to donate through your method of choice.
| Donate With | Address |
| :-------------: | :-------------------------------------------------: |
| Open Collective | [Click Here](https://sapphirejs.dev/opencollective) |
| Ko-fi | [Click Here](https://sapphirejs.dev/kofi) |
| Patreon | [Click Here](https://sapphirejs.dev/patreon) |
| PayPal | [Click Here](https://sapphirejs.dev/paypal) |
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://favware.tech/"><img src="https://avatars3.githubusercontent.com/u/4019718?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jeroen Claassens</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Code">💻</a> <a href="#infra-favna" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#projectManagement-favna" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Documentation">📖</a> <a href="https://github.com/sapphiredev/utilities/commits?author=favna" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/kyranet"><img src="https://avatars0.githubusercontent.com/u/24852502?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Antonio Román</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=kyranet" title="Code">💻</a> <a href="#projectManagement-kyranet" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3Akyranet" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/sapphiredev/utilities/commits?author=kyranet" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/PyroTechniac"><img src="https://avatars2.githubusercontent.com/u/39341355?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Gryffon Bellish</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=PyroTechniac" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3APyroTechniac" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/sapphiredev/utilities/commits?author=PyroTechniac" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/vladfrangu"><img src="https://avatars3.githubusercontent.com/u/17960496?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vlad Frangu</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=vladfrangu" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3Avladfrangu" title="Bug reports">🐛</a> <a href="https://github.com/sapphiredev/utilities/pulls?q=is%3Apr+reviewed-by%3Avladfrangu" title="Reviewed Pull Requests">👀</a> <a href="#userTesting-vladfrangu" title="User Testing">📓</a> <a href="https://github.com/sapphiredev/utilities/commits?author=vladfrangu" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/Stitch07"><img src="https://avatars0.githubusercontent.com/u/29275227?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stitch07</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Stitch07" title="Code">💻</a> <a href="#projectManagement-Stitch07" title="Project Management">📆</a> <a href="https://github.com/sapphiredev/utilities/commits?author=Stitch07" title="Tests">⚠️</a></td>
<td align="center"><a href="https://github.com/apps/depfu"><img src="https://avatars3.githubusercontent.com/in/715?v=4?s=100" width="100px;" alt=""/><br /><sub><b>depfu[bot]</b></sub></a><br /><a href="#maintenance-depfu[bot]" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://github.com/apps/allcontributors"><img src="https://avatars0.githubusercontent.com/in/23186?v=4?s=100" width="100px;" alt=""/><br /><sub><b>allcontributors[bot]</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=allcontributors[bot]" title="Documentation">📖</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/Nytelife26"><img src="https://avatars1.githubusercontent.com/u/22531310?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tyler J Russell</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Nytelife26" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/Alcremie"><img src="https://avatars0.githubusercontent.com/u/54785334?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ivan Lieder</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Alcremie" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3AAlcremie" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/RealShadowNova"><img src="https://avatars3.githubusercontent.com/u/46537907?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hezekiah Hendry</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=RealShadowNova" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/Vetlix"><img src="https://avatars.githubusercontent.com/u/31412314?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Vetlix</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Vetlix" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/ethamitc"><img src="https://avatars.githubusercontent.com/u/27776796?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ethan Mitchell</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=ethamitc" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/noftaly"><img src="https://avatars.githubusercontent.com/u/34779161?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Elliot</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=noftaly" title="Code">💻</a></td>
<td align="center"><a href="https://jurien.dev"><img src="https://avatars.githubusercontent.com/u/5418114?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jurien Hamaker</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=jurienhamaker" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://fanoulis.dev/"><img src="https://avatars.githubusercontent.com/u/38255093?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Charalampos Fanoulis</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=cfanoulis" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/apps/dependabot"><img src="https://avatars.githubusercontent.com/in/29110?v=4?s=100" width="100px;" alt=""/><br /><sub><b>dependabot[bot]</b></sub></a><br /><a href="#maintenance-dependabot[bot]" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://kaname.netlify.app/"><img src="https://avatars.githubusercontent.com/u/56084970?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kaname</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=kaname-png" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/nandhagk"><img src="https://avatars.githubusercontent.com/u/62976649?v=4?s=100" width="100px;" alt=""/><br /><sub><b>nandhagk</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/issues?q=author%3Anandhagk" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://megatank58.me/"><img src="https://avatars.githubusercontent.com/u/51410502?v=4?s=100" width="100px;" alt=""/><br /><sub><b>megatank58</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=megatank58" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/UndiedGamer"><img src="https://avatars.githubusercontent.com/u/84702365?v=4?s=100" width="100px;" alt=""/><br /><sub><b>UndiedGamer</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=UndiedGamer" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/Lioness100"><img src="https://avatars.githubusercontent.com/u/65814829?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Lioness100</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Lioness100" title="Documentation">📖</a> <a href="https://github.com/sapphiredev/utilities/commits?author=Lioness100" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://gitlab.com/DavidPH/"><img src="https://avatars.githubusercontent.com/u/44669930?v=4?s=100" width="100px;" alt=""/><br /><sub><b>David</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=DavidPHH" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/apps/renovate"><img src="https://avatars.githubusercontent.com/in/2740?v=4?s=100" width="100px;" alt=""/><br /><sub><b>renovate[bot]</b></sub></a><br /><a href="#maintenance-renovate[bot]" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://renovate.whitesourcesoftware.com/"><img src="https://avatars.githubusercontent.com/u/25180681?v=4?s=100" width="100px;" alt=""/><br /><sub><b>WhiteSource Renovate</b></sub></a><br /><a href="#maintenance-renovate-bot" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://fc5570.me/"><img src="https://avatars.githubusercontent.com/u/68158483?v=4?s=100" width="100px;" alt=""/><br /><sub><b>FC</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=FC5570" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/Tokipudi"><img src="https://avatars.githubusercontent.com/u/29551076?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jérémy de Saint Denis</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Tokipudi" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/ItsMrCube"><img src="https://avatars.githubusercontent.com/u/25201357?v=4?s=100" width="100px;" alt=""/><br /><sub><b>MrCube</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=ItsMrCube" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/bitomic"><img src="https://avatars.githubusercontent.com/u/35199700?v=4?s=100" width="100px;" alt=""/><br /><sub><b>bitomic</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=bitomic" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://c43721.dev/"><img src="https://avatars.githubusercontent.com/u/55610086?v=4?s=100" width="100px;" alt=""/><br /><sub><b>c43721</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=c43721" title="Code">💻</a></td>
<td align="center"><a href="https://commandtechno.com/"><img src="https://avatars.githubusercontent.com/u/68407783?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Commandtechno</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Commandtechno" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/dhruv-kaushikk"><img src="https://avatars.githubusercontent.com/u/73697546?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aura</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=dhruv-kaushikk" title="Code">💻</a></td>
<td align="center"><a href="https://axis.moe/"><img src="https://avatars.githubusercontent.com/u/54381371?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jonathan</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=axisiscool" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/imranbarbhuiya"><img src="https://avatars.githubusercontent.com/u/74945038?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Parbez</b></sub></a><br /><a href="#maintenance-imranbarbhuiya" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://github.com/NotKaskus"><img src="https://avatars.githubusercontent.com/u/75168528?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Paul Andrew</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=NotKaskus" title="Documentation">📖</a></td>
<td align="center"><a href="https://linktr.ee/mzato0001"><img src="https://avatars.githubusercontent.com/u/62367547?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mzato</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=Mzato0001" title="Code">💻</a> <a href="https://github.com/sapphiredev/utilities/issues?q=author%3AMzato0001" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/MajesticString"><img src="https://avatars.githubusercontent.com/u/66224939?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Harry Allen</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=MajesticString" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/EvolutionX-10"><img src="https://avatars.githubusercontent.com/u/85353424?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Evo</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=EvolutionX-10" title="Code">💻</a></td>
<td align="center"><a href="https://enes.ovh/"><img src="https://avatars.githubusercontent.com/u/61084101?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Enes Genç</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=enxg" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/muchnameless"><img src="https://avatars.githubusercontent.com/u/12682826?v=4?s=100" width="100px;" alt=""/><br /><sub><b>muchnameless</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=muchnameless" title="Code">💻</a></td>
</tr>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

55
node_modules/@sapphire/async-queue/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,55 @@
/**
* The AsyncQueue class used to sequentialize burst requests
*/
declare class AsyncQueue {
/**
* The amount of entries in the queue, including the head.
* @seealso {@link queued} for the queued count.
*/
get remaining(): number;
/**
* The amount of queued entries.
* @seealso {@link remaining} for the count with the head.
*/
get queued(): number;
/**
* The promises array
*/
private promises;
/**
* Waits for last promise and queues a new one
* @example
* ```typescript
* const queue = new AsyncQueue();
* async function request(url, options) {
* await queue.wait({ signal: options.signal });
* try {
* const result = await fetch(url, options);
* // Do some operations with 'result'
* } finally {
* // Remove first entry from the queue and resolve for the next entry
* queue.shift();
* }
* }
*
* request(someUrl1, someOptions1); // Will call fetch() immediately
* request(someUrl2, someOptions2); // Will call fetch() after the first finished
* request(someUrl3, someOptions3); // Will call fetch() after the second finished
* ```
*/
wait(options?: Readonly<AsyncQueueWaitOptions>): Promise<void>;
/**
* Unlocks the head lock and transfers the next lock (if any) to the head.
*/
shift(): void;
/**
* Aborts all the pending promises.
* @note To avoid race conditions, this does **not** unlock the head lock.
*/
abortAll(): void;
}
interface AsyncQueueWaitOptions {
signal?: AbortSignal | undefined | null;
}
export { AsyncQueue, AsyncQueueWaitOptions };

125
node_modules/@sapphire/async-queue/dist/index.global.js generated vendored Normal file
View file

@ -0,0 +1,125 @@
"use strict";
var SapphireAsyncQueue = (() => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/index.ts
var src_exports = {};
__export(src_exports, {
AsyncQueue: () => AsyncQueue
});
// src/lib/AsyncQueueEntry.ts
var AsyncQueueEntry = class {
constructor(queue) {
__publicField(this, "promise");
__publicField(this, "resolve");
__publicField(this, "reject");
__publicField(this, "queue");
__publicField(this, "signal", null);
__publicField(this, "signalListener", null);
this.queue = queue;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
setSignal(signal) {
if (signal.aborted)
return this;
this.signal = signal;
this.signalListener = () => {
const index = this.queue["promises"].indexOf(this);
if (index !== -1)
this.queue["promises"].splice(index, 1);
this.reject(new Error("Request aborted manually"));
};
this.signal.addEventListener("abort", this.signalListener);
return this;
}
use() {
this.dispose();
this.resolve();
return this;
}
abort() {
this.dispose();
this.reject(new Error("Request aborted manually"));
return this;
}
dispose() {
if (this.signal) {
this.signal.removeEventListener("abort", this.signalListener);
this.signal = null;
this.signalListener = null;
}
}
};
__name(AsyncQueueEntry, "AsyncQueueEntry");
// src/lib/AsyncQueue.ts
var AsyncQueue = class {
constructor() {
__publicField(this, "promises", []);
}
get remaining() {
return this.promises.length;
}
get queued() {
return this.remaining === 0 ? 0 : this.remaining - 1;
}
wait(options) {
const entry = new AsyncQueueEntry(this);
if (this.promises.length === 0) {
this.promises.push(entry);
return Promise.resolve();
}
this.promises.push(entry);
if (options?.signal)
entry.setSignal(options.signal);
return entry.promise;
}
shift() {
if (this.promises.length === 0)
return;
if (this.promises.length === 1) {
this.promises.shift();
return;
}
this.promises.shift();
this.promises[0].use();
}
abortAll() {
if (this.queued === 0)
return;
for (let i = 1; i < this.promises.length; ++i) {
this.promises[i].abort();
}
this.promises.length = 1;
}
};
__name(AsyncQueue, "AsyncQueue");
return __toCommonJS(src_exports);
})();
//# sourceMappingURL=index.global.js.map

File diff suppressed because one or more lines are too long

128
node_modules/@sapphire/async-queue/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,128 @@
"use strict";
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/index.ts
var src_exports = {};
__export(src_exports, {
AsyncQueue: () => AsyncQueue
});
module.exports = __toCommonJS(src_exports);
// src/lib/AsyncQueueEntry.ts
var AsyncQueueEntry = class {
constructor(queue) {
__publicField(this, "promise");
__publicField(this, "resolve");
__publicField(this, "reject");
__publicField(this, "queue");
__publicField(this, "signal", null);
__publicField(this, "signalListener", null);
this.queue = queue;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
setSignal(signal) {
if (signal.aborted)
return this;
this.signal = signal;
this.signalListener = () => {
const index = this.queue["promises"].indexOf(this);
if (index !== -1)
this.queue["promises"].splice(index, 1);
this.reject(new Error("Request aborted manually"));
};
this.signal.addEventListener("abort", this.signalListener);
return this;
}
use() {
this.dispose();
this.resolve();
return this;
}
abort() {
this.dispose();
this.reject(new Error("Request aborted manually"));
return this;
}
dispose() {
if (this.signal) {
this.signal.removeEventListener("abort", this.signalListener);
this.signal = null;
this.signalListener = null;
}
}
};
__name(AsyncQueueEntry, "AsyncQueueEntry");
// src/lib/AsyncQueue.ts
var AsyncQueue = class {
constructor() {
__publicField(this, "promises", []);
}
get remaining() {
return this.promises.length;
}
get queued() {
return this.remaining === 0 ? 0 : this.remaining - 1;
}
wait(options) {
const entry = new AsyncQueueEntry(this);
if (this.promises.length === 0) {
this.promises.push(entry);
return Promise.resolve();
}
this.promises.push(entry);
if (options?.signal)
entry.setSignal(options.signal);
return entry.promise;
}
shift() {
if (this.promises.length === 0)
return;
if (this.promises.length === 1) {
this.promises.shift();
return;
}
this.promises.shift();
this.promises[0].use();
}
abortAll() {
if (this.queued === 0)
return;
for (let i = 1; i < this.promises.length; ++i) {
this.promises[i].abort();
}
this.promises.length = 1;
}
};
__name(AsyncQueue, "AsyncQueue");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AsyncQueue
});
//# sourceMappingURL=index.js.map

1
node_modules/@sapphire/async-queue/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

102
node_modules/@sapphire/async-queue/dist/index.mjs generated vendored Normal file
View file

@ -0,0 +1,102 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/lib/AsyncQueueEntry.ts
var AsyncQueueEntry = class {
constructor(queue) {
__publicField(this, "promise");
__publicField(this, "resolve");
__publicField(this, "reject");
__publicField(this, "queue");
__publicField(this, "signal", null);
__publicField(this, "signalListener", null);
this.queue = queue;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
setSignal(signal) {
if (signal.aborted)
return this;
this.signal = signal;
this.signalListener = () => {
const index = this.queue["promises"].indexOf(this);
if (index !== -1)
this.queue["promises"].splice(index, 1);
this.reject(new Error("Request aborted manually"));
};
this.signal.addEventListener("abort", this.signalListener);
return this;
}
use() {
this.dispose();
this.resolve();
return this;
}
abort() {
this.dispose();
this.reject(new Error("Request aborted manually"));
return this;
}
dispose() {
if (this.signal) {
this.signal.removeEventListener("abort", this.signalListener);
this.signal = null;
this.signalListener = null;
}
}
};
__name(AsyncQueueEntry, "AsyncQueueEntry");
// src/lib/AsyncQueue.ts
var AsyncQueue = class {
constructor() {
__publicField(this, "promises", []);
}
get remaining() {
return this.promises.length;
}
get queued() {
return this.remaining === 0 ? 0 : this.remaining - 1;
}
wait(options) {
const entry = new AsyncQueueEntry(this);
if (this.promises.length === 0) {
this.promises.push(entry);
return Promise.resolve();
}
this.promises.push(entry);
if (options?.signal)
entry.setSignal(options.signal);
return entry.promise;
}
shift() {
if (this.promises.length === 0)
return;
if (this.promises.length === 1) {
this.promises.shift();
return;
}
this.promises.shift();
this.promises[0].use();
}
abortAll() {
if (this.queued === 0)
return;
for (let i = 1; i < this.promises.length; ++i) {
this.promises[i].abort();
}
this.promises.length = 1;
}
};
__name(AsyncQueue, "AsyncQueue");
export {
AsyncQueue
};
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

65
node_modules/@sapphire/async-queue/package.json generated vendored Normal file
View file

@ -0,0 +1,65 @@
{
"name": "@sapphire/async-queue",
"version": "1.5.0",
"description": "Sequential asynchronous lock-based queue for promises",
"author": "@sapphire",
"license": "MIT",
"main": "dist/index.js",
"module": "dist/index.mjs",
"browser": "dist/index.global.js",
"unpkg": "dist/index.global.js",
"types": "dist/index.d.ts",
"exports": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"sideEffects": false,
"homepage": "https://github.com/sapphiredev/utilities/tree/main/packages/async-queue",
"scripts": {
"test": "vitest run",
"lint": "eslint src tests --ext ts --fix -c ../../.eslintrc",
"build": "tsup",
"prepack": "yarn build",
"bump": "cliff-jumper",
"check-update": "cliff-jumper --dry-run"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sapphiredev/utilities.git",
"directory": "packages/async-queue"
},
"files": [
"dist/**/*.js*",
"dist/**/*.mjs*",
"dist/**/*.d*"
],
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
},
"keywords": [
"@sapphire/async-queue",
"bot",
"typescript",
"ts",
"yarn",
"discord",
"sapphire",
"standalone"
],
"bugs": {
"url": "https://github.com/sapphiredev/utilities/issues"
},
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@favware/cliff-jumper": "^1.8.6",
"@vitest/coverage-c8": "^0.22.0",
"c8": "^7.12.0",
"tsup": "^6.2.2",
"typescript": "^4.7.4",
"vitest": "^0.22.0"
}
}

292
node_modules/@sapphire/shapeshift/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,292 @@
# Changelog
All notable changes to this project will be documented in this file.
# [3.9.2](https://github.com/sapphiredev/shapeshift/compare/v3.9.1...v3.9.2) - (2023-06-04)
## 🐛 Bug Fixes
- **arrayvalidator:** Fixed runaway type instantiation with TypeScript >=5.1 (#275) ([f59d901](https://github.com/sapphiredev/shapeshift/commit/f59d90112181e6625230c28e6a4f0f065ced6344))
# [3.9.1](https://github.com/sapphiredev/shapeshift/compare/v3.9.0...v3.9.1) - (2023-06-02)
## 🐛 Bug Fixes
- **types:** Move the `types` condition to the front (#273) ([5a3e202](https://github.com/sapphiredev/shapeshift/commit/5a3e202e9ceafb3d330a568e93c060dd5aac1dde))
# [3.9.0](https://github.com/sapphiredev/shapeshift/compare/v3.8.2...v3.9.0) - (2023-05-09)
## 🐛 Bug Fixes
- Resolve minor grammar mistake (#260) ([62df609](https://github.com/sapphiredev/shapeshift/commit/62df6094845ffa118aa93ea3c5f47f81f1c5d99f))
## 🚀 Features
- Add BaseValidator.describe (#267) ([d9e1a2d](https://github.com/sapphiredev/shapeshift/commit/d9e1a2d2f3c5e6378f0025becf8497138ee6d97c))
# [3.8.2](https://github.com/sapphiredev/shapeshift/compare/v3.8.1...v3.8.2) - (2023-04-02)
## 🐛 Bug Fixes
- ***:** TypeScript 5.x compatibility (#253) ([eba2a88](https://github.com/sapphiredev/shapeshift/commit/eba2a88b91fb6631f431313753299ec7a70cf6ce))
- Remove `node:` prefix (#249) ([af766b5](https://github.com/sapphiredev/shapeshift/commit/af766b504c1013f3cd24f7bf803ac9ff7442a8d7))
# [3.8.1](https://github.com/sapphiredev/shapeshift/compare/v3.8.0...v3.8.1) - (2022-12-15)
## 🐛 Bug Fixes
- Fixed lodash esm import (#230) ([63def7b](https://github.com/sapphiredev/shapeshift/commit/63def7bcec6319b3792093945ba7ba9f871ced6f))
# [3.8.0](https://github.com/sapphiredev/shapeshift/compare/v3.7.1...v3.8.0) - (2022-12-11)
## 🏠 Refactor
- Remove `NonNullObject` (#227) ([04d3934](https://github.com/sapphiredev/shapeshift/commit/04d39343f55a4e1571f54870a84d8b95447bd682))
## 🚀 Features
- Add `when` constraint (#223) ([8eade90](https://github.com/sapphiredev/shapeshift/commit/8eade90cd4c02b80746ecdcdc612829d7f765178))
# [3.7.1](https://github.com/sapphiredev/shapeshift/compare/v3.7.0...v3.7.1) - (2022-11-27)
## 🐛 Bug Fixes
- Fixed "jump to definition" for `undefinedToOptional` going to wrong symbol (#226) ([6aab6d0](https://github.com/sapphiredev/shapeshift/commit/6aab6d01450fd7abbeaa95e91fb58568240e02ff))
## 📝 Documentation
- Add @legendhimslef as a contributor ([499522a](https://github.com/sapphiredev/shapeshift/commit/499522a782c3ecd4df80978d0811df1a75d08212))
# [3.7.0](https://github.com/sapphiredev/shapeshift/compare/v3.6.0...v3.7.0) - (2022-10-02)
## 📝 Documentation
- Add phone in readme (#203) ([4ec9b7a](https://github.com/sapphiredev/shapeshift/commit/4ec9b7ab85124d84b3404cb548b17b9221a716c5))
- Add RealShadowNova as a contributor for tool (#185) ([6dfc442](https://github.com/sapphiredev/shapeshift/commit/6dfc442af6ef26d6bbca39078eca5727257b6dab))
## 🚀 Features
- Add `s.string.phone` (#202) ([7d122d5](https://github.com/sapphiredev/shapeshift/commit/7d122d5dc0eaa63c639b9cde1514e63566a681bd))
# [3.6.0](https://github.com/sapphiredev/shapeshift/compare/v3.5.1...v3.6.0) - (2022-08-29)
## 🐛 Bug Fixes
- Typescript 4.8 compatibility (#179) ([2281535](https://github.com/sapphiredev/shapeshift/commit/2281535f7589a987510828e46bf66accc8393c34))
## 🚀 Features
- Add `Validator#is` (#183) ([5114f95](https://github.com/sapphiredev/shapeshift/commit/5114f9516e5406cd1ca4a7ceb5ea5761158af1c6))
# [3.5.1](https://github.com/sapphiredev/shapeshift/compare/v3.5.0...v3.5.1) - (2022-07-17)
## 🐛 Bug Fixes
- Fast deep equal import (#155) ([5ce8ff6](https://github.com/sapphiredev/shapeshift/commit/5ce8ff6803b70624af07c3e406bc1cdc9e3cdafe))
# [3.5.0](https://github.com/sapphiredev/shapeshift/compare/v3.4.1...v3.5.0) - (2022-07-10)
## 🏠 Refactor
- Port net module (#149) ([5f26e32](https://github.com/sapphiredev/shapeshift/commit/5f26e32b0f87d2b100ca13471d5835c0067ddee8))
## 🐛 Bug Fixes
- Ensure browser compatibility (#150) ([92d05d8](https://github.com/sapphiredev/shapeshift/commit/92d05d83c1fbab53f98f61219fb01d49fc031bae))
- Fixed `s.array` type inference (#153) ([a5948dc](https://github.com/sapphiredev/shapeshift/commit/a5948dc67ce6a0ea73986d32084898a4ce0b9c3a))
- Fixed `shape#array` types (#146) ([43016a0](https://github.com/sapphiredev/shapeshift/commit/43016a025b04a676d906758ed065d26a17231888))
## 🚀 Features
- Lazy validator (#147) ([807666e](https://github.com/sapphiredev/shapeshift/commit/807666ef537c84d2e0f8bd9f4ce1a8060bfb3fb5))
- Reshape finally (#148) ([d3751f6](https://github.com/sapphiredev/shapeshift/commit/d3751f6d3d99f415d797369f98158f932371e02c))
- **arrays:** Add unique (#141) ([ad7af34](https://github.com/sapphiredev/shapeshift/commit/ad7af34eb811541253150b7ff0b58a6bd7200796))
# [3.4.1](https://github.com/sapphiredev/shapeshift/compare/v3.4.0...v3.4.1) - (2022-07-03)
## 🏠 Refactor
- Move all type utilities to one file (#139) ([61cab3d](https://github.com/sapphiredev/shapeshift/commit/61cab3d0e486d9dc74c8f6160ff8c75c91b595b2))
## 🐛 Bug Fixes
- Return array-validator from length* methods (#140) ([75b1f9a](https://github.com/sapphiredev/shapeshift/commit/75b1f9a6efffb6c27dcfd48eb4ec6269a3614633))
## 🧪 Testing
- Typechecking for tests (#145) ([273cdc8](https://github.com/sapphiredev/shapeshift/commit/273cdc82c1cf65ba4111ca6e70b050e02cbdf485))
# [3.4.0](https://github.com/sapphiredev/shapeshift/compare/v3.3.2...v3.4.0) - (2022-06-29)
## 🚀 Features
- Add `required` in object validation (#137) ([928f7be](https://github.com/sapphiredev/shapeshift/commit/928f7beb5e727b47868e9e46f2191f2def228080))
# [3.3.2](https://github.com/sapphiredev/shapeshift/compare/v3.3.1...v3.3.2) - (2022-06-26)
## 🐛 Bug Fixes
- Make keys optional in object parsing (#134) ([57a3719](https://github.com/sapphiredev/shapeshift/commit/57a37193d64399aae1431b041012d582e8defecf))
# [3.3.1](https://github.com/sapphiredev/shapeshift/compare/v3.3.0...v3.3.1) - (2022-06-22)
## 🐛 Bug Fixes
- Add generic type to parse (#133) ([90c91aa](https://github.com/sapphiredev/shapeshift/commit/90c91aad572d51a2bfbd1ed32a51e1d4201c5d4a))
# [3.3.0](https://github.com/sapphiredev/shapeshift/compare/v3.2.0...v3.3.0) - (2022-06-19)
## 🐛 Bug Fixes
- Compile for es2020 instead of es2021 (#128) ([051344d](https://github.com/sapphiredev/shapeshift/commit/051344debe1cf423713d7fc64b8908353348f301))
## 🚀 Features
- Allow passing functions in `setValidationEnabled` (#131) ([e1991cf](https://github.com/sapphiredev/shapeshift/commit/e1991cfef1ffe92f9167d11d7f2ded65379df8d2))
## 🧪 Testing
- Migrate to vitest (#126) ([4d80969](https://github.com/sapphiredev/shapeshift/commit/4d80969b714c39768499569456405a73c1444da8))
# [3.2.0](https://github.com/sapphiredev/shapeshift/compare/v3.1.0...v3.2.0) - (2022-06-11)
## 🚀 Features
- Add disabling of validators (#125) ([e17af95](https://github.com/sapphiredev/shapeshift/commit/e17af95d697be62796c57d03385b0c74b9d2d580))
# [3.1.0](https://github.com/sapphiredev/shapeshift/compare/v3.0.0...v3.1.0) - (2022-06-04)
## 🐛 Bug Fixes
- **ObjectValidator:** Fix #121 (#122) ([ecfad7e](https://github.com/sapphiredev/shapeshift/commit/ecfad7ec2cdd9e0cee0b3e227e55a91b28c29c30))
## 📝 Documentation
- **readme:** Clarify the difference between validations and schemas and add table of contents (#108) ([dc492a3](https://github.com/sapphiredev/shapeshift/commit/dc492a395349cc5bc680f313146127ea510b4ada))
## 🚀 Features
- **StringValidator:** Add date string checks (#106) ([1b72907](https://github.com/sapphiredev/shapeshift/commit/1b729078be32a88aeddf574c9cff3098990d4f94))
# [3.0.0](https://github.com/sapphiredev/shapeshift/compare/v2.2.0...v3.0.0) - (2022-05-06)
## 🏃 Performance
- Speed up object validation a LOT (#101) ([817278e](https://github.com/sapphiredev/shapeshift/commit/817278e6a3ac128ca342e5ae1737f40b98788c37))
## 🐛 Bug Fixes
- Expand method names (#100) ([741490f](https://github.com/sapphiredev/shapeshift/commit/741490fb6907f618fa25fe53808f7dcb5a59a96c))}
### 💥 Breaking Changes:
- `date.eq` has been renamed to `date.equal`
- `string.lengthLt` has been renamed to `string.lengthLessThan`
- `string.lengthLe` has been renamed to `string.lengthLessThanOrEqual`
- `string.lengthGt` has been renamed to `string.lengthGreaterThan`
- `string.lengthGe` has been renamed to `string.lengthGreaterThanOrEqual`
- `string.lengthEq` has been renamed to `string.lengthEqual`
- `string.lengthNe` has been renamed to `string.lengthNotEqual`
- `number.gt` has been renamed to `number.greaterThan`
- `number.ge` has been renamed to `number.greaterThanOrEqual`
- `number.lt` has been renamed to `number.lessThan`
- `number.le` has been renamed to `number.lessThanOrEqual`
- `number.eq` has been renamed to `number.equal`
- `number.ne` has been renamed to `number.notEqual`
- `bigint.gt` has been renamed to `bigint.greaterThan`
- `bigint.ge` has been renamed to `bigint.greaterThanOrEqual`
- `bigint.lt` has been renamed to `bigint.lessThan`
- `bigint.le` has been renamed to `bigint.lessThanOrEqual`
- `bigint.eq` has been renamed to `bigint.equal`
- `bigint.ne` has been renamed to `bigint.notEqual`
- `boolean.eq` has been renamed to `boolean.equal`
- `boolean.ne` has been renamed to `boolean.notEqual`
- `array.lengthLt` has been renamed to `array.lengthLessThan`
- `array.lengthLe` has been renamed to `array.lengthLessThanOrEqual`
- `array.lengthGt` has been renamed to `array.lengthGreaterThan`
- `array.lengthGe` has been renamed to `array.lengthGreaterThanOrEqual`
- `array.lengthEq` has been renamed to `array.lengthEqual`
- `array.lengthNe` has been renamed to `array.lengthNotEqual`
- `typedArray.lengthLt` has been renamed to `typedArray.lengthLessThan`
- `typedArray.lengthLe` has been renamed to `typedArray.lengthLessThanOrEqual`
- `typedArray.lengthGt` has been renamed to `typedArray.lengthGreaterThan`
- `typedArray.lengthGe` has been renamed to `typedArray.lengthGreaterThanOrEqual`
- `typedArray.lengthEq` has been renamed to `typedArray.lengthEqual`
- `typedArray.lengthNe` has been renamed to `typedArray.lengthNotEqual`
- `typedArray.byteLengthLt` has been renamed to `typedArray.byteLengthLessThan`
- `typedArray.byteLengthLe` has been renamed to `typedArray.byteLengthLessThanOrEqual`
- `typedArray.byteLengthGt` has been renamed to `typedArray.byteLengthGreaterThan`
- `typedArray.byteLengthGe` has been renamed to `typedArray.byteLengthGreaterThanOrEqual`
- `typedArray.byteLengthEq` has been renamed to `typedArray.byteLengthEqual`
- `typedArray.byteLengthNe` has been renamed to `typedArray.byteLengthNotEqual`
- **ObjectValidator:** Don't run validation on arrays (#99) ([c83b3d0](https://github.com/sapphiredev/shapeshift/commit/c83b3d03a201d38cc230d9c831ca1d9b66ca533b))
## 🚀 Features
- Add 2 utility types inspired by yup and co (#102) ([2fef902](https://github.com/sapphiredev/shapeshift/commit/2fef9026c30f2f1825aa55511d0ab088a3dd13ab))
# [2.2.0](https://github.com/sapphiredev/shapeshift/compare/v2.0.0...v2.2.0) - (2022-04-29)
## Bug Fixes
- Ensure `BaseError` is exported as value (#95) ([335d799](https://github.com/sapphiredev/shapeshift/commit/335d799ef7a8c1a19a12e3eeec07e6d210db113d))
## Documentation
- **readme:** Add todo notice for `reshape` and `function` validations (#75) ([d5f16f6](https://github.com/sapphiredev/shapeshift/commit/d5f16f615de83503187dc834c6245fafbf138f5e))
## Features
- Add Typed Array (#78) ([ca5ea5f](https://github.com/sapphiredev/shapeshift/commit/ca5ea5f568084bd5d3aa004911d4ea64329e1a89))
## Performance
- Optimize `NativeEnum` (#79) ([e9ae280](https://github.com/sapphiredev/shapeshift/commit/e9ae280f73e9ea08239bd8bd22165fe0b2178f82))
# [@sapphire/shapeshift@2.1.0](https://github.com/sapphiredev/shapeshift/compare/v2.0.0...@sapphire/shapeshift@2.1.0) - (2022-04-24)
## Documentation
- **readme:** Add todo notice for `reshape` and `function` validations (#75) ([d5f16f6](https://github.com/sapphiredev/shapeshift/commit/d5f16f615de83503187dc834c6245fafbf138f5e))
## Performance
- Optimize `NativeEnum` (#79) ([e9ae280](https://github.com/sapphiredev/shapeshift/commit/e9ae280f73e9ea08239bd8bd22165fe0b2178f82))
## [2.0.0](https://github.com/sapphiredev/shapeshift/compare/v1.0.0...v2.0.0) (2022-03-13)
### Features
- add `default` ([#25](https://github.com/sapphiredev/shapeshift/issues/25)) ([378c51f](https://github.com/sapphiredev/shapeshift/commit/378c51fb4ba2c501fd782387169db888d6bfe662))
- add bigint methods ([#32](https://github.com/sapphiredev/shapeshift/issues/32)) ([4c444c1](https://github.com/sapphiredev/shapeshift/commit/4c444c15657c4610b99481b6dec9812bd136d72b))
- add MapValidator ([#21](https://github.com/sapphiredev/shapeshift/issues/21)) ([c4d1258](https://github.com/sapphiredev/shapeshift/commit/c4d12586762d446b858454077b66635d9d11e2d6))
- add NativeEnum validator ([#54](https://github.com/sapphiredev/shapeshift/issues/54)) ([7359042](https://github.com/sapphiredev/shapeshift/commit/7359042843d1119f396ac2c038aaff89dbd90c8e))
- add RecordValidator ([#20](https://github.com/sapphiredev/shapeshift/issues/20)) ([8727427](https://github.com/sapphiredev/shapeshift/commit/8727427be4656792eebcdc5bddf6bcd61bc7e846))
- add remaining string validations ([#38](https://github.com/sapphiredev/shapeshift/issues/38)) ([1c2fd7b](https://github.com/sapphiredev/shapeshift/commit/1c2fd7bbb20463f09ac461b697c312bec6ae9195))
- add tuple ([#39](https://github.com/sapphiredev/shapeshift/issues/39)) ([b7704bf](https://github.com/sapphiredev/shapeshift/commit/b7704bf87cf5225021408cf4a6b9ceff8cba25b3))
- added number transformers ([#17](https://github.com/sapphiredev/shapeshift/issues/17)) ([89a8ddd](https://github.com/sapphiredev/shapeshift/commit/89a8ddd8583774e68c43260c28ee1589ef44516c))
- allow the use of module: NodeNext ([#55](https://github.com/sapphiredev/shapeshift/issues/55)) ([e6827c5](https://github.com/sapphiredev/shapeshift/commit/e6827c5a12b6a2803a137b71fe4c21bd1c35034b))
- **array:** add array length Comparators ([#40](https://github.com/sapphiredev/shapeshift/issues/40)) ([1e564c2](https://github.com/sapphiredev/shapeshift/commit/1e564c204b6c9b0a798b3121d31dd4cc99165f60))
- **Array:** generate tuple types with given length ([#52](https://github.com/sapphiredev/shapeshift/issues/52)) ([793648b](https://github.com/sapphiredev/shapeshift/commit/793648b4cde1f72c5b735ceebb0c48272179be06))
- **ArrayValidator:** add length ranges ([#53](https://github.com/sapphiredev/shapeshift/issues/53)) ([e431d62](https://github.com/sapphiredev/shapeshift/commit/e431d6218b86fc1480fce14c4466cb36567cad2f))
- display the property that errored ([#35](https://github.com/sapphiredev/shapeshift/issues/35)) ([fe188b0](https://github.com/sapphiredev/shapeshift/commit/fe188b0d17eeaa5f73b08085562903e23e91717c))
- improve how errors are returned ([#29](https://github.com/sapphiredev/shapeshift/issues/29)) ([8bc7669](https://github.com/sapphiredev/shapeshift/commit/8bc7669a1a66a10449b321cc4447e411383977d9))
- **s.object:** add passthrough ([#66](https://github.com/sapphiredev/shapeshift/issues/66)) ([ee9f6f3](https://github.com/sapphiredev/shapeshift/commit/ee9f6f367e513c0120a04cfafe05057c7907c327))
### Bug Fixes
- copy/paste error and `ge` ([#22](https://github.com/sapphiredev/shapeshift/issues/22)) ([fe6505f](https://github.com/sapphiredev/shapeshift/commit/fe6505f8e698bcaf9f8024b2d8f012559827cbb0))
- fix union type and add test ([#41](https://github.com/sapphiredev/shapeshift/issues/41)) ([fbcf8a9](https://github.com/sapphiredev/shapeshift/commit/fbcf8a9c617c16b33fdddb0a44aa0fe506164fd3))
- **s.union:** fix union overrides ([#62](https://github.com/sapphiredev/shapeshift/issues/62)) ([56e9b19](https://github.com/sapphiredev/shapeshift/commit/56e9b1947d9b2b129dbed374671114b2242e6d35))
## 1.0.0 (2022-01-16)
### Features
- added more primitives ([#2](https://github.com/sapphiredev/shapeshift/issues/2)) ([16af17b](https://github.com/sapphiredev/shapeshift/commit/16af17b5d9ee40dce284ee120e0b099f7b2cc0b8))
- added more things ([7c73d82](https://github.com/sapphiredev/shapeshift/commit/7c73d82cf3740d5b2d4eebcac7767da9d3562437))
- added ObjectValidator ([#3](https://github.com/sapphiredev/shapeshift/issues/3)) ([abe7ead](https://github.com/sapphiredev/shapeshift/commit/abe7eaddee981ef485713ff5e7b7f32ff97c645b))
### Bug Fixes
- resolved install error ([a5abe13](https://github.com/sapphiredev/shapeshift/commit/a5abe1362bb6d9ce6d6471bffa47fe8983b0d1a4))

24
node_modules/@sapphire/shapeshift/LICENSE.md generated vendored Normal file
View file

@ -0,0 +1,24 @@
# The MIT License (MIT)
Copyright © `2021` `The Sapphire Community and its contributors`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

934
node_modules/@sapphire/shapeshift/README.md generated vendored Normal file
View file

@ -0,0 +1,934 @@
<div align="center">
![Sapphire Logo](https://raw.githubusercontent.com/sapphiredev/assets/main/banners/SapphireCommunity.png)
# @sapphire/shapeshift
**Shapeshift**
Blazing fast input validation and transformation ⚡
[![GitHub](https://img.shields.io/github/license/sapphiredev/shapeshift)](https://github.com/sapphiredev/shapeshift/blob/main/LICENSE.md)
[![codecov](https://codecov.io/gh/sapphiredev/shapeshift/branch/main/graph/badge.svg?token=RF4mMKx6lL)](https://codecov.io/gh/sapphiredev/shapeshift)
[![npm](https://img.shields.io/npm/v/@sapphire/shapeshift?color=crimson&logo=npm&style=flat-square)](https://www.npmjs.com/package/@sapphire/shapeshift)
</div>
## Table of Contents
- [@sapphire/shapeshift](#sapphireshapeshift)
- [Table of Contents](#table-of-contents)
- [Description](#description)
- [Features](#features)
- [Usage](#usage)
- [Basic usage](#basic-usage)
- [Defining validations](#defining-validations)
- [Primitives](#primitives)
- [Literals](#literals)
- [Strings](#strings)
- [Numbers](#numbers)
- [BigInts](#bigints)
- [Booleans](#booleans)
- [Arrays](#arrays)
- [Tuples](#tuples)
- [Unions](#unions)
- [Enums](#enums)
- [Maps](#maps)
- [Sets](#sets)
- [Instances](#instances)
- [Records](#records)
- [Functions // TODO](#functions--todo)
- [TypedArray](#typedarray)
- [Defining schemas (objects)](#defining-schemas-objects)
- [Utility types for TypeScript](#utility-types-for-typescript)
- [Extracting an interface from a schema](#extracting-an-interface-from-a-schema)
- [Defining the structure of a schema through an interface](#defining-the-structure-of-a-schema-through-an-interface)
- [`.extend`:](#extend)
- [`.pick` / `.omit`:](#pick--omit)
- [`.partial`](#partial)
- [`.required`](#required)
- [Handling unrecognized keys](#handling-unrecognized-keys)
- [`.strict`](#strict)
- [`.ignore`](#ignore)
- [`.passthrough`](#passthrough)
- [BaseValidator: methods and properties](#basevalidator-methods-and-properties)
- [`.run`](#rundata-unknown-resultt-error-given-a-validation-you-can-call-this-method-to-check-whether-or-not-the)
- [`.parse`](#parsedata-unknown-t-given-a-validations-you-can-call-this-method-to-check-whether-or-not-the-input-is-valid)
- [`.transform`](#transformrvalue-t--r-nopvalidatorr-adds-a-constraint-that-modifies-the-input)
- [`.reshape`](#reshapervalue-t--resultr-error--iconstraint-nopvalidatorr-adds-a-constraint-able-to-both-validate)
- [`.default`](#defaultvalue-t----t-transform-undefined-into-the-given-value-or-the-callbacks-returned-value)
- [`.optional`](#optional-a-convenience-method-that-returns-a-union-of-the-type-with-sundefined)
- [`.nullable`](#nullable-a-convenience-method-that-returns-a-union-of-the-type-with-snullable)
- [`.nullish`](#nullish-a-convenience-method-that-returns-a-union-of-the-type-with-snullish)
- [`.array`](#array-a-convenience-method-that-returns-an-arrayvalidator-with-the-type)
- [`.or`](#or-a-convenience-method-that-returns-an-unionvalidator-with-the-type-this-method-is-also-overridden-in)
- [`.when`](#when-adjust-the-schema-based-on-a-sibling-or-sinbling-children-fields)
- [Available options for providing `is`](#available-options-for-providing-is)
- [Resolving of the `key` (first) parameter](#resolving-of-the-key-first-parameter)
- [Examples](#examples)
- [Enabling and disabling validation](#enabling-and-disabling-validation)
- [Buy us some doughnuts](#buy-us-some-doughnuts)
- [Contributors](#contributors)
## Description
[Back to top][toc]
A very fast and lightweight input validation and transformation library for JavaScript.
> **Note**: Shapeshift requires Node.js v14.0.0 or higher to work.
## Features
[Back to top][toc]
- TypeScript friendly
- Offers CJS, ESM and UMD builds
- API similar to [`zod`]
- Faster than ⚡
## Usage
[Back to top][toc]
**_For complete usages, please dive into our [documentation]_**
### Basic usage
[Back to top][toc]
Creating a simple string validation
```typescript
import { s } from '@sapphire/shapeshift';
const myStringValidation = s.string;
// Parse
myStringValidation.parse('sapphire'); // => returns 'sapphire'
myStringValidation.parse(12); // throws ValidationError
```
Creating an object schema
```typescript
import { s } from '@sapphire/shapeshift';
const user = s.object({
username: s.string
});
user.parse({ username: 'Sapphire' });
```
### Defining validations
[Back to top][toc]
#### Primitives
[Back to top][toc]
```typescript
import { s } from '@sapphire/shapeshift';
// Primitives
s.string;
s.number;
s.bigint;
s.boolean;
s.date;
// Empty Types
s.undefined;
s.null;
s.nullish; // Accepts undefined | null
// Catch-all Types
s.any;
s.unknown;
// Never Type
s.never;
```
#### Literals
[Back to top][toc]
```typescript
s.literal('sapphire');
s.literal(12);
s.literal(420n);
s.literal(true);
s.literal(new Date(1639278160000)); // s.date.equal(1639278160000);
```
#### Strings
[Back to top][toc]
Shapeshift includes a handful of string-specific validations:
```typescript
s.string.lengthLessThan(5);
s.string.lengthLessThanOrEqual(5);
s.string.lengthGreaterThan(5);
s.string.lengthGreaterThanOrEqual(5);
s.string.lengthEqual(5);
s.string.lengthNotEqual(5);
s.string.email;
s.string.url();
s.string.uuid();
s.string.regex(regex);
s.string.ip();
s.string.ipv4;
s.string.ipv6;
s.string.phone();
```
#### Numbers
[Back to top][toc]
Shapeshift includes a handful of number-specific validations:
```typescript
s.number.greaterThan(5); // > 5
s.number.greaterThanOrEqual(5); // >= 5
s.number.lessThan(5); // < 5
s.number.lessThanOrEqual(5); // <= 5
s.number.equal(5); // === 5
s.number.notEqual(5); // !== 5
s.number.equal(NaN); // special case: Number.isNaN
s.number.notEqual(NaN); // special case: !Number.isNaN
s.number.int; // value must be an integer
s.number.safeInt; // value must be a safe integer
s.number.finite; // value must be finite
s.number.positive; // .greaterThanOrEqual(0)
s.number.negative; // .lessThan(0)
s.number.divisibleBy(5); // Divisible by 5
```
And transformations:
```typescript
s.number.abs; // Transforms the number to an absolute number
s.number.sign; // Gets the number's sign
s.number.trunc; // Transforms the number to the result of `Math.trunc`
s.number.floor; // Transforms the number to the result of `Math.floor`
s.number.fround; // Transforms the number to the result of `Math.fround`
s.number.round; // Transforms the number to the result of `Math.round`
s.number.ceil; // Transforms the number to the result of `Math.ceil`
```
#### BigInts
[Back to top][toc]
Shapeshift includes a handful of number-specific validations:
```typescript
s.bigint.greaterThan(5n); // > 5n
s.bigint.greaterThanOrEqual(5n); // >= 5n
s.bigint.lessThan(5n); // < 5n
s.bigint.lessThanOrEqual(5n); // <= 5n
s.bigint.equal(5n); // === 5n
s.bigint.notEqual(5n); // !== 5n
s.bigint.positive; // .greaterThanOrEqual(0n)
s.bigint.negative; // .lessThan(0n)
s.bigint.divisibleBy(5n); // Divisible by 5n
```
And transformations:
```typescript
s.bigint.abs; // Transforms the bigint to an absolute bigint
s.bigint.intN(5); // Clamps to a bigint to a signed bigint with 5 digits, see BigInt.asIntN
s.bigint.uintN(5); // Clamps to a bigint to an unsigned bigint with 5 digits, see BigInt.asUintN
```
#### Booleans
[Back to top][toc]
Shapeshift includes a few boolean-specific validations:
```typescript
s.boolean.true; // value must be true
s.boolean.false; // value must be false
s.boolean.equal(true); // s.boolean.true
s.boolean.equal(false); // s.boolean.false
s.boolean.notEqual(true); // s.boolean.false
s.boolean.notEqual(false); // s.boolean.true
```
#### Arrays
[Back to top][toc]
```typescript
const stringArray = s.array(s.string);
const stringArray = s.string.array;
```
Shapeshift includes a handful of array-specific validations:
```typescript
s.string.array.lengthLessThan(5); // Must have less than 5 elements
s.string.array.lengthLessThanOrEqual(5); // Must have 5 or less elements
s.string.array.lengthGreaterThan(5); // Must have more than 5 elements
s.string.array.lengthGreaterThanOrEqual(5); // Must have 5 or more elements
s.string.array.lengthEqual(5); // Must have exactly 5 elements
s.string.array.lengthNotEqual(5); // Must not have exactly 5 elements
s.string.array.lengthRange(0, 4); // Must have at least 0 elements and less than 4 elements (in math, that is [0, 4))
s.string.array.lengthRangeInclusive(0, 4); // Must have at least 0 elements and at most 4 elements (in math, that is [0, 4])
s.string.array.lengthRangeExclusive(0, 4); // Must have more than 0 element and less than 4 elements (in math, that is (0, 4))
s.string.array.unique; // All elements must be unique. Deep equality is used to check for uniqueness.
```
> **Note**: All `.length` methods define tuple types with the given amount of elements. For example,
> `s.string.array.lengthGreaterThanOrEqual(2)`'s inferred type is `[string, string, ...string[]]`
#### Tuples
[Back to top][toc]
Unlike arrays, tuples have a fixed number of elements and each element can have a different type:
```typescript
const dish = s.tuple([
s.string, // Dish's name
s.number.int, // Table's number
s.date // Date the dish was ready for delivery
]);
dish.parse(['Iberian ham', 10, new Date()]);
```
#### Unions
[Back to top][toc]
Shapeshift includes a built-in method for composing OR types:
```typescript
const stringOrNumber = s.union(s.string, s.number);
stringOrNumber.parse('Sapphire'); // => 'Sapphire'
stringOrNumber.parse(42); // => 42
stringOrNumber.parse({}); // => throws CombinedError
```
#### Enums
[Back to top][toc]
Enums are a convenience method that aliases `s.union(s.literal(a), s.literal(b), ...)`:
```typescript
s.enum('Red', 'Green', 'Blue');
// s.union(s.literal('Red'), s.literal('Green'), s.literal('Blue'));
```
#### Maps
[Back to top][toc]
```typescript
const map = s.map(s.string, s.number);
// Map<string, number>
```
#### Sets
[Back to top][toc]
```typescript
const set = s.set(s.number);
// Set<number>
```
#### Instances
[Back to top][toc]
You can use `s.instance(Class)` to check that the input is an instance of a class. This is useful to validate inputs
against classes:
```typescript
class User {
public constructor(public name: string) {}
}
const userInstanceValidation = s.instance(User);
userInstanceValidation.parse(new User('Sapphire')); // => User { name: 'Sapphire' }
userInstanceValidation.parse('oops'); // => throws ValidatorError
```
#### Records
[Back to top][toc]
Record validations are similar to objects, but validate `Record<string, T>` types. Keep in mind this does not check for
the keys, and cannot support validation for specific ones:
```typescript
const tags = s.record(s.string);
tags.parse({ foo: 'bar', hello: 'world' }); // => { foo: 'bar', hello: 'world' }
tags.parse({ foo: 42 }); // => throws CombinedError
tags.parse('Hello'); // => throws ValidateError
```
---
_**Function validation is not yet implemented and will be made available starting v2.1.0**_
#### Functions // TODO
[Back to top][toc]
You can define function validations. This checks for whether or not an input is a function:
```typescript
s.function; // () => unknown
```
You can define arguments by passing an array as the first argument, as well as the return type as the second:
```typescript
s.function([s.string]); // (arg0: string) => unknown
s.function([s.string, s.number], s.string); // (arg0: string, arg1: number) => string
```
> **Note**: Shapeshift will transform the given function into one with validation on arguments and output. You can
> access the `.raw` property of the function to get the unchecked function.
---
#### TypedArray
[Back to top][toc]
```ts
const typedArray = s.typedArray();
const int16Array = s.int16Array;
const uint16Array = s.uint16Array;
const uint8ClampedArray = s.uint8ClampedArray;
const int16Array = s.int16Array;
const uint16Array = s.uint16Array;
const int32Array = s.int32Array;
const uint32Array = s.uint32Array;
const float32Array = s.float32Array;
const float64Array = s.float64Array;
const bigInt64Array = s.bigInt64Array;
const bigUint64Array = s.bigUint64Array;
```
Shapeshift includes a handful of validations specific to typed arrays.
```typescript
s.typedArray().lengthLessThan(5); // Length must be less than 5
s.typedArray().lengthLessThanOrEqual(5); // Length must be 5 or less
s.typedArray().lengthGreaterThan(5); // Length must be more than 5
s.typedArray().lengthGreaterThanOrEqual(5); // Length must be 5 or more
s.typedArray().lengthEqual(5); // Length must be exactly 5
s.typedArray().lengthNotEqual(5); // Length must not be 5
s.typedArray().lengthRange(0, 4); // Length L must satisfy 0 <= L < 4
s.typedArray().lengthRangeInclusive(0, 4); // Length L must satisfy 0 <= L <= 4
s.typedArray().lengthRangeExclusive(0, 4); // Length L must satisfy 0 < L < 4
```
Note that all of these methods have analogous methods for working with the typed array's byte length,
`s.typedArray().byteLengthX()` - for instance, `s.typedArray().byteLengthLessThan(5)` is the same as
`s.typedArray().lengthLessThan(5)` but for the array's byte length.
---
### Defining schemas (objects)
[Back to top][toc]
```typescript
// Properties are required by default:
const animal = s.object({
name: s.string,
age: s.number
});
```
#### Utility types for TypeScript
[Back to top][toc]
For object validation Shapeshift exports 2 utility types that can be used to extract interfaces from schemas and define
the structure of a schema as an interface beforehand respectively.
##### Extracting an interface from a schema
[Back to top][toc]
You can use the `InferType` type to extract the interface from a schema, for example:
```typescript
import { InferType, s } from '@sapphire/shapeshift';
const schema = s.object({
foo: s.string,
bar: s.number,
baz: s.boolean,
qux: s.bigint,
quux: s.date
});
type Inferredtype = InferType<typeof schema>;
// Expected type:
type Inferredtype = {
foo: string;
bar: number;
baz: boolean;
qux: bigint;
quux: Date;
};
```
##### Defining the structure of a schema through an interface
[Back to top][toc]
You can use the `SchemaOf` type to define the structure of a schema before defining the actual schema, for example:
```typescript
import { s, SchemaOf } from '@sapphire/shapeshift';
interface IIngredient {
ingredientId: string | undefined;
name: string | undefined;
}
interface IInstruction {
instructionId: string | undefined;
message: string | undefined;
}
interface IRecipe {
recipeId: string | undefined;
title: string;
description: string;
instructions: IInstruction[];
ingredients: IIngredient[];
}
type InstructionSchemaType = SchemaOf<IInstruction>;
// Expected Type: ObjectValidator<IInstruction>
type IngredientSchemaType = SchemaOf<IIngredient>;
// Expected Type: ObjectValidator<IIngredient>
type RecipeSchemaType = SchemaOf<IRecipe>;
// Expected Type: ObjectValidator<IRecipe>
const instructionSchema: InstructionSchemaType = s.object({
instructionId: s.string.optional,
message: s.string
});
const ingredientSchema: IngredientSchemaType = s.object({
ingredientId: s.string.optional,
name: s.string
});
const recipeSchema: RecipeSchemaType = s.object({
recipeId: s.string.optional,
title: s.string,
description: s.string,
instructions: s.array(instructionSchema),
ingredients: s.array(ingredientSchema)
});
```
#### `.extend`:
[Back to top][toc]
You can add additional fields using either an object or an ObjectValidator, in this case, you will get a new object
validator with the merged properties:
```typescript
const animal = s.object({
name: s.string.optional,
age: s.number
});
const pet = animal.extend({
owner: s.string.nullish
});
const pet = animal.extend(
s.object({
owner: s.string.nullish
})
);
```
> If both schemas share keys, an error will be thrown. Please use `.omit` on the first object if you desire this
> behaviour.
#### `.pick` / `.omit`:
[Back to top][toc]
Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all object schemas have the aforementioned methods
that return a modifier version:
```typescript
const pkg = s.object({
name: s.string,
description: s.string,
dependencies: s.string.array
});
const justTheName = pkg.pick(['name']);
// s.object({ name: s.string });
const noDependencies = pkg.omit(['dependencies']);
// s.object({ name: s.string, description: s.string });
```
#### `.partial`
[Back to top][toc]
Inspired by TypeScript's built-in `Partial` utility type, all object schemas have the aforementioned method that makes
all properties optional:
```typescript
const user = s.object({
username: s.string,
password: s.string
}).partial;
```
Which is the same as doing:
```typescript
const user = s.object({
username: s.string.optional,
password: s.string.optional
});
```
---
#### `.required`
[Back to top][toc]
Inspired by TypeScript's built-in `Required` utility type, all object schemas have the aforementioned method that makes
all properties required:
```typescript
const user = s.object({
username: s.string.optional,
password: s.string.optional
}).required;
```
Which is the same as doing:
```typescript
const user = s.object({
username: s.string,
password: s.string
});
```
---
### Handling unrecognized keys
[Back to top][toc]
By default, Shapeshift will not include keys that are not defined by the schema during parsing:
```typescript
const person = s.object({
framework: s.string
});
person.parse({
framework: 'Sapphire',
awesome: true
});
// => { name: 'Sapphire' }
```
#### `.strict`
[Back to top][toc]
You can disallow unknown keys with `.strict`. If the input includes any unknown keys, an error will be thrown.
```typescript
const person = s.object({
framework: s.string
}).strict;
person.parse({
framework: 'Sapphire',
awesome: true
});
// => throws ValidationError
```
#### `.ignore`
[Back to top][toc]
You can use the `.ignore` getter to reset an object schema to the default behaviour (ignoring unrecognized keys).
#### `.passthrough`
[Back to top][toc]
You can use the `.passthrough` getter to make the validator add the unrecognized properties the shape does not have,
from the input.
---
### BaseValidator: methods and properties
[Back to top][toc]
All validations in Shapeshift contain certain methods.
- #### `.run(data: unknown): Result<T, Error>`: given a validation, you can call this method to check whether or not the
input is valid. If it is, a `Result` with `success: true` and a deep-cloned value will be returned with the given
constraints and transformations. Otherwise, a `Result` with `success: false` and an error is returned.
- #### `.parse(data: unknown): T`: given a validations, you can call this method to check whether or not the input is valid.
If it is, a deep-cloned value will be returned with the given constraints and transformations. Otherwise, an error is
thrown.
- #### `.transform<R>((value: T) => R): NopValidator<R>`: adds a constraint that modifies the input:
```typescript
import { s } from '@sapphire/shapeshift';
const getLength = s.string.transform((value) => value.length);
getLength.parse('Hello There'); // => 11
```
> :warning: `.transform`'s functions **must not throw**. If a validation error is desired to be thrown, `.reshape`
> instead.
- #### `.reshape<R>((value: T) => Result<R, Error> | IConstraint): NopValidator<R>`: adds a constraint able to both validate
and modify the input:
```typescript
import { s, Result } from '@sapphire/shapeshift';
const getLength = s.string.reshape((value) => Result.ok(value.length));
getLength.parse('Hello There'); // => 11
```
> :warning: `.reshape`'s functions **must not throw**. If a validation error is desired to be thrown, use
> `Result.err(error)` instead.
- #### `.default(value: T | (() => T))`: transform `undefined` into the given value or the callback's returned value:
```typescript
const name = s.string.default('Sapphire');
name.parse('Hello'); // => 'Hello'
name.parse(undefined); // => 'Sapphire'
```
```typescript
const number = s.number.default(Math.random);
number.parse(12); // => 12
number.parse(undefined); // => 0.989911985608602
number.parse(undefined); // => 0.3224350185068794
```
> :warning: The default values are not validated.
- #### `.optional`: a convenience method that returns a union of the type with `s.undefined`.
```typescript
s.string.optional; // s.union(s.string, s.undefined)
```
- #### `.nullable`: a convenience method that returns a union of the type with `s.nullable`.
```typescript
s.string.nullable; // s.union(s.string, s.nullable)
```
- #### `.nullish`: a convenience method that returns a union of the type with `s.nullish`.
```typescript
s.string.nullish; // s.union(s.string, s.nullish)
```
- #### `.array`: a convenience method that returns an ArrayValidator with the type.
```typescript
s.string.array; // s.array(s.string)
```
- #### `.or`: a convenience method that returns an UnionValidator with the type. This method is also overridden in
UnionValidator to just append one more entry.
```typescript
s.string.or(s.number);
// => s.union(s.string, s.number)
s.object({ name: s.string }).or(s.string, s.number);
// => s.union(s.object({ name: s.string }), s.string, s.number)
```
- #### `.when`: Adjust the schema based on a sibling or sinbling children fields.
For using when you provide an object literal where the key `is` is undefined, a value, or a matcher function; `then`
provides the schema when `is` resolves truthy, and `otherwise` provides the schema when `is` resolves falsey.
##### Available options for providing `is`
When `is` is not provided (`=== undefined`) it is strictly resolved as `Boolean(value)` wherein `value` is the current
value of the referenced sibling. Note that if multiple siblings are referenced then all the values of the array need to
resolve truthy for the `is` to resolve truthy.
When `is` is a primitive literal it is strictly compared (`===`) to the current value.
If you want to use a different form of equality you can provide a function like: `is: (value) => value === true`.
##### Resolving of the `key` (first) parameter
For resolving the `key` parameter to its respective value we use [lodash/get](https://lodash.com/docs#get). This means
that every way that Lodash supports resolving a key to its respective value is also supported by Shapeshift. This
includes:
- Simply providing a string or number like `'name'` or `1`.
- Providing a string or number with a dot notation like `'name.first'` (representative of a nested object structure of
`{ 'name': { 'first': 'Sapphire' } }` => resolves to `Sapphire`).
- Providing a string or number with a bracket notation like `'name[0]'` (representative of an array structure of
`{ 'name': ['Sapphire', 'Framework'] }` => resolves to `Sapphire`).
- Providing a string or number with a dot and bracket notation like `'name[1].first'` (representative of a nested object
structure of `{ 'name': [{ 'first': 'Sapphire' }, { 'first': 'Framework' }] }` => resolves to `Framework`).
##### Examples
Let's start with a basic example:
```typescript
const whenPredicate = s.object({
booleanLike: s.boolean,
numberLike: s.number.when('booleanLike', {
then: (schema) => schema.greaterThanOrEqual(5),
otherwise: (schema) => schema.lessThanOrEqual(5)
})
});
whenPredicate.parse({ booleanLike: true, numberLike: 6 });
// => { booleanLike: true, numberLike: 6 }
whenPredicate.parse({ booleanLike: true, numberLike: 4 });
// => ExpectedConstraintError('s.number.greaterThanOrEqual', 'Invalid number value', 4, 'expected >= 5')
whenPredicate.parse({ booleanLike: false, numberLike: 4 });
// => { booleanLike: false, numberLike: 4 }
```
The provided key can also be an array of sibling children:
```typescript
const whenPredicate = s.object({
booleanLike: s.boolean,
stringLike: s.string,
numberLike: s.number.when(['booleanLike', 'stringLike'], {
is: ([booleanLikeValue, stringLikeValue]) => booleanLikeValue === true && stringLikeValue === 'foobar',
then: (schema) => schema.greaterThanOrEqual(5),
otherwise: (schema) => schema.lessThanOrEqual(5)
})
});
whenPredicate.parse({ booleanLike: true, stringLike: 'foobar', numberLike: 6 });
// => { booleanLike: true, numberLike: 6 }
whenPredicate.parse({ booleanLike: true, stringLike: 'barfoo', numberLike: 4 });
// => ExpectedConstraintError('s.number.greaterThanOrEqual', 'Invalid number value', 4, 'expected >= 5')
whenPredicate.parse({ booleanLike: false, stringLike: 'foobar' numberLike: 4 });
// => ExpectedConstraintError('s.number.greaterThanOrEqual', 'Invalid number value', 4, 'expected >= 5')
```
### Enabling and disabling validation
[Back to top][toc]
At times, you might want to have a consistent code base with validation, but would like to keep validation to the strict
necessities instead of the in-depth constraints available in shapeshift. By calling `setGlobalValidationEnabled` you can
disable validation at a global level, and by calling `setValidationEnabled` you can disable validation on a
per-validator level.
> When setting the validation enabled status per-validator, you can also set it to `null` to use the global setting.
```typescript
import { setGlobalValidationEnabled } from '@sapphire/shapeshift';
setGlobalValidationEnabled(false);
```
```typescript
import { s } from '@sapphire/shapeshift';
const predicate = s.string.lengthGreaterThan(5).setValidationEnabled(false);
```
## Buy us some doughnuts
[Back to top][toc]
Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are
amazing people who may still want to donate just to show their appreciation. Thank you very much in advance!
We accept donations through Open Collective, Ko-fi, Paypal, Patreon and GitHub Sponsorships. You can use the buttons
below to donate through your method of choice.
| Donate With | Address |
| :-------------: | :-------------------------------------------------: |
| Open Collective | [Click Here](https://sapphirejs.dev/opencollective) |
| Ko-fi | [Click Here](https://sapphirejs.dev/kofi) |
| Patreon | [Click Here](https://sapphirejs.dev/patreon) |
| PayPal | [Click Here](https://sapphirejs.dev/paypal) |
## Contributors
[Back to top][toc]
Please make sure to read the [Contributing Guide][contributing] before making a pull request.
Thank you to all the people who already contributed to Sapphire!
<a href="https://github.com/sapphiredev/shapeshift/graphs/contributors">
<img src="https://contrib.rocks/image?repo=sapphiredev/shapeshift" />
</a>
[contributing]: https://github.com/sapphiredev/.github/blob/main/.github/CONTRIBUTING.md
[`zod`]: https://github.com/colinhacks/zod
[documentation]: https://www.sapphirejs.dev/docs/Documentation/api-shapeshift/
[toc]: #table-of-contents

715
node_modules/@sapphire/shapeshift/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,715 @@
import { InspectOptionsStylized } from 'util';
declare class Result<T, E extends Error = Error> {
readonly success: boolean;
readonly value?: T;
readonly error?: E;
private constructor();
isOk(): this is {
success: true;
value: T;
};
isErr(): this is {
success: false;
error: E;
};
unwrap(): T;
static ok<T, E extends Error = Error>(value: T): Result<T, E>;
static err<T, E extends Error = Error>(error: E): Result<T, E>;
}
type ArrayConstraintName = `s.array(T).${'unique' | `length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual' | 'Range' | 'RangeInclusive' | 'RangeExclusive'}`}`;
declare function arrayLengthLessThan<T>(value: number): IConstraint<T[]>;
declare function arrayLengthLessThanOrEqual<T>(value: number): IConstraint<T[]>;
declare function arrayLengthGreaterThan<T>(value: number): IConstraint<T[]>;
declare function arrayLengthGreaterThanOrEqual<T>(value: number): IConstraint<T[]>;
declare function arrayLengthEqual<T>(value: number): IConstraint<T[]>;
declare function arrayLengthNotEqual<T>(value: number): IConstraint<T[]>;
declare function arrayLengthRange<T>(start: number, endBefore: number): IConstraint<T[]>;
declare function arrayLengthRangeInclusive<T>(start: number, end: number): IConstraint<T[]>;
declare function arrayLengthRangeExclusive<T>(startAfter: number, endBefore: number): IConstraint<T[]>;
type BigIntConstraintName = `s.bigint.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'notEqual' | 'divisibleBy'}`;
declare function bigintLessThan(value: bigint): IConstraint<bigint>;
declare function bigintLessThanOrEqual(value: bigint): IConstraint<bigint>;
declare function bigintGreaterThan(value: bigint): IConstraint<bigint>;
declare function bigintGreaterThanOrEqual(value: bigint): IConstraint<bigint>;
declare function bigintEqual(value: bigint): IConstraint<bigint>;
declare function bigintNotEqual(value: bigint): IConstraint<bigint>;
declare function bigintDivisibleBy(divider: bigint): IConstraint<bigint>;
type BooleanConstraintName = `s.boolean.${boolean}`;
declare const booleanTrue: IConstraint<boolean, true>;
declare const booleanFalse: IConstraint<boolean, false>;
type DateConstraintName = `s.date.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'notEqual' | 'valid' | 'invalid'}`;
declare function dateLessThan(value: Date): IConstraint<Date>;
declare function dateLessThanOrEqual(value: Date): IConstraint<Date>;
declare function dateGreaterThan(value: Date): IConstraint<Date>;
declare function dateGreaterThanOrEqual(value: Date): IConstraint<Date>;
declare function dateEqual(value: Date): IConstraint<Date>;
declare function dateNotEqual(value: Date): IConstraint<Date>;
declare const dateInvalid: IConstraint<Date>;
declare const dateValid: IConstraint<Date>;
type NumberConstraintName = `s.number.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'equal(NaN)' | 'notEqual' | 'notEqual(NaN)' | 'int' | 'safeInt' | 'finite' | 'divisibleBy'}`;
declare function numberLessThan(value: number): IConstraint<number>;
declare function numberLessThanOrEqual(value: number): IConstraint<number>;
declare function numberGreaterThan(value: number): IConstraint<number>;
declare function numberGreaterThanOrEqual(value: number): IConstraint<number>;
declare function numberEqual(value: number): IConstraint<number>;
declare function numberNotEqual(value: number): IConstraint<number>;
declare const numberInt: IConstraint<number>;
declare const numberSafeInt: IConstraint<number>;
declare const numberFinite: IConstraint<number>;
declare const numberNaN: IConstraint<number>;
declare const numberNotNaN: IConstraint<number>;
declare function numberDivisibleBy(divider: number): IConstraint<number>;
declare const customInspectSymbol: unique symbol;
declare const customInspectSymbolStackLess: unique symbol;
declare abstract class BaseError extends Error {
protected [customInspectSymbol](depth: number, options: InspectOptionsStylized): string;
protected abstract [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
declare class CombinedError extends BaseError {
readonly errors: readonly BaseError[];
constructor(errors: readonly BaseError[]);
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
declare class ValidationError extends BaseError {
readonly validator: string;
readonly given: unknown;
constructor(validator: string, message: string, given: unknown);
toJSON(): {
name: string;
validator: string;
given: unknown;
};
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
declare class ExpectedValidationError<T> extends ValidationError {
readonly expected: T;
constructor(validator: string, message: string, given: unknown, expected: T);
toJSON(): {
name: string;
validator: string;
given: unknown;
expected: T;
};
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
declare class MissingPropertyError extends BaseError {
readonly property: PropertyKey;
constructor(property: PropertyKey);
toJSON(): {
name: string;
property: PropertyKey;
};
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
declare class MultiplePossibilitiesConstraintError<T = unknown> extends BaseConstraintError<T> {
readonly expected: readonly string[];
constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: readonly string[]);
toJSON(): {
name: string;
constraint: ConstraintErrorNames;
given: T;
expected: readonly string[];
};
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
declare class UnknownEnumValueError extends BaseError {
readonly value: string | number;
readonly enumKeys: string[];
readonly enumMappings: Map<string | number, string | number>;
constructor(value: string | number, keys: string[], enumMappings: Map<string | number, string | number>);
toJSON(): {
name: string;
value: string | number;
enumKeys: string[];
enumMappings: [string | number, string | number][];
};
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
declare class UnknownPropertyError extends BaseError {
readonly property: PropertyKey;
readonly value: unknown;
constructor(property: PropertyKey, value: unknown);
toJSON(): {
name: string;
property: PropertyKey;
value: unknown;
};
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
declare class BigIntValidator<T extends bigint> extends BaseValidator<T> {
lessThan(number: bigint): this;
lessThanOrEqual(number: bigint): this;
greaterThan(number: bigint): this;
greaterThanOrEqual(number: bigint): this;
equal<N extends bigint>(number: N): BigIntValidator<N>;
notEqual(number: bigint): this;
get positive(): this;
get negative(): this;
divisibleBy(number: bigint): this;
get abs(): this;
intN(bits: number): this;
uintN(bits: number): this;
protected handle(value: unknown): Result<T, ValidationError>;
}
declare class BooleanValidator<T extends boolean = boolean> extends BaseValidator<T> {
get true(): BooleanValidator<true>;
get false(): BooleanValidator<false>;
equal<R extends true | false>(value: R): BooleanValidator<R>;
notEqual<R extends true | false>(value: R): BooleanValidator<R>;
protected handle(value: unknown): Result<T, ValidationError>;
}
declare class DateValidator extends BaseValidator<Date> {
lessThan(date: Date | number | string): this;
lessThanOrEqual(date: Date | number | string): this;
greaterThan(date: Date | number | string): this;
greaterThanOrEqual(date: Date | number | string): this;
equal(date: Date | number | string): this;
notEqual(date: Date | number | string): this;
get valid(): this;
get invalid(): this;
protected handle(value: unknown): Result<Date, ValidationError>;
}
declare class DefaultValidator<T> extends BaseValidator<T> {
private readonly validator;
private defaultValue;
constructor(validator: BaseValidator<T>, value: T | (() => T), constraints?: readonly IConstraint<T>[]);
default(value: Exclude<T, undefined> | (() => Exclude<T, undefined>)): DefaultValidator<Exclude<T, undefined>>;
protected handle(value: unknown): Result<T, ValidatorError>;
protected clone(): this;
}
declare class InstanceValidator<T> extends BaseValidator<T> {
readonly expected: Constructor<T>;
constructor(expected: Constructor<T>, constraints?: readonly IConstraint<T>[]);
protected handle(value: unknown): Result<T, ExpectedValidationError<Constructor<T>>>;
protected clone(): this;
}
declare class LiteralValidator<T> extends BaseValidator<T> {
readonly expected: T;
constructor(literal: T, constraints?: readonly IConstraint<T>[]);
protected handle(value: unknown): Result<T, ExpectedValidationError<T>>;
protected clone(): this;
}
declare class CombinedPropertyError extends BaseError {
readonly errors: [PropertyKey, BaseError][];
constructor(errors: [PropertyKey, BaseError][]);
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
private static formatProperty;
}
declare class MapValidator<K, V> extends BaseValidator<Map<K, V>> {
private readonly keyValidator;
private readonly valueValidator;
constructor(keyValidator: BaseValidator<K>, valueValidator: BaseValidator<V>, constraints?: readonly IConstraint<Map<K, V>>[]);
protected clone(): this;
protected handle(value: unknown): Result<Map<K, V>, ValidationError | CombinedPropertyError>;
}
declare class NativeEnumValidator<T extends NativeEnumLike> extends BaseValidator<T[keyof T]> {
readonly enumShape: T;
readonly hasNumericElements: boolean;
private readonly enumKeys;
private readonly enumMapping;
constructor(enumShape: T);
protected handle(value: unknown): Result<T[keyof T], ValidationError | UnknownEnumValueError>;
protected clone(): this;
}
interface NativeEnumLike {
[key: string]: string | number;
[key: number]: string;
}
declare class NeverValidator extends BaseValidator<never> {
protected handle(value: unknown): Result<never, ValidationError>;
}
declare class NullishValidator extends BaseValidator<undefined | null> {
protected handle(value: unknown): Result<undefined | null, ValidationError>;
}
declare class NumberValidator<T extends number> extends BaseValidator<T> {
lessThan(number: number): this;
lessThanOrEqual(number: number): this;
greaterThan(number: number): this;
greaterThanOrEqual(number: number): this;
equal<N extends number>(number: N): NumberValidator<N>;
notEqual(number: number): this;
get int(): this;
get safeInt(): this;
get finite(): this;
get positive(): this;
get negative(): this;
divisibleBy(divider: number): this;
get abs(): this;
get sign(): this;
get trunc(): this;
get floor(): this;
get fround(): this;
get round(): this;
get ceil(): this;
protected handle(value: unknown): Result<T, ValidationError>;
}
declare class ObjectValidator<T extends object, I = UndefinedToOptional<T>> extends BaseValidator<I> {
readonly shape: MappedObjectValidator<T>;
readonly strategy: ObjectValidatorStrategy;
private readonly keys;
private readonly handleStrategy;
private readonly requiredKeys;
private readonly possiblyUndefinedKeys;
private readonly possiblyUndefinedKeysWithDefaults;
constructor(shape: MappedObjectValidator<T>, strategy?: ObjectValidatorStrategy, constraints?: readonly IConstraint<I>[]);
get strict(): this;
get ignore(): this;
get passthrough(): this;
get partial(): ObjectValidator<{
[Key in keyof I]?: I[Key];
}>;
get required(): ObjectValidator<{
[Key in keyof I]-?: I[Key];
}>;
extend<ET extends object>(schema: ObjectValidator<ET> | MappedObjectValidator<ET>): ObjectValidator<T & ET>;
pick<K extends keyof I>(keys: readonly K[]): ObjectValidator<{
[Key in keyof Pick<I, K>]: I[Key];
}>;
omit<K extends keyof I>(keys: readonly K[]): ObjectValidator<{
[Key in keyof Omit<I, K>]: I[Key];
}>;
protected handle(value: unknown): Result<I, ValidationError | CombinedPropertyError>;
protected clone(): this;
private handleIgnoreStrategy;
private handleStrictStrategy;
private handlePassthroughStrategy;
}
declare enum ObjectValidatorStrategy {
Ignore = 0,
Strict = 1,
Passthrough = 2
}
declare class PassthroughValidator<T extends any | unknown> extends BaseValidator<T> {
protected handle(value: unknown): Result<T, ValidationError>;
}
declare class RecordValidator<T> extends BaseValidator<Record<string, T>> {
private readonly validator;
constructor(validator: BaseValidator<T>, constraints?: readonly IConstraint<Record<string, T>>[]);
protected clone(): this;
protected handle(value: unknown): Result<Record<string, T>, ValidationError | CombinedPropertyError>;
}
declare class SetValidator<T> extends BaseValidator<Set<T>> {
private readonly validator;
constructor(validator: BaseValidator<T>, constraints?: readonly IConstraint<Set<T>>[]);
protected clone(): this;
protected handle(values: unknown): Result<Set<T>, ValidationError | CombinedError>;
}
type StringConstraintName = `s.string.${`length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual'}` | 'regex' | 'url' | 'uuid' | 'email' | `ip${'v4' | 'v6' | ''}` | 'date' | 'phone'}`;
type StringProtocol = `${string}:`;
type StringDomain = `${string}.${string}`;
interface UrlOptions {
allowedProtocols?: StringProtocol[];
allowedDomains?: StringDomain[];
}
type UUIDVersion = 1 | 3 | 4 | 5;
interface StringUuidOptions {
version?: UUIDVersion | `${UUIDVersion}-${UUIDVersion}` | null;
nullable?: boolean;
}
declare function stringLengthLessThan(length: number): IConstraint<string>;
declare function stringLengthLessThanOrEqual(length: number): IConstraint<string>;
declare function stringLengthGreaterThan(length: number): IConstraint<string>;
declare function stringLengthGreaterThanOrEqual(length: number): IConstraint<string>;
declare function stringLengthEqual(length: number): IConstraint<string>;
declare function stringLengthNotEqual(length: number): IConstraint<string>;
declare function stringEmail(): IConstraint<string>;
declare function stringUrl(options?: UrlOptions): IConstraint<string>;
declare function stringIp(version?: 4 | 6): IConstraint<string>;
declare function stringRegex(regex: RegExp): IConstraint<string, string>;
declare function stringUuid({ version, nullable }?: StringUuidOptions): IConstraint<string, string>;
declare class StringValidator<T extends string> extends BaseValidator<T> {
lengthLessThan(length: number): this;
lengthLessThanOrEqual(length: number): this;
lengthGreaterThan(length: number): this;
lengthGreaterThanOrEqual(length: number): this;
lengthEqual(length: number): this;
lengthNotEqual(length: number): this;
get email(): this;
url(options?: UrlOptions): this;
uuid(options?: StringUuidOptions): this;
regex(regex: RegExp): this;
get date(): this;
get ipv4(): this;
get ipv6(): this;
ip(version?: 4 | 6): this;
phone(): this;
protected handle(value: unknown): Result<T, ValidationError>;
}
declare class TupleValidator<T extends any[]> extends BaseValidator<[...T]> {
private readonly validators;
constructor(validators: BaseValidator<[...T]>[], constraints?: readonly IConstraint<[...T]>[]);
protected clone(): this;
protected handle(values: unknown): Result<[...T], ValidationError | CombinedPropertyError>;
}
type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
declare const TypedArrays: {
readonly Int8Array: (x: unknown) => x is Int8Array;
readonly Uint8Array: (x: unknown) => x is Uint8Array;
readonly Uint8ClampedArray: (x: unknown) => x is Uint8ClampedArray;
readonly Int16Array: (x: unknown) => x is Int16Array;
readonly Uint16Array: (x: unknown) => x is Uint16Array;
readonly Int32Array: (x: unknown) => x is Int32Array;
readonly Uint32Array: (x: unknown) => x is Uint32Array;
readonly Float32Array: (x: unknown) => x is Float32Array;
readonly Float64Array: (x: unknown) => x is Float64Array;
readonly BigInt64Array: (x: unknown) => x is BigInt64Array;
readonly BigUint64Array: (x: unknown) => x is BigUint64Array;
readonly TypedArray: (x: unknown) => x is TypedArray;
};
type TypedArrayName = keyof typeof TypedArrays;
declare class TypedArrayValidator<T extends TypedArray> extends BaseValidator<T> {
private readonly type;
constructor(type: TypedArrayName, constraints?: readonly IConstraint<T>[]);
byteLengthLessThan(length: number): this;
byteLengthLessThanOrEqual(length: number): this;
byteLengthGreaterThan(length: number): this;
byteLengthGreaterThanOrEqual(length: number): this;
byteLengthEqual(length: number): this;
byteLengthNotEqual(length: number): this;
byteLengthRange(start: number, endBefore: number): this;
byteLengthRangeInclusive(startAt: number, endAt: number): this;
byteLengthRangeExclusive(startAfter: number, endBefore: number): this;
lengthLessThan(length: number): this;
lengthLessThanOrEqual(length: number): this;
lengthGreaterThan(length: number): this;
lengthGreaterThanOrEqual(length: number): this;
lengthEqual(length: number): this;
lengthNotEqual(length: number): this;
lengthRange(start: number, endBefore: number): this;
lengthRangeInclusive(startAt: number, endAt: number): this;
lengthRangeExclusive(startAfter: number, endBefore: number): this;
protected clone(): this;
protected handle(value: unknown): Result<T, ValidationError>;
}
declare class UnionValidator<T> extends BaseValidator<T> {
private validators;
constructor(validators: readonly BaseValidator<T>[], constraints?: readonly IConstraint<T>[]);
get optional(): UnionValidator<T | undefined>;
get required(): UnionValidator<Exclude<T, undefined>>;
get nullable(): UnionValidator<T | null>;
get nullish(): UnionValidator<T | null | undefined>;
or<O>(...predicates: readonly BaseValidator<O>[]): UnionValidator<T | O>;
protected clone(): this;
protected handle(value: unknown): Result<T, ValidationError | CombinedError>;
}
type ObjectConstraintName = `s.object(T.when)`;
type WhenKey = PropertyKey | PropertyKey[];
interface WhenOptions<T extends BaseValidator<any>, Key extends WhenKey> {
is?: boolean | ((value: Key extends Array<any> ? any[] : any) => boolean);
then: (predicate: T) => T;
otherwise?: (predicate: T) => T;
}
declare class ExpectedConstraintError<T = unknown> extends BaseConstraintError<T> {
readonly expected: string;
constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: string);
toJSON(): {
name: string;
constraint: ConstraintErrorNames;
given: T;
expected: string;
};
protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;
}
type TypedArrayConstraintName = `s.typedArray(T).${'byteLength' | 'length'}${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual' | 'Range' | 'RangeInclusive' | 'RangeExclusive'}`;
declare function typedArrayByteLengthLessThan<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayByteLengthLessThanOrEqual<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayByteLengthGreaterThan<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayByteLengthGreaterThanOrEqual<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayByteLengthEqual<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayByteLengthNotEqual<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayByteLengthRange<T extends TypedArray>(start: number, endBefore: number): IConstraint<T>;
declare function typedArrayByteLengthRangeInclusive<T extends TypedArray>(start: number, end: number): {
run(input: T): Result<T, Error> | Result<unknown, ExpectedConstraintError<T>>;
};
declare function typedArrayByteLengthRangeExclusive<T extends TypedArray>(startAfter: number, endBefore: number): IConstraint<T>;
declare function typedArrayLengthLessThan<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayLengthLessThanOrEqual<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayLengthGreaterThan<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayLengthGreaterThanOrEqual<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayLengthEqual<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayLengthNotEqual<T extends TypedArray>(value: number): IConstraint<T>;
declare function typedArrayLengthRange<T extends TypedArray>(start: number, endBefore: number): IConstraint<T>;
declare function typedArrayLengthRangeInclusive<T extends TypedArray>(start: number, end: number): IConstraint<T>;
declare function typedArrayLengthRangeExclusive<T extends TypedArray>(startAfter: number, endBefore: number): IConstraint<T>;
type ConstraintErrorNames = TypedArrayConstraintName | ArrayConstraintName | BigIntConstraintName | BooleanConstraintName | DateConstraintName | NumberConstraintName | ObjectConstraintName | StringConstraintName;
declare abstract class BaseConstraintError<T = unknown> extends BaseError {
readonly constraint: ConstraintErrorNames;
readonly given: T;
constructor(constraint: ConstraintErrorNames, message: string, given: T);
}
interface IConstraint<Input, Return extends Input = Input> {
run(input: Input, parent?: any): Result<Return, BaseConstraintError<Input>>;
}
declare class ArrayValidator<T extends unknown[], I = T[number]> extends BaseValidator<T> {
private readonly validator;
constructor(validator: BaseValidator<I>, constraints?: readonly IConstraint<T>[]);
lengthLessThan<N extends number>(length: N): ArrayValidator<ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, N>]>>>;
lengthLessThanOrEqual<N extends number>(length: N): ArrayValidator<ExpandSmallerTuples<[...Tuple<I, N>]>>;
lengthGreaterThan<N extends number>(length: N): ArrayValidator<[...Tuple<I, N>, I, ...T]>;
lengthGreaterThanOrEqual<N extends number>(length: N): ArrayValidator<[...Tuple<I, N>, ...T]>;
lengthEqual<N extends number>(length: N): ArrayValidator<[...Tuple<I, N>]>;
lengthNotEqual(length: number): ArrayValidator<[...T]>;
lengthRange<S extends number, E extends number>(start: S, endBefore: E): ArrayValidator<Exclude<ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, E>]>>, ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, S>]>>>>;
lengthRangeInclusive<S extends number, E extends number>(startAt: S, endAt: E): ArrayValidator<Exclude<ExpandSmallerTuples<[...Tuple<I, E>]>, ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, S>]>>>>;
lengthRangeExclusive<S extends number, E extends number>(startAfter: S, endBefore: E): ArrayValidator<Exclude<ExpandSmallerTuples<UnshiftTuple<[...Tuple<I, E>]>>, ExpandSmallerTuples<[...Tuple<T, S>]>>>;
get unique(): this;
protected clone(): this;
protected handle(values: unknown): Result<T, ValidationError | CombinedPropertyError>;
}
declare abstract class BaseValidator<T> {
description?: string;
protected parent?: object;
protected constraints: readonly IConstraint<T>[];
protected isValidationEnabled: boolean | (() => boolean) | null;
constructor(constraints?: readonly IConstraint<T>[]);
setParent(parent: object): this;
get optional(): UnionValidator<T | undefined>;
get nullable(): UnionValidator<T | null>;
get nullish(): UnionValidator<T | null | undefined>;
get array(): ArrayValidator<T[]>;
get set(): SetValidator<T>;
or<O>(...predicates: readonly BaseValidator<O>[]): UnionValidator<T | O>;
transform(cb: (value: T) => T): this;
transform<O>(cb: (value: T) => O): BaseValidator<O>;
reshape(cb: (input: T) => Result<T>): this;
reshape<R extends Result<unknown>, O = InferResultType<R>>(cb: (input: T) => R): BaseValidator<O>;
default(value: Exclude<T, undefined> | (() => Exclude<T, undefined>)): DefaultValidator<Exclude<T, undefined>>;
when<Key extends WhenKey, This extends BaseValidator<any> = this>(key: Key, options: WhenOptions<This, Key>): this;
describe(description: string): this;
run(value: unknown): Result<T, BaseError>;
parse<R extends T = T>(value: unknown): R;
is<R extends T = T>(value: unknown): value is R;
/**
* Sets if the validator should also run constraints or just do basic checks.
* @param isValidationEnabled Whether this validator should be enabled or disabled. You can pass boolean or a function returning boolean which will be called just before parsing.
* Set to `null` to go off of the global configuration.
*/
setValidationEnabled(isValidationEnabled: boolean | (() => boolean) | null): this;
getValidationEnabled(): boolean | null;
protected get shouldRunConstraints(): boolean;
protected clone(): this;
protected abstract handle(value: unknown): Result<T, ValidatorError>;
protected addConstraint(constraint: IConstraint<T>): this;
}
type ValidatorError = ValidationError | CombinedError | CombinedPropertyError | UnknownEnumValueError;
type Constructor<T> = (new (...args: readonly any[]) => T) | (abstract new (...args: readonly any[]) => T);
type Type<V> = V extends BaseValidator<infer T> ? T : never;
/**
* @deprecated Use `object` instead.
*/
type NonNullObject = {} & object;
/**
* @deprecated This type is no longer used and will be removed in the next major version.
*/
type PickDefined<T> = {
[K in keyof T as undefined extends T[K] ? never : K]: T[K];
};
/**
* @deprecated This type is no longer used and will be removed in the next major version.
*/
type PickUndefinedMakeOptional<T> = {
[K in keyof T as undefined extends T[K] ? K : never]+?: Exclude<T[K], undefined>;
};
type FilterDefinedKeys<TObj extends object> = Exclude<{
[TKey in keyof TObj]: undefined extends TObj[TKey] ? never : TKey;
}[keyof TObj], undefined>;
type UndefinedToOptional<T extends object> = Pick<T, FilterDefinedKeys<T>> & {
[k in keyof Omit<T, FilterDefinedKeys<T>>]?: Exclude<T[k], undefined>;
};
type MappedObjectValidator<T> = {
[key in keyof T]: BaseValidator<T[key]>;
};
/**
* An alias of {@link ObjectValidator} with a name more common among object validation libraries.
* This is the type of a schema after using `s.object({ ... })`
* @example
* ```typescript
* import { s, SchemaOf } from '@sapphire/shapeshift';
*
* interface IIngredient {
* ingredientId: string | undefined;
* name: string | undefined;
* }
*
* interface IInstruction {
* instructionId: string | undefined;
* message: string | undefined;
* }
*
* interface IRecipe {
* recipeId: string | undefined;
* title: string;
* description: string;
* instructions: IInstruction[];
* ingredients: IIngredient[];
* }
*
* type InstructionSchemaType = SchemaOf<IInstruction>;
* // Expected Type: ObjectValidator<IInstruction>
*
* type IngredientSchemaType = SchemaOf<IIngredient>;
* // Expected Type: ObjectValidator<IIngredient>
*
* type RecipeSchemaType = SchemaOf<IRecipe>;
* // Expected Type: ObjectValidator<IRecipe>
*
* const instructionSchema: InstructionSchemaType = s.object({
* instructionId: s.string.optional,
* message: s.string
* });
*
* const ingredientSchema: IngredientSchemaType = s.object({
* ingredientId: s.string.optional,
* name: s.string
* });
*
* const recipeSchema: RecipeSchemaType = s.object({
* recipeId: s.string.optional,
* title: s.string,
* description: s.string,
* instructions: s.array(instructionSchema),
* ingredients: s.array(ingredientSchema)
* });
* ```
*/
type SchemaOf<T extends object> = ObjectValidator<T>;
/**
* Infers the type of a schema object given `typeof schema`.
* The schema has to extend {@link ObjectValidator}.
* @example
* ```typescript
* import { InferType, s } from '@sapphire/shapeshift';
*
* const schema = s.object({
* foo: s.string,
* bar: s.number,
* baz: s.boolean,
* qux: s.bigint,
* quux: s.date
* });
*
* type Inferredtype = InferType<typeof schema>;
* // Expected type:
* // type Inferredtype = {
* // foo: string;
* // bar: number;
* // baz: boolean;
* // qux: bigint;
* // quux: Date;
* // };
* ```
*/
type InferType<T extends ObjectValidator<any>> = T extends ObjectValidator<any, infer U> ? U : never;
type InferResultType<T extends Result<any>> = T extends Result<infer U> ? U : never;
type UnwrapTuple<T extends [...any[]]> = T extends [infer Head, ...infer Tail] ? [Unwrap<Head>, ...UnwrapTuple<Tail>] : [];
type Unwrap<T> = T extends BaseValidator<infer V> ? V : never;
type UnshiftTuple<T extends [...any[]]> = T extends [T[0], ...infer Tail] ? Tail : never;
type ExpandSmallerTuples<T extends [...any[]]> = T extends [T[0], ...infer Tail] ? T | ExpandSmallerTuples<Tail> : [];
type Shift<A extends Array<any>> = ((...args: A) => void) extends (...args: [A[0], ...infer R]) => void ? R : never;
type GrowExpRev<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : GrowExpRev<[...A, ...P[0]][N] extends undefined ? [...A, ...P[0]] : A, N, Shift<P>>;
type GrowExp<A extends Array<any>, N extends number, P extends Array<Array<any>>> = [...A, ...A][N] extends undefined ? GrowExp<[...A, ...A], N, [A, ...P]> : GrowExpRev<A, N, P>;
type Tuple<T, N extends number> = N extends number ? number extends N ? Array<T> : N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T], N, [[]]> : never;
declare class LazyValidator<T extends BaseValidator<unknown>, R = Unwrap<T>> extends BaseValidator<R> {
private readonly validator;
constructor(validator: (value: unknown) => T, constraints?: readonly IConstraint<R>[]);
protected clone(): this;
protected handle(values: unknown): Result<R, ValidatorError>;
}
declare class Shapes {
get string(): StringValidator<string>;
get number(): NumberValidator<number>;
get bigint(): BigIntValidator<bigint>;
get boolean(): BooleanValidator<boolean>;
get date(): DateValidator;
object<T extends object>(shape: MappedObjectValidator<T>): ObjectValidator<T, UndefinedToOptional<T>>;
get undefined(): BaseValidator<undefined>;
get null(): BaseValidator<null>;
get nullish(): NullishValidator;
get any(): PassthroughValidator<any>;
get unknown(): PassthroughValidator<unknown>;
get never(): NeverValidator;
enum<T>(...values: readonly T[]): UnionValidator<T>;
nativeEnum<T extends NativeEnumLike>(enumShape: T): NativeEnumValidator<T>;
literal<T>(value: T): BaseValidator<T>;
instance<T>(expected: Constructor<T>): InstanceValidator<T>;
union<T extends [...BaseValidator<any>[]]>(...validators: [...T]): UnionValidator<Unwrap<T[number]>>;
array<T>(validator: BaseValidator<T[][number]>): ArrayValidator<T[], T[][number]>;
array<T extends unknown[]>(validator: BaseValidator<T[number]>): ArrayValidator<T, T[number]>;
typedArray<T extends TypedArray>(type?: TypedArrayName): TypedArrayValidator<T>;
get int8Array(): TypedArrayValidator<Int8Array>;
get uint8Array(): TypedArrayValidator<Uint8Array>;
get uint8ClampedArray(): TypedArrayValidator<Uint8ClampedArray>;
get int16Array(): TypedArrayValidator<Int16Array>;
get uint16Array(): TypedArrayValidator<Uint16Array>;
get int32Array(): TypedArrayValidator<Int32Array>;
get uint32Array(): TypedArrayValidator<Uint32Array>;
get float32Array(): TypedArrayValidator<Float32Array>;
get float64Array(): TypedArrayValidator<Float64Array>;
get bigInt64Array(): TypedArrayValidator<BigInt64Array>;
get bigUint64Array(): TypedArrayValidator<BigUint64Array>;
tuple<T extends [...BaseValidator<any>[]]>(validators: [...T]): TupleValidator<UnwrapTuple<T>>;
set<T>(validator: BaseValidator<T>): SetValidator<T>;
record<T>(validator: BaseValidator<T>): RecordValidator<T>;
map<T, U>(keyValidator: BaseValidator<T>, valueValidator: BaseValidator<U>): MapValidator<T, U>;
lazy<T extends BaseValidator<unknown>>(validator: (value: unknown) => T): LazyValidator<T, Unwrap<T>>;
}
/**
* Sets whether validators should run on the input, or if the input should be passed through.
* @param enabled Whether validation should be done on inputs
*/
declare function setGlobalValidationEnabled(enabled: boolean): void;
/**
* @returns Whether validation is enabled
*/
declare function getGlobalValidationEnabled(): boolean;
declare const s: Shapes;
export { ArrayConstraintName, ArrayValidator, BaseConstraintError, BaseError, BaseValidator, BigIntConstraintName, BigIntValidator, BooleanConstraintName, BooleanValidator, CombinedError, CombinedPropertyError, ConstraintErrorNames, Constructor, DateConstraintName, DateValidator, DefaultValidator, ExpandSmallerTuples, ExpectedConstraintError, ExpectedValidationError, GrowExp, GrowExpRev, IConstraint, InferResultType, InferType, InstanceValidator, LiteralValidator, MapValidator, MappedObjectValidator, MissingPropertyError, MultiplePossibilitiesConstraintError, NativeEnumLike, NativeEnumValidator, NeverValidator, NonNullObject, NullishValidator, NumberConstraintName, NumberValidator, ObjectValidator, ObjectValidatorStrategy, PassthroughValidator, PickDefined, PickUndefinedMakeOptional, RecordValidator, Result, SchemaOf, SetValidator, Shapes, Shift, StringConstraintName, StringDomain, StringProtocol, StringUuidOptions, StringValidator, Tuple, TupleValidator, Type, TypedArrayConstraintName, TypedArrayValidator, UUIDVersion, UndefinedToOptional, UnionValidator, UnknownEnumValueError, UnknownPropertyError, UnshiftTuple, Unwrap, UnwrapTuple, UrlOptions, ValidationError, ValidatorError, arrayLengthEqual, arrayLengthGreaterThan, arrayLengthGreaterThanOrEqual, arrayLengthLessThan, arrayLengthLessThanOrEqual, arrayLengthNotEqual, arrayLengthRange, arrayLengthRangeExclusive, arrayLengthRangeInclusive, bigintDivisibleBy, bigintEqual, bigintGreaterThan, bigintGreaterThanOrEqual, bigintLessThan, bigintLessThanOrEqual, bigintNotEqual, booleanFalse, booleanTrue, customInspectSymbol, customInspectSymbolStackLess, dateEqual, dateGreaterThan, dateGreaterThanOrEqual, dateInvalid, dateLessThan, dateLessThanOrEqual, dateNotEqual, dateValid, getGlobalValidationEnabled, numberDivisibleBy, numberEqual, numberFinite, numberGreaterThan, numberGreaterThanOrEqual, numberInt, numberLessThan, numberLessThanOrEqual, numberNaN, numberNotEqual, numberNotNaN, numberSafeInt, s, setGlobalValidationEnabled, stringEmail, stringIp, stringLengthEqual, stringLengthGreaterThan, stringLengthGreaterThanOrEqual, stringLengthLessThan, stringLengthLessThanOrEqual, stringLengthNotEqual, stringRegex, stringUrl, stringUuid, typedArrayByteLengthEqual, typedArrayByteLengthGreaterThan, typedArrayByteLengthGreaterThanOrEqual, typedArrayByteLengthLessThan, typedArrayByteLengthLessThanOrEqual, typedArrayByteLengthNotEqual, typedArrayByteLengthRange, typedArrayByteLengthRangeExclusive, typedArrayByteLengthRangeInclusive, typedArrayLengthEqual, typedArrayLengthGreaterThan, typedArrayLengthGreaterThanOrEqual, typedArrayLengthLessThan, typedArrayLengthLessThanOrEqual, typedArrayLengthNotEqual, typedArrayLengthRange, typedArrayLengthRangeExclusive, typedArrayLengthRangeInclusive };

4174
node_modules/@sapphire/shapeshift/dist/index.global.js generated vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

2242
node_modules/@sapphire/shapeshift/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@sapphire/shapeshift/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2219
node_modules/@sapphire/shapeshift/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load diff

1
node_modules/@sapphire/shapeshift/dist/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

125
node_modules/@sapphire/shapeshift/package.json generated vendored Normal file
View file

@ -0,0 +1,125 @@
{
"name": "@sapphire/shapeshift",
"version": "3.9.2",
"description": "Blazing fast input validation and transformation ⚡",
"author": "@sapphire",
"license": "MIT",
"main": "dist/index.js",
"module": "dist/index.mjs",
"browser": "dist/index.global.js",
"unpkg": "dist/index.global.js",
"types": "dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"sideEffects": false,
"homepage": "https://www.sapphirejs.dev",
"scripts": {
"lint": "eslint src tests --ext ts --fix",
"format": "prettier --write \"{src,tests}/**/*.ts\"",
"docs": "typedoc-json-parser",
"test": "vitest run",
"build": "tsup",
"clean": "node scripts/clean.mjs",
"typecheck": "tsc -p tsconfig.eslint.json",
"bump": "cliff-jumper",
"check-update": "cliff-jumper --dry-run",
"_postinstall": "husky install .github/husky",
"prepack": "yarn build && pinst --disable",
"postpack": "pinst --enable"
},
"dependencies": {
"fast-deep-equal": "^3.1.3",
"lodash": "^4.17.21"
},
"devDependencies": {
"@commitlint/cli": "^17.6.5",
"@commitlint/config-conventional": "^17.6.5",
"@favware/cliff-jumper": "^2.0.1",
"@favware/npm-deprecate": "^1.0.7",
"@sapphire/eslint-config": "^4.4.2",
"@sapphire/prettier-config": "^1.4.5",
"@sapphire/ts-config": "^4.0.0",
"@types/jsdom": "^21.1.1",
"@types/lodash": "^4.14.195",
"@types/node": "^18.16.16",
"@typescript-eslint/eslint-plugin": "^5.59.8",
"@typescript-eslint/parser": "^5.59.8",
"@vitest/coverage-c8": "^0.31.4",
"cz-conventional-changelog": "^3.3.0",
"esbuild-plugins-node-modules-polyfill": "^1.0.14",
"eslint": "^8.42.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^4.2.1",
"husky": "^8.0.3",
"jsdom": "^22.1.0",
"lint-staged": "^13.2.2",
"pinst": "^3.0.0",
"prettier": "^2.8.8",
"pretty-quick": "^3.1.3",
"ts-node": "^10.9.1",
"tsup": "^6.7.0",
"typedoc": "^0.24.7",
"typedoc-json-parser": "^8.1.2",
"typescript": "^5.1.3",
"vite": "^4.3.9",
"vitest": "^0.31.4"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sapphiredev/shapeshift.git"
},
"files": [
"dist/**/*.js*",
"dist/**/*.mjs*",
"dist/**/*.d*"
],
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
},
"keywords": [
"@sapphire/shapeshift",
"shapeshift",
"bot",
"typescript",
"ts",
"yarn",
"sapphire",
"schema",
"validation",
"type-checking",
"checking",
"input-validation",
"runtime-validation",
"ow",
"type-validation",
"zod"
],
"bugs": {
"url": "https://github.com/sapphiredev/shapeshift/issues"
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"lint-staged": {
"*.{mjs,js,ts}": "eslint --fix --ext mjs,js,ts"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"publishConfig": {
"access": "public"
},
"resolutions": {
"ansi-regex": "^5.0.1",
"minimist": "^1.2.8"
},
"packageManager": "yarn@3.6.0"
}

294
node_modules/@sapphire/snowflake/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,294 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@sapphire/snowflake@3.5.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.5.0...@sapphire/snowflake@3.5.1) - (2023-05-12)
## 🏠 Refactor
- **snowflake:** Handle out-of-bounds `increment` correctly (#596) ([b5276d7](https://github.com/sapphiredev/utilities/commit/b5276d7372c33356975a302bafb5ae8aba604431))
# [@sapphire/snowflake@3.5.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.4.3...@sapphire/snowflake@3.5.0) - (2023-05-10)
## 🚀 Features
- **snowflake:** Expose `processId` and `workerId` (#595) ([b873c1c](https://github.com/sapphiredev/utilities/commit/b873c1cc3b30cb54d710a49f7618e125ac1132ad))
# [@sapphire/snowflake@3.4.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.4.1...@sapphire/snowflake@3.4.2) - (2023-04-12)
## 🏠 Refactor
- **Snowflake:** Simplify `compare` logic (#578) ([886254e](https://github.com/sapphiredev/utilities/commit/886254eea2f0cc5e8f63d015acffaf0e61489357))
# [@sapphire/snowflake@3.4.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.4.0...@sapphire/snowflake@3.4.1) - (2023-04-10)
## 🐛 Bug Fixes
- **snowflake:** Ensure strings are never compared with bigints ([22199a5](https://github.com/sapphiredev/utilities/commit/22199a5aa0c6150f46e01bfbe328deecb9f818ba))
- **deps:** Update all non-major dependencies (#577) ([291dd67](https://github.com/sapphiredev/utilities/commit/291dd6783e57d8f075ce566218ba076ef6c4bbbd))
- **deps:** Update all non-major dependencies (#545) ([40ca040](https://github.com/sapphiredev/utilities/commit/40ca040a21d8a0949682051a3a974538183a400e))
- **deps:** Update all non-major dependencies (#544) ([cc78f17](https://github.com/sapphiredev/utilities/commit/cc78f17390c7f3db08af92bf46a5a70a9c11dd5f))
## 🧪 Testing
- Cleanup tests ([aec1bb2](https://github.com/sapphiredev/utilities/commit/aec1bb290d0f3c00a1ae4f4c86302ebbb161d348))
# [@sapphire/snowflake@3.4.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.3.0...@sapphire/snowflake@3.4.0) - (2022-12-27)
## 🐛 Bug Fixes
- **deps:** Update all non-major dependencies (#532) ([8033d1f](https://github.com/sapphiredev/utilities/commit/8033d1ff7a5a1974134c61f424f171cccb2915e1))
## 📝 Documentation
- Add @06000208 as a contributor ([fa3349e](https://github.com/sapphiredev/utilities/commit/fa3349e55ce4ad008785211dec7bf8e2b5d933df))
## 🚀 Features
- **snowflake:** Added `Snowflake.compare` (#531) ([6accd6d](https://github.com/sapphiredev/utilities/commit/6accd6d15eab12e312034f8ef43cff032835c972))
# [@sapphire/snowflake@3.3.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.2.2...@sapphire/snowflake@3.3.0) - (2022-12-03)
## 🏠 Refactor
- Split `@sapphire/time-utilities` into 4 sub-packages (#462) ([574299a](https://github.com/sapphiredev/utilities/commit/574299a99e658f6500a2a7efa587a0919b2d1313))
## 🐛 Bug Fixes
- **snowflake:** TwitterSnowflake using incorrect epoch (#522) ([4ad4117](https://github.com/sapphiredev/utilities/commit/4ad41170488161b2998bd72da5a8b7fea10539a0))
- **deps:** Update all non-major dependencies (#514) ([21b07d5](https://github.com/sapphiredev/utilities/commit/21b07d5db529a0d982647a60de98e46f36f1ac93))
- **deps:** Update all non-major dependencies (#505) ([6178296](https://github.com/sapphiredev/utilities/commit/617829649e1e4deeee02b14533b5377cd5bc1fb3))
- **deps:** Update all non-major dependencies (#466) ([dc08606](https://github.com/sapphiredev/utilities/commit/dc08606a97154e47c65536123ac5f8b1262f7bd2))
- **deps:** Update all non-major dependencies ([e20f299](https://github.com/sapphiredev/utilities/commit/e20f29906e83cee000aaba9c6827e3bec5173d28))
- **deps:** Update all non-major dependencies ([2308bd7](https://github.com/sapphiredev/utilities/commit/2308bd74356b6b2e0c12995b25f4d8ade4803fe9))
- **deps:** Update all non-major dependencies ([84af0db](https://github.com/sapphiredev/utilities/commit/84af0db2db749223b036aa99fe19a2e9af5681c6))
- **deps:** Update all non-major dependencies ([50cd8de](https://github.com/sapphiredev/utilities/commit/50cd8dea593b6f5ae75571209456b3421e2ca59a))
## 📝 Documentation
- Add @didinele as a contributor ([42ef7b6](https://github.com/sapphiredev/utilities/commit/42ef7b656c48fd0e720119db1d622c8bba2791e9))
- Add @goestav as a contributor ([0e56a92](https://github.com/sapphiredev/utilities/commit/0e56a92a4e2d0942bfa207f81a8cb03b32312034))
- Add @CitTheDev as a contributor ([34169ea](https://github.com/sapphiredev/utilities/commit/34169eae1dc0476ccf5a6c4f36e28602a204829e))
- Add @legendhimslef as a contributor ([059b6f1](https://github.com/sapphiredev/utilities/commit/059b6f1ab5362d46d58624d06c1aa39192b0716f))
- Add @r-priyam as a contributor ([fb278ba](https://github.com/sapphiredev/utilities/commit/fb278bacf627ec6fc88752eafeb12df5f3177a2c))
- Change name of @kyranet (#451) ([df4fdef](https://github.com/sapphiredev/utilities/commit/df4fdefce18659975a4ebc224723638507d02d35))
- Update @RealShadowNova as a contributor ([a869ba0](https://github.com/sapphiredev/utilities/commit/a869ba0abfad041610b9115187d426aebe671af6))
- Add @muchnameless as a contributor ([a1221fe](https://github.com/sapphiredev/utilities/commit/a1221fea68506e99591d5d00ec552a07c26833f9))
- Add @enxg as a contributor ([d2382f0](https://github.com/sapphiredev/utilities/commit/d2382f04e3909cb4ad11798a0a10e683f6cf5383))
- Add @EvolutionX-10 as a contributor ([efc3a32](https://github.com/sapphiredev/utilities/commit/efc3a320a72ae258996dd62866d206c33f8d4961))
- Add @MajesticString as a contributor ([295b3e9](https://github.com/sapphiredev/utilities/commit/295b3e9849a4b0fe64074bae02f6426378a303c3))
- Add @Mzato0001 as a contributor ([c790ef2](https://github.com/sapphiredev/utilities/commit/c790ef25df2d7e22888fa9f8169167aa555e9e19))
## 🚀 Features
- **utilities:** Add possibility to import single functions by appending them to the import path. (#454) ([374c145](https://github.com/sapphiredev/utilities/commit/374c145a5dd329cfc1a867ed6720abf408683a88))
## 🧪 Testing
- Migrate to vitest (#380) ([075ec73](https://github.com/sapphiredev/utilities/commit/075ec73c7a8e3374fad3ada612d37eb4ac36ec8d))
# [@sapphire/snowflake@3.2.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.2.1...@sapphire/snowflake@3.2.2) - (2022-04-24)
## Bug Fixes
- Fix typo (#333) ([ae2f257](https://github.com/sapphiredev/utilities/commit/ae2f25766d5985735f2d9b257eebd27cdc8a7c52))
## Documentation
- Add @NotKaskus as a contributor ([00da8f1](https://github.com/sapphiredev/utilities/commit/00da8f199137b9277119823f322d1f2d168d928a))
- Add @imranbarbhuiya as a contributor ([fb674c2](https://github.com/sapphiredev/utilities/commit/fb674c2c5594d41e71662263553dcb4bac9e37f4))
- Add @axisiscool as a contributor ([ce1aa31](https://github.com/sapphiredev/utilities/commit/ce1aa316871a88d3663efbdf2a42d3d8dfe6a27f))
- Add @dhruv-kaushikk as a contributor ([ebbf43f](https://github.com/sapphiredev/utilities/commit/ebbf43f63617daba96e72c50a234bf8b64f6ddc4))
- Add @Commandtechno as a contributor ([f1d69fa](https://github.com/sapphiredev/utilities/commit/f1d69fabe1ee0abe4be08b19e63dbec03102f7ce))
- Fix typedoc causing OOM crashes ([63ba41c](https://github.com/sapphiredev/utilities/commit/63ba41c4b6678554b1c7043a22d3296db4f59360))
## [3.2.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.2.0...@sapphire/snowflake@3.2.1) (2022-04-01)
**Note:** Version bump only for package @sapphire/snowflake
# [3.2.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.1.0...@sapphire/snowflake@3.2.0) (2022-03-06)
### Bug Fixes
- **snowflake:** fixed the examples for `DiscordSnowflake` and `TwitterSnowflake` ([#282](https://github.com/sapphiredev/utilities/issues/282)) ([2e5ed7f](https://github.com/sapphiredev/utilities/commit/2e5ed7fdadccf261967c45f73d0dc78e2497eed3))
### Features
- allow module: NodeNext ([#306](https://github.com/sapphiredev/utilities/issues/306)) ([9dc6dd6](https://github.com/sapphiredev/utilities/commit/9dc6dd619efab879bb2b0b3c9e64304e10a67ed6))
- **ts-config:** add multi-config structure ([#281](https://github.com/sapphiredev/utilities/issues/281)) ([b5191d7](https://github.com/sapphiredev/utilities/commit/b5191d7f2416dc5838590c4ff221454925553e37))
# [3.1.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.0.1...@sapphire/snowflake@3.1.0) (2022-01-28)
### Features
- change build system to tsup ([#270](https://github.com/sapphiredev/utilities/issues/270)) ([365a53a](https://github.com/sapphiredev/utilities/commit/365a53a5517a01a0926cf28a83c96b63f32ed9f8))
## [3.0.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.0.0...@sapphire/snowflake@3.0.1) (2022-01-10)
**Note:** Version bump only for package @sapphire/snowflake
# [3.0.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.4...@sapphire/snowflake@3.0.0) (2021-12-08)
### Bug Fixes
- **snowflake:** remove env-based defaults ([#232](https://github.com/sapphiredev/utilities/issues/232)) ([10408e4](https://github.com/sapphiredev/utilities/commit/10408e4d3677e91490d967c3d89bf9575946090b))
### Features
- **Snowflake:** rework entire package ([#231](https://github.com/sapphiredev/utilities/issues/231)) ([1d02f1a](https://github.com/sapphiredev/utilities/commit/1d02f1a2f520efcbc194c3992af593d0e493873b))
### BREAKING CHANGES
- **Snowflake:** Renamed `processID` to `processId`
- **Snowflake:** Renamed `workerID` to `workerId`
- **Snowflake:** `workerId` now defaults to 0n instead of 1n
- **Snowflake:** `DiscordSnowflake` is not longer a class, but a constructed Snowflake
- **Snowflake:** `TwitterSnowflake` is not longer a class, but a constructed Snowflake
## [2.1.4](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.3...@sapphire/snowflake@2.1.4) (2021-11-06)
**Note:** Version bump only for package @sapphire/snowflake
## [2.1.3](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.2...@sapphire/snowflake@2.1.3) (2021-10-26)
**Note:** Version bump only for package @sapphire/snowflake
## [2.1.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.1...@sapphire/snowflake@2.1.2) (2021-10-17)
### Bug Fixes
- allow more node & npm versions in engines field ([5977d2a](https://github.com/sapphiredev/utilities/commit/5977d2a30a4b2cfdf84aff3f33af03ffde1bbec5))
## [2.1.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.0...@sapphire/snowflake@2.1.1) (2021-10-11)
**Note:** Version bump only for package @sapphire/snowflake
# [2.1.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.0.0...@sapphire/snowflake@2.1.0) (2021-10-04)
### Bug Fixes
- **snowflake:** fixed snowflake generating duplicate IDs ([#166](https://github.com/sapphiredev/utilities/issues/166)) ([f0cf4ad](https://github.com/sapphiredev/utilities/commit/f0cf4ad6bc0b8b2447499ca36581d2b453e52715))
### Features
- **snowflake:** set minimum NodeJS to v14 ([11a61c7](https://github.com/sapphiredev/utilities/commit/11a61c72bc29e683f9a4492815db3db094103bbc))
# [2.0.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.6...@sapphire/snowflake@2.0.0) (2021-07-17)
### Code Refactoring
- **rateLimits:** rewrite all of it ([#130](https://github.com/sapphiredev/utilities/issues/130)) ([320778c](https://github.com/sapphiredev/utilities/commit/320778ca65cbf3591bd1ce0b1f2eb430693eef9a))
### BREAKING CHANGES
- **rateLimits:** Removed `Bucket`
## [1.3.6](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.5...@sapphire/snowflake@1.3.6) (2021-07-11)
**Note:** Version bump only for package @sapphire/snowflake
## [1.3.5](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.4...@sapphire/snowflake@1.3.5) (2021-06-27)
**Note:** Version bump only for package @sapphire/snowflake
## [1.3.4](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.3...@sapphire/snowflake@1.3.4) (2021-06-19)
### Bug Fixes
- **doc:** change `[@link](https://github.com/link)` to `[@linkplain](https://github.com/linkplain)` for support in VSCode IntelliSense ([703d460](https://github.com/sapphiredev/utilities/commit/703d4605b547a8787aff62d6f1054ea26dfd9d1c))
- **docs:** update-tsdoc-for-vscode-may-2021 ([#126](https://github.com/sapphiredev/utilities/issues/126)) ([f8581bf](https://github.com/sapphiredev/utilities/commit/f8581bfe97a1b2f8aac3a3d3ed342d8ba92d730b))
## [1.3.3](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.2...@sapphire/snowflake@1.3.3) (2021-06-06)
### Bug Fixes
- remove peer deps, update dev deps, update READMEs ([#124](https://github.com/sapphiredev/utilities/issues/124)) ([67256ed](https://github.com/sapphiredev/utilities/commit/67256ed43b915b02a8b5c68230ba82d6210c5032))
- **snowflake:** fixed parsing for timestamps as Date objects ([c17a515](https://github.com/sapphiredev/utilities/commit/c17a515b02931cf778ca69913132e8d4558504a1))
## [1.3.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.1...@sapphire/snowflake@1.3.2) (2021-05-20)
### Bug Fixes
- **snowflake:** mark package as side effect free ([6a9bafc](https://github.com/sapphiredev/utilities/commit/6a9bafc24caba4b0ebbdd6896ac245ae6d60dede))
## [1.3.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.0...@sapphire/snowflake@1.3.1) (2021-05-02)
### Bug Fixes
- drop the `www.` from the SapphireJS URL ([494d89f](https://github.com/sapphiredev/utilities/commit/494d89ffa04f78c195b93d7905b3232884f7d7e2))
- update all the SapphireJS URLs from `.com` to `.dev` ([f59b46d](https://github.com/sapphiredev/utilities/commit/f59b46d1a0ebd39cad17b17d71cd3b9da808d5fd))
# [1.3.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.8...@sapphire/snowflake@1.3.0) (2021-04-21)
### Features
- add @sapphire/embed-jsx ([#100](https://github.com/sapphiredev/utilities/issues/100)) ([7277a23](https://github.com/sapphiredev/utilities/commit/7277a236015236ed8e81b7882875410facc4ce17))
## [1.2.8](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.7...@sapphire/snowflake@1.2.8) (2021-04-19)
### Bug Fixes
- change all Sapphire URLs from "project"->"community" & use our domain where applicable 👨‍🌾🚜 ([#102](https://github.com/sapphiredev/utilities/issues/102)) ([835b408](https://github.com/sapphiredev/utilities/commit/835b408e8e57130c3787aca2e32613346ff23e4d))
## [1.2.7](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.6...@sapphire/snowflake@1.2.7) (2021-04-03)
**Note:** Version bump only for package @sapphire/snowflake
## [1.2.6](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.5...@sapphire/snowflake@1.2.6) (2021-03-16)
### Bug Fixes
- remove terser from all packages ([#79](https://github.com/sapphiredev/utilities/issues/79)) ([1cfe4e7](https://github.com/sapphiredev/utilities/commit/1cfe4e7c804e62c142495686d2b83b81d0026c02))
## [1.2.5](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.4...@sapphire/snowflake@1.2.5) (2021-02-16)
**Note:** Version bump only for package @sapphire/snowflake
## [1.2.4](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.3...@sapphire/snowflake@1.2.4) (2021-01-16)
**Note:** Version bump only for package @sapphire/snowflake
## [1.2.3](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.2...@sapphire/snowflake@1.2.3) (2021-01-01)
**Note:** Version bump only for package @sapphire/snowflake
## [1.2.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.1...@sapphire/snowflake@1.2.2) (2020-12-26)
**Note:** Version bump only for package @sapphire/snowflake
## [1.2.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.0...@sapphire/snowflake@1.2.1) (2020-12-22)
**Note:** Version bump only for package @sapphire/snowflake
# [1.2.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.1.0...@sapphire/snowflake@1.2.0) (2020-11-15)
### Bug Fixes
- **snowflake:** pass keep_classnames to terser ([76ea062](https://github.com/sapphiredev/utilities/commit/76ea062d07000b169d9781f1a199b85ad3db0ba6))
- **snowflake:** pass keep_fnames to terser ([b52aa76](https://github.com/sapphiredev/utilities/commit/b52aa764d8b02535496e0ceea3204a37552ce3d1))
### Features
- added time-utilities package ([#26](https://github.com/sapphiredev/utilities/issues/26)) ([f17a333](https://github.com/sapphiredev/utilities/commit/f17a3339667a452e8745fad7884272176e5d65e8))
# [1.1.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.0.1...@sapphire/snowflake@1.1.0) (2020-11-04)
### Bug Fixes
- **ratelimits,snowflake,utilities:** fixed esm output target ([9fdab3f](https://github.com/sapphiredev/utilities/commit/9fdab3fca283c8c0b47cc32661c5cf8e0a5e583c))
- **snowflake:** properly specify ESM and CommonJS exports ([e3278e6](https://github.com/sapphiredev/utilities/commit/e3278e6868a4f31d5b2a100710bcbce2b79bc218))
### Features
- added ratelimits package ([#15](https://github.com/sapphiredev/utilities/issues/15)) ([e0ae18c](https://github.com/sapphiredev/utilities/commit/e0ae18c5e1d0ae4e68a982829f1cf251fddfc80d))
## [1.0.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.0.0...@sapphire/snowflake@1.0.1) (2020-09-20)
**Note:** Version bump only for package @sapphire/snowflake
# 1.0.0 (2020-09-05)
### Features
- implement snowflake ([5ba4e2d](https://github.com/sapphiredev/utilities/commit/5ba4e2d82557dd4ff60ffe891a7b46e46373bea2))
- **decorators:** add decorators package ([#4](https://github.com/sapphiredev/utilities/issues/4)) ([677b3e5](https://github.com/sapphiredev/utilities/commit/677b3e59d5c6160cbe6fb410821cadd7c0f00e3c))

170
node_modules/@sapphire/snowflake/README.md generated vendored Normal file
View file

@ -0,0 +1,170 @@
<div align="center">
![Sapphire Logo](https://raw.githubusercontent.com/sapphiredev/assets/main/banners/SapphireCommunity.png)
# @sapphire/snowflake
**Deconstruct and generate snowflake IDs using BigInts.**
[![GitHub](https://img.shields.io/github/license/sapphiredev/utilities)](https://github.com/sapphiredev/utilities/blob/main/LICENSE.md)
[![codecov](https://codecov.io/gh/sapphiredev/utilities/branch/main/graph/badge.svg?token=OEGIV6RFDO)](https://codecov.io/gh/sapphiredev/utilities)
[![npm bundle size](https://img.shields.io/bundlephobia/min/@sapphire/snowflake?logo=webpack&style=flat-square)](https://bundlephobia.com/result?p=@sapphire/snowflake)
[![npm](https://img.shields.io/npm/v/@sapphire/snowflake?color=crimson&logo=npm&style=flat-square)](https://www.npmjs.com/package/@sapphire/snowflake)
</div>
**Table of Contents**
- [Description](#description)
- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
- [Constructing snowflakes](#constructing-snowflakes)
- [Snowflakes with custom epoch](#snowflakes-with-custom-epoch)
- [Snowflake with Discord epoch constant](#snowflake-with-discord-epoch-constant)
- [Snowflake with Twitter epoch constant](#snowflake-with-twitter-epoch-constant)
- [Deconstructing snowflakes](#deconstructing-snowflakes)
- [Snowflakes with custom epoch](#snowflakes-with-custom-epoch-1)
- [Snowflake with Discord epoch constant](#snowflake-with-discord-epoch-constant-1)
- [Snowflake with Twitter epoch constant](#snowflake-with-twitter-epoch-constant-1)
- [Buy us some doughnuts](#buy-us-some-doughnuts)
- [Contributors ✨](#contributors-%E2%9C%A8)
## Description
There is often a need to get a unique ID for entities, be that for Discord messages/channels/servers, keys in a database or many other similar examples. There are many ways to get such a unique ID, and one of those is using a so-called "snowflake". You can read more about snowflake IDs in [this Medium article](https://medium.com/better-programming/uuid-generation-snowflake-identifiers-unique-2aed8b1771bc).
## Features
- Written in TypeScript
- Bundled with esbuild so it can be used in NodeJS and browsers
- Offers CommonJS, ESM and UMD bundles
- Offers predefined epochs for Discord and Twitter
- Fully tested
## Installation
You can use the following command to install this package, or replace `npm install` with your package manager of choice.
```sh
npm install @sapphire/snowflake
```
## Usage
**Note:** While this section uses `require`, the imports match 1:1 with ESM imports. For example `const { Snowflake } = require('@sapphire/snowflake')` equals `import { Snowflake } from '@sapphire/snowflake'`.
### Constructing snowflakes
#### Snowflakes with custom epoch
```typescript
// Import the Snowflake class
const { Snowflake } = require('@sapphire/snowflake');
// Define a custom epoch
const epoch = new Date('2000-01-01T00:00:00.000Z');
// Create an instance of Snowflake
const snowflake = new Snowflake(epoch);
// Generate a snowflake with the given epoch
const uniqueId = snowflake.generate();
```
#### Snowflake with Discord epoch constant
```typescript
// Import the Snowflake class
const { DiscordSnowflake } = require('@sapphire/snowflake');
// Generate a snowflake with Discord's epoch
const uniqueId = DiscordSnowflake.generate();
// Alternatively, you can use the method directly
const uniqueId = DiscordSnowflake.generate();
```
#### Snowflake with Twitter epoch constant
```typescript
// Import the Snowflake class
const { TwitterSnowflake } = require('@sapphire/snowflake');
// Generate a snowflake with Twitter's epoch
const uniqueId = TwitterSnowflake.generate();
// Alternatively, you can use the method directly
const uniqueId = TwitterSnowflake.generate();
```
### Deconstructing snowflakes
#### Snowflakes with custom epoch
```typescript
// Import the Snowflake class
const { Snowflake } = require('@sapphire/snowflake');
// Define a custom epoch
const epoch = new Date('2000-01-01T00:00:00.000Z');
// Create an instance of Snowflake
const snowflake = new Snowflake(epoch);
// Deconstruct a snowflake with the given epoch
const uniqueId = snowflake.deconstruct('3971046231244935168');
```
#### Snowflake with Discord epoch constant
```typescript
// Import the Snowflake class
const { DiscordSnowflake } = require('@sapphire/snowflake');
// Deconstruct a snowflake with Discord's epoch
const uniqueId = DiscordSnowflake.deconstruct('3971046231244935168');
// Alternatively, you can use the method directly
const uniqueId = DiscordSnowflake.deconstruct('3971046231244935168');
```
#### Snowflake with Twitter epoch constant
```typescript
// Import the Snowflake class
const { TwitterSnowflake } = require('@sapphire/snowflake');
// Deconstruct a snowflake with Twitter's epoch
const uniqueId = TwitterSnowflake.deconstruct('3971046231244935168');
// Alternatively, you can use the method directly
const uniqueId = TwitterSnowflake.deconstruct('3971046231244935168');
```
---
## Buy us some doughnuts
Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are amazing people who may still want to donate just to show their appreciation. Thank you very much in advance!
We accept donations through Open Collective, Ko-fi, PayPal, Patreon and GitHub Sponsorships. You can use the buttons below to donate through your method of choice.
| Donate With | Address |
| :-------------: | :-------------------------------------------------: |
| Open Collective | [Click Here](https://sapphirejs.dev/opencollective) |
| Ko-fi | [Click Here](https://sapphirejs.dev/kofi) |
| Patreon | [Click Here](https://sapphirejs.dev/patreon) |
| PayPal | [Click Here](https://sapphirejs.dev/paypal) |
## Contributors
Please make sure to read the [Contributing Guide][contributing] before making a pull request.
Thank you to all the people who already contributed to Sapphire!
<a href="https://github.com/sapphiredev/utilities/graphs/contributors">
<img src="https://contrib.rocks/image?repo=sapphiredev/utilities" />
</a>
[contributing]: https://github.com/sapphiredev/.github/blob/main/.github/CONTRIBUTING.md

202
node_modules/@sapphire/snowflake/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,202 @@
declare const IncrementSymbol: unique symbol;
declare const EpochSymbol: unique symbol;
declare const ProcessIdSymbol: unique symbol;
declare const WorkerIdSymbol: unique symbol;
/**
* The maximum value the `workerId` field accepts in snowflakes.
*/
declare const MaximumWorkerId = 31n;
/**
* The maximum value the `processId` field accepts in snowflakes.
*/
declare const MaximumProcessId = 31n;
/**
* The maximum value the `increment` field accepts in snowflakes.
*/
declare const MaximumIncrement = 4095n;
/**
* A class for generating and deconstructing Twitter snowflakes.
*
* A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}
* is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.
*
* If we have a snowflake `266241948824764416` we can represent it as binary:
* ```
* 64 22 17 12 0
* 000000111011000111100001101001000101000000 00001 00000 000000000000
* number of ms since epoch worker pid increment
* ```
*/
declare class Snowflake {
/**
* Alias for {@link deconstruct}
*/
decode: (id: string | bigint) => DeconstructedSnowflake;
/**
* Internal reference of the epoch passed in the constructor
* @internal
*/
private readonly [EpochSymbol];
/**
* Internal incrementor for generating snowflakes
* @internal
*/
private [IncrementSymbol];
/**
* The process ID that will be used by default in the generate method
* @internal
*/
private [ProcessIdSymbol];
/**
* The worker ID that will be used by default in the generate method
* @internal
*/
private [WorkerIdSymbol];
/**
* @param epoch the epoch to use
*/
constructor(epoch: number | bigint | Date);
/**
* The epoch for this snowflake
*/
get epoch(): bigint;
/**
* Gets the configured process ID
*/
get processId(): bigint;
/**
* Sets the process ID that will be used by default for the {@link generate} method
* @param value The new value, will be coerced to BigInt and masked with `0b11111n`
*/
set processId(value: number | bigint);
/**
* Gets the configured worker ID
*/
get workerId(): bigint;
/**
* Sets the worker ID that will be used by default for the {@link generate} method
* @param value The new value, will be coerced to BigInt and masked with `0b11111n`
*/
set workerId(value: number | bigint);
/**
* Generates a snowflake given an epoch and optionally a timestamp
* @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}
*
* **note** when `increment` is not provided it defaults to the private `increment` of the instance
* @example
* ```typescript
* const epoch = new Date('2000-01-01T00:00:00.000Z');
* const snowflake = new Snowflake(epoch).generate();
* ```
* @returns A unique snowflake
*/
generate({ increment, timestamp, workerId, processId }?: SnowflakeGenerateOptions): bigint;
/**
* Deconstructs a snowflake given a snowflake ID
* @param id the snowflake to deconstruct
* @returns a deconstructed snowflake
* @example
* ```typescript
* const epoch = new Date('2000-01-01T00:00:00.000Z');
* const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');
* ```
*/
deconstruct(id: string | bigint): DeconstructedSnowflake;
/**
* Retrieves the timestamp field's value from a snowflake.
* @param id The snowflake to get the timestamp value from.
* @returns The UNIX timestamp that is stored in `id`.
*/
timestampFrom(id: string | bigint): number;
/**
* Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given
* snowflake in sort order.
* @param a The first snowflake to compare.
* @param b The second snowflake to compare.
* @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.
* @example Sort snowflakes in ascending order
* ```typescript
* const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];
* console.log(ids.sort((a, b) => Snowflake.compare(a, b)));
* // → ['254360814063058944', '737141877803057244', '1056191128120082432'];
* ```
* @example Sort snowflakes in descending order
* ```typescript
* const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];
* console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));
* // → ['1056191128120082432', '737141877803057244', '254360814063058944'];
* ```
*/
static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1;
}
/**
* Options for Snowflake#generate
*/
interface SnowflakeGenerateOptions {
/**
* Timestamp or date of the snowflake to generate
* @default Date.now()
*/
timestamp?: number | bigint | Date;
/**
* The increment to use
* @default 0n
* @remark keep in mind that this bigint is auto-incremented between generate calls
*/
increment?: bigint;
/**
* The worker ID to use, will be truncated to 5 bits (0-31)
* @default 0n
*/
workerId?: bigint;
/**
* The process ID to use, will be truncated to 5 bits (0-31)
* @default 1n
*/
processId?: bigint;
}
/**
* Object returned by Snowflake#deconstruct
*/
interface DeconstructedSnowflake {
/**
* The id in BigInt form
*/
id: bigint;
/**
* The timestamp stored in the snowflake
*/
timestamp: bigint;
/**
* The worker id stored in the snowflake
*/
workerId: bigint;
/**
* The process id stored in the snowflake
*/
processId: bigint;
/**
* The increment stored in the snowflake
*/
increment: bigint;
/**
* The epoch to use in the snowflake
*/
epoch: bigint;
}
/**
* A class for parsing snowflake ids using Discord's snowflake epoch
*
* Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}
*/
declare const DiscordSnowflake: Snowflake;
/**
* A class for parsing snowflake ids using Twitter's snowflake epoch
*
* Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}
*/
declare const TwitterSnowflake: Snowflake;
export { DeconstructedSnowflake, DiscordSnowflake, MaximumIncrement, MaximumProcessId, MaximumWorkerId, Snowflake, SnowflakeGenerateOptions, TwitterSnowflake };

198
node_modules/@sapphire/snowflake/dist/index.global.js generated vendored Normal file
View file

@ -0,0 +1,198 @@
var SapphireSnowflake = (function (exports) {
'use strict';
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/lib/Snowflake.ts
var IncrementSymbol = Symbol("@sapphire/snowflake.increment");
var EpochSymbol = Symbol("@sapphire/snowflake.epoch");
var ProcessIdSymbol = Symbol("@sapphire/snowflake.processId");
var WorkerIdSymbol = Symbol("@sapphire/snowflake.workerId");
var MaximumWorkerId = 0b11111n;
var MaximumProcessId = 0b11111n;
var MaximumIncrement = 0b111111111111n;
var _a, _b, _c, _d;
var Snowflake = class {
/**
* @param epoch the epoch to use
*/
constructor(epoch) {
/**
* Alias for {@link deconstruct}
*/
// eslint-disable-next-line @typescript-eslint/unbound-method
__publicField(this, "decode", this.deconstruct);
/**
* Internal reference of the epoch passed in the constructor
* @internal
*/
__publicField(this, _a);
/**
* Internal incrementor for generating snowflakes
* @internal
*/
__publicField(this, _b, 0n);
/**
* The process ID that will be used by default in the generate method
* @internal
*/
__publicField(this, _c, 1n);
/**
* The worker ID that will be used by default in the generate method
* @internal
*/
__publicField(this, _d, 0n);
this[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);
}
/**
* The epoch for this snowflake
*/
get epoch() {
return this[EpochSymbol];
}
/**
* Gets the configured process ID
*/
get processId() {
return this[ProcessIdSymbol];
}
/**
* Sets the process ID that will be used by default for the {@link generate} method
* @param value The new value, will be coerced to BigInt and masked with `0b11111n`
*/
set processId(value) {
this[ProcessIdSymbol] = BigInt(value) & MaximumProcessId;
}
/**
* Gets the configured worker ID
*/
get workerId() {
return this[WorkerIdSymbol];
}
/**
* Sets the worker ID that will be used by default for the {@link generate} method
* @param value The new value, will be coerced to BigInt and masked with `0b11111n`
*/
set workerId(value) {
this[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId;
}
/**
* Generates a snowflake given an epoch and optionally a timestamp
* @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}
*
* **note** when `increment` is not provided it defaults to the private `increment` of the instance
* @example
* ```typescript
* const epoch = new Date('2000-01-01T00:00:00.000Z');
* const snowflake = new Snowflake(epoch).generate();
* ```
* @returns A unique snowflake
*/
generate({
increment,
timestamp = Date.now(),
workerId = this[WorkerIdSymbol],
processId = this[ProcessIdSymbol]
} = {}) {
if (timestamp instanceof Date)
timestamp = BigInt(timestamp.getTime());
else if (typeof timestamp === "number")
timestamp = BigInt(timestamp);
else if (typeof timestamp !== "bigint") {
throw new TypeError(`"timestamp" argument must be a number, bigint, or Date (received ${typeof timestamp})`);
}
if (typeof increment !== "bigint") {
increment = this[IncrementSymbol];
this[IncrementSymbol] = increment + 1n & MaximumIncrement;
}
return timestamp - this[EpochSymbol] << 22n | (workerId & MaximumWorkerId) << 17n | (processId & MaximumProcessId) << 12n | increment & MaximumIncrement;
}
/**
* Deconstructs a snowflake given a snowflake ID
* @param id the snowflake to deconstruct
* @returns a deconstructed snowflake
* @example
* ```typescript
* const epoch = new Date('2000-01-01T00:00:00.000Z');
* const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');
* ```
*/
deconstruct(id) {
const bigIntId = BigInt(id);
const epoch = this[EpochSymbol];
return {
id: bigIntId,
timestamp: (bigIntId >> 22n) + epoch,
workerId: bigIntId >> 17n & MaximumWorkerId,
processId: bigIntId >> 12n & MaximumProcessId,
increment: bigIntId & MaximumIncrement,
epoch
};
}
/**
* Retrieves the timestamp field's value from a snowflake.
* @param id The snowflake to get the timestamp value from.
* @returns The UNIX timestamp that is stored in `id`.
*/
timestampFrom(id) {
return Number((BigInt(id) >> 22n) + this[EpochSymbol]);
}
/**
* Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given
* snowflake in sort order.
* @param a The first snowflake to compare.
* @param b The second snowflake to compare.
* @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.
* @example Sort snowflakes in ascending order
* ```typescript
* const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];
* console.log(ids.sort((a, b) => Snowflake.compare(a, b)));
* // → ['254360814063058944', '737141877803057244', '1056191128120082432'];
* ```
* @example Sort snowflakes in descending order
* ```typescript
* const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];
* console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));
* // → ['1056191128120082432', '737141877803057244', '254360814063058944'];
* ```
*/
static compare(a, b) {
const typeA = typeof a;
return typeA === typeof b ? typeA === "string" ? cmpString(a, b) : cmpBigInt(a, b) : cmpBigInt(BigInt(a), BigInt(b));
}
};
__name(Snowflake, "Snowflake");
_a = EpochSymbol, _b = IncrementSymbol, _c = ProcessIdSymbol, _d = WorkerIdSymbol;
function cmpBigInt(a, b) {
return a === b ? 0 : a < b ? -1 : 1;
}
__name(cmpBigInt, "cmpBigInt");
function cmpString(a, b) {
return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;
}
__name(cmpString, "cmpString");
// src/lib/DiscordSnowflake.ts
var DiscordSnowflake = new Snowflake(1420070400000n);
// src/lib/TwitterSnowflake.ts
var TwitterSnowflake = new Snowflake(1288834974657n);
exports.DiscordSnowflake = DiscordSnowflake;
exports.MaximumIncrement = MaximumIncrement;
exports.MaximumProcessId = MaximumProcessId;
exports.MaximumWorkerId = MaximumWorkerId;
exports.Snowflake = Snowflake;
exports.TwitterSnowflake = TwitterSnowflake;
return exports;
})({});
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.global.js.map

File diff suppressed because one or more lines are too long

193
node_modules/@sapphire/snowflake/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,193 @@
'use strict';
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/lib/Snowflake.ts
var IncrementSymbol = Symbol("@sapphire/snowflake.increment");
var EpochSymbol = Symbol("@sapphire/snowflake.epoch");
var ProcessIdSymbol = Symbol("@sapphire/snowflake.processId");
var WorkerIdSymbol = Symbol("@sapphire/snowflake.workerId");
var MaximumWorkerId = 0b11111n;
var MaximumProcessId = 0b11111n;
var MaximumIncrement = 0b111111111111n;
var _a, _b, _c, _d;
var Snowflake = class {
/**
* @param epoch the epoch to use
*/
constructor(epoch) {
/**
* Alias for {@link deconstruct}
*/
// eslint-disable-next-line @typescript-eslint/unbound-method
__publicField(this, "decode", this.deconstruct);
/**
* Internal reference of the epoch passed in the constructor
* @internal
*/
__publicField(this, _a);
/**
* Internal incrementor for generating snowflakes
* @internal
*/
__publicField(this, _b, 0n);
/**
* The process ID that will be used by default in the generate method
* @internal
*/
__publicField(this, _c, 1n);
/**
* The worker ID that will be used by default in the generate method
* @internal
*/
__publicField(this, _d, 0n);
this[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);
}
/**
* The epoch for this snowflake
*/
get epoch() {
return this[EpochSymbol];
}
/**
* Gets the configured process ID
*/
get processId() {
return this[ProcessIdSymbol];
}
/**
* Sets the process ID that will be used by default for the {@link generate} method
* @param value The new value, will be coerced to BigInt and masked with `0b11111n`
*/
set processId(value) {
this[ProcessIdSymbol] = BigInt(value) & MaximumProcessId;
}
/**
* Gets the configured worker ID
*/
get workerId() {
return this[WorkerIdSymbol];
}
/**
* Sets the worker ID that will be used by default for the {@link generate} method
* @param value The new value, will be coerced to BigInt and masked with `0b11111n`
*/
set workerId(value) {
this[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId;
}
/**
* Generates a snowflake given an epoch and optionally a timestamp
* @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}
*
* **note** when `increment` is not provided it defaults to the private `increment` of the instance
* @example
* ```typescript
* const epoch = new Date('2000-01-01T00:00:00.000Z');
* const snowflake = new Snowflake(epoch).generate();
* ```
* @returns A unique snowflake
*/
generate({
increment,
timestamp = Date.now(),
workerId = this[WorkerIdSymbol],
processId = this[ProcessIdSymbol]
} = {}) {
if (timestamp instanceof Date)
timestamp = BigInt(timestamp.getTime());
else if (typeof timestamp === "number")
timestamp = BigInt(timestamp);
else if (typeof timestamp !== "bigint") {
throw new TypeError(`"timestamp" argument must be a number, bigint, or Date (received ${typeof timestamp})`);
}
if (typeof increment !== "bigint") {
increment = this[IncrementSymbol];
this[IncrementSymbol] = increment + 1n & MaximumIncrement;
}
return timestamp - this[EpochSymbol] << 22n | (workerId & MaximumWorkerId) << 17n | (processId & MaximumProcessId) << 12n | increment & MaximumIncrement;
}
/**
* Deconstructs a snowflake given a snowflake ID
* @param id the snowflake to deconstruct
* @returns a deconstructed snowflake
* @example
* ```typescript
* const epoch = new Date('2000-01-01T00:00:00.000Z');
* const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');
* ```
*/
deconstruct(id) {
const bigIntId = BigInt(id);
const epoch = this[EpochSymbol];
return {
id: bigIntId,
timestamp: (bigIntId >> 22n) + epoch,
workerId: bigIntId >> 17n & MaximumWorkerId,
processId: bigIntId >> 12n & MaximumProcessId,
increment: bigIntId & MaximumIncrement,
epoch
};
}
/**
* Retrieves the timestamp field's value from a snowflake.
* @param id The snowflake to get the timestamp value from.
* @returns The UNIX timestamp that is stored in `id`.
*/
timestampFrom(id) {
return Number((BigInt(id) >> 22n) + this[EpochSymbol]);
}
/**
* Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given
* snowflake in sort order.
* @param a The first snowflake to compare.
* @param b The second snowflake to compare.
* @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.
* @example Sort snowflakes in ascending order
* ```typescript
* const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];
* console.log(ids.sort((a, b) => Snowflake.compare(a, b)));
* // → ['254360814063058944', '737141877803057244', '1056191128120082432'];
* ```
* @example Sort snowflakes in descending order
* ```typescript
* const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];
* console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));
* // → ['1056191128120082432', '737141877803057244', '254360814063058944'];
* ```
*/
static compare(a, b) {
const typeA = typeof a;
return typeA === typeof b ? typeA === "string" ? cmpString(a, b) : cmpBigInt(a, b) : cmpBigInt(BigInt(a), BigInt(b));
}
};
__name(Snowflake, "Snowflake");
_a = EpochSymbol, _b = IncrementSymbol, _c = ProcessIdSymbol, _d = WorkerIdSymbol;
function cmpBigInt(a, b) {
return a === b ? 0 : a < b ? -1 : 1;
}
__name(cmpBigInt, "cmpBigInt");
function cmpString(a, b) {
return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;
}
__name(cmpString, "cmpString");
// src/lib/DiscordSnowflake.ts
var DiscordSnowflake = new Snowflake(1420070400000n);
// src/lib/TwitterSnowflake.ts
var TwitterSnowflake = new Snowflake(1288834974657n);
exports.DiscordSnowflake = DiscordSnowflake;
exports.MaximumIncrement = MaximumIncrement;
exports.MaximumProcessId = MaximumProcessId;
exports.MaximumWorkerId = MaximumWorkerId;
exports.Snowflake = Snowflake;
exports.TwitterSnowflake = TwitterSnowflake;
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map

1
node_modules/@sapphire/snowflake/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

186
node_modules/@sapphire/snowflake/dist/index.mjs generated vendored Normal file
View file

@ -0,0 +1,186 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/lib/Snowflake.ts
var IncrementSymbol = Symbol("@sapphire/snowflake.increment");
var EpochSymbol = Symbol("@sapphire/snowflake.epoch");
var ProcessIdSymbol = Symbol("@sapphire/snowflake.processId");
var WorkerIdSymbol = Symbol("@sapphire/snowflake.workerId");
var MaximumWorkerId = 0b11111n;
var MaximumProcessId = 0b11111n;
var MaximumIncrement = 0b111111111111n;
var _a, _b, _c, _d;
var Snowflake = class {
/**
* @param epoch the epoch to use
*/
constructor(epoch) {
/**
* Alias for {@link deconstruct}
*/
// eslint-disable-next-line @typescript-eslint/unbound-method
__publicField(this, "decode", this.deconstruct);
/**
* Internal reference of the epoch passed in the constructor
* @internal
*/
__publicField(this, _a);
/**
* Internal incrementor for generating snowflakes
* @internal
*/
__publicField(this, _b, 0n);
/**
* The process ID that will be used by default in the generate method
* @internal
*/
__publicField(this, _c, 1n);
/**
* The worker ID that will be used by default in the generate method
* @internal
*/
__publicField(this, _d, 0n);
this[EpochSymbol] = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);
}
/**
* The epoch for this snowflake
*/
get epoch() {
return this[EpochSymbol];
}
/**
* Gets the configured process ID
*/
get processId() {
return this[ProcessIdSymbol];
}
/**
* Sets the process ID that will be used by default for the {@link generate} method
* @param value The new value, will be coerced to BigInt and masked with `0b11111n`
*/
set processId(value) {
this[ProcessIdSymbol] = BigInt(value) & MaximumProcessId;
}
/**
* Gets the configured worker ID
*/
get workerId() {
return this[WorkerIdSymbol];
}
/**
* Sets the worker ID that will be used by default for the {@link generate} method
* @param value The new value, will be coerced to BigInt and masked with `0b11111n`
*/
set workerId(value) {
this[WorkerIdSymbol] = BigInt(value) & MaximumWorkerId;
}
/**
* Generates a snowflake given an epoch and optionally a timestamp
* @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}
*
* **note** when `increment` is not provided it defaults to the private `increment` of the instance
* @example
* ```typescript
* const epoch = new Date('2000-01-01T00:00:00.000Z');
* const snowflake = new Snowflake(epoch).generate();
* ```
* @returns A unique snowflake
*/
generate({
increment,
timestamp = Date.now(),
workerId = this[WorkerIdSymbol],
processId = this[ProcessIdSymbol]
} = {}) {
if (timestamp instanceof Date)
timestamp = BigInt(timestamp.getTime());
else if (typeof timestamp === "number")
timestamp = BigInt(timestamp);
else if (typeof timestamp !== "bigint") {
throw new TypeError(`"timestamp" argument must be a number, bigint, or Date (received ${typeof timestamp})`);
}
if (typeof increment !== "bigint") {
increment = this[IncrementSymbol];
this[IncrementSymbol] = increment + 1n & MaximumIncrement;
}
return timestamp - this[EpochSymbol] << 22n | (workerId & MaximumWorkerId) << 17n | (processId & MaximumProcessId) << 12n | increment & MaximumIncrement;
}
/**
* Deconstructs a snowflake given a snowflake ID
* @param id the snowflake to deconstruct
* @returns a deconstructed snowflake
* @example
* ```typescript
* const epoch = new Date('2000-01-01T00:00:00.000Z');
* const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');
* ```
*/
deconstruct(id) {
const bigIntId = BigInt(id);
const epoch = this[EpochSymbol];
return {
id: bigIntId,
timestamp: (bigIntId >> 22n) + epoch,
workerId: bigIntId >> 17n & MaximumWorkerId,
processId: bigIntId >> 12n & MaximumProcessId,
increment: bigIntId & MaximumIncrement,
epoch
};
}
/**
* Retrieves the timestamp field's value from a snowflake.
* @param id The snowflake to get the timestamp value from.
* @returns The UNIX timestamp that is stored in `id`.
*/
timestampFrom(id) {
return Number((BigInt(id) >> 22n) + this[EpochSymbol]);
}
/**
* Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given
* snowflake in sort order.
* @param a The first snowflake to compare.
* @param b The second snowflake to compare.
* @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.
* @example Sort snowflakes in ascending order
* ```typescript
* const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];
* console.log(ids.sort((a, b) => Snowflake.compare(a, b)));
* // → ['254360814063058944', '737141877803057244', '1056191128120082432'];
* ```
* @example Sort snowflakes in descending order
* ```typescript
* const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];
* console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));
* // → ['1056191128120082432', '737141877803057244', '254360814063058944'];
* ```
*/
static compare(a, b) {
const typeA = typeof a;
return typeA === typeof b ? typeA === "string" ? cmpString(a, b) : cmpBigInt(a, b) : cmpBigInt(BigInt(a), BigInt(b));
}
};
__name(Snowflake, "Snowflake");
_a = EpochSymbol, _b = IncrementSymbol, _c = ProcessIdSymbol, _d = WorkerIdSymbol;
function cmpBigInt(a, b) {
return a === b ? 0 : a < b ? -1 : 1;
}
__name(cmpBigInt, "cmpBigInt");
function cmpString(a, b) {
return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;
}
__name(cmpString, "cmpString");
// src/lib/DiscordSnowflake.ts
var DiscordSnowflake = new Snowflake(1420070400000n);
// src/lib/TwitterSnowflake.ts
var TwitterSnowflake = new Snowflake(1288834974657n);
export { DiscordSnowflake, MaximumIncrement, MaximumProcessId, MaximumWorkerId, Snowflake, TwitterSnowflake };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.mjs.map

1
node_modules/@sapphire/snowflake/dist/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

67
node_modules/@sapphire/snowflake/package.json generated vendored Normal file
View file

@ -0,0 +1,67 @@
{
"name": "@sapphire/snowflake",
"version": "3.5.1",
"description": "Deconstructs and generates snowflake IDs using BigInts",
"author": "@sapphire",
"license": "MIT",
"main": "dist/index.js",
"module": "dist/index.mjs",
"browser": "dist/index.global.js",
"unpkg": "dist/index.global.js",
"types": "dist/index.d.ts",
"exports": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"sideEffects": false,
"homepage": "https://github.com/sapphiredev/utilities/tree/main/packages/snowflake",
"scripts": {
"test": "vitest run",
"lint": "eslint src tests --ext ts --fix -c ../../.eslintrc",
"build": "tsup",
"docs": "typedoc-json-parser",
"prepack": "yarn build",
"bump": "cliff-jumper",
"check-update": "cliff-jumper --dry-run"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sapphiredev/utilities.git",
"directory": "packages/snowflake"
},
"files": [
"dist/**/*.js*",
"dist/**/*.mjs*",
"dist/**/*.d*"
],
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
},
"keywords": [
"@sapphire/snowflake",
"bot",
"typescript",
"ts",
"yarn",
"discord",
"sapphire",
"standalone"
],
"bugs": {
"url": "https://github.com/sapphiredev/utilities/issues"
},
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@vitest/coverage-c8": "^0.31.0",
"tsup": "^6.7.0",
"typedoc": "^0.24.7",
"typedoc-json-parser": "^7.4.0",
"typescript": "^5.0.4",
"vitest": "^0.31.0"
}
}

Some files were not shown because too many files have changed in this diff Show more