Initial work is done

master
Chloe Fontenot 🏳️‍⚧️ 2023-03-31 00:34:58 +07:00
parent 78b267fad0
commit d965541c59
2900 changed files with 299483 additions and 0 deletions

2
.gitignore vendored

@ -0,0 +1,2 @@
key.json
/nbproject/private/

@ -0,0 +1 @@
{"target_phrases":{"test":"test2","test3":"test4","test5":"test6"}}

@ -0,0 +1,6 @@
{
"target_phrases":
{
}
}

@ -0,0 +1,47 @@
const { SlashCommandBuilder } = require('discord.js');
var abbreviationKey = require("../abbreviation_key.json");
const fs = require('node:fs');
var path = require('node:path');;
console.log(abbreviationKey);
module.exports = {
data: new SlashCommandBuilder()
.setName("add_phrase")
.setDescription("adds_abbreviation_to_respond_to")
.addStringOption( (option) =>
option.setName("abbreviation")
.setDescription("The_abbreviation_to_target")
.setRequired(true)
)
.addStringOption( option =>
option.setName('phrase')
.setDescription("The phrase that the abbreviation shortens")
.setRequired(true)
),
async execute(interaction) {
var abbreviation = interaction.options.getString('abbreviation');
var phrase = interaction.options.getString('phrase');
await interaction.reply('Adding phrase `' + abbreviation + "` to target list. This will complete to the phrase `" + phrase + "`");
addPhrase(abbreviation, phrase);
},
};
function addPhrase(abbrevation, phrase) {
console.log(abbrevation, phrase);
abbreviationKey.target_phrases[abbrevation] = phrase;
console.log(abbreviationKey);
updatePhraseList();
// Write data to file
var jsonString = JSON.stringify(abbreviationKey);
try {
//console.log(fs.existsSync("../abbreviation_key.json"));
var jsonPath = path.join(__dirname, '..', 'abbreviation_key.json');
fs.unlinkSync(jsonPath);
fs.writeFileSync(jsonPath, jsonString, { encoding: 'utf8' }, "\t");
} catch (err) {
console.error(err);
}
}

@ -0,0 +1,11 @@
const { SlashCommandBuilder, Discord } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply('Pong!');
console.log("User " + interaction.user.tag + " ran /ping");
},
};

@ -0,0 +1,36 @@
const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./key.json');
const fs = require('node:fs');
const path = require('node:path');
const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.ts'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(token);
// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();

@ -0,0 +1,5 @@
{
"token": "MTA5MTEyMDI2Nzg1MTQ4NTIxNQ.GUw1W5.SGkSWCfeyAs6cktoAhVE4ivkKAI5kGfhw-8wRc",
"clientId": "1091120267851485215",
"guildId": "475327576110268466"
}

@ -0,0 +1,93 @@
// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits, REST, Routes, Collection, FLAGS } = require('discord.js');
const Discord = require('discord.js');
const { clientId, guildId, token } = require('./key.json');
const fs = require('node:fs');
const path = require('node:path');
// Create a new client instance
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
});
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// Log in to Discord with your client's token
client.login(token);
// Retrieve commands
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.ts'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
});
// My code
var abbreviationKey = require("./abbreviation_key.json");
function updatePhraseList() {
abbreviationKey = require("./abbreviation_key.json");
}
client.on('messageCreate', message => {
console.log(`${message.author.tag} in #${message.channel.name} sent: ${message.content}`);
if (message.author.bot) {
return;
}
var messageArray = message.content.toLowerCase().split(/[ ,!@#$%^&*()]+/);
console.log(messageArray);
for (let i = 0; i < messageArray.length; ++i) {
if (abbreviationKey.target_phrases[messageArray[i]] != undefined) {
console.log("Found an abbreviation!");
break;
}
}
message.reply("Test");
console.log(abbreviationKey.target_phrases[messageArray[0]]);
}
);

366
node_modules/.package-lock.json generated vendored

@ -0,0 +1,366 @@
{
"name": "nomoreacronyms",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/@discordjs/builders": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.5.0.tgz",
"integrity": "sha512-7XxT78mnNBPigHn2y6KAXkicxIBFtZREGWaRZ249EC1l6gBUEP8IyVY5JTciIjJArxkF+tg675aZvsTNTKBpmA==",
"dependencies": {
"@discordjs/formatters": "^0.2.0",
"@discordjs/util": "^0.2.0",
"@sapphire/shapeshift": "^3.8.1",
"discord-api-types": "^0.37.35",
"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.4.0",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.4.0.tgz",
"integrity": "sha512-hiOJyk2CPFf1+FL3a4VKCuu1f448LlROVuu8nLz1+jCOAPokUcdFAV+l4pd3B3h6uJlJQSASoZzrdyNdjdtfzQ==",
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@discordjs/formatters": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.2.0.tgz",
"integrity": "sha512-vn4oMSXuMZUm8ITqVOtvE7/fMMISj4cI5oLsR09PEQXHKeKDAMLltG/DWeeIs7Idfy6V8Fk3rn1e69h7NfzuNA==",
"dependencies": {
"discord-api-types": "^0.37.35"
},
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@discordjs/rest": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.6.0.tgz",
"integrity": "sha512-HGvqNCZ5Z5j0tQHjmT1lFvE5ETO4hvomJ1r0cbnpC1zM23XhCpZ9wgTCiEmaxKz05cyf2CI9p39+9LL+6Yz1bA==",
"dependencies": {
"@discordjs/collection": "^1.4.0",
"@discordjs/util": "^0.2.0",
"@sapphire/async-queue": "^1.5.0",
"@sapphire/snowflake": "^3.4.0",
"discord-api-types": "^0.37.35",
"file-type": "^18.2.1",
"tslib": "^2.5.0",
"undici": "^5.20.0"
},
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/@discordjs/util": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.2.0.tgz",
"integrity": "sha512-/8qNbebFzLWKOOg+UV+RB8itp4SmU5jw0tBUD3ifElW6rYNOj1Ku5JaSW7lLl/WgjjxF01l/1uQPCzkwr110vg==",
"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.8.1",
"resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.8.1.tgz",
"integrity": "sha512-xG1oXXBhCjPKbxrRTlox9ddaZTvVpOhYLmKmApD/vIWOV1xEYXnpoFs68zHIZBGbqztq6FrUPNPerIrO1Hqeaw==",
"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.4.0",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.4.0.tgz",
"integrity": "sha512-zZxymtVO6zeXVMPds+6d7gv/OfnCc25M1Z+7ZLB0oPmeMTPeRWVPQSS16oDJy5ZsyCOLj7M6mbZml5gWXcVRNw==",
"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": "18.15.11",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.15.11.tgz",
"integrity": "sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q=="
},
"node_modules/@types/ws": {
"version": "8.5.4",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz",
"integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==",
"dependencies": {
"@types/node": "*"
}
},
"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.37",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.37.tgz",
"integrity": "sha512-LDMBKzl/zbvHO/yCzno5hevuA6lFIXJwdKSJZQrB+1ToDpFfN9thK+xxgZNR4aVkI7GHRDja0p4Sl2oYVPnHYg=="
},
"node_modules/discord.js": {
"version": "14.8.0",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.8.0.tgz",
"integrity": "sha512-UOxYtc/YnV7jAJ2gISluJyYeBw4e+j8gWn+IoqG8unaHAVuvZ13DdYN0M1f9fbUgUvSarV798inIrYFtDNDjwQ==",
"dependencies": {
"@discordjs/builders": "^1.5.0",
"@discordjs/collection": "^1.4.0",
"@discordjs/formatters": "^0.2.0",
"@discordjs/rest": "^1.6.0",
"@discordjs/util": "^0.2.0",
"@sapphire/snowflake": "^3.4.0",
"@types/ws": "^8.5.4",
"discord-api-types": "^0.37.35",
"fast-deep-equal": "^3.1.3",
"lodash.snakecase": "^4.1.1",
"tslib": "^2.5.0",
"undici": "^5.20.0",
"ws": "^8.12.1"
},
"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.2.1",
"resolved": "https://registry.npmjs.org/file-type/-/file-type-18.2.1.tgz",
"integrity": "sha512-Yw5MtnMv7vgD2/6Bjmmuegc8bQEVA9GmAyaR18bMYWKqsWDG9wgYZ1j4I6gNMF5Y5JBDcUcjRQqNQx7Y8uotcg==",
"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.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz",
"integrity": "sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg=="
},
"node_modules/undici": {
"version": "5.21.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-5.21.0.tgz",
"integrity": "sha512-HOjK8l6a57b2ZGXOcUsI5NLfoTrfmbOl90ixJDl0AEFG4wgHNDQxtZy15/ZQp7HhjkpaGlp/eneMgtsu1dIlUA==",
"dependencies": {
"busboy": "^1.6.0"
},
"engines": {
"node": ">=12.18"
}
},
"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
}
}
}
}
}

@ -0,0 +1,233 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@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))

@ -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.

@ -0,0 +1,70 @@
<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>
## Installation
**Node.js 16.9.0 or newer is required.**
```sh-session
npm install @discordjs/builders
yarn add @discordjs/builders
pnpm add @discordjs/builders
```
## Examples
Here are some examples for the builders and utilities you can find in this package:
- [Slash Command Builders][example]
## Links
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
See also the [Update Guide][guide-update], including updated and removed items in 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/builders
[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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -0,0 +1,88 @@
{
"name": "@discordjs/builders",
"version": "1.5.0",
"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",
"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": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"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"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/formatters": "^0.2.0",
"@discordjs/util": "^0.2.0",
"@sapphire/shapeshift": "^3.8.1",
"discord-api-types": "^0.37.35",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.3",
"tslib": "^2.5.0"
},
"devDependencies": {
"@favware/cliff-jumper": "^1.10.0",
"@microsoft/api-extractor": "^7.34.4",
"@types/node": "16.18.13",
"@vitest/coverage-c8": "^0.29.1",
"cross-env": "^7.0.3",
"downlevel-dts": "^0.11.0",
"esbuild-plugin-version-injector": "^1.0.3",
"eslint": "^8.35.0",
"eslint-config-neon": "^0.1.40",
"eslint-formatter-pretty": "^4.1.0",
"prettier": "^2.8.4",
"tsup": "^6.6.3",
"typescript": "^4.9.5",
"vitest": "^0.29.1"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

@ -0,0 +1,128 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@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))

@ -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.

@ -0,0 +1,67 @@
<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-session
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])
See also the [Update Guide][guide-update], including updated and removed items in 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/collection
[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

@ -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 };

@ -0,0 +1,569 @@
"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((k) => super.has(k));
}
/**
* 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((k) => super.has(k));
}
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`);
this.forEach(fn, thisArg);
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 [k, v] of entries) {
super.set(k, v);
}
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 [k, v] of other) {
if (this.has(k) && Object.is(v, this.get(k))) {
coll.set(k, v);
}
}
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 [k, v] of this) {
if (!other.has(k) || !Object.is(v, other.get(k))) {
coll.set(k, v);
}
}
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 [k, v] of other) {
if (!this.has(k))
coll.set(k, v);
}
for (const [k, v] of this) {
if (!other.has(k))
coll.set(k, v);
}
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 k of keys) {
const hasInSelf = this.has(k);
const hasInOther = other.has(k);
if (hasInSelf && hasInOther) {
const r = whenInBoth(this.get(k), other.get(k), k);
if (r.keep)
coll.set(k, r.value);
} else if (hasInSelf) {
const r = whenInSelf(this.get(k), k);
if (r.keep)
coll.set(k, r.value);
} else if (hasInOther) {
const r = whenInOther(other.get(k), k);
if (r.keep)
coll.set(k, r.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 [k, v] of entries) {
if (coll.has(k)) {
coll.set(k, combine(coll.get(k), v, k));
} else {
coll.set(k, v);
}
}
return coll;
}
};
__name(Collection, "Collection");
// src/index.ts
var version = "[VI]{{inject}}[/VI]";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Collection,
version
});
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

@ -0,0 +1,543 @@
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((k) => super.has(k));
}
/**
* 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((k) => super.has(k));
}
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`);
this.forEach(fn, thisArg);
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 [k, v] of entries) {
super.set(k, v);
}
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 [k, v] of other) {
if (this.has(k) && Object.is(v, this.get(k))) {
coll.set(k, v);
}
}
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 [k, v] of this) {
if (!other.has(k) || !Object.is(v, other.get(k))) {
coll.set(k, v);
}
}
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 [k, v] of other) {
if (!this.has(k))
coll.set(k, v);
}
for (const [k, v] of this) {
if (!other.has(k))
coll.set(k, v);
}
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 k of keys) {
const hasInSelf = this.has(k);
const hasInOther = other.has(k);
if (hasInSelf && hasInOther) {
const r = whenInBoth(this.get(k), other.get(k), k);
if (r.keep)
coll.set(k, r.value);
} else if (hasInSelf) {
const r = whenInSelf(this.get(k), k);
if (r.keep)
coll.set(k, r.value);
} else if (hasInOther) {
const r = whenInOther(other.get(k), k);
if (r.keep)
coll.set(k, r.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 [k, v] of entries) {
if (coll.has(k)) {
coll.set(k, combine(coll.get(k), v, k));
} else {
coll.set(k, v);
}
}
return coll;
}
};
__name(Collection, "Collection");
// src/index.ts
var version = "[VI]{{inject}}[/VI]";
export {
Collection,
version
};
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

@ -0,0 +1,74 @@
{
"name": "@discordjs/collection",
"version": "1.4.0",
"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",
"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": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"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": "git+https://github.com/discordjs/discord.js.git"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"devDependencies": {
"@favware/cliff-jumper": "^1.10.0",
"@microsoft/api-extractor": "^7.34.4",
"@types/node": "16.18.13",
"@vitest/coverage-c8": "^0.29.1",
"cross-env": "^7.0.3",
"esbuild-plugin-version-injector": "^1.0.3",
"eslint": "^8.35.0",
"eslint-config-neon": "^0.1.40",
"eslint-formatter-pretty": "^4.1.0",
"prettier": "^2.8.4",
"tsup": "^6.6.3",
"typescript": "^4.9.5",
"vitest": "^0.29.1"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

@ -0,0 +1,25 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@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))

@ -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.

@ -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` set of functions to format strings for Discord.
## Installation
**Node.js 16.9.0 or newer is required.**
```sh-session
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])
See also the [Update Guide][guide-update], including updated and removed items in 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/
[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

@ -0,0 +1,444 @@
import { URL } from 'node:url';
import { Snowflake } from 'discord-api-types/globals';
interface EscapeMarkdownOptions {
/**
* Whether to escape bolds
*
* @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 escape characters
*
* @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-flavour 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 codeblock with no language
*
* @param content - The content to wrap
*/
declare function codeBlock<C extends string>(content: C): `\`\`\`\n${C}\n\`\`\``;
/**
* Wraps the content inside a codeblock with the specified language
*
* @param language - The language for the codeblock
* @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
*
* @param content - The content to wrap
*/
declare function inlineCode<C extends string>(content: C): `\`${C}\``;
/**
* Formats the content into italic text
*
* @param content - The content to wrap
*/
declare function italic<C extends string>(content: C): `_${C}_`;
/**
* Formats the content into bold text
*
* @param content - The content to wrap
*/
declare function bold<C extends string>(content: C): `**${C}**`;
/**
* Formats the content into underscored text
*
* @param content - The content to wrap
*/
declare function underscore<C extends string>(content: C): `__${C}__`;
/**
* Formats the content into strike-through text
*
* @param content - The content to wrap
*/
declare function strikethrough<C extends string>(content: C): `~~${C}~~`;
/**
* Formats the content into a quote. This needs to be at the start of the line for Discord to format it
*
* @param content - The content to wrap
*/
declare function quote<C extends string>(content: C): `> ${C}`;
/**
* Formats the content into a block quote. This needs to be at the start of the line for Discord to format it
*
* @param content - The content to wrap
*/
declare function blockQuote<C extends string>(content: C): `>>> ${C}`;
/**
* Wraps the URL into `<>`, which stops it from embedding
*
* @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
*
* @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
*
* @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
*
* @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
*
* @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}")`;
/**
* Wraps the content inside spoiler (hidden text)
*
* @param content - The content to wrap
*/
declare function spoiler<C extends string>(content: C): `||${C}||`;
/**
* Formats a user ID into a user mention
*
* @param userId - The user ID to format
*/
declare function userMention<C extends Snowflake>(userId: C): `<@${C}>`;
/**
* Formats a channel ID into a channel mention
*
* @param channelId - The channel ID to format
*/
declare function channelMention<C extends Snowflake>(channelId: C): `<#${C}>`;
/**
* Formats a role ID into a role mention
*
* @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
*
* @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
*
* @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
*
* @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 an emoji ID into a fully qualified emoji identifier
*
* @param emojiId - The emoji ID to format
*/
declare function formatEmoji<C extends Snowflake>(emojiId: C, animated?: false): `<:_:${C}>`;
/**
* Formats an emoji ID into a fully qualified emoji identifier
*
* @param emojiId - The emoji ID to format
* @param animated - Whether the emoji is animated or not. Defaults to `false`
*/
declare function formatEmoji<C extends Snowflake>(emojiId: C, animated?: true): `<a:_:${C}>`;
/**
* Formats an emoji ID into a fully qualified emoji identifier
*
* @param emojiId - The emoji ID to format
* @param animated - Whether the emoji is animated or not. Defaults to `false`
*/
declare function formatEmoji<C extends Snowflake>(emojiId: C, animated?: boolean): `<:_:${C}>` | `<a:_:${C}>`;
/**
* Formats a channel link for a direct message channel.
*
* @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.
*
* @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.
*
* @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.
*
* @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
*
* @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
*
* @param seconds - The time to format, represents an UNIX timestamp in seconds
*/
declare function time<C extends number>(seconds: C): `<t:${C}>`;
/**
* Formats the given timestamp into a short date-time string
*
* @param seconds - The time to format, represents an 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, e.g. 16:20
*/
readonly ShortTime: "t";
/**
* Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30
*/
readonly LongTime: "T";
/**
* Short date format, consisting of day, month, and year, e.g. 20/04/2021
*/
readonly ShortDate: "d";
/**
* Long date format, consisting of day, month, and year, e.g. 20 April 2021
*/
readonly LongDate: "D";
/**
* Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20
*/
readonly ShortDateTime: "f";
/**
* Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20
*/
readonly LongDateTime: "F";
/**
* Relative time format, consisting of a relative duration format, e.g. 2 months ago
*/
readonly RelativeTime: "R";
};
/**
* The possible values, see {@link TimestampStyles} for more information
*/
type TimestampStylesString = (typeof TimestampStyles)[keyof typeof TimestampStyles];
/**
* An enum with all the available faces from Discord's native slash commands
*/
declare enum Faces {
/**
* ¯\\_()\\_/¯
*/
Shrug = "\u00AF\\_(\u30C4)\\_/\u00AF",
/**
* (°°
*/
Tableflip = "(\u256F\u00B0\u25A1\u00B0\uFF09\u256F\uFE35 \u253B\u2501\u253B",
/**
* ( -)
*/
Unflip = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\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 };

@ -0,0 +1,379 @@
"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, e.g. 16:20
*/
ShortTime: "t",
/**
* Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30
*/
LongTime: "T",
/**
* Short date format, consisting of day, month, and year, e.g. 20/04/2021
*/
ShortDate: "d",
/**
* Long date format, consisting of day, month, and year, e.g. 20 April 2021
*/
LongDate: "D",
/**
* Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20
*/
ShortDateTime: "f",
/**
* Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20
*/
LongDateTime: "F",
/**
* Relative time format, consisting of a relative duration format, e.g. 2 months ago
*/
RelativeTime: "R"
};
var Faces;
(function(Faces2) {
Faces2[
/**
* ¯\\_()\\_/¯
*/
"Shrug"
] = "\xAF\\_(\u30C4)\\_/\xAF";
Faces2[
/**
* (°°
*/
"Tableflip"
] = "(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B";
Faces2[
/**
* ( -)
*/
"Unflip"
] = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)";
})(Faces || (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

File diff suppressed because one or more lines are too long

@ -0,0 +1,321 @@
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, e.g. 16:20
*/
ShortTime: "t",
/**
* Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30
*/
LongTime: "T",
/**
* Short date format, consisting of day, month, and year, e.g. 20/04/2021
*/
ShortDate: "d",
/**
* Long date format, consisting of day, month, and year, e.g. 20 April 2021
*/
LongDate: "D",
/**
* Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20
*/
ShortDateTime: "f",
/**
* Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20
*/
LongDateTime: "F",
/**
* Relative time format, consisting of a relative duration format, e.g. 2 months ago
*/
RelativeTime: "R"
};
var Faces;
(function(Faces2) {
Faces2[
/**
* ¯\\_()\\_/¯
*/
"Shrug"
] = "\xAF\\_(\u30C4)\\_/\xAF";
Faces2[
/**
* (°°
*/
"Tableflip"
] = "(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B";
Faces2[
/**
* ( -)
*/
"Unflip"
] = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)";
})(Faces || (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

@ -0,0 +1,70 @@
{
"name": "@discordjs/formatters",
"version": "0.2.0",
"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",
"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": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"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": "git+https://github.com/discordjs/discord.js.git"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"discord-api-types": "^0.37.35"
},
"devDependencies": {
"@favware/cliff-jumper": "^1.10.0",
"@microsoft/api-extractor": "^7.34.4",
"@types/node": "16.18.13",
"@vitest/coverage-c8": "^0.29.1",
"cross-env": "^7.0.3",
"eslint": "^8.35.0",
"eslint-config-neon": "^0.1.40",
"eslint-formatter-pretty": "^4.1.0",
"prettier": "^2.8.4",
"tsup": "^6.6.3",
"typescript": "^4.9.5",
"vitest": "^0.29.1"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

@ -0,0 +1,185 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@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))

@ -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.

@ -0,0 +1,112 @@
<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>
## Installation
**Node.js 16.9.0 or newer is required.**
```sh-session
npm install @discordjs/rest
yarn add @discordjs/rest
pnpm add @discordjs/rest
```
## Examples
Install all required dependencies:
```sh-session
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])
See also the [Update Guide][guide-update], including updated and removed items in 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/rest
[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

@ -0,0 +1,870 @@
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})`;
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: `Node.js ${string}`;
readonly version: "10";
readonly hashSweepInterval: 14400000;
readonly hashLifetime: 86400000;
readonly handlerSweepInterval: 3600000;
};
/**
* The events that the REST manager emits
*/
declare const 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";
};
/**
* 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 `Node.js ${process.version}`
*/
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 const 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, CDN, DefaultRestOptions, DefaultUserAgent, 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 };

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -0,0 +1,86 @@
{
"name": "@discordjs/rest",
"version": "1.6.0",
"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",
"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": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"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": "git+https://github.com/discordjs/discord.js.git"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/collection": "^1.4.0",
"@discordjs/util": "^0.2.0",
"@sapphire/async-queue": "^1.5.0",
"@sapphire/snowflake": "^3.4.0",
"discord-api-types": "^0.37.35",
"file-type": "^18.2.1",
"tslib": "^2.5.0",
"undici": "^5.20.0"
},
"devDependencies": {
"@favware/cliff-jumper": "^1.10.0",
"@microsoft/api-extractor": "^7.34.4",
"@types/node": "16.18.13",
"@vitest/coverage-c8": "^0.29.1",
"cross-env": "^7.0.3",
"esbuild-plugin-version-injector": "^1.0.3",
"eslint": "^8.35.0",
"eslint-config-neon": "^0.1.40",
"eslint-formatter-pretty": "^4.1.0",
"prettier": "^2.8.4",
"tsup": "^6.6.3",
"typescript": "^4.9.5",
"vitest": "^0.29.1"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

@ -0,0 +1,21 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@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))

@ -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.

@ -0,0 +1,60 @@
<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>
## Installation
**Node.js 16.9.0 or newer is required.**
```sh-session
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])
See also the [Update Guide][guide-update], including updated and removed items in 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/util
[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

@ -0,0 +1,104 @@
/**
* 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>;
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 };

@ -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) % BigInt(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

@ -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","export function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number((BigInt(guildId) >> 22n) % BigInt(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;;;;;;;;;;;ACaO,SAASA,KAAQC,IAAsB;AAC7C,MAAIC;AAEJ,SAAO,MAAOA,iBAAiBD,GAAAA;AAChC;AAJgBD;;;AC+BT,UAAUG,MAAMA,QAA8B;AACpD,MAAIC;AACJ,MAAIC,QAAQ;AACZ,MAAIC,OAAO;AAEX,MAAI,OAAOH,WAAU,UAAU;AAC9BC,eAAWD;EACZ,OAAO;AACNE,YAAQF,OAAME;AACdD,eAAWD,OAAMI;AACjBD,WAAOH,OAAMG,QAAQ;EACtB;AAEA,WAASE,QAAQH,OAAOG,QAAQJ,UAAUI,SAASF,MAAM;AACxD,UAAME;EACP;AACD;AAhBiBL;;;AC5CV,SAASM,iBAAiBC,SAAiBC,YAAoB;AACrE,SAAOC,QAAQC,OAAOH,OAAAA,KAAY,OAAOG,OAAOF,UAAAA,CAAAA;AACjD;AAFgBF;;;ACiBT,SAASK,gBAAgBC,gBAAmE;AAClG,SAAOA,mBAAmB,QAAQ,OAAOA,mBAAmB,YAAY,YAAYA;AACrF;AAFgBD;;;ACCT,SAASE,YAAYC,gBAA+D;AAC1F,SAAOA,mBAAmB,QAAQ,OAAOA,mBAAmB,YAAY,YAAYA;AACrF;AAFgBD;","names":["lazy","cb","defaultValue","range","rangeEnd","start","step","end","index","calculateShardId","guildId","shardCount","Number","BigInt","isJSONEncodable","maybeEncodable","isEquatable","maybeEquatable"]}

@ -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) % BigInt(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

@ -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","export function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number((BigInt(guildId) >> 22n) % BigInt(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,SAASA,KAAQC,IAAsB;AAC7C,MAAIC;AAEJ,SAAO,MAAOA,iBAAiBD,GAAAA;AAChC;AAJgBD;;;AC+BT,UAAUG,MAAMA,QAA8B;AACpD,MAAIC;AACJ,MAAIC,QAAQ;AACZ,MAAIC,OAAO;AAEX,MAAI,OAAOH,WAAU,UAAU;AAC9BC,eAAWD;EACZ,OAAO;AACNE,YAAQF,OAAME;AACdD,eAAWD,OAAMI;AACjBD,WAAOH,OAAMG,QAAQ;EACtB;AAEA,WAASE,QAAQH,OAAOG,QAAQJ,UAAUI,SAASF,MAAM;AACxD,UAAME;EACP;AACD;AAhBiBL;;;AC5CV,SAASM,iBAAiBC,SAAiBC,YAAoB;AACrE,SAAOC,QAAQC,OAAOH,OAAAA,KAAY,OAAOG,OAAOF,UAAAA,CAAAA;AACjD;AAFgBF;;;ACiBT,SAASK,gBAAgBC,gBAAmE;AAClG,SAAOA,mBAAmB,QAAQ,OAAOA,mBAAmB,YAAY,YAAYA;AACrF;AAFgBD;;;ACCT,SAASE,YAAYC,gBAA+D;AAC1F,SAAOA,mBAAmB,QAAQ,OAAOA,mBAAmB,YAAY,YAAYA;AACrF;AAFgBD;","names":["lazy","cb","defaultValue","range","rangeEnd","start","step","end","index","calculateShardId","guildId","shardCount","Number","BigInt","isJSONEncodable","maybeEncodable","isEquatable","maybeEquatable"]}

@ -0,0 +1,78 @@
{
"name": "@discordjs/util",
"version": "0.2.0",
"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",
"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": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"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"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"devDependencies": {
"@favware/cliff-jumper": "^1.10.0",
"@microsoft/api-extractor": "^7.34.4",
"@types/node": "16.18.13",
"@vitest/coverage-c8": "^0.29.1",
"cross-env": "^7.0.3",
"eslint": "^8.35.0",
"eslint-config-neon": "^0.1.40",
"eslint-formatter-pretty": "^4.1.0",
"prettier": "^2.8.4",
"tsd": "^0.25.0",
"tsup": "^6.6.3",
"typescript": "^4.9.5",
"vitest": "^0.29.1"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
},
"tsd": {
"directory": "__tests__/types"
}
}

@ -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))

@ -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!

@ -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 };

@ -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

@ -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

File diff suppressed because one or more lines are too long

@ -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

@ -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"
}
}

@ -0,0 +1,263 @@
# Changelog
All notable changes to this project will be documented in this file.
# [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))

@ -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.

@ -0,0 +1,955 @@
<div align="center">
![Sapphire Logo](https://cdn.skyra.pw/gh-assets/sapphire-banner.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]
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://github.com/kyranet"><img src="https://avatars.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/shapeshift/commits?author=kyranet" title="Code">💻</a> <a href="https://github.com/sapphiredev/shapeshift/commits?author=kyranet" title="Documentation">📖</a> <a href="#ideas-kyranet" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="https://github.com/vladfrangu"><img src="https://avatars.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/shapeshift/commits?author=vladfrangu" title="Code">💻</a> <a href="https://github.com/sapphiredev/shapeshift/commits?author=vladfrangu" title="Documentation">📖</a> <a href="#ideas-vladfrangu" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="https://favware.tech/"><img src="https://avatars.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/shapeshift/commits?author=favna" title="Documentation">📖</a> <a href="#maintenance-favna" title="Maintenance">🚧</a> <a href="#infra-favna" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</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://github.com/Khasms"><img src="https://avatars.githubusercontent.com/u/36800359?v=4?s=100" width="100px;" alt=""/><br /><sub><b>John</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=Khasms" 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="https://github.com/sapphiredev/shapeshift/commits?author=imranbarbhuiya" title="Code">💻</a> <a href="https://github.com/sapphiredev/shapeshift/commits?author=imranbarbhuiya" title="Tests">⚠️</a> <a href="https://github.com/sapphiredev/shapeshift/issues?q=author%3Aimranbarbhuiya" title="Bug reports">🐛</a> <a href="https://github.com/sapphiredev/shapeshift/commits?author=imranbarbhuiya" title="Documentation">📖</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/apps/allcontributors"><img src="https://avatars.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/shapeshift/commits?author=allcontributors[bot]" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/RealShadowNova"><img src="https://avatars.githubusercontent.com/u/46537907?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Hezekiah Hendry</b></sub></a><br /><a href="#tool-RealShadowNova" title="Tools">🔧</a></td>
<td align="center"><a href="https://github.com/legendhimslef"><img src="https://avatars.githubusercontent.com/u/69213593?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Voxelli</b></sub></a><br /><a href="https://github.com/sapphiredev/shapeshift/commits?author=legendhimslef" title="Documentation">📖</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!
[`zod`]: https://github.com/colinhacks/zod
[documentation]: https://www.sapphirejs.dev/docs/Documentation/api-shapeshift/
[toc]: #table-of-contents

@ -0,0 +1,713 @@
import { InspectOptionsStylized } from 'node: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 const 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> {
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;
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> = number extends N ? Array<T> : N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T], N, [[]]>;
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 };

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -0,0 +1,127 @@
{
"name": "@sapphire/shapeshift",
"version": "3.8.1",
"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": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"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",
"test:watch": "vitest",
"update": "yarn upgrade-interactive",
"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"
},
"devDependencies": {
"@commitlint/cli": "^17.3.0",
"@commitlint/config-conventional": "^17.3.0",
"@favware/cliff-jumper": "^1.9.0",
"@favware/npm-deprecate": "^1.0.7",
"@sapphire/eslint-config": "^4.3.8",
"@sapphire/prettier-config": "^1.4.4",
"@sapphire/ts-config": "^3.3.4",
"@types/jsdom": "^20.0.1",
"@types/lodash": "^4.14.191",
"@types/node": "^18.11.13",
"@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
"@vitest/coverage-c8": "^0.25.7",
"cz-conventional-changelog": "^3.3.0",
"esbuild-plugins-node-modules-polyfill": "^1.0.7",
"eslint": "^8.29.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"husky": "^8.0.2",
"jsdom": "^20.0.3",
"lint-staged": "^13.1.0",
"pinst": "^3.0.0",
"prettier": "^2.8.1",
"pretty-quick": "^3.1.3",
"ts-node": "^10.9.1",
"tsup": "^6.5.0",
"typedoc": "^0.23.22",
"typedoc-json-parser": "^7.0.2",
"typescript": "^4.9.4",
"vite": "^4.0.0",
"vitest": "^0.25.7"
},
"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.7"
},
"packageManager": "yarn@3.3.0",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"lodash": "^4.17.21"
}
}

@ -0,0 +1,263 @@
# Changelog
All notable changes to this project will be documented in this file.
# [@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))

@ -0,0 +1,234 @@
<div align="center">
![Sapphire Logo](https://cdn.skyra.pw/gh-assets/sapphire-banner.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 ✨
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>Aura 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> <a href="#tool-RealShadowNova" title="Tools">🔧</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>
<td align="center"><a href="https://github.com/r-priyam"><img src="https://avatars.githubusercontent.com/u/50884372?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Priyam</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=r-priyam" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/legendhimslef"><img src="https://avatars.githubusercontent.com/u/69213593?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Voxelli</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=legendhimslef" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/CitTheDev"><img src="https://avatars.githubusercontent.com/u/94020875?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Cit The Dev</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=CitTheDev" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://www.goestav.com/"><img src="https://avatars.githubusercontent.com/u/27970303?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Goestav</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=goestav" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/didinele"><img src="https://avatars.githubusercontent.com/u/27137376?v=4?s=100" width="100px;" alt=""/><br /><sub><b>DD</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=didinele" title="Code">💻</a></td>
<td align="center"><a href="https://steamcommunity.com/id/06000208"><img src="https://avatars.githubusercontent.com/u/52764066?v=4?s=100" width="100px;" alt=""/><br /><sub><b>amber</b></sub></a><br /><a href="https://github.com/sapphiredev/utilities/commits?author=06000208" 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!

@ -0,0 +1,149 @@
/**
* 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 {
#private;
/**
* Alias for {@link deconstruct}
*/
decode: (id: string | bigint) => DeconstructedSnowflake;
/**
* @param epoch the epoch to use
*/
constructor(epoch: number | bigint | Date);
/**
* The epoch for this snowflake.
*/
get epoch(): 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, Snowflake, SnowflakeGenerateOptions, TwitterSnowflake };

@ -0,0 +1,112 @@
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;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
// src/lib/Snowflake.ts
var ProcessId = 1n;
var WorkerId = 0n;
var _increment, _epoch;
var Snowflake = class {
constructor(epoch) {
__publicField(this, "decode", this.deconstruct);
__privateAdd(this, _increment, 0n);
__privateAdd(this, _epoch, void 0);
__privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch));
}
get epoch() {
return __privateGet(this, _epoch);
}
generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) {
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 >= 4095n)
increment = 0n;
else {
increment = __privateWrapper(this, _increment)._++;
if (__privateGet(this, _increment) >= 4095n)
__privateSet(this, _increment, 0n);
}
return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment;
}
deconstruct(id) {
const bigIntId = BigInt(id);
return {
id: bigIntId,
timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch),
workerId: bigIntId >> 17n & 0b11111n,
processId: bigIntId >> 12n & 0b11111n,
increment: bigIntId & 0b111111111111n,
epoch: __privateGet(this, _epoch)
};
}
timestampFrom(id) {
return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch));
}
static compare(a, b) {
if (typeof a === "bigint" || typeof b === "bigint") {
if (typeof a === "string")
a = BigInt(a);
else if (typeof b === "string")
b = BigInt(b);
return a === b ? 0 : a < b ? -1 : 1;
}
return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;
}
};
__name(Snowflake, "Snowflake");
_increment = new WeakMap();
_epoch = new WeakMap();
// src/lib/DiscordSnowflake.ts
var DiscordSnowflake = new Snowflake(1420070400000n);
// src/lib/TwitterSnowflake.ts
var TwitterSnowflake = new Snowflake(1288834974657n);
exports.DiscordSnowflake = DiscordSnowflake;
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

@ -0,0 +1,107 @@
'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;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
// src/lib/Snowflake.ts
var ProcessId = 1n;
var WorkerId = 0n;
var _increment, _epoch;
var Snowflake = class {
constructor(epoch) {
__publicField(this, "decode", this.deconstruct);
__privateAdd(this, _increment, 0n);
__privateAdd(this, _epoch, void 0);
__privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch));
}
get epoch() {
return __privateGet(this, _epoch);
}
generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) {
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 >= 4095n)
increment = 0n;
else {
increment = __privateWrapper(this, _increment)._++;
if (__privateGet(this, _increment) >= 4095n)
__privateSet(this, _increment, 0n);
}
return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment;
}
deconstruct(id) {
const bigIntId = BigInt(id);
return {
id: bigIntId,
timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch),
workerId: bigIntId >> 17n & 0b11111n,
processId: bigIntId >> 12n & 0b11111n,
increment: bigIntId & 0b111111111111n,
epoch: __privateGet(this, _epoch)
};
}
timestampFrom(id) {
return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch));
}
static compare(a, b) {
if (typeof a === "bigint" || typeof b === "bigint") {
if (typeof a === "string")
a = BigInt(a);
else if (typeof b === "string")
b = BigInt(b);
return a === b ? 0 : a < b ? -1 : 1;
}
return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;
}
};
__name(Snowflake, "Snowflake");
_increment = new WeakMap();
_epoch = new WeakMap();
// src/lib/DiscordSnowflake.ts
var DiscordSnowflake = new Snowflake(1420070400000n);
// src/lib/TwitterSnowflake.ts
var TwitterSnowflake = new Snowflake(1288834974657n);
exports.DiscordSnowflake = DiscordSnowflake;
exports.Snowflake = Snowflake;
exports.TwitterSnowflake = TwitterSnowflake;
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

@ -0,0 +1,103 @@
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;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
// src/lib/Snowflake.ts
var ProcessId = 1n;
var WorkerId = 0n;
var _increment, _epoch;
var Snowflake = class {
constructor(epoch) {
__publicField(this, "decode", this.deconstruct);
__privateAdd(this, _increment, 0n);
__privateAdd(this, _epoch, void 0);
__privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch));
}
get epoch() {
return __privateGet(this, _epoch);
}
generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) {
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 >= 4095n)
increment = 0n;
else {
increment = __privateWrapper(this, _increment)._++;
if (__privateGet(this, _increment) >= 4095n)
__privateSet(this, _increment, 0n);
}
return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment;
}
deconstruct(id) {
const bigIntId = BigInt(id);
return {
id: bigIntId,
timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch),
workerId: bigIntId >> 17n & 0b11111n,
processId: bigIntId >> 12n & 0b11111n,
increment: bigIntId & 0b111111111111n,
epoch: __privateGet(this, _epoch)
};
}
timestampFrom(id) {
return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch));
}
static compare(a, b) {
if (typeof a === "bigint" || typeof b === "bigint") {
if (typeof a === "string")
a = BigInt(a);
else if (typeof b === "string")
b = BigInt(b);
return a === b ? 0 : a < b ? -1 : 1;
}
return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;
}
};
__name(Snowflake, "Snowflake");
_increment = new WeakMap();
_epoch = new WeakMap();
// src/lib/DiscordSnowflake.ts
var DiscordSnowflake = new Snowflake(1420070400000n);
// src/lib/TwitterSnowflake.ts
var TwitterSnowflake = new Snowflake(1288834974657n);
export { DiscordSnowflake, Snowflake, TwitterSnowflake };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

@ -0,0 +1,67 @@
{
"name": "@sapphire/snowflake",
"version": "3.4.0",
"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": "^1.9.0",
"@vitest/coverage-c8": "^0.26.2",
"tsup": "^6.5.0",
"typedoc": "^0.23.23",
"typedoc-json-parser": "^7.0.2",
"typescript": "^4.9.4",
"vitest": "^0.26.2"
}
}

@ -0,0 +1,19 @@
[![npm version](https://badge.fury.io/js/%40tokenizer%2Ftoken.svg)](https://www.npmjs.com/package/@tokenizer/token)
[![npm downloads](http://img.shields.io/npm/dm/@tokenizer/token.svg)](https://npmcharts.com/compare/@tokenizer/token?interval=30)
# @tokenizer/token
TypeScript definition of an [strtok3](https://github.com/Borewit/strtok3) token.
## Licence
(The MIT License)
Copyright (c) 2020 Borewit
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.

@ -0,0 +1,30 @@
/**
* Read-only token
* See https://github.com/Borewit/strtok3 for more information
*/
export interface IGetToken<Value, Array extends Uint8Array = Uint8Array> {
/**
* Length of encoded token in bytes
*/
len: number;
/**
* Decode value from buffer at offset
* @param array - Uint8Array to read the decoded value from
* @param offset - Decode offset
* @return decoded value
*/
get(array: Array, offset: number): Value;
}
export interface IToken<Value, Array extends Uint8Array = Uint8Array> extends IGetToken<Value, Array> {
/**
* Encode value to buffer
* @param array - Uint8Array to write the encoded value to
* @param offset - Buffer write offset
* @param value - Value to decode of type T
* @return offset plus number of bytes written
*/
put(array: Array, offset: number, value: Value): number
}

@ -0,0 +1,33 @@
{
"name": "@tokenizer/token",
"version": "0.3.0",
"description": "TypeScript definition for strtok3 token",
"main": "",
"types": "index.d.ts",
"files": [
"index.d.ts"
],
"keywords": [
"token",
"interface",
"tokenizer",
"TypeScript"
],
"author": {
"name": "Borewit",
"url": "https://github.com/Borewit"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Borewit/tokenizer-token.git"
},
"bugs": {
"url": "https://github.com/Borewit/tokenizer-token/issues"
},
"typeScriptVersion": "3.0",
"dependencies": {},
"devDependencies": {
"@types/node": "^13.1.0"
}
}

21
node_modules/@types/node/LICENSE generated vendored

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
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

@ -0,0 +1,16 @@
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for Node.js (https://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
### Additional Details
* Last updated: Tue, 28 Mar 2023 21:33:10 GMT
* Dependencies: none
* Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require`, `structuredClone`
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky).

@ -0,0 +1,961 @@
/**
* The `assert` module provides a set of assertion functions for verifying
* invariants.
* @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/assert.js)
*/
declare module 'assert' {
/**
* An alias of {@link ok}.
* @since v0.5.9
* @param value The input that is checked for being truthy.
*/
function assert(value: unknown, message?: string | Error): asserts value;
namespace assert {
/**
* Indicates the failure of an assertion. All errors thrown by the `assert` module
* will be instances of the `AssertionError` class.
*/
class AssertionError extends Error {
actual: unknown;
expected: unknown;
operator: string;
generatedMessage: boolean;
code: 'ERR_ASSERTION';
constructor(options?: {
/** If provided, the error message is set to this value. */
message?: string | undefined;
/** The `actual` property on the error instance. */
actual?: unknown | undefined;
/** The `expected` property on the error instance. */
expected?: unknown | undefined;
/** The `operator` property on the error instance. */
operator?: string | undefined;
/** If provided, the generated stack trace omits frames before this function. */
// tslint:disable-next-line:ban-types
stackStartFn?: Function | undefined;
});
}
/**
* This feature is currently experimental and behavior might still change.
* @since v14.2.0, v12.19.0
* @experimental
*/
class CallTracker {
/**
* The wrapper function is expected to be called exactly `exact` times. If the
* function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an
* error.
*
* ```js
* import assert from 'assert';
*
* // Creates call tracker.
* const tracker = new assert.CallTracker();
*
* function func() {}
*
* // Returns a function that wraps func() that must be called exact times
* // before tracker.verify().
* const callsfunc = tracker.calls(func);
* ```
* @since v14.2.0, v12.19.0
* @param [fn='A no-op function']
* @param [exact=1]
* @return that wraps `fn`.
*/
calls(exact?: number): () => void;
calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func;
/**
* Example:
*
* ```js
* import assert from 'node:assert';
*
* const tracker = new assert.CallTracker();
*
* function func() {}
* const callsfunc = tracker.calls(func);
* callsfunc(1, 2, 3);
*
* assert.deepStrictEqual(tracker.getCalls(callsfunc),
* [{ thisArg: this, arguments: [1, 2, 3 ] }]);
* ```
*
* @since v18.8.0, v16.18.0
* @params fn
* @returns An Array with the calls to a tracked function.
*/
getCalls(fn: Function): CallTrackerCall[];
/**
* The arrays contains information about the expected and actual number of calls of
* the functions that have not been called the expected number of times.
*
* ```js
* import assert from 'assert';
*
* // Creates call tracker.
* const tracker = new assert.CallTracker();
*
* function func() {}
*
* function foo() {}
*
* // Returns a function that wraps func() that must be called exact times
* // before tracker.verify().
* const callsfunc = tracker.calls(func, 2);
*
* // Returns an array containing information on callsfunc()
* tracker.report();
* // [
* // {
* // message: 'Expected the func function to be executed 2 time(s) but was
* // executed 0 time(s).',
* // actual: 0,
* // expected: 2,
* // operator: 'func',
* // stack: stack trace
* // }
* // ]
* ```
* @since v14.2.0, v12.19.0
* @return of objects containing information about the wrapper functions returned by `calls`.
*/
report(): CallTrackerReportInformation[];
/**
* Reset calls of the call tracker.
* If a tracked function is passed as an argument, the calls will be reset for it.
* If no arguments are passed, all tracked functions will be reset.
*
* ```js
* import assert from 'node:assert';
*
* const tracker = new assert.CallTracker();
*
* function func() {}
* const callsfunc = tracker.calls(func);
*
* callsfunc();
* // Tracker was called once
* tracker.getCalls(callsfunc).length === 1;
*
* tracker.reset(callsfunc);
* tracker.getCalls(callsfunc).length === 0;
* ```
*
* @since v18.8.0, v16.18.0
* @param fn a tracked function to reset.
*/
reset(fn?: Function): void;
/**
* Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that
* have not been called the expected number of times.
*
* ```js
* import assert from 'assert';
*
* // Creates call tracker.
* const tracker = new assert.CallTracker();
*
* function func() {}
*
* // Returns a function that wraps func() that must be called exact times
* // before tracker.verify().
* const callsfunc = tracker.calls(func, 2);
*
* callsfunc();
*
* // Will throw an error since callsfunc() was only called once.
* tracker.verify();
* ```
* @since v14.2.0, v12.19.0
*/
verify(): void;
}
interface CallTrackerCall {
thisArg: object;
arguments: unknown[];
}
interface CallTrackerReportInformation {
message: string;
/** The actual number of times the function was called. */
actual: number;
/** The number of times the function was expected to be called. */
expected: number;
/** The name of the function that is wrapped. */
operator: string;
/** A stack trace of the function. */
stack: object;
}
type AssertPredicate = RegExp | (new () => object) | ((thrown: unknown) => boolean) | object | Error;
/**
* Throws an `AssertionError` with the provided error message or a default
* error message. If the `message` parameter is an instance of an `Error` then
* it will be thrown instead of the `AssertionError`.
*
* ```js
* import assert from 'assert/strict';
*
* assert.fail();
* // AssertionError [ERR_ASSERTION]: Failed
*
* assert.fail('boom');
* // AssertionError [ERR_ASSERTION]: boom
*
* assert.fail(new TypeError('need array'));
* // TypeError: need array
* ```
*
* Using `assert.fail()` with more than two arguments is possible but deprecated.
* See below for further details.
* @since v0.1.21
* @param [message='Failed']
*/
function fail(message?: string | Error): never;
/** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */
function fail(
actual: unknown,
expected: unknown,
message?: string | Error,
operator?: string,
// tslint:disable-next-line:ban-types
stackStartFn?: Function
): never;
/**
* Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`.
*
* If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default
* error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`.
* If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``.
*
* Be aware that in the `repl` the error message will be different to the one
* thrown in a file! See below for further details.
*
* ```js
* import assert from 'assert/strict';
*
* assert.ok(true);
* // OK
* assert.ok(1);
* // OK
*
* assert.ok();
* // AssertionError: No value argument passed to `assert.ok()`
*
* assert.ok(false, 'it\'s false');
* // AssertionError: it's false
*
* // In the repl:
* assert.ok(typeof 123 === 'string');
* // AssertionError: false == true
*
* // In a file (e.g. test.js):
* assert.ok(typeof 123 === 'string');
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert.ok(typeof 123 === 'string')
*
* assert.ok(false);
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert.ok(false)
*
* assert.ok(0);
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert.ok(0)
* ```
*
* ```js
* import assert from 'assert/strict';
*
* // Using `assert()` works the same:
* assert(0);
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert(0)
* ```
* @since v0.1.21
*/
function ok(value: unknown, message?: string | Error): asserts value;
/**
* **Strict assertion mode**
*
* An alias of {@link strictEqual}.
*
* **Legacy assertion mode**
*
* > Stability: 3 - Legacy: Use {@link strictEqual} instead.
*
* Tests shallow, coercive equality between the `actual` and `expected` parameters
* using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled
* and treated as being identical if both sides are `NaN`.
*
* ```js
* import assert from 'assert';
*
* assert.equal(1, 1);
* // OK, 1 == 1
* assert.equal(1, '1');
* // OK, 1 == '1'
* assert.equal(NaN, NaN);
* // OK
*
* assert.equal(1, 2);
* // AssertionError: 1 == 2
* assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
* // AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
* ```
*
* If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default
* error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`.
* @since v0.1.21
*/
function equal(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* **Strict assertion mode**
*
* An alias of {@link notStrictEqual}.
*
* **Legacy assertion mode**
*
* > Stability: 3 - Legacy: Use {@link notStrictEqual} instead.
*
* Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is
* specially handled and treated as being identical if both sides are `NaN`.
*
* ```js
* import assert from 'assert';
*
* assert.notEqual(1, 2);
* // OK
*
* assert.notEqual(1, 1);
* // AssertionError: 1 != 1
*
* assert.notEqual(1, '1');
* // AssertionError: 1 != '1'
* ```
*
* If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error
* message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`.
* @since v0.1.21
*/
function notEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* **Strict assertion mode**
*
* An alias of {@link deepStrictEqual}.
*
* **Legacy assertion mode**
*
* > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead.
*
* Tests for deep equality between the `actual` and `expected` parameters. Consider
* using {@link deepStrictEqual} instead. {@link deepEqual} can have
* surprising results.
*
* _Deep equality_ means that the enumerable "own" properties of child objects
* are also recursively evaluated by the following rules.
* @since v0.1.21
*/
function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* **Strict assertion mode**
*
* An alias of {@link notDeepStrictEqual}.
*
* **Legacy assertion mode**
*
* > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead.
*
* Tests for any deep inequality. Opposite of {@link deepEqual}.
*
* ```js
* import assert from 'assert';
*
* const obj1 = {
* a: {
* b: 1
* }
* };
* const obj2 = {
* a: {
* b: 2
* }
* };
* const obj3 = {
* a: {
* b: 1
* }
* };
* const obj4 = Object.create(obj1);
*
* assert.notDeepEqual(obj1, obj1);
* // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
*
* assert.notDeepEqual(obj1, obj2);
* // OK
*
* assert.notDeepEqual(obj1, obj3);
* // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
*
* assert.notDeepEqual(obj1, obj4);
* // OK
* ```
*
* If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default
* error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown
* instead of the `AssertionError`.
* @since v0.1.21
*/
function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* Tests strict equality between the `actual` and `expected` parameters as
* determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
*
* ```js
* import assert from 'assert/strict';
*
* assert.strictEqual(1, 2);
* // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
* //
* // 1 !== 2
*
* assert.strictEqual(1, 1);
* // OK
*
* assert.strictEqual('Hello foobar', 'Hello World!');
* // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
* // + actual - expected
* //
* // + 'Hello foobar'
* // - 'Hello World!'
* // ^
*
* const apples = 1;
* const oranges = 2;
* assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
* // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
*
* assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
* // TypeError: Inputs are not identical
* ```
*
* If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a
* default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown
* instead of the `AssertionError`.
* @since v0.1.21
*/
function strictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
/**
* Tests strict inequality between the `actual` and `expected` parameters as
* determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
*
* ```js
* import assert from 'assert/strict';
*
* assert.notStrictEqual(1, 2);
* // OK
*
* assert.notStrictEqual(1, 1);
* // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
* //
* // 1
*
* assert.notStrictEqual(1, '1');
* // OK
* ```
*
* If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a
* default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown
* instead of the `AssertionError`.
* @since v0.1.21
*/
function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* Tests for deep equality between the `actual` and `expected` parameters.
* "Deep" equality means that the enumerable "own" properties of child objects
* are recursively evaluated also by the following rules.
* @since v1.2.0
*/
function deepStrictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
/**
* Tests for deep strict inequality. Opposite of {@link deepStrictEqual}.
*
* ```js
* import assert from 'assert/strict';
*
* assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
* // OK
* ```
*
* If the values are deeply and strictly equal, an `AssertionError` is thrown
* with a `message` property set equal to the value of the `message` parameter. If
* the `message` parameter is undefined, a default error message is assigned. If
* the `message` parameter is an instance of an `Error` then it will be thrown
* instead of the `AssertionError`.
* @since v1.2.0
*/
function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* Expects the function `fn` to throw an error.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function,
* a validation object where each property will be tested for strict deep equality,
* or an instance of error where each property will be tested for strict deep
* equality including the non-enumerable `message` and `name` properties. When
* using an object, it is also possible to use a regular expression, when
* validating against a string property. See below for examples.
*
* If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation
* fails.
*
* Custom validation object/error instance:
*
* ```js
* import assert from 'assert/strict';
*
* const err = new TypeError('Wrong value');
* err.code = 404;
* err.foo = 'bar';
* err.info = {
* nested: true,
* baz: 'text'
* };
* err.reg = /abc/i;
*
* assert.throws(
* () => {
* throw err;
* },
* {
* name: 'TypeError',
* message: 'Wrong value',
* info: {
* nested: true,
* baz: 'text'
* }
* // Only properties on the validation object will be tested for.
* // Using nested objects requires all properties to be present. Otherwise
* // the validation is going to fail.
* }
* );
*
* // Using regular expressions to validate error properties:
* throws(
* () => {
* throw err;
* },
* {
* // The `name` and `message` properties are strings and using regular
* // expressions on those will match against the string. If they fail, an
* // error is thrown.
* name: /^TypeError$/,
* message: /Wrong/,
* foo: 'bar',
* info: {
* nested: true,
* // It is not possible to use regular expressions for nested properties!
* baz: 'text'
* },
* // The `reg` property contains a regular expression and only if the
* // validation object contains an identical regular expression, it is going
* // to pass.
* reg: /abc/i
* }
* );
*
* // Fails due to the different `message` and `name` properties:
* throws(
* () => {
* const otherErr = new Error('Not found');
* // Copy all enumerable properties from `err` to `otherErr`.
* for (const [key, value] of Object.entries(err)) {
* otherErr[key] = value;
* }
* throw otherErr;
* },
* // The error's `message` and `name` properties will also be checked when using
* // an error as validation object.
* err
* );
* ```
*
* Validate instanceof using constructor:
*
* ```js
* import assert from 'assert/strict';
*
* assert.throws(
* () => {
* throw new Error('Wrong value');
* },
* Error
* );
* ```
*
* Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions):
*
* Using a regular expression runs `.toString` on the error object, and will
* therefore also include the error name.
*
* ```js
* import assert from 'assert/strict';
*
* assert.throws(
* () => {
* throw new Error('Wrong value');
* },
* /^Error: Wrong value$/
* );
* ```
*
* Custom error validation:
*
* The function must return `true` to indicate all internal validations passed.
* It will otherwise fail with an `AssertionError`.
*
* ```js
* import assert from 'assert/strict';
*
* assert.throws(
* () => {
* throw new Error('Wrong value');
* },
* (err) => {
* assert(err instanceof Error);
* assert(/value/.test(err));
* // Avoid returning anything from validation functions besides `true`.
* // Otherwise, it's not clear what part of the validation failed. Instead,
* // throw an error about the specific validation that failed (as done in this
* // example) and add as much helpful debugging information to that error as
* // possible.
* return true;
* },
* 'unexpected error'
* );
* ```
*
* `error` cannot be a string. If a string is provided as the second
* argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same
* message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using
* a string as the second argument gets considered:
*
* ```js
* import assert from 'assert/strict';
*
* function throwingFirst() {
* throw new Error('First');
* }
*
* function throwingSecond() {
* throw new Error('Second');
* }
*
* function notThrowing() {}
*
* // The second argument is a string and the input function threw an Error.
* // The first case will not throw as it does not match for the error message
* // thrown by the input function!
* assert.throws(throwingFirst, 'Second');
* // In the next example the message has no benefit over the message from the
* // error and since it is not clear if the user intended to actually match
* // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
* assert.throws(throwingSecond, 'Second');
* // TypeError [ERR_AMBIGUOUS_ARGUMENT]
*
* // The string is only used (as message) in case the function does not throw:
* assert.throws(notThrowing, 'Second');
* // AssertionError [ERR_ASSERTION]: Missing expected exception: Second
*
* // If it was intended to match for the error message do this instead:
* // It does not throw because the error messages match.
* assert.throws(throwingSecond, /Second$/);
*
* // If the error message does not match, an AssertionError is thrown.
* assert.throws(throwingFirst, /Second$/);
* // AssertionError [ERR_ASSERTION]
* ```
*
* Due to the confusing error-prone notation, avoid a string as the second
* argument.
* @since v0.1.21
*/
function throws(block: () => unknown, message?: string | Error): void;
function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void;
/**
* Asserts that the function `fn` does not throw an error.
*
* Using `assert.doesNotThrow()` is actually not useful because there
* is no benefit in catching an error and then rethrowing it. Instead, consider
* adding a comment next to the specific code path that should not throw and keep
* error messages as expressive as possible.
*
* When `assert.doesNotThrow()` is called, it will immediately call the `fn`function.
*
* If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a
* different type, or if the `error` parameter is undefined, the error is
* propagated back to the caller.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation
* function. See {@link throws} for more details.
*
* The following, for instance, will throw the `TypeError` because there is no
* matching error type in the assertion:
*
* ```js
* import assert from 'assert/strict';
*
* assert.doesNotThrow(
* () => {
* throw new TypeError('Wrong value');
* },
* SyntaxError
* );
* ```
*
* However, the following will result in an `AssertionError` with the message
* 'Got unwanted exception...':
*
* ```js
* import assert from 'assert/strict';
*
* assert.doesNotThrow(
* () => {
* throw new TypeError('Wrong value');
* },
* TypeError
* );
* ```
*
* If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message:
*
* ```js
* import assert from 'assert/strict';
*
* assert.doesNotThrow(
* () => {
* throw new TypeError('Wrong value');
* },
* /Wrong value/,
* 'Whoops'
* );
* // Throws: AssertionError: Got unwanted exception: Whoops
* ```
* @since v0.1.21
*/
function doesNotThrow(block: () => unknown, message?: string | Error): void;
function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void;
/**
* Throws `value` if `value` is not `undefined` or `null`. This is useful when
* testing the `error` argument in callbacks. The stack trace contains all frames
* from the error passed to `ifError()` including the potential new frames for`ifError()` itself.
*
* ```js
* import assert from 'assert/strict';
*
* assert.ifError(null);
* // OK
* assert.ifError(0);
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
* assert.ifError('error');
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
* assert.ifError(new Error());
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
*
* // Create some random error frames.
* let err;
* (function errorFrame() {
* err = new Error('test error');
* })();
*
* (function ifErrorFrame() {
* assert.ifError(err);
* })();
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
* // at ifErrorFrame
* // at errorFrame
* ```
* @since v0.1.97
*/
function ifError(value: unknown): asserts value is null | undefined;
/**
* Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
* calls the function and awaits the returned promise to complete. It will then
* check that the promise is rejected.
*
* If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the
* function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error
* handler is skipped.
*
* Besides the async nature to await the completion behaves identically to {@link throws}.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function,
* an object where each property will be tested for, or an instance of error where
* each property will be tested for including the non-enumerable `message` and`name` properties.
*
* If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject.
*
* ```js
* import assert from 'assert/strict';
*
* await assert.rejects(
* async () => {
* throw new TypeError('Wrong value');
* },
* {
* name: 'TypeError',
* message: 'Wrong value'
* }
* );
* ```
*
* ```js
* import assert from 'assert/strict';
*
* await assert.rejects(
* async () => {
* throw new TypeError('Wrong value');
* },
* (err) => {
* assert.strictEqual(err.name, 'TypeError');
* assert.strictEqual(err.message, 'Wrong value');
* return true;
* }
* );
* ```
*
* ```js
* import assert from 'assert/strict';
*
* assert.rejects(
* Promise.reject(new Error('Wrong value')),
* Error
* ).then(() => {
* // ...
* });
* ```
*
* `error` cannot be a string. If a string is provided as the second
* argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the
* example in {@link throws} carefully if using a string as the second
* argument gets considered.
* @since v10.0.0
*/
function rejects(block: (() => Promise<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>;
function rejects(block: (() => Promise<unknown>) | Promise<unknown>, error: AssertPredicate, message?: string | Error): Promise<void>;
/**
* Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
* calls the function and awaits the returned promise to complete. It will then
* check that the promise is not rejected.
*
* If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If
* the function does not return a promise, `assert.doesNotReject()` will return a
* rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases
* the error handler is skipped.
*
* Using `assert.doesNotReject()` is actually not useful because there is little
* benefit in catching a rejection and then rejecting it again. Instead, consider
* adding a comment next to the specific code path that should not reject and keep
* error messages as expressive as possible.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation
* function. See {@link throws} for more details.
*
* Besides the async nature to await the completion behaves identically to {@link doesNotThrow}.
*
* ```js
* import assert from 'assert/strict';
*
* await assert.doesNotReject(
* async () => {
* throw new TypeError('Wrong value');
* },
* SyntaxError
* );
* ```
*
* ```js
* import assert from 'assert/strict';
*
* assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
* .then(() => {
* // ...
* });
* ```
* @since v10.0.0
*/
function doesNotReject(block: (() => Promise<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>;
function doesNotReject(block: (() => Promise<unknown>) | Promise<unknown>, error: AssertPredicate, message?: string | Error): Promise<void>;
/**
* Expects the `string` input to match the regular expression.
*
* ```js
* import assert from 'assert/strict';
*
* assert.match('I will fail', /pass/);
* // AssertionError [ERR_ASSERTION]: The input did not match the regular ...
*
* assert.match(123, /pass/);
* // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
*
* assert.match('I will pass', /pass/);
* // OK
* ```
*
* If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal
* to the value of the `message` parameter. If the `message` parameter is
* undefined, a default error message is assigned. If the `message` parameter is an
* instance of an `Error` then it will be thrown instead of the `AssertionError`.
* @since v13.6.0, v12.16.0
*/
function match(value: string, regExp: RegExp, message?: string | Error): void;
/**
* Expects the `string` input not to match the regular expression.
*
* ```js
* import assert from 'assert/strict';
*
* assert.doesNotMatch('I will fail', /fail/);
* // AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
*
* assert.doesNotMatch(123, /pass/);
* // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
*
* assert.doesNotMatch('I will pass', /different/);
* // OK
* ```
*
* If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal
* to the value of the `message` parameter. If the `message` parameter is
* undefined, a default error message is assigned. If the `message` parameter is an
* instance of an `Error` then it will be thrown instead of the `AssertionError`.
* @since v13.6.0, v12.16.0
*/
function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void;
const strict: Omit<typeof assert, 'equal' | 'notEqual' | 'deepEqual' | 'notDeepEqual' | 'ok' | 'strictEqual' | 'deepStrictEqual' | 'ifError' | 'strict'> & {
(value: unknown, message?: string | Error): asserts value;
equal: typeof strictEqual;
notEqual: typeof notStrictEqual;
deepEqual: typeof deepStrictEqual;
notDeepEqual: typeof notDeepStrictEqual;
// Mapped types and assertion functions are incompatible?
// TS2775: Assertions require every name in the call target
// to be declared with an explicit type annotation.
ok: typeof ok;
strictEqual: typeof strictEqual;
deepStrictEqual: typeof deepStrictEqual;
ifError: typeof ifError;
strict: typeof strict;
};
}
export = assert;
}
declare module 'node:assert' {
import assert = require('assert');
export = assert;
}

@ -0,0 +1,8 @@
declare module 'assert/strict' {
import { strict } from 'node:assert';
export = strict;
}
declare module 'node:assert/strict' {
import { strict } from 'node:assert';
export = strict;
}

@ -0,0 +1,513 @@
/**
* The `async_hooks` module provides an API to track asynchronous resources. It
* can be accessed using:
*
* ```js
* import async_hooks from 'async_hooks';
* ```
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/async_hooks.js)
*/
declare module 'async_hooks' {
/**
* ```js
* import { executionAsyncId } from 'async_hooks';
*
* console.log(executionAsyncId()); // 1 - bootstrap
* fs.open(path, 'r', (err, fd) => {
* console.log(executionAsyncId()); // 6 - open()
* });
* ```
*
* The ID returned from `executionAsyncId()` is related to execution timing, not
* causality (which is covered by `triggerAsyncId()`):
*
* ```js
* const server = net.createServer((conn) => {
* // Returns the ID of the server, not of the new connection, because the
* // callback runs in the execution scope of the server's MakeCallback().
* async_hooks.executionAsyncId();
*
* }).listen(port, () => {
* // Returns the ID of a TickObject (process.nextTick()) because all
* // callbacks passed to .listen() are wrapped in a nextTick().
* async_hooks.executionAsyncId();
* });
* ```
*
* Promise contexts may not get precise `executionAsyncIds` by default.
* See the section on `promise execution tracking`.
* @since v8.1.0
* @return The `asyncId` of the current execution context. Useful to track when something calls.
*/
function executionAsyncId(): number;
/**
* Resource objects returned by `executionAsyncResource()` are most often internal
* Node.js handle objects with undocumented APIs. Using any functions or properties
* on the object is likely to crash your application and should be avoided.
*
* Using `executionAsyncResource()` in the top-level execution context will
* return an empty object as there is no handle or request object to use,
* but having an object representing the top-level can be helpful.
*
* ```js
* import { open } from 'fs';
* import { executionAsyncId, executionAsyncResource } from 'async_hooks';
*
* console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
* open(new URL(import.meta.url), 'r', (err, fd) => {
* console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
* });
* ```
*
* This can be used to implement continuation local storage without the
* use of a tracking `Map` to store the metadata:
*
* ```js
* import { createServer } from 'http';
* import {
* executionAsyncId,
* executionAsyncResource,
* createHook
* } from 'async_hooks';
* const sym = Symbol('state'); // Private symbol to avoid pollution
*
* createHook({
* init(asyncId, type, triggerAsyncId, resource) {
* const cr = executionAsyncResource();
* if (cr) {
* resource[sym] = cr[sym];
* }
* }
* }).enable();
*
* const server = createServer((req, res) => {
* executionAsyncResource()[sym] = { state: req.url };
* setTimeout(function() {
* res.end(JSON.stringify(executionAsyncResource()[sym]));
* }, 100);
* }).listen(3000);
* ```
* @since v13.9.0, v12.17.0
* @return The resource representing the current execution. Useful to store data within the resource.
*/
function executionAsyncResource(): object;
/**
* ```js
* const server = net.createServer((conn) => {
* // The resource that caused (or triggered) this callback to be called
* // was that of the new connection. Thus the return value of triggerAsyncId()
* // is the asyncId of "conn".
* async_hooks.triggerAsyncId();
*
* }).listen(port, () => {
* // Even though all callbacks passed to .listen() are wrapped in a nextTick()
* // the callback itself exists because the call to the server's .listen()
* // was made. So the return value would be the ID of the server.
* async_hooks.triggerAsyncId();
* });
* ```
*
* Promise contexts may not get valid `triggerAsyncId`s by default. See
* the section on `promise execution tracking`.
* @return The ID of the resource responsible for calling the callback that is currently being executed.
*/
function triggerAsyncId(): number;
interface HookCallbacks {
/**
* Called when a class is constructed that has the possibility to emit an asynchronous event.
* @param asyncId a unique ID for the async resource
* @param type the type of the async resource
* @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created
* @param resource reference to the resource representing the async operation, needs to be released during destroy
*/
init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void;
/**
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
* The before callback is called just before said callback is executed.
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
*/
before?(asyncId: number): void;
/**
* Called immediately after the callback specified in before is completed.
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
*/
after?(asyncId: number): void;
/**
* Called when a promise has resolve() called. This may not be in the same execution id
* as the promise itself.
* @param asyncId the unique id for the promise that was resolve()d.
*/
promiseResolve?(asyncId: number): void;
/**
* Called after the resource corresponding to asyncId is destroyed
* @param asyncId a unique ID for the async resource
*/
destroy?(asyncId: number): void;
}
interface AsyncHook {
/**
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
*/
enable(): this;
/**
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
*/
disable(): this;
}
/**
* Registers functions to be called for different lifetime events of each async
* operation.
*
* The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the
* respective asynchronous event during a resource's lifetime.
*
* All callbacks are optional. For example, if only resource cleanup needs to
* be tracked, then only the `destroy` callback needs to be passed. The
* specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section.
*
* ```js
* import { createHook } from 'async_hooks';
*
* const asyncHook = createHook({
* init(asyncId, type, triggerAsyncId, resource) { },
* destroy(asyncId) { }
* });
* ```
*
* The callbacks will be inherited via the prototype chain:
*
* ```js
* class MyAsyncCallbacks {
* init(asyncId, type, triggerAsyncId, resource) { }
* destroy(asyncId) {}
* }
*
* class MyAddedCallbacks extends MyAsyncCallbacks {
* before(asyncId) { }
* after(asyncId) { }
* }
*
* const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
* ```
*
* Because promises are asynchronous resources whose lifecycle is tracked
* via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises.
* @since v8.1.0
* @param callbacks The `Hook Callbacks` to register
* @return Instance used for disabling and enabling hooks
*/
function createHook(callbacks: HookCallbacks): AsyncHook;
interface AsyncResourceOptions {
/**
* The ID of the execution context that created this async event.
* @default executionAsyncId()
*/
triggerAsyncId?: number | undefined;
/**
* Disables automatic `emitDestroy` when the object is garbage collected.
* This usually does not need to be set (even if `emitDestroy` is called
* manually), unless the resource's `asyncId` is retrieved and the
* sensitive API's `emitDestroy` is called with it.
* @default false
*/
requireManualDestroy?: boolean | undefined;
}
/**
* The class `AsyncResource` is designed to be extended by the embedder's async
* resources. Using this, users can easily trigger the lifetime events of their
* own resources.
*
* The `init` hook will trigger when an `AsyncResource` is instantiated.
*
* The following is an overview of the `AsyncResource` API.
*
* ```js
* import { AsyncResource, executionAsyncId } from 'async_hooks';
*
* // AsyncResource() is meant to be extended. Instantiating a
* // new AsyncResource() also triggers init. If triggerAsyncId is omitted then
* // async_hook.executionAsyncId() is used.
* const asyncResource = new AsyncResource(
* type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
* );
*
* // Run a function in the execution context of the resource. This will
* // * establish the context of the resource
* // * trigger the AsyncHooks before callbacks
* // * call the provided function `fn` with the supplied arguments
* // * trigger the AsyncHooks after callbacks
* // * restore the original execution context
* asyncResource.runInAsyncScope(fn, thisArg, ...args);
*
* // Call AsyncHooks destroy callbacks.
* asyncResource.emitDestroy();
*
* // Return the unique ID assigned to the AsyncResource instance.
* asyncResource.asyncId();
*
* // Return the trigger ID for the AsyncResource instance.
* asyncResource.triggerAsyncId();
* ```
*/
class AsyncResource {
/**
* AsyncResource() is meant to be extended. Instantiating a
* new AsyncResource() also triggers init. If triggerAsyncId is omitted then
* async_hook.executionAsyncId() is used.
* @param type The type of async event.
* @param triggerAsyncId The ID of the execution context that created
* this async event (default: `executionAsyncId()`), or an
* AsyncResourceOptions object (since v9.3.0)
*/
constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions);
/**
* Binds the given function to the current execution context.
*
* The returned function will have an `asyncResource` property referencing
* the `AsyncResource` to which the function is bound.
* @since v14.8.0, v12.19.0
* @param fn The function to bind to the current execution context.
* @param type An optional name to associate with the underlying `AsyncResource`.
*/
static bind<Func extends (this: ThisArg, ...args: any[]) => any, ThisArg>(
fn: Func,
type?: string,
thisArg?: ThisArg
): Func & {
asyncResource: AsyncResource;
};
/**
* Binds the given function to execute to this `AsyncResource`'s scope.
*
* The returned function will have an `asyncResource` property referencing
* the `AsyncResource` to which the function is bound.
* @since v14.8.0, v12.19.0
* @param fn The function to bind to the current `AsyncResource`.
*/
bind<Func extends (...args: any[]) => any>(
fn: Func
): Func & {
asyncResource: AsyncResource;
};
/**
* Call the provided function with the provided arguments in the execution context
* of the async resource. This will establish the context, trigger the AsyncHooks
* before callbacks, call the function, trigger the AsyncHooks after callbacks, and
* then restore the original execution context.
* @since v9.6.0
* @param fn The function to call in the execution context of this async resource.
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runInAsyncScope<This, Result>(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result;
/**
* Call all `destroy` hooks. This should only ever be called once. An error will
* be thrown if it is called more than once. This **must** be manually called. If
* the resource is left to be collected by the GC then the `destroy` hooks will
* never be called.
* @return A reference to `asyncResource`.
*/
emitDestroy(): this;
/**
* @return The unique `asyncId` assigned to the resource.
*/
asyncId(): number;
/**
*
* @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor.
*/
triggerAsyncId(): number;
}
interface AsyncLocalStorageOptions<T> {
/**
* Optional callback invoked before a store is propagated to a new async resource.
* Returning `true` allows propagation, returning `false` avoids it. Default is to propagate always.
* @param type The type of async event.
* @param store The current store.
* @since v18.13.0
*/
onPropagate?: ((type: string, store: T) => boolean) | undefined;
}
/**
* This class creates stores that stay coherent through asynchronous operations.
*
* While you can create your own implementation on top of the `async_hooks` module,`AsyncLocalStorage` should be preferred as it is a performant and memory safe
* implementation that involves significant optimizations that are non-obvious to
* implement.
*
* The following example uses `AsyncLocalStorage` to build a simple logger
* that assigns IDs to incoming HTTP requests and includes them in messages
* logged within each request.
*
* ```js
* import http from 'http';
* import { AsyncLocalStorage } from 'async_hooks';
*
* const asyncLocalStorage = new AsyncLocalStorage();
*
* function logWithId(msg) {
* const id = asyncLocalStorage.getStore();
* console.log(`${id !== undefined ? id : '-'}:`, msg);
* }
*
* let idSeq = 0;
* http.createServer((req, res) => {
* asyncLocalStorage.run(idSeq++, () => {
* logWithId('start');
* // Imagine any chain of async operations here
* setImmediate(() => {
* logWithId('finish');
* res.end();
* });
* });
* }).listen(8080);
*
* http.get('http://localhost:8080');
* http.get('http://localhost:8080');
* // Prints:
* // 0: start
* // 1: start
* // 0: finish
* // 1: finish
* ```
*
* Each instance of `AsyncLocalStorage` maintains an independent storage context.
* Multiple instances can safely exist simultaneously without risk of interfering
* with each other's data.
* @since v13.10.0, v12.17.0
*/
class AsyncLocalStorage<T> {
constructor(options?: AsyncLocalStorageOptions<T>);
/**
* Disables the instance of `AsyncLocalStorage`. All subsequent calls
* to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again.
*
* When calling `asyncLocalStorage.disable()`, all current contexts linked to the
* instance will be exited.
*
* Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores
* provided by the `asyncLocalStorage`, as those objects are garbage collected
* along with the corresponding async resources.
*
* Use this method when the `asyncLocalStorage` is not in use anymore
* in the current process.
* @since v13.10.0, v12.17.0
* @experimental
*/
disable(): void;
/**
* Returns the current store.
* If called outside of an asynchronous context initialized by
* calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it
* returns `undefined`.
* @since v13.10.0, v12.17.0
*/
getStore(): T | undefined;
/**
* Runs a function synchronously within a context and returns its
* return value. The store is not accessible outside of the callback function.
* The store is accessible to any asynchronous operations created within the
* callback.
*
* The optional `args` are passed to the callback function.
*
* If the callback function throws an error, the error is thrown by `run()` too.
* The stacktrace is not impacted by this call and the context is exited.
*
* Example:
*
* ```js
* const store = { id: 2 };
* try {
* asyncLocalStorage.run(store, () => {
* asyncLocalStorage.getStore(); // Returns the store object
* setTimeout(() => {
* asyncLocalStorage.getStore(); // Returns the store object
* }, 200);
* throw new Error();
* });
* } catch (e) {
* asyncLocalStorage.getStore(); // Returns undefined
* // The error will be caught here
* }
* ```
* @since v13.10.0, v12.17.0
*/
run<R, TArgs extends any[]>(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R;
/**
* Runs a function synchronously outside of a context and returns its
* return value. The store is not accessible within the callback function or
* the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`.
*
* The optional `args` are passed to the callback function.
*
* If the callback function throws an error, the error is thrown by `exit()` too.
* The stacktrace is not impacted by this call and the context is re-entered.
*
* Example:
*
* ```js
* // Within a call to run
* try {
* asyncLocalStorage.getStore(); // Returns the store object or value
* asyncLocalStorage.exit(() => {
* asyncLocalStorage.getStore(); // Returns undefined
* throw new Error();
* });
* } catch (e) {
* asyncLocalStorage.getStore(); // Returns the same object or value
* // The error will be caught here
* }
* ```
* @since v13.10.0, v12.17.0
* @experimental
*/
exit<R, TArgs extends any[]>(callback: (...args: TArgs) => R, ...args: TArgs): R;
/**
* Transitions into the context for the remainder of the current
* synchronous execution and then persists the store through any following
* asynchronous calls.
*
* Example:
*
* ```js
* const store = { id: 1 };
* // Replaces previous store with the given store object
* asyncLocalStorage.enterWith(store);
* asyncLocalStorage.getStore(); // Returns the store object
* someAsyncOperation(() => {
* asyncLocalStorage.getStore(); // Returns the same object
* });
* ```
*
* This transition will continue for the _entire_ synchronous execution.
* This means that if, for example, the context is entered within an event
* handler subsequent event handlers will also run within that context unless
* specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons
* to use the latter method.
*
* ```js
* const store = { id: 1 };
*
* emitter.on('my-event', () => {
* asyncLocalStorage.enterWith(store);
* });
* emitter.on('my-event', () => {
* asyncLocalStorage.getStore(); // Returns the same object
* });
*
* asyncLocalStorage.getStore(); // Returns undefined
* emitter.emit('my-event');
* asyncLocalStorage.getStore(); // Returns the same object
* ```
* @since v13.11.0, v12.17.0
* @experimental
*/
enterWith(store: T): void;
}
}
declare module 'node:async_hooks' {
export * from 'async_hooks';
}

2312
node_modules/@types/node/buffer.d.ts generated vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,410 @@
/**
* Clusters of Node.js processes can be used to run multiple instances of Node.js
* that can distribute workloads among their application threads. When process
* isolation is not needed, use the `worker_threads` module instead, which
* allows running multiple application threads within a single Node.js instance.
*
* The cluster module allows easy creation of child processes that all share
* server ports.
*
* ```js
* import cluster from 'cluster';
* import http from 'http';
* import { cpus } from 'os';
* import process from 'process';
*
* const numCPUs = cpus().length;
*
* if (cluster.isPrimary) {
* console.log(`Primary ${process.pid} is running`);
*
* // Fork workers.
* for (let i = 0; i < numCPUs; i++) {
* cluster.fork();
* }
*
* cluster.on('exit', (worker, code, signal) => {
* console.log(`worker ${worker.process.pid} died`);
* });
* } else {
* // Workers can share any TCP connection
* // In this case it is an HTTP server
* http.createServer((req, res) => {
* res.writeHead(200);
* res.end('hello world\n');
* }).listen(8000);
*
* console.log(`Worker ${process.pid} started`);
* }
* ```
*
* Running Node.js will now share port 8000 between the workers:
*
* ```console
* $ node server.js
* Primary 3596 is running
* Worker 4324 started
* Worker 4520 started
* Worker 6056 started
* Worker 5644 started
* ```
*
* On Windows, it is not yet possible to set up a named pipe server in a worker.
* @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/cluster.js)
*/
declare module 'cluster' {
import * as child from 'node:child_process';
import EventEmitter = require('node:events');
import * as net from 'node:net';
export interface ClusterSettings {
execArgv?: string[] | undefined; // default: process.execArgv
exec?: string | undefined;
args?: string[] | undefined;
silent?: boolean | undefined;
stdio?: any[] | undefined;
uid?: number | undefined;
gid?: number | undefined;
inspectPort?: number | (() => number) | undefined;
}
export interface Address {
address: string;
port: number;
addressType: number | 'udp4' | 'udp6'; // 4, 6, -1, "udp4", "udp6"
}
/**
* A `Worker` object contains all public information and method about a worker.
* In the primary it can be obtained using `cluster.workers`. In a worker
* it can be obtained using `cluster.worker`.
* @since v0.7.0
*/
export class Worker extends EventEmitter {
/**
* Each new worker is given its own unique id, this id is stored in the`id`.
*
* While a worker is alive, this is the key that indexes it in`cluster.workers`.
* @since v0.8.0
*/
id: number;
/**
* All workers are created using `child_process.fork()`, the returned object
* from this function is stored as `.process`. In a worker, the global `process`is stored.
*
* See: `Child Process module`.
*
* Workers will call `process.exit(0)` if the `'disconnect'` event occurs
* on `process` and `.exitedAfterDisconnect` is not `true`. This protects against
* accidental disconnection.
* @since v0.7.0
*/
process: child.ChildProcess;
/**
* Send a message to a worker or primary, optionally with a handle.
*
* In the primary, this sends a message to a specific worker. It is identical to `ChildProcess.send()`.
*
* In a worker, this sends a message to the primary. It is identical to`process.send()`.
*
* This example will echo back all messages from the primary:
*
* ```js
* if (cluster.isPrimary) {
* const worker = cluster.fork();
* worker.send('hi there');
*
* } else if (cluster.isWorker) {
* process.on('message', (msg) => {
* process.send(msg);
* });
* }
* ```
* @since v0.7.0
* @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:
*/
send(message: child.Serializable, callback?: (error: Error | null) => void): boolean;
send(message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void): boolean;
send(message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void): boolean;
/**
* This function will kill the worker. In the primary worker, it does this by
* disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`.
*
* The `kill()` function kills the worker process without waiting for a graceful
* disconnect, it has the same behavior as `worker.process.kill()`.
*
* This method is aliased as `worker.destroy()` for backwards compatibility.
*
* In a worker, `process.kill()` exists, but it is not this function;
* it is `kill()`.
* @since v0.9.12
* @param [signal='SIGTERM'] Name of the kill signal to send to the worker process.
*/
kill(signal?: string): void;
destroy(signal?: string): void;
/**
* In a worker, this function will close all servers, wait for the `'close'` event
* on those servers, and then disconnect the IPC channel.
*
* In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself.
*
* Causes `.exitedAfterDisconnect` to be set.
*
* After a server is closed, it will no longer accept new connections,
* but connections may be accepted by any other listening worker. Existing
* connections will be allowed to close as usual. When no more connections exist,
* see `server.close()`, the IPC channel to the worker will close allowing it
* to die gracefully.
*
* The above applies _only_ to server connections, client connections are not
* automatically closed by workers, and disconnect does not wait for them to close
* before exiting.
*
* In a worker, `process.disconnect` exists, but it is not this function;
* it is `disconnect()`.
*
* Because long living server connections may block workers from disconnecting, it
* may be useful to send a message, so application specific actions may be taken to
* close them. It also may be useful to implement a timeout, killing a worker if
* the `'disconnect'` event has not been emitted after some time.
*
* ```js
* if (cluster.isPrimary) {
* const worker = cluster.fork();
* let timeout;
*
* worker.on('listening', (address) => {
* worker.send('shutdown');
* worker.disconnect();
* timeout = setTimeout(() => {
* worker.kill();
* }, 2000);
* });
*
* worker.on('disconnect', () => {
* clearTimeout(timeout);
* });
*
* } else if (cluster.isWorker) {
* const net = require('net');
* const server = net.createServer((socket) => {
* // Connections never end
* });
*
* server.listen(8000);
*
* process.on('message', (msg) => {
* if (msg === 'shutdown') {
* // Initiate graceful close of any connections to server
* }
* });
* }
* ```
* @since v0.7.7
* @return A reference to `worker`.
*/
disconnect(): void;
/**
* This function returns `true` if the worker is connected to its primary via its
* IPC channel, `false` otherwise. A worker is connected to its primary after it
* has been created. It is disconnected after the `'disconnect'` event is emitted.
* @since v0.11.14
*/
isConnected(): boolean;
/**
* This function returns `true` if the worker's process has terminated (either
* because of exiting or being signaled). Otherwise, it returns `false`.
*
* ```js
* import cluster from 'cluster';
* import http from 'http';
* import { cpus } from 'os';
* import process from 'process';
*
* const numCPUs = cpus().length;
*
* if (cluster.isPrimary) {
* console.log(`Primary ${process.pid} is running`);
*
* // Fork workers.
* for (let i = 0; i < numCPUs; i++) {
* cluster.fork();
* }
*
* cluster.on('fork', (worker) => {
* console.log('worker is dead:', worker.isDead());
* });
*
* cluster.on('exit', (worker, code, signal) => {
* console.log('worker is dead:', worker.isDead());
* });
* } else {
* // Workers can share any TCP connection. In this case, it is an HTTP server.
* http.createServer((req, res) => {
* res.writeHead(200);
* res.end(`Current process\n ${process.pid}`);
* process.kill(process.pid);
* }).listen(8000);
* }
* ```
* @since v0.11.14
*/
isDead(): boolean;
/**
* This property is `true` if the worker exited due to `.disconnect()`.
* If the worker exited any other way, it is `false`. If the
* worker has not exited, it is `undefined`.
*
* The boolean `worker.exitedAfterDisconnect` allows distinguishing between
* voluntary and accidental exit, the primary may choose not to respawn a worker
* based on this value.
*
* ```js
* cluster.on('exit', (worker, code, signal) => {
* if (worker.exitedAfterDisconnect === true) {
* console.log('Oh, it was just voluntary no need to worry');
* }
* });
*
* // kill worker
* worker.kill();
* ```
* @since v6.0.0
*/
exitedAfterDisconnect: boolean;
/**
* events.EventEmitter
* 1. disconnect
* 2. error
* 3. exit
* 4. listening
* 5. message
* 6. online
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'disconnect', listener: () => void): this;
addListener(event: 'error', listener: (error: Error) => void): this;
addListener(event: 'exit', listener: (code: number, signal: string) => void): this;
addListener(event: 'listening', listener: (address: Address) => void): this;
addListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: 'online', listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'disconnect'): boolean;
emit(event: 'error', error: Error): boolean;
emit(event: 'exit', code: number, signal: string): boolean;
emit(event: 'listening', address: Address): boolean;
emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean;
emit(event: 'online'): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'disconnect', listener: () => void): this;
on(event: 'error', listener: (error: Error) => void): this;
on(event: 'exit', listener: (code: number, signal: string) => void): this;
on(event: 'listening', listener: (address: Address) => void): this;
on(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: 'online', listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'disconnect', listener: () => void): this;
once(event: 'error', listener: (error: Error) => void): this;
once(event: 'exit', listener: (code: number, signal: string) => void): this;
once(event: 'listening', listener: (address: Address) => void): this;
once(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: 'online', listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'disconnect', listener: () => void): this;
prependListener(event: 'error', listener: (error: Error) => void): this;
prependListener(event: 'exit', listener: (code: number, signal: string) => void): this;
prependListener(event: 'listening', listener: (address: Address) => void): this;
prependListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: 'online', listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'disconnect', listener: () => void): this;
prependOnceListener(event: 'error', listener: (error: Error) => void): this;
prependOnceListener(event: 'exit', listener: (code: number, signal: string) => void): this;
prependOnceListener(event: 'listening', listener: (address: Address) => void): this;
prependOnceListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: 'online', listener: () => void): this;
}
export interface Cluster extends EventEmitter {
disconnect(callback?: () => void): void;
fork(env?: any): Worker;
/** @deprecated since v16.0.0 - use isPrimary. */
readonly isMaster: boolean;
readonly isPrimary: boolean;
readonly isWorker: boolean;
schedulingPolicy: number;
readonly settings: ClusterSettings;
/** @deprecated since v16.0.0 - use setupPrimary. */
setupMaster(settings?: ClusterSettings): void;
/**
* `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings.
*/
setupPrimary(settings?: ClusterSettings): void;
readonly worker?: Worker | undefined;
readonly workers?: NodeJS.Dict<Worker> | undefined;
readonly SCHED_NONE: number;
readonly SCHED_RR: number;
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'disconnect', listener: (worker: Worker) => void): this;
addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
addListener(event: 'fork', listener: (worker: Worker) => void): this;
addListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
addListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: 'online', listener: (worker: Worker) => void): this;
addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'disconnect', worker: Worker): boolean;
emit(event: 'exit', worker: Worker, code: number, signal: string): boolean;
emit(event: 'fork', worker: Worker): boolean;
emit(event: 'listening', worker: Worker, address: Address): boolean;
emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
emit(event: 'online', worker: Worker): boolean;
emit(event: 'setup', settings: ClusterSettings): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'disconnect', listener: (worker: Worker) => void): this;
on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
on(event: 'fork', listener: (worker: Worker) => void): this;
on(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
on(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: 'online', listener: (worker: Worker) => void): this;
on(event: 'setup', listener: (settings: ClusterSettings) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'disconnect', listener: (worker: Worker) => void): this;
once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
once(event: 'fork', listener: (worker: Worker) => void): this;
once(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
once(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: 'online', listener: (worker: Worker) => void): this;
once(event: 'setup', listener: (settings: ClusterSettings) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'disconnect', listener: (worker: Worker) => void): this;
prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
prependListener(event: 'fork', listener: (worker: Worker) => void): this;
prependListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
// the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: 'message', listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void): this;
prependListener(event: 'online', listener: (worker: Worker) => void): this;
prependListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this;
prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this;
prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this;
prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this;
// the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this;
prependOnceListener(event: 'online', listener: (worker: Worker) => void): this;
prependOnceListener(event: 'setup', listener: (settings: ClusterSettings) => void): this;
}
const cluster: Cluster;
export default cluster;
}
declare module 'node:cluster' {
export * from 'cluster';
export { default as default } from 'cluster';
}

@ -0,0 +1,412 @@
/**
* The `console` module provides a simple debugging console that is similar to the
* JavaScript console mechanism provided by web browsers.
*
* The module exports two specific components:
*
* * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream.
* * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`.
*
* _**Warning**_: The global console object's methods are neither consistently
* synchronous like the browser APIs they resemble, nor are they consistently
* asynchronous like all other Node.js streams. See the `note on process I/O` for
* more information.
*
* Example using the global `console`:
*
* ```js
* console.log('hello world');
* // Prints: hello world, to stdout
* console.log('hello %s', 'world');
* // Prints: hello world, to stdout
* console.error(new Error('Whoops, something bad happened'));
* // Prints error message and stack trace to stderr:
* // Error: Whoops, something bad happened
* // at [eval]:5:15
* // at Script.runInThisContext (node:vm:132:18)
* // at Object.runInThisContext (node:vm:309:38)
* // at node:internal/process/execution:77:19
* // at [eval]-wrapper:6:22
* // at evalScript (node:internal/process/execution:76:60)
* // at node:internal/main/eval_string:23:3
*
* const name = 'Will Robinson';
* console.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to stderr
* ```
*
* Example using the `Console` class:
*
* ```js
* const out = getStreamSomehow();
* const err = getStreamSomehow();
* const myConsole = new console.Console(out, err);
*
* myConsole.log('hello world');
* // Prints: hello world, to out
* myConsole.log('hello %s', 'world');
* // Prints: hello world, to out
* myConsole.error(new Error('Whoops, something bad happened'));
* // Prints: [Error: Whoops, something bad happened], to err
*
* const name = 'Will Robinson';
* myConsole.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to err
* ```
* @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/console.js)
*/
declare module 'console' {
import console = require('node:console');
export = console;
}
declare module 'node:console' {
import { InspectOptions } from 'node:util';
global {
// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build
interface Console {
Console: console.ConsoleConstructor;
/**
* `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only
* writes a message and does not otherwise affect execution. The output always
* starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`.
*
* If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens.
*
* ```js
* console.assert(true, 'does nothing');
*
* console.assert(false, 'Whoops %s work', 'didn\'t');
* // Assertion failed: Whoops didn't work
*
* console.assert();
* // Assertion failed
* ```
* @since v0.1.101
* @param value The value tested for being truthy.
* @param message All arguments besides `value` are used as error message.
*/
assert(value: any, message?: string, ...optionalParams: any[]): void;
/**
* When `stdout` is a TTY, calling `console.clear()` will attempt to clear the
* TTY. When `stdout` is not a TTY, this method does nothing.
*
* The specific operation of `console.clear()` can vary across operating systems
* and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the
* current terminal viewport for the Node.js
* binary.
* @since v8.3.0
*/
clear(): void;
/**
* Maintains an internal counter specific to `label` and outputs to `stdout` the
* number of times `console.count()` has been called with the given `label`.
*
* ```js
* > console.count()
* default: 1
* undefined
* > console.count('default')
* default: 2
* undefined
* > console.count('abc')
* abc: 1
* undefined
* > console.count('xyz')
* xyz: 1
* undefined
* > console.count('abc')
* abc: 2
* undefined
* > console.count()
* default: 3
* undefined
* >
* ```
* @since v8.3.0
* @param label The display label for the counter.
*/
count(label?: string): void;
/**
* Resets the internal counter specific to `label`.
*
* ```js
* > console.count('abc');
* abc: 1
* undefined
* > console.countReset('abc');
* undefined
* > console.count('abc');
* abc: 1
* undefined
* >
* ```
* @since v8.3.0
* @param label The display label for the counter.
*/
countReset(label?: string): void;
/**
* The `console.debug()` function is an alias for {@link log}.
* @since v8.0.0
*/
debug(message?: any, ...optionalParams: any[]): void;
/**
* Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`.
* This function bypasses any custom `inspect()` function defined on `obj`.
* @since v0.1.101
*/
dir(obj: any, options?: InspectOptions): void;
/**
* This method calls `console.log()` passing it the arguments received.
* This method does not produce any XML formatting.
* @since v8.0.0
*/
dirxml(...data: any[]): void;
/**
* Prints to `stderr` with newline. Multiple arguments can be passed, with the
* first used as the primary message and all additional used as substitution
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`).
*
* ```js
* const code = 5;
* console.error('error #%d', code);
* // Prints: error #5, to stderr
* console.error('error', code);
* // Prints: error 5, to stderr
* ```
*
* If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string
* values are concatenated. See `util.format()` for more information.
* @since v0.1.100
*/
error(message?: any, ...optionalParams: any[]): void;
/**
* Increases indentation of subsequent lines by spaces for `groupIndentation`length.
*
* If one or more `label`s are provided, those are printed first without the
* additional indentation.
* @since v8.5.0
*/
group(...label: any[]): void;
/**
* An alias for {@link group}.
* @since v8.5.0
*/
groupCollapsed(...label: any[]): void;
/**
* Decreases indentation of subsequent lines by spaces for `groupIndentation`length.
* @since v8.5.0
*/
groupEnd(): void;
/**
* The `console.info()` function is an alias for {@link log}.
* @since v0.1.100
*/
info(message?: any, ...optionalParams: any[]): void;
/**
* Prints to `stdout` with newline. Multiple arguments can be passed, with the
* first used as the primary message and all additional used as substitution
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`).
*
* ```js
* const count = 5;
* console.log('count: %d', count);
* // Prints: count: 5, to stdout
* console.log('count:', count);
* // Prints: count: 5, to stdout
* ```
*
* See `util.format()` for more information.
* @since v0.1.100
*/
log(message?: any, ...optionalParams: any[]): void;
/**
* Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just
* logging the argument if it cant be parsed as tabular.
*
* ```js
* // These can't be parsed as tabular data
* console.table(Symbol());
* // Symbol()
*
* console.table(undefined);
* // undefined
*
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
* // ┌─────────┬─────┬─────┐
* // │ (index) │ a │ b │
* // ├─────────┼─────┼─────┤
* // │ 0 │ 1 │ 'Y' │
* // │ 1 │ 'Z' │ 2 │
* // └─────────┴─────┴─────┘
*
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
* // ┌─────────┬─────┐
* // │ (index) │ a │
* // ├─────────┼─────┤
* // │ 0 │ 1 │
* // │ 1 │ 'Z' │
* // └─────────┴─────┘
* ```
* @since v10.0.0
* @param properties Alternate properties for constructing the table.
*/
table(tabularData: any, properties?: ReadonlyArray<string>): void;
/**
* Starts a timer that can be used to compute the duration of an operation. Timers
* are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in
* suitable time units to `stdout`. For example, if the elapsed
* time is 3869ms, `console.timeEnd()` displays "3.869s".
* @since v0.1.104
*/
time(label?: string): void;
/**
* Stops a timer that was previously started by calling {@link time} and
* prints the result to `stdout`:
*
* ```js
* console.time('100-elements');
* for (let i = 0; i < 100; i++) {}
* console.timeEnd('100-elements');
* // prints 100-elements: 225.438ms
* ```
* @since v0.1.104
*/
timeEnd(label?: string): void;
/**
* For a timer that was previously started by calling {@link time}, prints
* the elapsed time and other `data` arguments to `stdout`:
*
* ```js
* console.time('process');
* const value = expensiveProcess1(); // Returns 42
* console.timeLog('process', value);
* // Prints "process: 365.227ms 42".
* doExpensiveProcess2(value);
* console.timeEnd('process');
* ```
* @since v10.7.0
*/
timeLog(label?: string, ...data: any[]): void;
/**
* Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code.
*
* ```js
* console.trace('Show me');
* // Prints: (stack trace will vary based on where trace is called)
* // Trace: Show me
* // at repl:2:9
* // at REPLServer.defaultEval (repl.js:248:27)
* // at bound (domain.js:287:14)
* // at REPLServer.runBound [as eval] (domain.js:300:12)
* // at REPLServer.<anonymous> (repl.js:412:12)
* // at emitOne (events.js:82:20)
* // at REPLServer.emit (events.js:169:7)
* // at REPLServer.Interface._onLine (readline.js:210:10)
* // at REPLServer.Interface._line (readline.js:549:8)
* // at REPLServer.Interface._ttyWrite (readline.js:826:14)
* ```
* @since v0.1.104
*/
trace(message?: any, ...optionalParams: any[]): void;
/**
* The `console.warn()` function is an alias for {@link error}.
* @since v0.1.100
*/
warn(message?: any, ...optionalParams: any[]): void;
// --- Inspector mode only ---
/**
* This method does not display anything unless used in the inspector.
* Starts a JavaScript CPU profile with an optional label.
*/
profile(label?: string): void;
/**
* This method does not display anything unless used in the inspector.
* Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector.
*/
profileEnd(label?: string): void;
/**
* This method does not display anything unless used in the inspector.
* Adds an event with the label `label` to the Timeline panel of the inspector.
*/
timeStamp(label?: string): void;
}
/**
* The `console` module provides a simple debugging console that is similar to the
* JavaScript console mechanism provided by web browsers.
*
* The module exports two specific components:
*
* * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream.
* * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`.
*
* _**Warning**_: The global console object's methods are neither consistently
* synchronous like the browser APIs they resemble, nor are they consistently
* asynchronous like all other Node.js streams. See the `note on process I/O` for
* more information.
*
* Example using the global `console`:
*
* ```js
* console.log('hello world');
* // Prints: hello world, to stdout
* console.log('hello %s', 'world');
* // Prints: hello world, to stdout
* console.error(new Error('Whoops, something bad happened'));
* // Prints error message and stack trace to stderr:
* // Error: Whoops, something bad happened
* // at [eval]:5:15
* // at Script.runInThisContext (node:vm:132:18)
* // at Object.runInThisContext (node:vm:309:38)
* // at node:internal/process/execution:77:19
* // at [eval]-wrapper:6:22
* // at evalScript (node:internal/process/execution:76:60)
* // at node:internal/main/eval_string:23:3
*
* const name = 'Will Robinson';
* console.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to stderr
* ```
*
* Example using the `Console` class:
*
* ```js
* const out = getStreamSomehow();
* const err = getStreamSomehow();
* const myConsole = new console.Console(out, err);
*
* myConsole.log('hello world');
* // Prints: hello world, to out
* myConsole.log('hello %s', 'world');
* // Prints: hello world, to out
* myConsole.error(new Error('Whoops, something bad happened'));
* // Prints: [Error: Whoops, something bad happened], to err
*
* const name = 'Will Robinson';
* myConsole.warn(`Danger ${name}! Danger!`);
* // Prints: Danger Will Robinson! Danger!, to err
* ```
* @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js)
*/
namespace console {
interface ConsoleConstructorOptions {
stdout: NodeJS.WritableStream;
stderr?: NodeJS.WritableStream | undefined;
ignoreErrors?: boolean | undefined;
colorMode?: boolean | 'auto' | undefined;
inspectOptions?: InspectOptions | undefined;
/**
* Set group indentation
* @default 2
*/
groupIndentation?: number | undefined;
}
interface ConsoleConstructor {
prototype: Console;
new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console;
new (options: ConsoleConstructorOptions): Console;
}
}
var console: Console;
}
export = globalThis.console;
}

@ -0,0 +1,18 @@
/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */
declare module 'constants' {
import { constants as osConstants, SignalConstants } from 'node:os';
import { constants as cryptoConstants } from 'node:crypto';
import { constants as fsConstants } from 'node:fs';
const exp: typeof osConstants.errno &
typeof osConstants.priority &
SignalConstants &
typeof cryptoConstants &
typeof fsConstants;
export = exp;
}
declare module 'node:constants' {
import constants = require('constants');
export = constants;
}

3973
node_modules/@types/node/crypto.d.ts generated vendored

File diff suppressed because it is too large Load Diff

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