update code

This commit is contained in:
Nawaaz 2024-03-07 18:31:44 +05:30
commit 3362fdbfc8
4521 changed files with 1818551 additions and 0 deletions

3
.env Normal file
View File

@ -0,0 +1,3 @@
PORT = 6200
URI = "mongodb+srv://suyash:JDZ71uD7DSUG1AaG@cluster0.9etwp.mongodb.net/"
secretKey = "Hello Mr DJ"

5
configs/auth.config.js Normal file
View File

@ -0,0 +1,5 @@
module.exports = {
secretKey : process.env.secretKey
}

5
configs/db.config.js Normal file
View File

@ -0,0 +1,5 @@
module.exports = {
URI : process.env.URI
}

9
configs/server.config.js Normal file
View File

@ -0,0 +1,9 @@
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
module.exports = {
PORT: process.env.PORT
}

View File

@ -0,0 +1,174 @@
const User = require('../models/user.model');
const constant = require('../util/constant')
const bcrypt = require('bcryptjs');
const objectConverter = require('../util/objectConverter');
const createAdmin = async (req, res) => {
try {
let user = await User.findOne({ userTypes: constant.userTypes.admin })
if (user) {
console.log('Admin Already Created', user);
return res.status(201).send({
message: 'Admin already created'
});
}
let obj = {
email: req.body.email ? req.body.email : undefined,
password: req.body.password ? bcrypt.hashSync(req.body.password) : undefined,
userName: 'Admin',
userTypes: constant.userTypes.admin
}
if (req.file) {
const { filename, path } = req.file;
obj["image"] = {
fileName: filename,
fileAddress: path
}
}
console.log(obj);
await User.create(obj);
res.status(200).send({
errorCode: 200,
message: 'Admin Got Created'
})
console.log('Admin got created');
} catch (err) {
console.log(err);
res.status(500).send({
errorCode: 500,
message: 'Internal Error while creating Admin'
})
}
}
const getList = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skipIndex = (page - 1) * limit;
const searchQuery = req.query.search || ''; // Get search query from request query parameters
let obj = {
userTypes: constant.userTypes.customer
};
// Add search functionality
if (searchQuery) {
obj.$or = [
{ username: { $regex: searchQuery, $options: 'i' } }, // Case-insensitive search for username
{ email: { $regex: searchQuery, $options: 'i' } } // Case-insensitive search for email
];
}
const users = await User.find(obj)
.limit(limit)
.skip(skipIndex);
const totalCount = await User.countDocuments(obj);
console.log('users', users)
return res.status(200).send({
status: 200,
message: 'Users retrieved successfully',
users: users,
total_pages: Math.ceil(totalCount / limit),
current_page: page
});
} catch (err) {
console.error(err);
return res.status(500).send({
status: 500,
message: 'Internal Server Error',
error: err.message
});
}
};
const update = async (req, res) => {
try {
let adminId = req.userId;
let obj = {
userName: req.body.userName ? req.body.userName : undefined,
email: req.body.email ? req.body.email : undefined,
password: req.body.password ? bcrypt.hashSync(req.body.password) : undefined,
}
if (req.file) {
const { filename, path } = req.file
obj.image = {
fileName: filename,
fileAddress: path,
}
}
await User.findOneAndUpdate({ _id: adminId }, { $set: obj });
return res.status(201).send({
error_code: 200,
message: 'Admin got updated'
})
} catch (err) {
console.log('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: "Internal Server Error"
})
}
}
const userStatus = async (req, res) => {
try {
const { id } = req.params;
const userData = await User.findById(id);
if (!userData) {
return res.status(400).send({
error_code: 400,
message: 'User not found'
});
}
userData.status = userData.status === 'activate' ? 'deactivate' : 'activate';
await userData.save();
res.status(200).send({
message: `User status toggled successfully to ${userData.status}`,
user: userData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
module.exports = {
createAdmin,
getList,
update, userStatus
}

View File

@ -0,0 +1,192 @@
const constant = require('../util/ads.constant');
const Ads = require('../models/Ads.model')
const create = async (req, res) => {
try {
console.log('create add')
const fileName = req.files[0].filename ;
let obj = {
adsTitle: req.body.adsTitle ? req.body.adsTitle : undefined,
redirectLink: req.body.redirectLink ? req.body.redirectLink : undefined,
advertiseAs: req.body.advertiseAs ? req.body.advertiseAs : undefined,
status: req.body.status ? req.body.status : undefined
}
if (req.body.advertiseAs == constant.adsType.image) {
obj[constant.field.advertiseImage] = "/uploads/" + fileName
}
else {
obj[constant.field.advertiseVideo] = "/uploads/" + fileName
}
const ad = await Ads.create(obj);
return res.status(201).send({
error_code : 200,
message: `Ad with ${req.body.advertiseAs} got created`
})
} catch (err) {
console.log('Error inside create of Ads Controller', err);
res.status(500).send({
error_code : 500,
message: "Internal Server Error"
})
}
}
const getad = async(req,res) => {
try{
let obj = {}
const ads = await Ads.find(obj);
return res.status(200).send(constant.adsGenerator(ads, req));
}catch(err){
console.log('Error inside getad Controller',err);
res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const updateAds = async(req,res) => {
try{
const ad = await Ads.findById(req.params.id);
let obj = {
adsTitle: req.body.adsTitle ? req.body.adsTitle : undefined,
redirectLink: req.body.redirectLink ? req.body.redirectLink : undefined,
status: req.body.status ? req.body.status : undefined
}
if(req.body.advertiseAs)
{
const fileName = req.files[0].filename ;
if (req.body.advertiseAs == constant.adsType.image) {
obj[constant.field.advertiseImage] = "/uploads/" + fileName
delete ad.advertiseVideo;
}
else {
obj[constant.field.advertiseVideo] = "/uploads/" + fileName
delete ad.advertiseImage;
}
}
await ad.updateOne(obj);
res.status(201).send({
error_code : 200,
message : 'Ads got updated'
})
}catch(err){
console.log('Error inside updateAds Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const deletead = async(req,res) => {
try{
let id = req.params.id;
await Ads.deleteOne({_id :id});
return res.status(201).send({
error_code : 200,
message : 'ads got deleted'
})
}catch(err){
console.log('Error Occured inside deletead of ads Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
};
const updateAdsTime = async (req, res) => {
try {
const { id } = req.params;
const { adsTiming } = req.body; // Assuming adsTiming is provided in minutes
// Find the advertisement by ID
const ad = await Ads.findById(id);
// If the advertisement is not found, return 404 Not Found
if (!ad) {
return res.status(404).json({ error_code: 404, message: 'Advertisement not found' });
}
// Update the advertisement's show timing
ad.adsTime = adsTiming; // Assuming adsTiming is in minutes
await ad.save();
// Send success response
return res.status(200).json({ error_code: 200, message: 'Advertisement show timing updated successfully' });
} catch (err) {
console.error('Error inside updateAdsTime Controller:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
// const updateAdsStatus = async (req, res) => {
// try {
// const { id } = req.params;
// // Find the advertisement by ID
// const ad = await Ads.findById(id);
// // If the advertisement is not found, return 404 Not Found
// if (!ad) {
// return res.status(404).json({ error_code: 404, message: 'Advertisement not found' });
// }
// // Toggle the advertisement status between active and inactive
// ad.status = ad.status === constant.status.active ? constant.status.inactive : constant.status.active;
// await ad.save();
// // Send success response
// return res.status(200).json({ error_code: 200, message: 'Advertisement status updated successfully' });
// } catch (err) {
// console.error('Error inside updateAdsStatus Controller:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
const updateAdsStatus = async (req, res) => {
try {
const { id } = req.params;
const adsData = await Ads.findById(id);
if (!adsData) {
return res.status(400).send({
error_code: 400,
message: 'Ads not found'
});
}
adsData.status = adsData.status === 'activate' ? 'deactivate' : 'activate';
await adsData.save();
res.status(200).send({
message: `ads status toggled successfully to ${adsData.status}`,
adsData: adsData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
module.exports = {
create,
getad,
updateAds,
deletead,
updateAdsTime,
// updateAdsStatus
updateAdsStatus
}

View File

@ -0,0 +1,208 @@
const Artist = require('../models/artist.model');
// Create Artist
const createArtist = async (req, res) => {
try {
const { ArtistName } = req.body;
// Check if the required fields are present in the request body
if (!ArtistName) {
return res.status(400).send({
error_code: 400,
message: "Artist name is required"
});
}
let obj = {
ArtistName: ArtistName,
};
if (req.file) {
obj["image"] = {
fileName: req.file.filename,
fileAddress: req.file.path
};
}
// Save 'obj' to the database
const newArtist = await Artist.create(obj);
// Return a success response with the newly created Artist
return res.status(201).send({
error_code: 200,
message: "Artist created",
Artist: newArtist
});
} catch (err) {
console.log("Error inside createArtist Controller", err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
};
// Update Artist
const updateArtist = async (req, res) => {
try {
const artistId = req.params.id;
const updates = req.body;
// Update artist by ID
const updatedArtist = await Artist.findByIdAndUpdate(artistId, updates, { new: true });
// Check if the artist exists
if (!updatedArtist) {
return res.status(404).send({
error_code: 404,
message: "Artist not found"
});
}
return res.status(200).send({
error_code: 200,
message: "Artist updated successfully",
Artist: updatedArtist
});
} catch (err) {
console.log("Error inside updateArtist Controller", err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
};
// Delete Artist
const deleteArtist = async (req, res) => {
try {
const artistId = req.params.id;
// Delete artist by ID
const deletedArtist = await Artist.findByIdAndDelete(artistId);
// Check if the artist exists
if (!deletedArtist) {
return res.status(404).send({
error_code: 404,
message: "Artist not found"
});
}
return res.status(200).send({
error_code: 200,
message: "Artist deleted successfully"
});
} catch (err) {
console.log("Error inside deleteArtist Controller", err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
};
// Get Artist by ID
const getArtistById = async (req, res) => {
try {
const { id } = req.params;
// Find artist by ID
const artist = await Artist.findById(id);
console.log("🚀 ~ getArtistById ~ artist:", artist)
// Check if the artist exists
if (!artist) {
return res.status(404).send({
error_code: 404,
message: "Artist not found"
});
}
return res.status(200).send({
error_code: 200,
message: "Artist found",
Artist: artist
});
} catch (err) {
console.log("Error inside getArtistById Controller", err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
};
// Change Artist Status
const changeArtistStatus = async (req, res) => {
try {
const { id } = req.params;
const artistData = await Artist.findById(id);
if (!artistData) {
return res.status(400).send({
error_code: 400,
message: 'Ads not found'
});
}
artistData.status = artistData.status === 'activate' ? 'deactivate' : 'activate';
await artistData.save();
res.status(200).send({
message: `ads status toggled successfully to ${artistData.status}`,
artistData: artistData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const getAllArtist = async (req, res) => {
try {
// Pagination parameters
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;
// Search query
const searchQuery = req.query.search || '';
// Fetch artists with pagination and search
const artistsQuery = Artist.find();
if (searchQuery) {
artistsQuery.where('ArtistName').regex(new RegExp(searchQuery, 'i'));
}
const artists = await artistsQuery.skip(skip).limit(limit);
// Count total number of artists for pagination
const totalCount = await Artist.countDocuments(artistsQuery.getQuery());
return res.status(200).json({
error_code: 200,
message: 'Artists fetched successfully',
artists,
currentPage: page,
totalPages: Math.ceil(totalCount / limit)
});
} catch (error) {
console.error('Error inside getAllArtist controller:', error);
return res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
module.exports = {
createArtist,
updateArtist,
deleteArtist,
getArtistById,
changeArtistStatus, getAllArtist
};

View File

@ -0,0 +1,73 @@
const Form = require('../models/Form.model');
const constant = require('../util/form.constant')
const create = async(req,res) => {
try {
let obj =
{
userName : req.body.userName ? req.body.userName : undefined,
email :req.body.email ? req.body.email : undefined,
subject : req.body.subject ? req.body.subject : undefined,
message : req.body.message ? req.body.message : undefined
}
await Form.create(obj);
return res.status(201).send({
error_code : 200,
message : 'Form got created'
})
}catch(err){
console.log('Error inside createform controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const updateForm = async(req,res) => {
try{
let id = req.params.id
const form = await Form.findById(id)
let obj = {
reply : req.body.reply ? req.body.reply : undefined
}
await form.updateOne(obj);
return res.status(201).send({
error_code : 200,
message : 'Form got updated'
})
}catch(err){
console.log('Error inside updateFrom controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const getForm = async(req,res) => {
try{
let obj= {};
if(req.query.userName){
obj['userName'] = req.query['userName'];
}
const form = await Form.find(obj);
console.log(form);
return res.status(201).send(constant.objectConverter(form));
}
catch(err){
console.log('Error inside getForm',err);
return res.status(201).send({
error_code : 200,
message : 'Internal server Error'
})
}
}
module.exports = {
create,
updateForm,
getForm
}

View File

@ -0,0 +1,82 @@
const Reward = require('../models/Reward.model');
const createReward = async(req,res) => {
try{
const obj = {
score : req.body.score ? req.body.score : undefined,
reward : req.body.reward ? req.body.reward : undefined
}
await Reward.create(obj);
return res.status(201).send({
error_code : 200,
message : 'Reward Got Created'
})
}catch(err){
console.log('Error inside createReward Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const updateReward = async(req,res) => {
try{
const reward = await Reward.findById(req.params.id);
const obj = {
reward : req.body.reward ? req.body.reward : undefined
}
await reward.updateOne(obj);
await reward.save();
return res.status(201).send({
error_code : 200,
message : 'Reward got updated'
})
}catch(err){
console.log('Error inside updateReward',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const deleteReward = async(req,res) => {
try{
await Reward.deleteOne(req.params.id);
return res.status(201).send({
error_code : 200,
message : 'Reward got Deleted'
})
}catch(err){
console.log('Error inside deleteReward Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const getReward = async(req,res) => {
try{
const rewardList = await Reward.find({});
return res.status(201).send(rewardList);
}catch(err){
console.log('Error inside getRewardController',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
module.exports = {
createReward,
updateReward,
deleteReward,
getReward,
}

View File

@ -0,0 +1,53 @@
const TermsandCondition = require('../models/TermsCondition.model');
const createTermsCondition = async function (req, res) {
try {
let obj = {
termsandCondition : req.body.termsandCondition ? req.body.termsandCondition : undefined
}
await TermsandCondition.create(obj);
return res.status(201).send({
error_code : 200,
message: "Terms and Condition added successfully..!",
});
} catch (error) {
console.log(error)
return res.status(500).send({
error_code : 500,
message: error,
});
}
};
const updateTermsCondition = async function (req, res) {
try {
let id = req.params.id;
let obj = {
termsandCondition : req.body.termsandCondition ? req.body.termsandCondition : undefined
}
await TermsandCondition.findByIdAndUpdate(
{ _id: id },
{ $set: obj },
{ new: true }
);
return res.status(201).send({
error_code : 200,
message: "Terms and Condition update successfully..!",
});
} catch (error) {
console.log(error);
return res.status(500).send({
error_code : 500,
message: error,
});
}
};
module.exports = {
createTermsCondition,
updateTermsCondition
}

View File

@ -0,0 +1,92 @@
const adsSetting = require('../models/adsSetting.model');
const objectGenerator = require('../util/adsSetting')
const createSetting = async(req,res) => {
try{
const present = await adsSetting.find({});
let data = req.body
console.log(present);
if(present.length){
return res.status(400).send({
error_code : 400,
message : "Can't be created"
})
}
let obj = {
adsTiming : {
minutes : req.body.adsTiming.minutes? req.body.adsTiming.minutes : undefined,
seconds : req.body.adsTiming.seconds ? req.body.adsTiming.seconds : undefined
},
adsStatus : req.body.adsStatus ? req.body.adsStatus : undefined,
}
console.log(obj);
const setting = await adsSetting.create(obj);
console.log(setting);
res.status(201).send({
error_code : 200,
message : 'AdsSetting got Configured'
})
}catch(err) {
console.log('Error inside CreatSetting Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const getSetting = async(req,res) => {
try{
const setting = await adsSetting.find({});
return res.status(200).send(objectGenerator.adsSettingGenerator(setting))
}catch(err){
console.log('Error inside getSetting Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const updateSetting = async(req,res) => {
try{
let id = req.params.id ;
const setting = await adsSetting.findById(id);
let obj = {
adsTiming : {
minutes : req.body.adsTiming.minutes? req.body.adsTiming.minutes : undefined,
seconds : req.body.adsTiming.seconds ? req.body.adsTiming.seconds : undefined
},
adsStatus : req.body.adsStatus ? req.body.adsStatus : undefined,
}
await setting.updateOne(obj);
await setting.save();
return res.status(201).send({
error_code : 200,
message : 'Setting got updated'
})
}catch(err){
console.log('Error inside updateSetting Controller',err);
return res.status(500).send({
error_code : 500,
message : "Internal server Error"
})
}
}
module.exports = {
createSetting,
getSetting,
updateSetting
}

View File

@ -0,0 +1,238 @@
const Album = require('../models/album.model');
const SubCategories = require('../models/subcategories.model')
const Categories = require('../models/categories.model')
const createAlbum = async (req, res) => {
try {
const { categoryId, subcategoryId, albumName, shortDescription } = req.body;
if (!categoryId || !subcategoryId) {
return res.status(400).json({
error_code: 400,
message: "Category ID and Subcategory ID are required"
});
}
const category = await Categories.findById(categoryId);
if (!category) {
return res.status(404).json({
error_code: 404,
message: "Category not found"
});
}
const subcategory = await SubCategories.findById(subcategoryId);
if (!subcategory) {
return res.status(404).json({
error_code: 404,
message: "Subcategory not found"
});
}
const albumObj = {
categoryId: categoryId,
subcategoryId: subcategoryId,
albumName,
shortDescription,
image: req.file ? {
fileName: req.file.filename,
fileAddress: req.file.path
} : undefined
};
const album = await Album.create(albumObj);
return res.status(201).json({ error_code: 200, message: "Album created successfully", album: album });
} catch (err) {
console.error("Error inside CreateAlbum Controller", err);
return res.status(500).json({ error_code: 500, message: "Internal Server Error" });
}
};
const updateAlbum = async (req, res) => {
try {
const { id } = req.params;
const { categoryId, subcategoryId, albumName, shortDescription } = req.body;
// Check if the album ID is provided
if (!id) {
return res.status(400).json({
error_code: 400,
message: "Album ID is required"
});
}
// Check if the required fields are present in the request body
if (!categoryId || !subcategoryId) {
return res.status(400).json({
error_code: 400,
message: "Category ID and Subcategory ID are required"
});
}
// Find the album by ID
const album = await Album.findById(id);
if (!album) {
return res.status(404).json({
error_code: 404,
message: "Album not found"
});
}
// Find the category and subcategory by their IDs
const category = await Categories.findById(categoryId);
const subcategory = await SubCategories.findById(subcategoryId);
// Check if the category and subcategory exist
if (!category || !subcategory) {
return res.status(404).json({
error_code: 404,
message: "Category or Subcategory not found"
});
}
// Update album fields
album.set({
categoryId,
subcategoryId,
albumName,
shortDescription,
image: req.file ? {
fileName: req.file.filename,
fileAddress: req.file.path
} : album.image // Retain existing image if no new file provided
});
// Save the updated album
await album.save();
return res.status(200).json({
error_code: 200,
message: "Album updated successfully",
album:album
});
} catch (err) {
console.error("Error inside UpdateAlbum Controller", err);
return res.status(500).json({
error_code: 500,
message: "Internal Server Error"
});
}
};
const deleteAlbum = async (req, res) => {
try {
// Find the album by ID and delete it
const deletedAlbum = await Album.findByIdAndDelete(req.params.id);
if (!deletedAlbum) {
return res.status(404).send({
error_code: 404,
message: "Album not found"
});
}
return res.status(200).send({
error_code: 200,
message: "Album deleted successfully"
});
} catch (err) {
console.log("Error inside DeleteAlbum Controller", err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
}
const changeAlbumStatus = async (req, res) => {
try {
const { id } = req.params;
const albumData = await Album.findById(id);
if (!albumData) {
return res.status(400).send({
error_code: 400,
message: 'album not found'
});
}
albumData.status = albumData.status === 'activate' ? 'deactivate' : 'activate';
await albumData.save();
res.status(200).send({
message: `ads status toggled successfully to ${albumData.status}`,
albumData: albumData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const getAlbums = async (req, res) => {
try {
// Pagination parameters
const { page = 1, limit = 10, search: searchQuery = '' } = req.query;
const skip = (page - 1) * limit;
// Find albums with pagination and search
const albums = await Album.find({
$or: [
{ albumName: { $regex: searchQuery, $options: 'i' } },
{ shortDescription: { $regex: searchQuery, $options: 'i' } }
]
})
.populate('categoryId') // Populate categoryId field
.populate('subcategoryId') // Populate subcategoryId field
.skip(skip)
.limit(limit);
const totalCount = await Album.countDocuments({
$or: [
{ albumName: { $regex: searchQuery, $options: 'i' } },
{ shortDescription: { $regex: searchQuery, $options: 'i' } }
]
});
const totalPages = Math.ceil(totalCount / limit);
return res.status(200).json({
error_code: 200,
message: "Albums retrieved successfully",
data: albums.map(album => ({
_id: album._id,
status: album.status,
image: album.image,
albumName: album.albumName,
shortDescription: album.shortDescription,
category: album.categoryId ? album.categoryId.name : null,
subcategory: album.subcategoryId ? album.subcategoryId.SubCategoriesName : null
})),
totalPages: totalPages,
currentPage: page
});
} catch (err) {
console.log("Error inside GetAlbums Controller", err);
return res.status(500).json({
error_code: 500,
message: "Internal Server Error"
});
}
};
module.exports = {
createAlbum,
updateAlbum,
deleteAlbum,
changeAlbumStatus,
getAlbums
}

View File

@ -0,0 +1,161 @@
const bcrypt = require('bcryptjs');
const User = require('../models/user.model');
const jwt = require('jsonwebtoken');
const authConfig = require('../configs/auth.config');
const constant = require('../util/constant')
const nodemailer = require('nodemailer');
const signUp = async(req,res) => {
try{
const obj = {
name : req.body.name,
password : bcrypt.hashSync(req.body.password,8),
email : req.body.email,
registerWith : constant.registerWith.Email
}
const generateOTP = () => {
return Math.floor(10000 + Math.random() * 90000);
}
const email = req.body.email;
const otp = generateOTP();
obj['otp'] = otp;
const user = await User.create(obj);
const transporter = nodemailer.createTransport({
service: 'Gmail', // e.g., 'Gmail'
auth: {
user: 'checkdemo02@gmail.com',
pass: 'vqdoqmekygtousli'
}
});
const mailOptions = {
from: 'checkdemo02@gmail.com',
to: req.body.email, // The user's email
subject: 'Your OTP Code',
text: `Your OTP code is: ${otp}`
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending OTP email:', error);
return res.status(500).send({
errorCode : 500,
message : "Mail not Send"
})
} else {
console.log('OTP email sent:', info.response);
}
});
const token = jwt.sign({id:user._id},authConfig.secretKey,{
expiresIn : 6000000
});
return res.status(201).send({
error_code : 200,
message : 'Success',
otp : otp,
accessToken : token
})
}catch(err){
console.log(err);
res.status(500).send({
error_code : 200,
message : 'Failed'
})
}
}
const signIn = async (req, res) => {
try {
const { email, password } = req.body;
if (!email){
return res.status(400).json({
error_code: 400,
message: 'Email is required'
});
}
if (!password){
return res.status(400).json({
error_code: 400,
message: 'Password is required'
});
}
// Find user by email
const user = await User.findOne({ email });
console.log("🚀 ~ signIn ~ user:", user)
if (!user) {
return res.status(404).json({
error_code: 404,
message: 'User not found'
});
}
// Check if the provided password matches the user's password
const isPasswordValid = bcrypt.compareSync(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({
error_code: 401,
message: 'Password is incorrect'
});
}
// Generate JWT token
const token = jwt.sign({ id: user._id,userTypes:user.userTypes }, authConfig.secretKey, { expiresIn: '1h' });
console.log("🚀 ~ signIn ~ token:", token)
return res.status(200).json({
error_code: 200,
message: 'User logged in successfully',
accessToken: token
});
} catch (err) {
console.error('Error inside signIn:', err);
return res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const verifyOtp = async(req,res,next) => {
try{
const otp = req.body.otp;
const user = await User.findOne({_id:req.userId});
console.log(user.otp,otp);
if(user.otp!=otp){
return res.status(400).send({
error_code : 400,
message : 'otp is incorrect'
})
}
return res.status(200).send({
error_code : 200,
message : 'otp Verified'
})
}catch(err){
console.log('Error inside verifyOtp Controller',err);
return res.status(500).send({
message : 'Internal Error',
error_code : 500,
})
}
}
module.exports = {
signIn,
signUp,
verifyOtp
}

View File

@ -0,0 +1,208 @@
const Category = require('../models/categories.model');
const createCategories = async (req, res) => {
try {
if (!req.body.categoriesName) {
return res.status(400).send({
error_code: 400,
message: "Category name is required"
});
}
let obj = {
name: req.body.categoriesName,
};
if (req.file) {
obj["image"] = {
fileName: req.file.filename,
fileAddress: req.file.filename
};
const baseUrl = `${req.protocol}://${req.get('host')}`;
const imagePath = `uploads/${req.file.filename}`;
const imageUrl = `${baseUrl}/${imagePath}`;
obj["imageUrl"] = imageUrl;
}
const newCategory = await Category.create(obj);
return res.status(201).send({
error_code: 200,
message: "Categories created",
category: newCategory
});
} catch (err) {
console.log("Error inside create Categories Controller", err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
};
const updateCategories = async (req, res) => {
try {
const categoryId = req.params.id;
let category = await Category.findById(categoryId);
if (!category) {
return res.status(404).send({
error_code: 404,
message: "Category not found"
});
}
if (req.file) {
const baseUrl = `${req.protocol}://${req.get('host')}`;
const imagePath = `uploads/${req.file.filename}`;
const imageUrl = `${baseUrl}/${imagePath}`;
category.imageUrl = imageUrl;
category.image = {
fileName: req.file.filename,
fileAddress: req.file.path,
};
}
const updatedCategory = await category.save();
console.log("🚀 ~ updateCategories ~ updatedCategory:", updatedCategory)
return res.status(200).send({
error_code: 200,
message: "Category updated",
category: updatedCategory
});
} catch (err) {
console.log("Error inside update Categories Controller", err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
};
const deleteCategories = async (req, res) => {
try {
const categoryId = req.params.id; // Assuming you're passing category id in the request params
// Find the category by id and remove it
const deletedCategory = await Category.findByIdAndRemove(categoryId);
// Check if the category exists
if (!deletedCategory) {
return res.status(404).send({
error_code: 404,
message: "Category not found"
});
}
// Return success response with the deleted category
return res.status(200).send({
error_code: 200,
message: "Category deleted",
category: deletedCategory
});
} catch (err) {
console.log("Error inside delete Categories Controller", err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
};
const changeCategoryStatus = async (req, res) => {
try {
const { id } = req.params;
const CategoryData = await Category.findById(id);
if (!CategoryData) {
return res.status(400).send({
error_code: 400,
message: 'Ads not found'
});
}
CategoryData.status = CategoryData.status === 'activate' ? 'deactivate' : 'activate';
await CategoryData.save();
res.status(200).send({
message: `ads status toggled successfully to ${CategoryData.status}`,
CategoryData: CategoryData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const getCategories = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5
const skip = (page - 1) * limit;
const searchQuery = req.query.search || '';
const categories = await Category.find({
name: { $regex: searchQuery, $options: 'i' }
})
.skip(skip)
.limit(limit);
console.log("🚀 ~ getCategories ~ categories:", categories)
const totalCount = await Category.countDocuments({
name: { $regex: searchQuery, $options: 'i' }
});
res.status(200).json({
error_code: 200,
message: 'Categories fetched successfully',
categories,
total_count: totalCount,
page,
limit
});
} catch (err) {
console.error('Error inside getCategories Controller', err);
res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
// const deleteMany = async (req, res) => {
// try {
// const deleted = await Category.deleteMany({}); // Passing an empty filter object deletes all documents
// res.status(200).json({
// error_code: 200,
// message: 'All categories deleted successfully',
// deleted
// });
// } catch (err) {
// console.error('Error inside deleteMany Controller', err);
// res.status(500).json({
// error_code: 500,
// message: 'Internal Server Error'
// });
// }
// };
module.exports = {
createCategories,
updateCategories,
deleteCategories,
changeCategoryStatus,
getCategories,
};

View File

@ -0,0 +1,61 @@
const ImportSong = require('../models/importsong.model');
const importSong = async (req, res) => {
try {
// Extract fields from request body
const {
category,
subcategory,
album,
artist,
title,
musicLink,
trackerID,
lyrics,
language
} = req.body;
// Check if files were uploaded
if (!req.files || !req.files.coverArtImage || !req.files.musicFile) {
console.error('Error: Both image and music file are required.');
return res.status(400).json({ error_code: 400, message: 'Both image and music file are required.' });
}
// Retrieve file paths
const coverArtImagePath = req.files.coverArtImage[0].path;
const musicFilePath = req.files.musicFile[0].path;
// Create a new importSong object
const newImportSong = await ImportSong.create({
category,
subcategory,
album,
artist,
title,
musicLink,
trackerID,
lyrics,
language,
coverArtImage: {
filename: req.files.coverArtImage[0].filename,
fileAddress: coverArtImagePath
},
musicFile: {
filename: req.files.musicFile[0].filename,
fileAddress: musicFilePath
}
});
// Respond with success message
return res.status(201).json({
error_code: 200,
message: 'Import Song successfully',
importSong: newImportSong
});
} catch (err) {
console.error('Error inside importSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
module.exports = { importSong };

View File

@ -0,0 +1,136 @@
const Language = require('../models/language.model');
// Function to create a new language
const createLanguage = async function (req, res) {
try {
let obj = {
language: req.body.language ? req.body.language : undefined
}
if (!obj.language) {
return res.status(400).json({ error: "Language name is required" });
}
// Call the model function to create language using obj.language
const language = await Language.create({ name: obj.language });
// If language is created successfully, send a success response
res.status(201).json({ message: "Language created successfully", language });
} catch (error) {
console.error('Error creating language:', error);
res.status(500).json({ error: 'Failed to create language' });
}
};
// Function to update the language
const updateLanguage = async function (req, res) {
try {
const languageId = req.params.id;
const { name } = req.body;
// Check if languageId is provided
if (!languageId) {
return res.status(400).json({ error: "Language ID is required" });
}
// Find the language by ID and update its name
const language = await Language.findByIdAndUpdate(languageId, { name }, { new: true });
if (!language) {
return res.status(404).json({ error: "Language not found" });
}
res.json({ message: "Language updated successfully", language });
} catch (error) {
console.error('Error updating language:', error);
res.status(500).json({ error: 'Failed to update language' });
}
};
const deleteLanguage = async function (req, res) {
try {
const languageId = req.params.id;
if (!languageId) {
return res.status(400).json({ error: "Language ID is required" });
}
const language = await Language.findByIdAndDelete(languageId);
if (!language) {
return res.status(404).json({ error: "Language not found" });
}
res.json({ message: "Language deleted successfully" });
} catch (error) {
console.error('Error deleting language:', error);
res.status(500).json({ error: 'Failed to delete language' });
}
};
const getLanguage = async function (req, res) {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;
const searchQuery = req.query.search || '';
const languages = await Language.find({
name: { $regex: searchQuery, $options: 'i' }
})
.skip(skip)
.limit(limit);
const totalCount = await Language.countDocuments({
name: { $regex: searchQuery, $options: 'i' }
});
res.json({
error_code: 200,
message: 'Languages retrieved successfully',
languages,
total_count: totalCount,
page,
limit
});
} catch (error) {
console.error('Error getting languages:', error);
res.status(500).json({ error: 'Failed to get languages' });
}
};
const changeLanguageStatus = async function (req, res) {
try {
const { id } = req.params;
const languageData = await Language.findById(id);
if (!languageData) {
return res.status(400).send({
error_code: 400,
message: 'Ads not found'
});
}
languageData.status = languageData.status === 'activate' ? 'deactivate' : 'activate';
await languageData.save();
res.status(200).send({
message: `ads status toggled successfully to ${languageData.status}`,
user: languageData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
module.exports = {
createLanguage,
updateLanguage,
deleteLanguage,
changeLanguageStatus,
getLanguage
};

View File

@ -0,0 +1,138 @@
const Notification = require('../models/notification.model');
const constant = require('../util/notification.constant');
const User = require('../models/user.model');
const userConst = require('../util/constant')
const createNotification = async (req, res) => {
try {
const { sendTo, Type, Title, message, user } = req.body;
// Validate sendTo value
if (!sendTo || !['toAll', 'host', 'specific'].includes(sendTo)) {
return res.status(400).json({ error_code: 400, message: 'Invalid sendTo value' });
}
let recipients = [];
// Determine recipients based on sendTo value
if (sendTo === 'toAll') {
recipients = await User.find().distinct('_id');
} else if (sendTo === 'host') {
const host = await User.findOne({ role: 'host' });
if (host) recipients = [host._id];
} else if (sendTo === 'specific') {
recipients = await User.find({ role: 'specificRole' }).distinct('_id');
}
const newNotification = new Notification({
sendTo,
Type,
Title,
message,
user,
recipients
});
const savedNotification = await newNotification.save();
return res.status(201).json({
error_code: 200,
message: 'Notification created successfully',
notification: savedNotification
});
} catch (err) {
console.error('Error inside createNotification controller:', err);
return res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const getNotifications = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const skip = (page - 1) * limit;
const searchQuery = req.query.search || '';
// Count total number of notifications for pagination
const totalCount = await Notification.countDocuments({
Title: { $regex: searchQuery, $options: 'i' }
});
// Fetch notifications with pagination and search
const notifications = await Notification.find({
Title: { $regex: searchQuery, $options: 'i' }
})
.skip(skip)
.limit(limit);
res.status(200).json({
error_code: 200,
message: 'Notifications retrieved successfully',
notifications,
currentPage: page,
totalPages: Math.ceil(totalCount / limit),
totalNotifications: totalCount
});
} catch (err) {
console.error('Error inside getNotifications controller:', err);
res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const deleteNotification = async (req, res) => {
try {
const { id } = req.params;
const notification = await Notification.findByIdAndDelete(id);
res.status(200).json({
error_code: 200,
message: 'Notification deleted successfully',
notification
});
} catch (err) {
console.error('Error inside deleteNotification controller:', err);
res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
}
const getNotificationId = async(req,res)=>{
try{
const { id } = req.params;
const notification = await Notification.findById(id);
console.log("🚀 ~ getNotificationId ~ notification:", notification)
res.status(200).json({
error_code: 200,
message: 'Notification retrieved successfully',
notification:notification.message
});
} catch (err) {
console.error('Error inside getNotificationId controller:', err);
res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
}
module.exports = {
createNotification,
getNotifications,
deleteNotification,getNotificationId
};

View File

@ -0,0 +1,79 @@
const Payment = require('../models/payment.model');
const Subscription = require('../models/subscription.model');
const constant = require('../util/payment.constant');
const createPayment = async(req,res) => {
try{
const subscription = await Subscription.findById(req.params.id);
let obj = {
userName : req.body.userName,
planName : subscription.subscriptionTitle,
mainAmount : Math.floor((subscription.price*100)/(100-subscription.offer)),
offer : subscription.offer + '%',
finalAmount : subscription.price,
paymentId : '#' + Math.floor(Math.random() * 100000)+1 ,
paymentMethod : req.body.paymentMethod
}
await Payment.create(obj);
res.status(201).send({
error_code : 200,
message : 'Payment has been created '
})
}catch(err){
console.log('Error inside createPayment',err);
res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const getPayment = async(req,res) => {
try{
let obj = {
userName : req.query.userName ? req.query.userName : undefined
}
console.log(obj);
const payment = await Payment.find(obj);
console.log(payment)
return res.status(200).send(constant.objectConverter(payment));
}catch(err){
console.log('Error inside getReview controller',err);
return res.status(500).send({
error_code : 500,
message : "Internal Server Error"
})
}
}
const deletePayment = async(req,res) => {
try{
let id = req.params.id;
await Payment.deleteOne({_id :id});
return res.status(201).send({
error_code : 200,
message : 'Payment got deleted'
})
}catch(err){
console.log('Error inside deletePay Controller',err)
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
module.exports = {
createPayment,
getPayment,
deletePayment
}

View File

@ -0,0 +1,134 @@
const PlayList = require('../models/playlist.model');
const User = require('../models/user.model');
const createPlaylist = async(req,res) => {
try{
console.log(req.body);
let obj = {
name : req.body.name ? req.body.name : undefined ,
songs : req.body.songs ? req.body.songs : undefined,
userId : req.userId
}
const created_playlist = await PlayList.create(obj);
const user = await User.findById(req.userId);
await user.playlist.push(created_playlist._id);
await user.save();
return res.status(201).send({
error_code : 200,
message : 'Playlist got created'
})
}catch(err)
{
console.log('Error inside createPlaylist ',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const addSong = async(req,res) => {
try{
const playlist = await PlayList.findById(req.params.id);
const obj = {
name : req.body.name ? req.body.name : undefined,
}
playlist.songs.push(req.body.song);
await playlist.save();
await playlist.updateOne(obj);
await playlist.save();
return res.status(201).send({
error_code : 200,
message : 'Songs added to playlist'
})
}catch(err){
console.log('Error inside update playlist',err);
return res.status(500).send({
error_code : 500,
message : 'Internal server Error'
})
}
}
const removeSong = async(req,res) => {
try{
let playlist = await PlayList.findById(req.params.id);
console.log(playlist);
for(let i=0; playlist.songs.length;i++){
if(playlist.songs[i]==req.body.song)
{
playlist.songs.splice(i,1);
await playlist.save();
return res.status(201).send({
error_code : 200,
message : 'Song got removed from playlist'
})
}
}
}catch(err){
console.log('Error inside removeSong Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const getPlaylist = async(req,res) => {
try{
let obj = {};
if(req.params.id){
obj['_id'] = req.params.id
}
const playlist = await PlayList.find(obj);
return res.status(200).send(playlist);
}catch(err){
console.log('Error inside getPlaylist Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const deletePlaylist = async(req,res) => {
try{
let id = req.params.id;
await PlayList.deleteOne({_id:id});
const user = await User.findById(req.userId);
for(let i=0;i<user.playlist.length;i++){
console.log(user.playlist[i] == req.params.id);
if(user.playlist[i] == req.params.id) user.playlist.splice(i,1);
}
return res.status(201).send({
message : 'Playlist got deleted'
})
}catch(err){
console.log('Error inside deletePlaylist Controller',err);
return res.status(500).send({
message : 'Internal Server Error'
})
}
}
module.exports = {
createPlaylist,
addSong,
removeSong,
getPlaylist,
deletePlaylist
}

View File

@ -0,0 +1,56 @@
const privacyPolicyModel = require('../models/privacy.model');
const add_privacy_policy = async function (req, res) {
try {
let privacyPolicy = await privacyPolicyModel.find({});
if(privacyPolicy.length != 0){
return res.status(400).send({
error_code : 400,
message : 'privacy policy are already exist..!'
})
}
await privacyPolicyModel.create(req.body);
return res.status(201).send({
error_code : 200,
message: "privacy and policy added successfully..!",
});
} catch (error) {
console.log(error)
return res.status(500).send({
error_code : 500,
message: error,
});
}
};
const update_privacy_policy = async function (req, res) {
try {
let id = req.params.id;
let obj = {
privacyPolicy : req.body.privacyPolicy ? req.body.privacyPolicy : undefined
}
await privacyPolicyModel.findByIdAndUpdate(
{ _id: id },
{ $set: obj },
{ new: true }
);
return res.status(201).send({
error_code : 200,
message: "privacy and policy update successfully..!",
});
} catch (error) {
console.log(error);
return res.status(500).send({
error_code : 500,
message: error,
});
}
};
module.exports = {
add_privacy_policy,
update_privacy_policy,
};

View File

@ -0,0 +1,137 @@
const User = require('../models/user.model');
const Review = require('../models/Review.model');
const constant = require('../util/review.constant')
const createReview = async(req,res)=> {
try{
const user = await User.findById(req.userId);
let obj = {
userName : user.userName,
review : req.body.review ? req.body.review : undefined,
}
await Review.create(obj);
return res.status(200).send({
error_code : 200,
message :'Review got Created'
})
}catch(err){
console.log('Error inside createReview Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const getReview = async (req, res) => {
try {
let query = {};
let pageNumber = req.query.pageNumber || 1; // Default to page 1 if pageNumber is not provided
let pageSize = req.query.pageSize || 10; // Default page size to 10 if pageSize is not provided
if (req.query.userName) {
query.userName = req.query.userName;
}
const totalReviews = await Review.countDocuments(query);
const totalPages = Math.ceil(totalReviews / pageSize);
const reviews = await Review.find(query)
.skip((pageNumber - 1) * pageSize)
.limit(pageSize);
return res.status(200).send({
total_reviews: totalReviews,
total_pages: totalPages,
current_page: pageNumber,
reviews: constant.objectConverter(reviews)
});
} catch (err) {
console.log('Error inside getReview controller', err);
return res.status(500).send({
error_code: 500,
message: "Internal Server Error"
});
}
};
const updateReview = async(req,res) => {
try{
const review = await Review.findById(req.params.id);
let obj = {
reply : req.body.reply ? req.body.reply : undefined,
status : req.body.status? req.body.status :undefined
}
await review.updateOne(obj);
await review.save();
return res.status(201).send({
error_code : 200,
message : 'Review got updated'
})
}catch(err){
console.log('Error inside updateReview Controller',err);
res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const deletereview = async(req,res) => {
try{
let id = req.params.id;
await Review.deleteOne({_id :id});
return res.status(201).send({
error_code : 200,
message : 'review got deleted'
})
}catch(err){
console.log('Error Occured inside deletereview of Review Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const changeReviewStatus = async(req,res) =>{
try{
const { id}=req.params;
const review = await Review.findById(id);
if(!review){
return res.status(400).send({
error_code : 400,
message : 'Review not found'
})
}
review.status = review.status === 'publish'? 'unpublish' : 'publish';
await review.save();
return res.status(200).send({
error_code : 200,
message : 'Review status changed'
})
}catch(error){
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
module.exports = {
createReview,
changeReviewStatus,
getReview,
updateReview,
deletereview
}

View File

@ -0,0 +1,229 @@
const Song = require('../models/song.model');
const Category = require('../models/categories.model');
const Subcategory = require('../models/subcategories.model');
const Album = require('../models/album.model');
const Artist =require('../models/artist.model')
const Language = require('../models/language.model')
const createSong = async (req, res) => {
try {
const {
categoryId,
subcategoryId,
albumId,
artistId,
title,
musicLink,
trackerID,
lyrics,
languageId
} = req.body;
const { coverArtImage, musicFile } = req.files;
// Check if both cover art image and music file are provided
// Find all related documents in parallel
const [category, subcategory, album, artist, language] = await Promise.all([
Category.findById(categoryId),
Subcategory.findById(subcategoryId),
Album.findById(albumId),
Artist.findById(artistId),
Language.findById(languageId)
]);
// Check if all related documents exist
if (!category || !subcategory || !album || !artist || !language) {
const missingEntities = [];
if (!category) missingEntities.push('Category');
if (!subcategory) missingEntities.push('Subcategory');
if (!album) missingEntities.push('Album');
if (!artist) missingEntities.push('Artist');
if (!language) missingEntities.push('Language');
const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
return res.status(404).json({ error_code: 404, message: errorMessage });
}
// Extract file paths
const coverArtImagePath = coverArtImage[0].path;
const musicFilePath = musicFile[0].path;
// Construct the image URL for cover art
const baseUrl = `${req.protocol}://${req.get('host')}`;
const coverArtImageUrl = `${baseUrl}/${coverArtImagePath}`;
// Create the new song
const newSong = await Song.create({
categoryId,
subcategoryId,
albumId,
artistId,
title,
musicLink,
trackerID,
lyrics,
languageId,
coverArtImage: {
filename: coverArtImage[0].filename,
fileAddress: coverArtImagePath,
imageUrl: coverArtImageUrl // Add imageUrl to coverArtImage object
},
musicFile: {
filename: musicFile[0].filename,
fileAddress: musicFilePath
}
});
// Return success response with the new song
return res.status(201).json({
error_code: 200,
message: 'Song created successfully',
song: newSong
});
} catch (err) {
console.error('Error inside createSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
const updateSong = async (req, res) => {
try {
const { id } = req.params; // Extract the song ID from the request parameters
const updatedSong = await Song.findByIdAndUpdate(id, req.body, { new: true }); // Find song by ID and update with the request body data
if (!updatedSong) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song updated successfully', song: updatedSong });
} catch (err) {
console.error('Error inside updateSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
const deleteSong = async (req, res) => {
try {
const { id } = req.params;
const deletedSong = await Song.findByIdAndDelete(id);
if (!deletedSong) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song deleted successfully' });
} catch (err) {
console.error('Error inside deleteSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
const getSong = async (req, res) => {
try {
const { id } = req.params;
const song = await Song.findById(id)
.populate('languageId', 'name')
.populate('artistId', 'ArtistName')
.select('title musicLink trackerID lyrics coverArtImage');
if (!song) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song retrieved successfully', song });
} catch (err) {
console.error('Error inside getSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
const changeSongStatus = async (req, res) => {
try {
const { id } = req.params;
const songData = await Song.findById(id);
if (!songData) {
return res.status(400).send({
error_code: 400,
message: 'song not found'
});
}
songData.status = songData.status === 'activate' ? 'deactivate' : 'activate';
await songData.save();
res.status(200).send({
message: `song status toggled successfully to ${songData.status}`,
songData: songData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const getAllSongs = async (req, res) => {
try {
const { title, artist, category } = req.query;
let query = {};
// Build query object based on search fields
const searchFields = ['title', 'artist', 'category'];
searchFields.forEach(field => {
if (req.query[field]) {
query[field] = { $regex: req.query[field], $options: 'i' };
}
});
// Pagination parameters
const pageNumber = Math.max(1, parseInt(req.query.pageNumber) || 1);
const pageSize = Math.max(1, parseInt(req.query.pageSize) || 10);
// Count total songs based on the query
const totalSongs = await Song.countDocuments(query);
const totalPages = Math.ceil(totalSongs / pageSize);
// Find songs based on the query and pagination
const songs = await Song.find(query)
.populate({ path: 'categoryId', select: 'name' })
.populate({ path: 'albumId', select: 'albumName' })
.populate({ path: 'subcategoryId', select: 'SubCategoriesName' })
.populate({ path: 'artistId', select: 'ArtistName' })
.sort({ title: 1 })
.skip((pageNumber - 1) * pageSize)
.limit(pageSize);
// Check if songs are found
if (songs.length === 0) {
return res.status(404).json({ error_code: 404, message: 'Songs not found' });
}
// Return songs along with pagination details
return res.status(200).json({
error_code: 200,
message: 'Songs retrieved successfully',
songs,
total_pages: totalPages,
current_page: pageNumber
});
} catch (err) {
console.error('Error inside getAllSongs:', err);
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
}
};
module.exports = {
createSong,
updateSong,
deleteSong,
getSong,
getAllSongs,
changeSongStatus
};

View File

@ -0,0 +1,316 @@
const SubCategories = require('../models/subcategories.model'); // Import SubCategories model
const Categories = require('../models/categories.model')
// const createsubCategories = async (req, res) => {
// try {
// // Check if the required fields are present in the request body
// if (!req.body.CategoriesName || !req.body.SubCategoriesName || !req.file) {
// return res.status(400).send({
// error_code: 400,
// message: "CategoriesName, SubCategoriesName, and image are required"
// });
// }
// let obj = {
// CategoriesName: req.body.CategoriesName,
// SubCategoriesName: req.body.SubCategoriesName,
// image: {
// fileName: req.file.filename,
// fileAddress: req.file.path
// }
// };
// // Save 'obj' to the database
// const newSubCategories = await SubCategories.create(obj);
// // Return a success response with the newly created category
// return res.status(201).send({
// error_code: 200,
// message: 'SubCategories Created',
// category: newSubCategories
// });
// } catch (err) {
// console.log('Error inside create SubCategories Controller', err);
// return res.status(500).send({
// error_code: 500,
// message: 'Internal Server Error'
// });
// }
// };
const createsubCategories = async (req, res) => {
try {
const category = await Categories.findOne({ _id: req.body.CategoriesId });
if (!category) {
return res.status(404).send({
error_code: 404,
message: "Category not found"
});
}
// Construct the image URL
const baseUrl = `${req.protocol}://${req.get('host')}`;
const imagePath = `uploads/${req.file.filename}`;
const imageUrl = `${baseUrl}/${imagePath}`;
const newSubCategory = new SubCategories({
CategoriesId: category._id,
SubCategoriesName: req.body.SubCategoriesName,
image: {
fileName: req.file.filename,
fileAddress: req.file.filename,
imageUrl: imageUrl
}
});
await newSubCategory.save();
return res.status(201).send({
error_code: 200,
message: 'Subcategory Created',
subcategory: newSubCategory
});
} catch (err) {
console.log('Error inside create SubCategory Controller', err);
return res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const updateSubCategories = async (req, res) => {
try {
const { id } = req.params;
const { CategoriesId, SubCategoriesName } = req.body;
// Check if CategoriesId is provided
if (!CategoriesId) {
return res.status(400).json({
error_code: 400,
message: "CategoriesId is required"
});
}
// Check if the category exists
const category = await Categories.findById(CategoriesId);
if (!category) {
return res.status(404).json({
error_code: 404,
message: "Category not found"
});
}
// Prepare update object
const updateObject = { CategoriesId, SubCategoriesName };
if (req.file) {
// Construct image URL
const baseUrl = `${req.protocol}://${req.get('host')}`;
const imagePath = `uploads/${req.file.filename}`;
const imageUrl = `${baseUrl}/${imagePath}`;
updateObject.image = {
fileName: req.file.filename,
fileAddress: req.file.path,
imageUrl: imageUrl
};
}
// Find and update the subcategory
const updatedSubCategories = await SubCategories.findByIdAndUpdate(id, updateObject, { new: true });
// Check if the subcategory exists
if (!updatedSubCategories) {
return res.status(404).json({
error_code: 404,
message: "SubCategories not found"
});
}
// Return a success response with the updated subcategory
return res.status(200).json({
error_code: 200,
message: "SubCategories updated",
category: updatedSubCategories
});
} catch (err) {
console.error('Error inside update SubCategories Controller', err);
return res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const deleteMany = async (req, res) => {
try {
const deleted = await SubCategories.deleteMany({}); // Passing an empty filter object deletes all documents
res.status(200).json({
error_code: 200,
message: 'All categories deleted successfully',
deleted
});
} catch (err) {
console.error('Error inside deleteMany Controller', err);
res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const deleteSubCategories = async (req, res) => {
try {
const { id } = req.params;
// Find and delete the subcategory
const deletedSubCategories = await SubCategories.findByIdAndDelete(id);
// Check if the subcategory exists
if (!deletedSubCategories) {
return res.status(404).send({
error_code: 404,
message: "SubCategories not found"
});
}
// Return a success response
return res.status(200).send({
error_code: 200,
message: "SubCategories deleted"
});
} catch (err) {
console.log('Error inside delete SubCategories Controller', err);
return res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const getSubCategories = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const skip = (page - 1) * limit;
const searchQuery = req.query.search || '';
const subcategories = await SubCategories.find({
SubCategoriesName: { $regex: searchQuery, $options: 'i' }
})
.populate('CategoriesId') // Populate the 'CategoriesId' field
.skip(skip)
.limit(limit);
const populatedSubcategories = subcategories.map(subcategory => ({
_id: subcategory._id,
SubCategoriesName: subcategory.SubCategoriesName,
image: subcategory.image,
status: subcategory.status,
CategoriesId: subcategory.CategoriesId ? subcategory.CategoriesId._id : null, // Reference the category ID if it exists
categoryName: subcategory.CategoriesId ? subcategory.CategoriesId.name : null // Display category name if it exists
}));
console.log("🚀 ~ populatedSubcategories ~ populatedSubcategories:", populatedSubcategories)
const totalCount = await SubCategories.countDocuments({
SubCategoriesName: { $regex: searchQuery, $options: 'i' }
});
res.status(200).json({
error_code: 200,
message: 'Subcategories retrieved successfully',
subcategories: populatedSubcategories,
total_count: totalCount,
page,
limit
});
} catch (err) {
console.error('Error inside get SubCategories Controller', err);
res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const changeSubCategoryStatus = async (req, res) => {
try {
const { id } = req.params;
const subCategoryData = await SubCategories.findById(id);
if (!subCategoryData) {
return res.status(400).send({
error_code: 400,
message: 'Ads not found'
});
}
subCategoryData.status = subCategoryData.status === 'activate' ? 'deactivate' : 'activate';
await subCategoryData.save();
res.status(200).send({
message: `ads status toggled successfully to ${subCategoryData.status}`,
subCategoryData: subCategoryData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const getCategories = async (req, res) => {
try {
const { CategoriesId } = req.params;
const categories = await SubCategories.find({ CategoriesId: CategoriesId });
console.log("🚀 ~ getCategories ~ categories:", categories)
if (!categories || categories.length === 0) {
return res.status(400).send({
error_code: 400,
message: 'Categories not found for the given category ID'
});
}
// Return the found categories
res.status(200).json({
error_code: 200,
message: 'Categories retrieved successfully',
categories: categories
});
} catch (err) {
console.error('Error inside getCategories', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
module.exports = {
createsubCategories,
updateSubCategories,
deleteSubCategories,
getSubCategories,
deleteMany,
changeSubCategoryStatus,getCategories
};

View File

@ -0,0 +1,191 @@
const Subscription = require('../models/subscription.model');
const subconstant = require('../util/subscriptionConstant');
const Create = async(req,res) => {
try{
let obj = {
subscriptionTitle: req.body.subscriptionTitle || undefined,
validity: {
duration: req.body.validity && req.body.validity.duration ? req.body.validity.duration : undefined,
count: req.body.validity && req.body.validity.count ? req.body.validity.count : undefined
},
price: req.body.price ? subconstant.priceCalculate(req.body.offer, req.body.price) : undefined,
offer: req.body.offer || undefined,
adfree: req.body.adfree || undefined,
download: req.body.download || undefined,
description: req.body.description || undefined,
}
const subscription = await Subscription.create(obj);
// console.log(subscription);
return res.status(200).send({
error_code : 200,
message : 'Subscription got created',
subscription:subscription
})
}catch(err){
console.log('Error inside subscription create',err);
return res.status(500).send({
error_code : 500,
message : 'Internal server Error while creating subscription'
})
}
}
const getAllsubs = async (req,res) => {
try
{
let obj = {};
const subs = await Subscription.find(obj);
res.status(201).send(subconstant.getSubscription(subs));
}
catch(err){
console.log('error inside update subscription controller',err);
return res.status(500).send({
error_code : 200,
message : 'Internal Server Error'
})
}
}
const getsub = async (req,res) => {
try
{
let obj = {};
if(req.params.id){
obj._id = req.params.id
}
const subs = await Subscription.find(obj);
console.log('list of subscription',subs);
return res.status(201).send(subconstant.getSubscription(subs));
}
catch(err){
console.log('error inside update subscription controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const updatesub = async(req,res) => {
try{
if(req.body == undefined){
return res.status(200).json({error_code : 400, message : 'Epmty Request Body'})
}
let id = req.params.id;
const sub = await Subscription.findById(id);
console.log(req.body,req.file);
let obj =
{
subscriptionTitle : req.body.subscriptionTitle ? req.body.subscriptionTitle : undefined,
validity : {
duration : req.body.validity.duration ? req.body.validity.duration : undefined,
count : req.body.validity.count ? req.body.validity.count : undefined
},
price : req.body.price ? req.body.price : undefined,
description : req.body.description ? req.body.description : undefined,
offer : req.body.offer ? req.body.offer : undefined,
adfree : req.body.adfree ? req.body.adfree :undefined,
description : req.body.description ? req.body.description : undefined,
status : req.body.status ? req.body.status : undefined,
download : req.body.download ? req.body.download : undefined
}
if(req.body.offer){
if(req.body.price)
obj.price = subconstant.priceCalculate(req.body.offer,req.body.price);
else{
let originalPrice = Math.floor((sub.price*100)/(100-sub.offer));
obj.price = subconstant.priceCalculate(req.body.offer,originalPrice)
}
}
else if(!req.body.offer && req.body.price){
obj.price = subconstant.priceCalculate(sub.offer,req.body.price)
}
await sub.updateOne(obj);
console.log('subscription got updated',sub);
return res.status(201).send({
error_code : 200,
message : 'subscription got updated'
})
} catch(err){
console.log('Error inside update subscription controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const deletesub = async(req,res) => {
try{
let id = req.params.id;
await Subscription.deleteOne({_id :id});
return res.status(201).send({
message : 'subscription got deleted'
})
}catch(err){
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
};
const updateStatus = async function(req, res){
try {
let id = req.params.id;
const sub = await Subscription.findById(id);
if(sub.status == 'activate'){
sub.status = 'deactivate'
}else if(sub.status == 'deactivate'){
sub.status = 'activate'
}
await sub.save()
return res.status(200).json({error_code : 200, message : 'Status Update Successfully.'})
} catch (error) {
console.log(error);
return res.status(50).json({ error_code : 500, message : 'Internal Server Error'})
}
}
const getSingleSub = async (req, res) => {
try {
const subId = req.params.id;
// Check if subscription ID is provided
if (!subId) {
return res.status(400).json({ error_code: 400, message: 'Subscription ID is required' });
}
// Find subscription by ID
const subscription = await Subscription.findById(subId);
// Check if subscription exists
if (!subscription) {
return res.status(404).json({ error_code: 404, message: 'Subscription not found' });
}
// Return the subscription details
return res.status(200).json({ error_code: 200, subscription });
} catch (error) {
console.log('Error inside getSingleSub controller:', error);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
}
module.exports = {
Create,
getAllsubs,
updatesub,
deletesub,
getsub,
updateStatus,
getSingleSub
}

View File

@ -0,0 +1,500 @@
const User = require('../models/user.model');
const jwt = require('jsonwebtoken');
const authConfig = require('../configs/auth.config');
const bcrypt = require('bcryptjs');
const constant = require('../util/constant');
const Artist = require('../models/artist.model');
const Reward = require('../models/Reward.model');
const Song = require('../models/song.model');
const createGoogle = async (req, res) => {
try {
let user = await User.findOne({ email: req.body.email });
var flag = 0;
if (!user) {
let obj = {
email: req.body.email,
registerWith: constant.registerWith.google
}
user = await User.create(obj);
flag = 1
}
if (user.registerWith != constant.registerWith.google) {
return res.status(400).send({
error_code : 400,
message: "Can't login Through google"
});
}
let str = flag ? 'User Got Created' : 'User was already Created';
const token = jwt.sign({ id: user._id }, authConfig.secretKey, {
expiresIn: 600000
});
return res.status(201).send({
error_code : 200,
message: str,
acessToken: token
})
} catch (err) {
console.log(err);
return res.status(500).send({
error_code : 500,
message: 'Error in creating user'
})
}
}
const update = async (req, res) => {
try {
let id = req.params.id;
let obj = {
userName: req.body.userName ? req.body.userName : undefined,
email: req.body.email ? req.body.email : undefined,
password: req.body.password ? bcrypt.hashSync(req.body.password) : undefined,
}
if (req.files.length > 0) {
obj['image'] = {
fileName: req.files[0].filename,
fileAddress: req.files[0].path
}
}
const user = await User.findById(id);
const admin = await User.findById(req.userId);
if (req.body.status) {
if (admin.userTypes == constant.userTypes.admin) {
obj.status = req.body.status ? req.body.status : undefined;
}
else {
return res.status(401).send({
error_code : 400,
message: 'status can only be updated by admin'
})
}
}
console.log(`object for updation of user is ${obj}`);
await user.updateOne(obj)
await user.save();
return res.status(201).send({
error_code : 200,
message: "User updated Successssssfully"
})
} catch (err) {
console.log(err);
res.status(500).send({
error_code : 500,
message: 'Error in update controller '
})
}
}
const passUpCreate = async (req, res) => {
console.log(req.body.email);
try {
let email = req.body.email
function generateRandomNumber() {
const min = 100000; // Minimum value (inclusive)
const max = 999999; // Maximum value (inclusive)
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
const uppercaseLetter = String.fromCharCode(Math.floor(Math.random() * 26) + 65); // Uppercase letter ASCII range: 65-90
const lowercaseLetter = String.fromCharCode(Math.floor(Math.random() * 26) + 97); // Lowercase letter ASCII range: 97-122
const specialCharacter = String.fromCharCode(Math.floor(Math.random() * 15) + 33); // Special character ASCII range: 33-47
const randomString = randomNumber.toString() + uppercaseLetter + lowercaseLetter + specialCharacter;
// Shuffle the characters in the string
const shuffledString = randomString.split('').sort(() => 0.5 - Math.random()).join('');
return shuffledString;
}
// Usage example
const TempPassword = generateRandomNumber();
let obj = {
password: bcrypt.hashSync(TempPassword)
}
const user = await User.findOneAndUpdate({ email: email }, { $set: obj });
user.save();
return res.status(201).send({
error_code : 200,
message: `Temporary Password is ${TempPassword} for this ${email}`
})
} catch (err) {
console.log(err);
return res.status(500).send({
error_code : 500,
message: 'Error in passUpCreate'
})
}
}
const createFacebook = async (req, res) => {
try {
let user = await User.findOne({ email: req.body.email });
var flag = 0;
if (!user) {
let obj = {
email: req.body.email,
registerWith: constant.registerWith.facebook
}
user = await User.create(obj);
flag = 1
}
if (user.registerWith != constant.registerWith.facebook) {
return res.status(400).send({
error_code : 400,
message: "Can't login Through facebook"
});
}
let str = flag ? 'User Got Created' : 'User was already Created';
const token = jwt.sign({ id: user._id }, authConfig.secretKey, {
expiresIn: 600000
});
return res.status(201).send({
error_code : 200,
message: str,
acessToken: token
})
} catch (err) {
console.log(err);
return res.status(500).send({
error_code : 500,
message: 'Error in creating user'
})
}
}
const deleteUser = async (req, res) => {
try {
let id = req.params.id;
await User.deleteOne({ _id: id });
return res.status(201).send({
error_code : 200,
message: 'User Deleted succefully'
})
}
catch (err) {
console.log('Error inside delete User controller', err);
return res.status(500).send({
error_code : 500,
message: 'internal server error'
})
}
}
const getUserPlaylist = async (req, res) => {
try {
const user = await User.findById(req.userId).populate('playlist');
console.log(user);
return res.status(201).send(constant.arrayConverterName(user.playlist));
} catch (err) {
console.log('Error inside getUserPlaylist Controller', err);
return res.status(500).send({
error_code : 500,
message: 'Internal Server Error'
})
}
}
const favrioteSong = async (req, res) => {
try {
const user = await User.findById(req.userId).populate('favrioteSongs');
console.log(user);
for (let i = 0; i < user.favrioteSongs.length; i++) {
if (user.favrioteSongs[i]._id == req.params.id) {
await user.updateOne({
$pull: {
favrioteSongs: req.params.id
}
});
await user.save();
return res.status(201).send({
error_code : 200,
message: 'Song got removed from favrioteSong'
})
}
}
user.favrioteSongs.push(req.params.id);
await user.save();
return res.status(201).send({
error_code : 200,
message: 'Song got added to favrioteSong'
})
} catch (err) {
console.log('Error inside favrioteSong Controller', err);
return res.status(500).send({
error_code : 500,
message: 'Internal Server Error'
})
}
}
const getfavrioteSongs = async (req, res) => {
try {
const user = await User.findById(req.userId).populate('favrioteSongs');
return res.status(200).send(user.favrioteSongs);
} catch (err) {
console.log('Error inside getFavrioteSong Controller', err);
return res.status(500).send({
error_code : 500,
message: 'Internal Server Error'
})
}
}
const PlayedSong = async (req, res) => {
try {
let key = req.params.id;
let userId = req.userId;
const user = await User.findById(userId);
if (user.mostPlayedSongs[key]) {
const updatedObj = {$set : {['mostPlayedSongs.'+key]:(++user.mostPlayedSongs[key])}}
await User.findByIdAndUpdate(userId,updatedObj);
}
else {
const updatedObj = {$set:{['mostPlayedSongs.'+key]:1 }}
console.log('not hello')
await User.findByIdAndUpdate(userId,updatedObj)
}
return res.status(201).send({
error_code : 200,
message: 'Song is Played '
})
} catch (err) {
console.log('Error inside playedSong', err);
return res.status(500).send({
error_code : 500,
message: 'Internal Server Error'
})
}
}
const getmostPlayedSong = async (req, res) => {
try {
const user = await User.findById(req.userId)
console.log(user.mostPlayedSongs);
// Convert the object to an array of key-value pairs
const objEntries = Object.entries(user.mostPlayedSongs);
// Sort the Array
objEntries.sort((a, b) => b[1] - a[1]);
// Convert the sorted array back to an object
const sortedObj = Object.fromEntries(objEntries);
return res.status(201).send(sortedObj);
} catch (err) {
console.log('Error inside mostPlayedSong', err);
return res.status(500).send({
error_code : 500,
message: 'Internal Server Error'
})
}
}
const followingArtist = async(req,res) => {
try{
const artistId = req.params.id;
const userId = req.userId;
const user = await User.findById(userId);
const artist = await Artist.findById(artistId);
for(let i=0;i<user.following.length;i++){
if(user.following[i]==artistId) {
user.following.pull(artistId);
await user.save();
artist.followers.pull(userId);
await artist.save();
return res.status(201).send({
message : `You Unfollowed ${artist.name}`
})
}
}
user.following.push(artistId);
await user.save();
artist.followers.push(userId);
await artist.save();
return res.status(200).send({
error_code : 200,
message : `you followed ${artist.name}`
})
}catch(err){
console.log('Error inside following Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
// Function to calculate word alignment accuracy using Levenshtein distance
// Function to calculate timing accuracy
// Function to evaluate word alignment accuracy and timing accuracy
const evaluateAccuracy= async(req, res) => {
try{
const song = await Song.findById(req.params.id);
const recognizedLyrics = req.recognizedLyrics;
const originalLyrics = song.lyricsTimeStamp;
const wordAlignmentAccuracy = constant.calculateWordAlignmentAccuracy(recognizedLyrics, originalLyrics);
const timingAccuracy = constant.calculateTimingAccuracy(recognizedLyrics, originalLyrics);
const totalAccuracy = (wordAlignmentAccuracy.toFixed(2) + timingAccuracy.toFixed(2))/2;
console.log(totalAccuracy);
var reward ;
switch(totalAccuracy){
case(totalAccuracy>90) :
reward = 'A+';
break ;
case(totalAccuracy>80) :
reward = 'A'
break;
case(totalAccuracy>70) :
reward = 'B+'
break;
case(totalAccuracy>60) :
reward = 'B'
break;
case(totalAccuracy>50) :
reward = 'C+'
break;
case(totalAccuracy>40) :
reward = 'C'
break ;
case(totalAccuracy<40) :
reward = 'F'
break;
}
const reward_score = await Reward.find({score : reward});
const user = await User.findById(req.userId);
user.score += reward_score.reward;
await user.save();
console.log(user);
return res.status(201).send({
error_code : 200,
Score : reward
})
}catch(err){
console.log('Error inside EvaluateAccuracy Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const ranking = async(req,res) => {
try{
const ranking = await User.find({}).sort({score : -1}).limit(5);
return res.status(201).send(ranking);
}catch(err){
console.log('Error inside Ranking Controller',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
const changeUserStatus = async (req, res) => {
try {
const { id } = req.params;
const { status } = req.body;
// Validate the status value
if (!['activate', 'deactivate'].includes(status)) {
return res.status(400).send({
error_code: 400,
message: 'Invalid status value. Status must be either "activate" or "deactivate".'
});
}
const user = await User.findById(id);
if (!user) {
return res.status(404).send({
error_code: 404,
message: 'User not found.'
});
}
user.status = status;
await user.save();
return res.status(200).send({
error_code: 200,
message: `User status updated to ${status} successfully.`
});
} catch (err) {
console.log('Error inside changeStatus controller', err);
return res.status(500).send({
error_code: 500,
message: 'Internal server error.'
});
}
}
module.exports = {
createGoogle,
createFacebook,
update,
passUpCreate,
getUserPlaylist,
favrioteSong,
deleteUser,
PlayedSong,
getmostPlayedSong,
getfavrioteSongs,
followingArtist,
evaluateAccuracy,
ranking,
changeUserStatus
};

30
middlewares/Admin.js Normal file
View File

@ -0,0 +1,30 @@
const User = require('../models/user.model');
const constant = require('../util/constant')
const isAdmin = async(req,res,next) => {
try {
console.log('admin midd')
let id = req.userId;
const user = await User.findById(id);
if(user.userTypes!= constant.userTypes.admin)
return res.status(401).send({
error_code : 400,
message : 'Only Admin can access this field'
})
next();
}
catch(err)
{
console.log('error occured inside isAdmin',err);
res.status(500).send({
error_code : 500,
message : err
})
}
}
module.exports = {
isAdmin
}

View File

@ -0,0 +1,84 @@
const regex = require('../regex');
const User = require('../../models/user.model')
const fieldCheck = async(req,res,next) => {
try{
if(!req.body.email){
return res.status(400).send({
error_code : 400,
message : 'Email not provided'
})
}
if(!req.body.password){
return res.status(400).send({
error_code : 400,
message : 'Password not provided'
})
}
if(!regex.emailRegex.test(req.body.email)){
return res.status(400).send({
error_code : 400,
message : 'Email format is Incorrect'
})
}
if(!regex.passRegex.test(req.body.password)){
return res.status(400).send({
error_code : 400,
message : 'Password format is Incorrect'
})
}
next();
}catch(err){
console.log('Error inside auth Middelware fieldCheck',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Error'
})
}
}
const uniqueEmail = async(req,res,next) => {
try{
const user = await User.findOne({email : req.body.email});
if(user){
return res.status(400).send({
error_code : 400,
message : 'Email already present'
})
}
next();
}catch(err){
console.log('Error insdie auth mid email Present',err);
return res.status(500).send({
error_code : 500,
message : 'Internal Error'
})
}
}
const userCheckEmail = async (req,res,next) => {
try{
const user = await User.findOne({email : req.body.email});
if(!user){
return res.status(400).send({
error_code : 400,
message : 'User not present'
})
}
next();
}catch(err){
return res.status(500).send({
error_code : 500,
message : 'Error inside userCheckEmail'
})
}
}
module.exports = {
fieldCheck,
uniqueEmail,
userCheckEmail
}

29
middlewares/Reward.js Normal file
View File

@ -0,0 +1,29 @@
const bodyCheck = async(req,res,next) => {
try{
if(!req.body.reward){
return res.status(400).send({
message : 'Provide reward value'
})
}
if(!req.body.score){
return res.status(400).send({
message : 'Provide Score value'
})
}
next();
}catch(err){
console.log('Error inside Bodycheck Middleware',err);
return res.status(500).send({
message : 'Internal Server Error'
})
}
}
module.exports = {
bodyCheck
}

View File

@ -0,0 +1,6 @@
const BodyCheck = (req,res,next) => {
}

32
middlewares/adsSetting.js Normal file
View File

@ -0,0 +1,32 @@
const secondConverter = async(req,res,next) => {
try{
if(req.body.adsTiming.seconds > 60){
let seconds = req.body.adsTiming.seconds;
minutes = Math.floor(seconds/60);
seconds = seconds%60;
console.log(typeof req.body.adsTiming.minutes)
req.body.adsTiming.minutes = Number(req.body.adsTiming.minutes) + minutes;
req.body.adsTiming.seconds = seconds;
}
next();
}catch(err){
console.log('Error inside SecondConveter Middleware',err);
res.status(500).send({
error_code : 500,
message : 'Internal Server Error'
})
}
}
module.exports = {
secondConverter
}

39
middlewares/authjwt.js Normal file
View File

@ -0,0 +1,39 @@
const jwt = require('jsonwebtoken');
const User = require('../models/user.model');
const authConfig = require('../configs/auth.config');
const verifyToken = (req,res,next)=>{
console.log('verify token')
const token = req.headers["x-access-token"];
if(!token){
return res.status(403).send({
error_code : 403,
message : "no token provided! Access prohibited"
})
}
jwt.verify(token, authConfig.secretKey, async (err, decoded)=>{
if(err){
return res.status(401).send({
error_code : 400,
message : "UnAuthorised!"
})
}
console.log(decoded);
req.userId = decoded.id;
const user = await User.findOne({_id:req.userId});
if(!user){
return res.status(400).send({
error_code : 400,
message : "The user that this token belongs to does not exist"
})
}
next();
})
}
module.exports = {
verifyToken
}

30
middlewares/idchecker.js Normal file
View File

@ -0,0 +1,30 @@
const mongoose = require('mongoose')
const idCheck = async(req,res,next)=>{
try{
if(!req.params.id)
{
return res.status(401).send({
message : 'id not present'
})
}
let check = mongoose.isValidObjectId(req.params.id);
if(!check){
return res.status(400).send({
message : 'Not a valid Param id'
})
}
next()
}catch(err){
return res.status(500).send({
message : 'Internal Server Error'
})
}
}
module.exports = {
idCheck
}

View File

@ -0,0 +1,26 @@
const User = require('../models/user.model');
const constant = require('../util/constant')
const AdminOrOwner = async(req,res,next)=> {
try{
let id = req.params.id;
const user = await User.findById(req.userId);
if(user._id == id || user.userTypes ==constant.userTypes.admin) return next();
else{
console.log('Only admin or user can access this field');
return res.status(400).send({
message : 'Invalid authorization'
})
}
}catch(err){
console.log('Error inside isAdminorUser',err);
res.status(500).send({
message : 'Internal Server Error'
})
}
}
module.exports = {
AdminOrOwner
}

24
middlewares/payment.js Normal file
View File

@ -0,0 +1,24 @@
const User = require('../models/user.model');
const paymentBody = async(req,res,next) => {
try{
const user = await User.findById(req.userId);
req.body['userName'] = user.userName
next();
}catch(err){
console.log('Error inside paymentBody middleware',err);
return res.status(500).send({
message : 'Internal Server Error'
})
}
}
module.exports = {
paymentBody
}

33
middlewares/playlist.js Normal file
View File

@ -0,0 +1,33 @@
const PlayList = require('../models/playlist.model');
const repeatedSongs = async(req,res,next) => {
try{
const playlist = await PlayList.findById(req.params.id);
console.log(playlist);
if(!playlist.songs == undefined) return next();
for(let i=0;i<playlist.songs.length;i++)
{
let value = playlist.songs[i];
const strValue = `${value}`
const cleanValue = strValue.replace(/new ObjectId\("(.*)"\)/, '$1');
if(req.body.song==cleanValue) return res.status(400).send({
message : 'Song already present in playlist'
})
}
next();
}catch(err){
console.log('Error inside repeatedSongs Middleware',err);
return res.status(500).send({
message : "Internal Server Error"
})
}
}
module.exports = {
repeatedSongs
}

11
middlewares/regex.js Normal file
View File

@ -0,0 +1,11 @@
let nameRegex = /^[.a-zA-Z\s]+$/;
let phoneRegex = /^(\+91[\-\s]?)?[0]?(91)?[6789]\d{9}$/;
let emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
let passRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$/;
module.exports = {
nameRegex,
phoneRegex,
emailRegex,passRegex
}

99
middlewares/reqBody.js Normal file
View File

@ -0,0 +1,99 @@
const User = require('../models/user.model');
const bodyCheck = async (req, res, next) => {
try {
console.log(req.body);
// Check if request body is undefined
if (req.body === undefined) {
return res.status(400).json({
message: 'Empty request body'
});
}
// Check if email is provided
if (!req.body.email) {
return res.status(400).json({
message: 'Email not provided'
});
}
// Validate email format
if (!isValidEmail(req.body.email)) {
return res.status(400).json({
message: 'Invalid email format'
});
}
// Check if password is provided
if (!req.body.password) {
return res.status(400).json({
message: 'Password not provided'
});
}
// Validate password format
if (!isValidPassword(req.body.password)) {
return res.status(400).json({
message: 'Invalid password format'
});
}
next(); // Proceed to the next middleware
} catch (err) {
console.error('Error inside bodyCheck:', err);
return res.status(500).json({
message: 'Internal Server Error'
});
}
};
const emailCheck = (req,res,next) => {
if(!req.body.email){
return res.status(401).send({
message : 'Email not provided'
})
}
if(!isValidEmail(req.body.email)){
return res.status(401).send({
messsage : 'Email format Incorrect'
})
}
next();
}
const userCheckEmail = async (req,res,next) => {
try{
const user = await User.findOne({email : req.body.email});
if(!user){
return res.status(404).send({
message : 'User not present'
})
}
next();
}catch(err){
return res.status(500).send({
message : 'Error inside userCheckEmail'
})
}
}
const isValidEmail = (email)=>{ // checks valid email format
return String(email).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
}
const isValidPassword = (password)=>{ // checks password meets requirements
return password.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,25}$/);
}
module.exports = {
bodyCheck,
emailCheck,
userCheckEmail
}

49
models/Ads.model.js Normal file
View File

@ -0,0 +1,49 @@
const mongoose = require('mongoose');
const constant = require('../util/ads.constant');
const adsSchema = new mongoose.Schema({
adsTitle: {
type: String,
required: true
},
redirectLink: {
type: String,
required: true
},
advertiseAs: {
type: String,
enum: [constant.adsType.image, constant.adsType.video],
required: true
},
advertiseImage: {
type: String
},
advertiseVideo: {
type: String
},
adsTime: {
type: Number,
default: 10
},
status: {
type: String,
enum: ['activate', 'deactivate'],
default: 'activate'
},
adsTiming: {
minutes: {
type: Number,
default: 0
},
seconds: {
type: Number,
default: 0
}
},
adsStatus: {
type: Boolean,
default: true
}
}, { timestamps: true });
module.exports = mongoose.model('Ads', adsSchema);

27
models/Form.model.js Normal file
View File

@ -0,0 +1,27 @@
const mongoose = require('mongoose');
const formSchema = new mongoose.Schema(
{
userName : {
type : String
},
message : {
type : String,
require : true
},
reply : {
type : String,
},
subject : {
type : String,
},
email : {
type : String,
required : true
}
},{timestamps:true});
module.exports = mongoose.model('Form',formSchema);

25
models/Review.model.js Normal file
View File

@ -0,0 +1,25 @@
const mongoose = require('mongoose');
const constant = require('../util/review.constant');
const reviewSchema = new mongoose.Schema({
userName : {
type : String
},
review : {
type : String,
require : true
},
reply : {
type : String,
require : true
},
status : {
type : String,
enum : [constant.status.publish,constant.status.unpublish],
default : constant.status.publish
}
},{timestamps:true});
module.exports = mongoose.model('Review',reviewSchema);

15
models/Reward.model.js Normal file
View File

@ -0,0 +1,15 @@
const mongoose = require('mongoose');
const rewardSchema = new mongoose.Schema({
score : {
type : String,
required : true
},
reward : {
type : Number,
required : true
}
})
module.exports = mongoose.model('Reward',rewardSchema);

View File

@ -0,0 +1,12 @@
const mongoose = require('mongoose');
const termsAndConditionSchema = new mongoose.Schema({
termsCondition: {
type: String,
required: true
}
}, { timestamps: true });
const TermsAndCondition = mongoose.model('TermsAndCondition', termsAndConditionSchema);
module.exports = TermsAndCondition;

View File

@ -0,0 +1,22 @@
const mongoose = require('mongoose');
const adsSettingSchema = new mongoose.Schema({
adsTiming : {
minutes :{
type : Number,
default : 0
},
seconds : {
type : Number,
default : 0
}
},
adsStatus : {
type : Boolean,
default : true
}
})
module.exports = mongoose.model('AdsSetting',adsSettingSchema)

25
models/album.model.js Normal file
View File

@ -0,0 +1,25 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Define the schema
const albumSchema = new mongoose.Schema({
categoryId: { type: Schema.Types.ObjectId, ref: 'Category' },
subcategoryId: { type: Schema.Types.ObjectId, ref: 'SubCategories' },
albumName: String,
shortDescription: String,
image: {
fileName: String,
fileAddress: String
},
status: {
type: String,
enum: ['activate', 'deactivate'],
default: 'activate'
}
}, { timestamps: true }); // This will add createdAt and updatedAt fields
// Create the model
const Album = mongoose.model('Album', albumSchema);
module.exports = Album;

24
models/artist.model.js Normal file
View File

@ -0,0 +1,24 @@
const mongoose = require('mongoose');
// Define the schema
const artistSchema = new mongoose.Schema({
ArtistName: {
type: String,
required: true
},
image: {
fileName: String,
fileAddress: String
},
status: {
type: String,
enum: ['activate', 'deactivate'],
default: 'activate'
}
}, { timestamps: true }); // This will add createdAt and updatedAt fields
// Create the model
const Artist = mongoose.model('Artist', artistSchema);
module.exports = Artist;

View File

@ -0,0 +1,28 @@
const mongoose = require('mongoose');
const categorySchema = new mongoose.Schema({
name: {
type: String,
required: true
},
image: {
fileName: {
type: String,
required: true
},
fileAddress: {
type: String,
required: true
}
},
imageUrl: { type: String },
status: {
type: String,
enum: ['activate', 'deactivate'],
default: 'activate'
}
}, { timestamps: true }); // Add timestamps option here
const Category = mongoose.model('Category', categorySchema);
module.exports = Category;

View File

@ -0,0 +1,24 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const importSongSchema = new Schema({
category: String,
subcategory: String,
album: String,
artist: String,
title: String,
musicLink: String,
trackerID: String,
lyrics: String,
language: String,
coverArtImage: {
filename: String,
fileAddress: String
},
musicFile: {
filename: String,
fileAddress: String
}
}, { timestamps: true });
module.exports = mongoose.model('ImportSong', importSongSchema);

18
models/language.model.js Normal file
View File

@ -0,0 +1,18 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const languageSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
status: {
type: String,
enum: ['activate', 'deactivate'],
default: 'activate'
}
}, { timestamps: true });
const Language = mongoose.model('Language', languageSchema);
module.exports = Language;

View File

@ -0,0 +1,33 @@
const mongoose = require('mongoose');
const constant = require('../util/notification.constant')
const notificationSchema = new mongoose.Schema({
sendTo: {
type: [String],
enum: [constant.sendTo.toAll, constant.sendTo.host, constant.sendTo.specific],
required: true
},
Type: {
type: [String],
enum: [constant.notificationType.email, constant.notificationType.sms, constant.notificationType.push],
required: true
},
user: {
type: [String],
default: []
},
Title: {
type: String,
required: true
},
message: {
type: String,
required: true
},
recipients: {
type: [mongoose.SchemaType.objectId],
default: []
}
}, { timestamps: true });
module.exports = mongoose.model('Notification', notificationSchema);

34
models/payment.model.js Normal file
View File

@ -0,0 +1,34 @@
const mongoose = require('mongoose');
const paymentSchema = new mongoose.Schema({
userName : {
type : String,
required : true
},
planName : {
type : String,
required : true
},
mainAmount : {
type : Number,
required : true
},
offer : {
type : String
},
finalAmount : {
type : Number
},
paymentId :{
type :String,
required : true
},
paymentMethod : {
type : String,
required : true,
},
},{timestamps:true});
module.exports = mongoose.model('Payment',paymentSchema);

17
models/playlist.model.js Normal file
View File

@ -0,0 +1,17 @@
const mongoose = require('mongoose');
const playlistSchema = new mongoose.Schema({
name : {
type : String,
required : true
},
songs : {
type : [mongoose.Schema.Types.ObjectId]
},
userId : {
type : mongoose.Schema.Types.ObjectId
}
})
module.exports = mongoose.model('PlayList',playlistSchema);

10
models/privacy.model.js Normal file
View File

@ -0,0 +1,10 @@
const mongoose = require('mongoose');
const privacyPolicySchema = new mongoose.Schema({
privacyPolicy : {
type : String,
trim : true
}
},{timestamps:true})
module.exports = mongoose.model('Privacy&Policy', privacyPolicySchema);

31
models/song.model.js Normal file
View File

@ -0,0 +1,31 @@
// song.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const songSchema = new Schema({
categoryId: { type: Schema.Types.ObjectId, ref: 'Category' },
subcategoryId: { type: Schema.Types.ObjectId, ref: 'SubCategories' },
albumId: { type: Schema.Types.ObjectId, ref: 'Album' },
artistId: { type: Schema.Types.ObjectId, ref: 'Artist' },
title: String,
musicLink: String,
trackerID: String,
lyrics: String,
languageId: { type: Schema.Types.ObjectId, ref: 'Language' },
coverArtImage: {
filename: String,
fileAddress: String,
imageUrl: String
},
musicFile: {
filename: String,
fileAddress: String
},
status: {
type: String,
enum: ['activate', 'deactivate'],
default: 'activate'
}
}, { timestamps: true });
module.exports = mongoose.model('Song', songSchema);

View File

@ -0,0 +1,36 @@
const mongoose = require('mongoose');
// Define the schema for the 'subcategories' collection
const subCategoriesSchema = new mongoose.Schema({
CategoriesId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
required: true
},
categoryName:{
type: String,
},
SubCategoriesName: {
type: String,
required: true
},
image: {
fileName: String,
fileAddress: String,
imageUrl: String
},
status: {
type: String,
enum: ['activate', 'deactivate'],
default: 'activate'
}
}, {
timestamps: true // Add createdAt and updatedAt fields
});
// Create a model based on the schema
const SubCategories = mongoose.model('SubCategories', subCategoriesSchema);
module.exports = SubCategories;

View File

@ -0,0 +1,54 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const subconstant = require('../util/subscriptionConstant');
const subcriptionSchema = new mongoose.Schema({
subscriptionTitle : {
type : String,
required :true
},
validity :{
duration : {
type : String,
enum : [subconstant.duration.day,subconstant.duration.month,subconstant.duration.year],
required : true
},
count : {
type : Number,
default:0
}
},
price : {
type : Number,
required : true
},
description : {
type : String,
},
offer : {
type : Number,
required : true,
default : 0
},
adfree : {
type : Boolean,
required : true,
},
download :{
type : Boolean,
required : true,
},
status : {
type : String,
enum : [subconstant.status.activate,subconstant.status.deactivate],
default : subconstant.status.activate
}
},{timestamps : true})
module.exports = mongoose.model('Subscription',subcriptionSchema);

111
models/user.model.js Normal file
View File

@ -0,0 +1,111 @@
const mongoose = require("mongoose");
const constant = require('../util/constant');
const userSchema = new mongoose.Schema({
userName: {
type: String,
unique: true,
default: function () {
let username = 'guest' + Math.floor(Math.random() * 10000);
return username;
}
},
image: {
fileName: {
type: String,
},
fileAddress: {
type: String,
}
},
email: {
type: String,
required: true,
lowercase: true, // it will covert the email into the lower case and then store in the db,
minLength: 10, // anything less than 10 will fail
unique: true
},
password: {
type: String,
},
userTypes: {
type: String,
enum: [constant.userTypes.admin, constant.userTypes.customer],
default: constant.userTypes.customer
},
status: {
type: String,
enum: ['activate', 'deactivate'],
default: 'activate'
},
registerWith: {
type: String,
enum: [constant.registerWith.Email, constant.registerWith.google, constant.registerWith.facebook],
default: constant.registerWith.Email
},
playlist: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'PlayList'
},
favrioteSongs: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'Song',
},
mostPlayedSongs: {
type: Object,
ref: 'Song',
default: {}
},
following: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'Artist'
},
score: {
type: Number,
default: 0
},
otp : Number,
createdAt: {
// I want to default to a new date
type: Date,
immutable: true, // This will ensure the createdAt column is never updated but once in the start
default: () => {
return Date.now();
}
},
updatedAt: {
type: Date,
default: () => {
return Date.now();
}
}
})
userSchema.pre('deleteOne', async function (next) {
const userId = this.getFilter()['_id'];
const Artist = require('../models/artist.model');
const artist = await Artist.find({
followers: userId
})
const artistPromises = artist.map(artist => {
artist.followers.pull(userId);
return artist.save();
})
await Promise.all(artistPromises);
})
module.exports = mongoose.model("User", userSchema);

1
node_modules/.bin/mime generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mime/cli.js

17
node_modules/.bin/mime.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mime\cli.js" %*

28
node_modules/.bin/mime.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../mime/cli.js" $args
} else {
& "$basedir/node$exe" "$basedir/../mime/cli.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../mime/cli.js" $args
} else {
& "node$exe" "$basedir/../mime/cli.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

1
node_modules/.bin/mkdirp generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mkdirp/bin/cmd.js

17
node_modules/.bin/mkdirp.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mkdirp\bin\cmd.js" %*

28
node_modules/.bin/mkdirp.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
} else {
& "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
} else {
& "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

1
node_modules/.bin/nodemon generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nodemon/bin/nodemon.js

17
node_modules/.bin/nodemon.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nodemon\bin\nodemon.js" %*

28
node_modules/.bin/nodemon.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../nodemon/bin/nodemon.js" $args
} else {
& "$basedir/node$exe" "$basedir/../nodemon/bin/nodemon.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../nodemon/bin/nodemon.js" $args
} else {
& "node$exe" "$basedir/../nodemon/bin/nodemon.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

1
node_modules/.bin/nodetouch generated vendored Symbolic link
View File

@ -0,0 +1 @@
../touch/bin/nodetouch.js

17
node_modules/.bin/nodetouch.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\touch\bin\nodetouch.js" %*

28
node_modules/.bin/nodetouch.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../touch/bin/nodetouch.js" $args
} else {
& "$basedir/node$exe" "$basedir/../touch/bin/nodetouch.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../touch/bin/nodetouch.js" $args
} else {
& "node$exe" "$basedir/../touch/bin/nodetouch.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

1
node_modules/.bin/nopt generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nopt/bin/nopt.js

17
node_modules/.bin/nopt.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nopt\bin\nopt.js" %*

28
node_modules/.bin/nopt.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args
} else {
& "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../nopt/bin/nopt.js" $args
} else {
& "node$exe" "$basedir/../nopt/bin/nopt.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

1
node_modules/.bin/semver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../semver/bin/semver.js

17
node_modules/.bin/semver.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*

28
node_modules/.bin/semver.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

1641
node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

21
node_modules/@types/node/LICENSE generated vendored Normal file
View File

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

15
node_modules/@types/node/README.md generated vendored Normal file
View File

@ -0,0 +1,15 @@
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for node (https://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
### Additional Details
* Last updated: Thu, 29 Feb 2024 15:35:59 GMT
* Dependencies: [undici-types](https://npmjs.com/package/undici-types)
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [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), [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).

996
node_modules/@types/node/assert.d.ts generated vendored Normal file
View File

@ -0,0 +1,996 @@
/**
* The `node:assert` module provides a set of assertion functions for verifying
* invariants.
* @see [source](https://github.com/nodejs/node/blob/v20.2.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 `node:assert`module will be instances of the `AssertionError` class.
*/
class AssertionError extends Error {
/**
* Set to the `actual` argument for methods such as {@link assert.strictEqual()}.
*/
actual: unknown;
/**
* Set to the `expected` argument for methods such as {@link assert.strictEqual()}.
*/
expected: unknown;
/**
* Set to the passed in operator value.
*/
operator: string;
/**
* Indicates if the message was auto-generated (`true`) or not.
*/
generatedMessage: boolean;
/**
* Value is always `ERR_ASSERTION` to show that the error is an assertion error.
*/
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. */
// eslint-disable-next-line @typescript-eslint/ban-types
stackStartFn?: Function | undefined;
});
}
/**
* This feature is deprecated and will be removed in a future version.
* Please consider using alternatives such as the `mock` helper function.
* @since v14.2.0, v12.19.0
* @deprecated Deprecated
*/
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 'node: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: undefined, arguments: [1, 2, 3] }]);
* ```
* @since v18.8.0, v16.18.0
* @param fn
* @return An Array with all 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 'node: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);
*
* // Returns an array containing information on callsfunc()
* console.log(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 An Array 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
* assert.strictEqual(tracker.getCalls(callsfunc).length, 1);
*
* tracker.reset(callsfunc);
* assert.strictEqual(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 'node: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 'node: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,
// eslint-disable-next-line @typescript-eslint/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 'node: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 'node: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 'node: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 'node: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 'node:assert';
*
* const obj1 = {
* a: {
* b: 1,
* },
* };
* const obj2 = {
* a: {
* b: 2,
* },
* };
* const obj3 = {
* a: {
* b: 1,
* },
* };
* const obj4 = { __proto__: 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 'node: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 'node: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 'node: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 'node: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:
* assert.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:
* assert.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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node: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 'node:assert/strict';
*
* await assert.rejects(
* async () => {
* throw new TypeError('Wrong value');
* },
* {
* name: 'TypeError',
* message: 'Wrong value',
* },
* );
* ```
*
* ```js
* import assert from 'node: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 'node: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 'node:assert/strict';
*
* await assert.doesNotReject(
* async () => {
* throw new TypeError('Wrong value');
* },
* SyntaxError,
* );
* ```
*
* ```js
* import assert from 'node: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 'node: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 'node: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;
}

8
node_modules/@types/node/assert/strict.d.ts generated vendored Normal file
View File

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

539
node_modules/@types/node/async_hooks.d.ts generated vendored Normal file
View File

@ -0,0 +1,539 @@
/**
* We strongly discourage the use of the `async_hooks` API.
* Other APIs that can cover most of its use cases include:
*
* * `AsyncLocalStorage` tracks async context
* * `process.getActiveResourcesInfo()` tracks active resources
*
* The `node:async_hooks` module provides an API to track asynchronous resources.
* It can be accessed using:
*
* ```js
* import async_hooks from 'node:async_hooks';
* ```
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js)
*/
declare module "async_hooks" {
/**
* ```js
* import { executionAsyncId } from 'node:async_hooks';
* import fs from 'node:fs';
*
* console.log(executionAsyncId()); // 1 - bootstrap
* const path = '.';
* 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 'node:fs';
* import { executionAsyncId, executionAsyncResource } from 'node: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 'node: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 'node: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 'node: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.
* @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;
/**
* Binds the given function to execute to this `AsyncResource`'s scope.
* @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;
/**
* 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;
}
/**
* This class creates stores that stay coherent through asynchronous operations.
*
* While you can create your own implementation on top of the `node: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 'node:http';
* import { AsyncLocalStorage } from 'node: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> {
/**
* Binds the given function to the current execution context.
* @since v19.8.0
* @experimental
* @param fn The function to bind to the current execution context.
* @return A new function that calls `fn` within the captured execution context.
*/
static bind<Func extends (...args: any[]) => any>(fn: Func): Func;
/**
* Captures the current execution context and returns a function that accepts a
* function as an argument. Whenever the returned function is called, it
* calls the function passed to it within the captured context.
*
* ```js
* const asyncLocalStorage = new AsyncLocalStorage();
* const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());
* const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
* console.log(result); // returns 123
* ```
*
* AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
* async context tracking purposes, for example:
*
* ```js
* class Foo {
* #runInAsyncScope = AsyncLocalStorage.snapshot();
*
* get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
* }
*
* const foo = asyncLocalStorage.run(123, () => new Foo());
* console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
* ```
* @since v19.8.0
* @experimental
* @return A new function with the signature `(fn: (...args) : R, ...args) : R`.
*/
static snapshot(): <R, TArgs extends any[]>(fn: (...args: TArgs) => R, ...args: TArgs) => R;
/**
* 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>(store: T, callback: () => R): R;
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";
}

2363
node_modules/@types/node/buffer.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

1542
node_modules/@types/node/child_process.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

432
node_modules/@types/node/cluster.d.ts generated vendored Normal file
View File

@ -0,0 +1,432 @@
/**
* 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 'node:cluster';
* import http from 'node:http';
* import { availableParallelism } from 'node:os';
* import process from 'node:process';
*
* const numCPUs = availableParallelism();
*
* 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/v20.2.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";
type SerializationType = "json" | "advanced";
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;
serialization?: SerializationType | undefined;
cwd?: string | undefined;
windowsHide?: boolean | 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('node: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 'node:cluster';
* import http from 'node:http';
* import { availableParallelism } from 'node:os';
* import process from 'node:process';
*
* const numCPUs = availableParallelism();
*
* 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";
}

415
node_modules/@types/node/console.d.ts generated vendored Normal file
View File

@ -0,0 +1,415 @@
/**
* The `node: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('node: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/v20.2.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='default'] 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='default'] 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 can't 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?: readonly 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
* @param [label='default']
*/
time(label?: string): void;
/**
* Stops a timer that was previously started by calling {@link time} and
* prints the result to `stdout`:
*
* ```js
* console.time('bunch-of-stuff');
* // Do a bunch of stuff.
* console.timeEnd('bunch-of-stuff');
* // Prints: bunch-of-stuff: 225.438ms
* ```
* @since v0.1.104
* @param [label='default']
*/
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
* @param [label='default']
*/
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;
}

19
node_modules/@types/node/constants.d.ts generated vendored Normal file
View File

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

4487
node_modules/@types/node/crypto.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

596
node_modules/@types/node/dgram.d.ts generated vendored Normal file
View File

@ -0,0 +1,596 @@
/**
* The `node:dgram` module provides an implementation of UDP datagram sockets.
*
* ```js
* import dgram from 'node:dgram';
*
* const server = dgram.createSocket('udp4');
*
* server.on('error', (err) => {
* console.error(`server error:\n${err.stack}`);
* server.close();
* });
*
* server.on('message', (msg, rinfo) => {
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
* });
*
* server.on('listening', () => {
* const address = server.address();
* console.log(`server listening ${address.address}:${address.port}`);
* });
*
* server.bind(41234);
* // Prints: server listening 0.0.0.0:41234
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dgram.js)
*/
declare module "dgram" {
import { AddressInfo } from "node:net";
import * as dns from "node:dns";
import { Abortable, EventEmitter } from "node:events";
interface RemoteInfo {
address: string;
family: "IPv4" | "IPv6";
port: number;
size: number;
}
interface BindOptions {
port?: number | undefined;
address?: string | undefined;
exclusive?: boolean | undefined;
fd?: number | undefined;
}
type SocketType = "udp4" | "udp6";
interface SocketOptions extends Abortable {
type: SocketType;
reuseAddr?: boolean | undefined;
/**
* @default false
*/
ipv6Only?: boolean | undefined;
recvBufferSize?: number | undefined;
sendBufferSize?: number | undefined;
lookup?:
| ((
hostname: string,
options: dns.LookupOneOptions,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
) => void)
| undefined;
}
/**
* Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram
* messages. When `address` and `port` are not passed to `socket.bind()` the
* method will bind the socket to the "all interfaces" address on a random port
* (it does the right thing for both `udp4` and `udp6` sockets). The bound address
* and port can be retrieved using `socket.address().address` and `socket.address().port`.
*
* If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket:
*
* ```js
* const controller = new AbortController();
* const { signal } = controller;
* const server = dgram.createSocket({ type: 'udp4', signal });
* server.on('message', (msg, rinfo) => {
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
* });
* // Later, when you want to close the server.
* controller.abort();
* ```
* @since v0.11.13
* @param options Available options are:
* @param callback Attached as a listener for `'message'` events. Optional.
*/
function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
/**
* Encapsulates the datagram functionality.
*
* New instances of `dgram.Socket` are created using {@link createSocket}.
* The `new` keyword is not to be used to create `dgram.Socket` instances.
* @since v0.1.99
*/
class Socket extends EventEmitter {
/**
* Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not
* specified, the operating system will choose
* one interface and will add membership to it. To add membership to every
* available interface, call `addMembership` multiple times, once per interface.
*
* When called on an unbound socket, this method will implicitly bind to a random
* port, listening on all interfaces.
*
* When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur:
*
* ```js
* import cluster from 'node:cluster';
* import dgram from 'node:dgram';
*
* if (cluster.isPrimary) {
* cluster.fork(); // Works ok.
* cluster.fork(); // Fails with EADDRINUSE.
* } else {
* const s = dgram.createSocket('udp4');
* s.bind(1234, () => {
* s.addMembership('224.0.0.114');
* });
* }
* ```
* @since v0.6.9
*/
addMembership(multicastAddress: string, multicastInterface?: string): void;
/**
* Returns an object containing the address information for a socket.
* For UDP sockets, this object will contain `address`, `family`, and `port`properties.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.1.99
*/
address(): AddressInfo;
/**
* For UDP sockets, causes the `dgram.Socket` to listen for datagram
* messages on a named `port` and optional `address`. If `port` is not
* specified or is `0`, the operating system will attempt to bind to a
* random port. If `address` is not specified, the operating system will
* attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is
* called.
*
* Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very
* useful.
*
* A bound datagram socket keeps the Node.js process running to receive
* datagram messages.
*
* If binding fails, an `'error'` event is generated. In rare case (e.g.
* attempting to bind with a closed socket), an `Error` may be thrown.
*
* Example of a UDP server listening on port 41234:
*
* ```js
* import dgram from 'node:dgram';
*
* const server = dgram.createSocket('udp4');
*
* server.on('error', (err) => {
* console.error(`server error:\n${err.stack}`);
* server.close();
* });
*
* server.on('message', (msg, rinfo) => {
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
* });
*
* server.on('listening', () => {
* const address = server.address();
* console.log(`server listening ${address.address}:${address.port}`);
* });
*
* server.bind(41234);
* // Prints: server listening 0.0.0.0:41234
* ```
* @since v0.1.99
* @param callback with no parameters. Called when binding is complete.
*/
bind(port?: number, address?: string, callback?: () => void): this;
bind(port?: number, callback?: () => void): this;
bind(callback?: () => void): this;
bind(options: BindOptions, callback?: () => void): this;
/**
* Close the underlying socket and stop listening for data on it. If a callback is
* provided, it is added as a listener for the `'close'` event.
* @since v0.1.99
* @param callback Called when the socket has been closed.
*/
close(callback?: () => void): this;
/**
* Associates the `dgram.Socket` to a remote address and port. Every
* message sent by this handle is automatically sent to that destination. Also,
* the socket will only receive messages from that remote peer.
* Trying to call `connect()` on an already connected socket will result
* in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not
* provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets)
* will be used by default. Once the connection is complete, a `'connect'` event
* is emitted and the optional `callback` function is called. In case of failure,
* the `callback` is called or, failing this, an `'error'` event is emitted.
* @since v12.0.0
* @param callback Called when the connection is completed or on error.
*/
connect(port: number, address?: string, callback?: () => void): void;
connect(port: number, callback: () => void): void;
/**
* A synchronous function that disassociates a connected `dgram.Socket` from
* its remote address. Trying to call `disconnect()` on an unbound or already
* disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception.
* @since v12.0.0
*/
disconnect(): void;
/**
* Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the
* kernel when the socket is closed or the process terminates, so most apps will
* never have reason to call this.
*
* If `multicastInterface` is not specified, the operating system will attempt to
* drop membership on all valid interfaces.
* @since v0.6.9
*/
dropMembership(multicastAddress: string, multicastInterface?: string): void;
/**
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
* @since v8.7.0
* @return the `SO_RCVBUF` socket receive buffer size in bytes.
*/
getRecvBufferSize(): number;
/**
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
* @since v8.7.0
* @return the `SO_SNDBUF` socket send buffer size in bytes.
*/
getSendBufferSize(): number;
/**
* @since v18.8.0, v16.19.0
* @return Number of bytes queued for sending.
*/
getSendQueueSize(): number;
/**
* @since v18.8.0, v16.19.0
* @return Number of send requests currently in the queue awaiting to be processed.
*/
getSendQueueCount(): number;
/**
* By default, binding a socket will cause it to block the Node.js process from
* exiting as long as the socket is open. The `socket.unref()` method can be used
* to exclude the socket from the reference counting that keeps the Node.js
* process active. The `socket.ref()` method adds the socket back to the reference
* counting and restores the default behavior.
*
* Calling `socket.ref()` multiples times will have no additional effect.
*
* The `socket.ref()` method returns a reference to the socket so calls can be
* chained.
* @since v0.9.1
*/
ref(): this;
/**
* Returns an object containing the `address`, `family`, and `port` of the remote
* endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception
* if the socket is not connected.
* @since v12.0.0
*/
remoteAddress(): AddressInfo;
/**
* Broadcasts a datagram on the socket.
* For connectionless sockets, the destination `port` and `address` must be
* specified. Connected sockets, on the other hand, will use their associated
* remote endpoint, so the `port` and `address` arguments must not be set.
*
* The `msg` argument contains the message to be sent.
* Depending on its type, different behavior can apply. If `msg` is a `Buffer`,
* any `TypedArray` or a `DataView`,
* the `offset` and `length` specify the offset within the `Buffer` where the
* message begins and the number of bytes in the message, respectively.
* If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that
* contain multi-byte characters, `offset` and `length` will be calculated with
* respect to `byte length` and not the character position.
* If `msg` is an array, `offset` and `length` must not be specified.
*
* The `address` argument is a string. If the value of `address` is a host name,
* DNS will be used to resolve the address of the host. If `address` is not
* provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default.
*
* If the socket has not been previously bound with a call to `bind`, the socket
* is assigned a random port number and is bound to the "all interfaces" address
* (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
*
* An optional `callback` function may be specified to as a way of reporting
* DNS errors or for determining when it is safe to reuse the `buf` object.
* DNS lookups delay the time to send for at least one tick of the
* Node.js event loop.
*
* The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be
* passed as the first argument to the `callback`. If a `callback` is not given,
* the error is emitted as an `'error'` event on the `socket` object.
*
* Offset and length are optional but both _must_ be set if either are used.
* They are supported only when the first argument is a `Buffer`, a `TypedArray`,
* or a `DataView`.
*
* This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket.
*
* Example of sending a UDP packet to a port on `localhost`;
*
* ```js
* import dgram from 'node:dgram';
* import { Buffer } from 'node:buffer';
*
* const message = Buffer.from('Some bytes');
* const client = dgram.createSocket('udp4');
* client.send(message, 41234, 'localhost', (err) => {
* client.close();
* });
* ```
*
* Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`;
*
* ```js
* import dgram from 'node:dgram';
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from('Some ');
* const buf2 = Buffer.from('bytes');
* const client = dgram.createSocket('udp4');
* client.send([buf1, buf2], 41234, (err) => {
* client.close();
* });
* ```
*
* Sending multiple buffers might be faster or slower depending on the
* application and operating system. Run benchmarks to
* determine the optimal strategy on a case-by-case basis. Generally speaking,
* however, sending multiple buffers is faster.
*
* Example of sending a UDP packet using a socket connected to a port on`localhost`:
*
* ```js
* import dgram from 'node:dgram';
* import { Buffer } from 'node:buffer';
*
* const message = Buffer.from('Some bytes');
* const client = dgram.createSocket('udp4');
* client.connect(41234, 'localhost', (err) => {
* client.send(message, (err) => {
* client.close();
* });
* });
* ```
* @since v0.1.99
* @param msg Message to be sent.
* @param offset Offset in the buffer where the message starts.
* @param length Number of bytes in the message.
* @param port Destination port.
* @param address Destination host name or IP address.
* @param callback Called when the message has been sent.
*/
send(
msg: string | Uint8Array | readonly any[],
port?: number,
address?: string,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array | readonly any[],
port?: number,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array | readonly any[],
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array,
offset: number,
length: number,
port?: number,
address?: string,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array,
offset: number,
length: number,
port?: number,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | Uint8Array,
offset: number,
length: number,
callback?: (error: Error | null, bytes: number) => void,
): void;
/**
* Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP
* packets may be sent to a local interface's broadcast address.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.6.9
*/
setBroadcast(flag: boolean): void;
/**
* _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC
* 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_
* _with a scope index is written as `'IP%scope'` where scope is an interface name_
* _or interface number._
*
* Sets the default outgoing multicast interface of the socket to a chosen
* interface or back to system interface selection. The `multicastInterface` must
* be a valid string representation of an IP from the socket's family.
*
* For IPv4 sockets, this should be the IP configured for the desired physical
* interface. All packets sent to multicast on the socket will be sent on the
* interface determined by the most recent successful use of this call.
*
* For IPv6 sockets, `multicastInterface` should include a scope to indicate the
* interface as in the examples that follow. In IPv6, individual `send` calls can
* also use explicit scope in addresses, so only packets sent to a multicast
* address without specifying an explicit scope are affected by the most recent
* successful use of this call.
*
* This method throws `EBADF` if called on an unbound socket.
*
* #### Example: IPv6 outgoing multicast interface
*
* On most systems, where scope format uses the interface name:
*
* ```js
* const socket = dgram.createSocket('udp6');
*
* socket.bind(1234, () => {
* socket.setMulticastInterface('::%eth1');
* });
* ```
*
* On Windows, where scope format uses an interface number:
*
* ```js
* const socket = dgram.createSocket('udp6');
*
* socket.bind(1234, () => {
* socket.setMulticastInterface('::%2');
* });
* ```
*
* #### Example: IPv4 outgoing multicast interface
*
* All systems use an IP of the host on the desired physical interface:
*
* ```js
* const socket = dgram.createSocket('udp4');
*
* socket.bind(1234, () => {
* socket.setMulticastInterface('10.0.0.2');
* });
* ```
* @since v8.6.0
*/
setMulticastInterface(multicastInterface: string): void;
/**
* Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`,
* multicast packets will also be received on the local interface.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.3.8
*/
setMulticastLoopback(flag: boolean): boolean;
/**
* Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for
* "Time to Live", in this context it specifies the number of IP hops that a
* packet is allowed to travel through, specifically for multicast traffic. Each
* router or gateway that forwards a packet decrements the TTL. If the TTL is
* decremented to 0 by a router, it will not be forwarded.
*
* The `ttl` argument may be between 0 and 255\. The default on most systems is `1`.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.3.8
*/
setMulticastTTL(ttl: number): number;
/**
* Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer
* in bytes.
*
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
* @since v8.7.0
*/
setRecvBufferSize(size: number): void;
/**
* Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer
* in bytes.
*
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
* @since v8.7.0
*/
setSendBufferSize(size: number): void;
/**
* Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live",
* in this context it specifies the number of IP hops that a packet is allowed to
* travel through. Each router or gateway that forwards a packet decrements the
* TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
* Changing TTL values is typically done for network probes or when multicasting.
*
* The `ttl` argument may be between 1 and 255\. The default on most systems
* is 64.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.1.101
*/
setTTL(ttl: number): number;
/**
* By default, binding a socket will cause it to block the Node.js process from
* exiting as long as the socket is open. The `socket.unref()` method can be used
* to exclude the socket from the reference counting that keeps the Node.js
* process active, allowing the process to exit even if the socket is still
* listening.
*
* Calling `socket.unref()` multiple times will have no additional effect.
*
* The `socket.unref()` method returns a reference to the socket so calls can be
* chained.
* @since v0.9.1
*/
unref(): this;
/**
* Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket
* option. If the `multicastInterface` argument
* is not specified, the operating system will choose one interface and will add
* membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface.
*
* When called on an unbound socket, this method will implicitly bind to a random
* port, listening on all interfaces.
* @since v13.1.0, v12.16.0
*/
addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
/**
* Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is
* automatically called by the kernel when the
* socket is closed or the process terminates, so most apps will never have
* reason to call this.
*
* If `multicastInterface` is not specified, the operating system will attempt to
* drop membership on all valid interfaces.
* @since v13.1.0, v12.16.0
*/
dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
/**
* events.EventEmitter
* 1. close
* 2. connect
* 3. error
* 4. listening
* 5. message
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "connect", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "listening", listener: () => void): this;
addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "connect"): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "listening"): boolean;
emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "connect", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this;
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "connect", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "listening", listener: () => void): this;
once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "connect", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "listening", listener: () => void): this;
prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "connect", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "listening", listener: () => void): this;
prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
/**
* Calls `socket.close()` and returns a promise that fulfills when the socket has closed.
* @since v20.5.0
*/
[Symbol.asyncDispose](): Promise<void>;
}
}
declare module "node:dgram" {
export * from "dgram";
}

545
node_modules/@types/node/diagnostics_channel.d.ts generated vendored Normal file
View File

@ -0,0 +1,545 @@
/**
* The `node:diagnostics_channel` module provides an API to create named channels
* to report arbitrary message data for diagnostics purposes.
*
* It can be accessed using:
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* ```
*
* It is intended that a module writer wanting to report diagnostics messages
* will create one or many top-level channels to report messages through.
* Channels may also be acquired at runtime but it is not encouraged
* due to the additional overhead of doing so. Channels may be exported for
* convenience, but as long as the name is known it can be acquired anywhere.
*
* If you intend for your module to produce diagnostics data for others to
* consume it is recommended that you include documentation of what named
* channels are used along with the shape of the message data. Channel names
* should generally include the module name to avoid collisions with data from
* other modules.
* @since v15.1.0, v14.17.0
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js)
*/
declare module "diagnostics_channel" {
import { AsyncLocalStorage } from "node:async_hooks";
/**
* Check if there are active subscribers to the named channel. This is helpful if
* the message you want to send might be expensive to prepare.
*
* This API is optional but helpful when trying to publish messages from very
* performance-sensitive code.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* if (diagnostics_channel.hasSubscribers('my-channel')) {
* // There are subscribers, prepare and publish message
* }
* ```
* @since v15.1.0, v14.17.0
* @param name The channel name
* @return If there are active subscribers
*/
function hasSubscribers(name: string | symbol): boolean;
/**
* This is the primary entry-point for anyone wanting to publish to a named
* channel. It produces a channel object which is optimized to reduce overhead at
* publish time as much as possible.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
* ```
* @since v15.1.0, v14.17.0
* @param name The channel name
* @return The named channel object
*/
function channel(name: string | symbol): Channel;
type ChannelListener = (message: unknown, name: string | symbol) => void;
/**
* Register a message handler to subscribe to this channel. This message handler
* will be run synchronously whenever a message is published to the channel. Any
* errors thrown in the message handler will trigger an `'uncaughtException'`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* diagnostics_channel.subscribe('my-channel', (message, name) => {
* // Received data
* });
* ```
* @since v18.7.0, v16.17.0
* @param name The channel name
* @param onMessage The handler to receive channel messages
*/
function subscribe(name: string | symbol, onMessage: ChannelListener): void;
/**
* Remove a message handler previously registered to this channel with {@link subscribe}.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* function onMessage(message, name) {
* // Received data
* }
*
* diagnostics_channel.subscribe('my-channel', onMessage);
*
* diagnostics_channel.unsubscribe('my-channel', onMessage);
* ```
* @since v18.7.0, v16.17.0
* @param name The channel name
* @param onMessage The previous subscribed handler to remove
* @return `true` if the handler was found, `false` otherwise.
*/
function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean;
/**
* Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing
* channels will be created in the form of `tracing:${name}:${eventType}` where`eventType` corresponds to the types of `TracingChannel Channels`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channelsByName = diagnostics_channel.tracingChannel('my-channel');
*
* // or...
*
* const channelsByCollection = diagnostics_channel.tracingChannel({
* start: diagnostics_channel.channel('tracing:my-channel:start'),
* end: diagnostics_channel.channel('tracing:my-channel:end'),
* asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
* asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
* error: diagnostics_channel.channel('tracing:my-channel:error'),
* });
* ```
* @since v19.9.0
* @experimental
* @param nameOrChannels Channel name or object containing all the `TracingChannel Channels`
* @return Collection of channels to trace with
*/
function tracingChannel<
StoreType = unknown,
ContextType extends object = StoreType extends object ? StoreType : object,
>(
nameOrChannels: string | TracingChannelCollection<StoreType, ContextType>,
): TracingChannel<StoreType, ContextType>;
/**
* The class `Channel` represents an individual named channel within the data
* pipeline. It is used to track subscribers and to publish messages when there
* are subscribers present. It exists as a separate object to avoid channel
* lookups at publish time, enabling very fast publish speeds and allowing
* for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly
* with `new Channel(name)` is not supported.
* @since v15.1.0, v14.17.0
*/
class Channel<StoreType = unknown, ContextType = StoreType> {
readonly name: string | symbol;
/**
* Check if there are active subscribers to this channel. This is helpful if
* the message you want to send might be expensive to prepare.
*
* This API is optional but helpful when trying to publish messages from very
* performance-sensitive code.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* if (channel.hasSubscribers) {
* // There are subscribers, prepare and publish message
* }
* ```
* @since v15.1.0, v14.17.0
*/
readonly hasSubscribers: boolean;
private constructor(name: string | symbol);
/**
* Publish a message to any subscribers to the channel. This will trigger
* message handlers synchronously so they will execute within the same context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.publish({
* some: 'message',
* });
* ```
* @since v15.1.0, v14.17.0
* @param message The message to send to the channel subscribers
*/
publish(message: unknown): void;
/**
* Register a message handler to subscribe to this channel. This message handler
* will be run synchronously whenever a message is published to the channel. Any
* errors thrown in the message handler will trigger an `'uncaughtException'`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.subscribe((message, name) => {
* // Received data
* });
* ```
* @since v15.1.0, v14.17.0
* @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)}
* @param onMessage The handler to receive channel messages
*/
subscribe(onMessage: ChannelListener): void;
/**
* Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* function onMessage(message, name) {
* // Received data
* }
*
* channel.subscribe(onMessage);
*
* channel.unsubscribe(onMessage);
* ```
* @since v15.1.0, v14.17.0
* @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)}
* @param onMessage The previous subscribed handler to remove
* @return `true` if the handler was found, `false` otherwise.
*/
unsubscribe(onMessage: ChannelListener): void;
/**
* When `channel.runStores(context, ...)` is called, the given context data
* will be applied to any store bound to the channel. If the store has already been
* bound the previous `transform` function will be replaced with the new one.
* The `transform` function may be omitted to set the given context data as the
* context directly.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store, (data) => {
* return { data };
* });
* ```
* @since v19.9.0
* @experimental
* @param store The store to which to bind the context data
* @param transform Transform context data before setting the store context
*/
bindStore(store: AsyncLocalStorage<StoreType>, transform?: (context: ContextType) => StoreType): void;
/**
* Remove a message handler previously registered to this channel with `channel.bindStore(store)`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store);
* channel.unbindStore(store);
* ```
* @since v19.9.0
* @experimental
* @param store The store to unbind from the channel.
* @return `true` if the store was found, `false` otherwise.
*/
unbindStore(store: any): void;
/**
* Applies the given data to any AsyncLocalStorage instances bound to the channel
* for the duration of the given function, then publishes to the channel within
* the scope of that data is applied to the stores.
*
* If a transform function was given to `channel.bindStore(store)` it will be
* applied to transform the message data before it becomes the context value for
* the store. The prior storage context is accessible from within the transform
* function in cases where context linking is required.
*
* The context applied to the store should be accessible in any async code which
* continues from execution which began during the given function, however
* there are some situations in which `context loss` may occur.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store, (message) => {
* const parent = store.getStore();
* return new Span(message, parent);
* });
* channel.runStores({ some: 'message' }, () => {
* store.getStore(); // Span({ some: 'message' })
* });
* ```
* @since v19.9.0
* @experimental
* @param context Message to send to subscribers and bind to stores
* @param fn Handler to run within the entered storage context
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runStores(): void;
}
interface TracingChannelSubscribers<ContextType extends object> {
start: (message: ContextType) => void;
end: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
asyncStart: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
asyncEnd: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
error: (
message: ContextType & {
error: unknown;
},
) => void;
}
interface TracingChannelCollection<StoreType = unknown, ContextType = StoreType> {
start: Channel<StoreType, ContextType>;
end: Channel<StoreType, ContextType>;
asyncStart: Channel<StoreType, ContextType>;
asyncEnd: Channel<StoreType, ContextType>;
error: Channel<StoreType, ContextType>;
}
/**
* The class `TracingChannel` is a collection of `TracingChannel Channels` which
* together express a single traceable action. It is used to formalize and
* simplify the process of producing events for tracing application flow.{@link tracingChannel} is used to construct a`TracingChannel`. As with `Channel` it is recommended to create and reuse a
* single `TracingChannel` at the top-level of the file rather than creating them
* dynamically.
* @since v19.9.0
* @experimental
*/
class TracingChannel<StoreType = unknown, ContextType extends object = {}> implements TracingChannelCollection {
start: Channel<StoreType, ContextType>;
end: Channel<StoreType, ContextType>;
asyncStart: Channel<StoreType, ContextType>;
asyncEnd: Channel<StoreType, ContextType>;
error: Channel<StoreType, ContextType>;
/**
* Helper to subscribe a collection of functions to the corresponding channels.
* This is the same as calling `channel.subscribe(onMessage)` on each channel
* individually.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.subscribe({
* start(message) {
* // Handle start message
* },
* end(message) {
* // Handle end message
* },
* asyncStart(message) {
* // Handle asyncStart message
* },
* asyncEnd(message) {
* // Handle asyncEnd message
* },
* error(message) {
* // Handle error message
* },
* });
* ```
* @since v19.9.0
* @experimental
* @param subscribers Set of `TracingChannel Channels` subscribers
*/
subscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
/**
* Helper to unsubscribe a collection of functions from the corresponding channels.
* This is the same as calling `channel.unsubscribe(onMessage)` on each channel
* individually.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.unsubscribe({
* start(message) {
* // Handle start message
* },
* end(message) {
* // Handle end message
* },
* asyncStart(message) {
* // Handle asyncStart message
* },
* asyncEnd(message) {
* // Handle asyncEnd message
* },
* error(message) {
* // Handle error message
* },
* });
* ```
* @since v19.9.0
* @experimental
* @param subscribers Set of `TracingChannel Channels` subscribers
* @return `true` if all handlers were successfully unsubscribed, and `false` otherwise.
*/
unsubscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
/**
* Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error.
* This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.traceSync(() => {
* // Do something
* }, {
* some: 'thing',
* });
* ```
* @since v19.9.0
* @experimental
* @param fn Function to wrap a trace around
* @param context Shared object to correlate events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return The return value of the given function
*/
traceSync<ThisArg = any, Args extends any[] = any[]>(
fn: (this: ThisArg, ...args: Args) => any,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): void;
/**
* Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the
* function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also
* produce an `error event` if the given function throws an error or the
* returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.tracePromise(async () => {
* // Do something
* }, {
* some: 'thing',
* });
* ```
* @since v19.9.0
* @experimental
* @param fn Promise-returning function to wrap a trace around
* @param context Shared object to correlate trace events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return Chained from promise returned by the given function
*/
tracePromise<ThisArg = any, Args extends any[] = any[]>(
fn: (this: ThisArg, ...args: Args) => Promise<any>,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): void;
/**
* Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the
* function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or
* the returned
* promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* The `position` will be -1 by default to indicate the final argument should
* be used as the callback.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.traceCallback((arg1, callback) => {
* // Do something
* callback(null, 'result');
* }, 1, {
* some: 'thing',
* }, thisArg, arg1, callback);
* ```
*
* The callback will also be run with `channel.runStores(context, ...)` which
* enables context loss recovery in some cases.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
* const myStore = new AsyncLocalStorage();
*
* // The start channel sets the initial store data to something
* // and stores that store data value on the trace context object
* channels.start.bindStore(myStore, (data) => {
* const span = new Span(data);
* data.span = span;
* return span;
* });
*
* // Then asyncStart can restore from that data it stored previously
* channels.asyncStart.bindStore(myStore, (data) => {
* return data.span;
* });
* ```
* @since v19.9.0
* @experimental
* @param fn callback using function to wrap a trace around
* @param position Zero-indexed argument position of expected callback
* @param context Shared object to correlate trace events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return The return value of the given function
*/
traceCallback<Fn extends (this: any, ...args: any) => any>(
fn: Fn,
position: number | undefined,
context: ContextType | undefined,
thisArg: any,
...args: Parameters<Fn>
): void;
}
}
declare module "node:diagnostics_channel" {
export * from "diagnostics_channel";
}

809
node_modules/@types/node/dns.d.ts generated vendored Normal file
View File

@ -0,0 +1,809 @@
/**
* The `node:dns` module enables name resolution. For example, use it to look up IP
* addresses of host names.
*
* Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the
* DNS protocol for lookups. {@link lookup} uses the operating system
* facilities to perform name resolution. It may not need to perform any network
* communication. To perform name resolution the way other applications on the same
* system do, use {@link lookup}.
*
* ```js
* const dns = require('node:dns');
*
* dns.lookup('example.org', (err, address, family) => {
* console.log('address: %j family: IPv%s', address, family);
* });
* // address: "93.184.216.34" family: IPv4
* ```
*
* All other functions in the `node:dns` module connect to an actual DNS server to
* perform name resolution. They will always use the network to perform DNS
* queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform
* DNS queries, bypassing other name-resolution facilities.
*
* ```js
* const dns = require('node:dns');
*
* dns.resolve4('archive.org', (err, addresses) => {
* if (err) throw err;
*
* console.log(`addresses: ${JSON.stringify(addresses)}`);
*
* addresses.forEach((a) => {
* dns.reverse(a, (err, hostnames) => {
* if (err) {
* throw err;
* }
* console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
* });
* });
* });
* ```
*
* See the `Implementation considerations section` for more information.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js)
*/
declare module "dns" {
import * as dnsPromises from "node:dns/promises";
// Supported getaddrinfo flags.
export const ADDRCONFIG: number;
export const V4MAPPED: number;
/**
* If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
* well as IPv4 mapped IPv6 addresses.
*/
export const ALL: number;
export interface LookupOptions {
family?: number | undefined;
hints?: number | undefined;
all?: boolean | undefined;
/**
* @default true
*/
verbatim?: boolean | undefined;
}
export interface LookupOneOptions extends LookupOptions {
all?: false | undefined;
}
export interface LookupAllOptions extends LookupOptions {
all: true;
}
export interface LookupAddress {
address: string;
family: number;
}
/**
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an
* integer, then it must be `4` or `6` if `options` is `0` or not provided, then
* IPv4 and IPv6 addresses are both returned if found.
*
* With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the
* properties `address` and `family`.
*
* On error, `err` is an `Error` object, where `err.code` is the error code.
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
* the host name does not exist but also when the lookup fails in other ways
* such as no available file descriptors.
*
* `dns.lookup()` does not necessarily have anything to do with the DNS protocol.
* The implementation uses an operating system facility that can associate names
* with addresses and vice versa. This implementation can have subtle but
* important consequences on the behavior of any Node.js program. Please take some
* time to consult the `Implementation considerations section` before using`dns.lookup()`.
*
* Example usage:
*
* ```js
* const dns = require('node:dns');
* const options = {
* family: 6,
* hints: dns.ADDRCONFIG | dns.V4MAPPED,
* };
* dns.lookup('example.com', options, (err, address, family) =>
* console.log('address: %j family: IPv%s', address, family));
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
*
* // When options.all is true, the result will be an Array.
* options.all = true;
* dns.lookup('example.com', options, (err, addresses) =>
* console.log('addresses: %j', addresses));
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
* ```
*
* If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties.
* @since v0.1.90
*/
export function lookup(
hostname: string,
family: number,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
export function lookup(
hostname: string,
options: LookupOneOptions,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
export function lookup(
hostname: string,
options: LookupAllOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void,
): void;
export function lookup(
hostname: string,
options: LookupOptions,
callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void,
): void;
export function lookup(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
export namespace lookup {
function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>;
function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
}
/**
* Resolves the given `address` and `port` into a host name and service using
* the operating system's underlying `getnameinfo` implementation.
*
* If `address` is not a valid IP address, a `TypeError` will be thrown.
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown.
*
* On an error, `err` is an `Error` object, where `err.code` is the error code.
*
* ```js
* const dns = require('node:dns');
* dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
* console.log(hostname, service);
* // Prints: localhost ssh
* });
* ```
*
* If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties.
* @since v0.11.14
*/
export function lookupService(
address: string,
port: number,
callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void,
): void;
export namespace lookupService {
function __promisify__(
address: string,
port: number,
): Promise<{
hostname: string;
service: string;
}>;
}
export interface ResolveOptions {
ttl: boolean;
}
export interface ResolveWithTtlOptions extends ResolveOptions {
ttl: true;
}
export interface RecordWithTtl {
address: string;
ttl: number;
}
/** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */
export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord;
export interface AnyARecord extends RecordWithTtl {
type: "A";
}
export interface AnyAaaaRecord extends RecordWithTtl {
type: "AAAA";
}
export interface CaaRecord {
critical: number;
issue?: string | undefined;
issuewild?: string | undefined;
iodef?: string | undefined;
contactemail?: string | undefined;
contactphone?: string | undefined;
}
export interface MxRecord {
priority: number;
exchange: string;
}
export interface AnyMxRecord extends MxRecord {
type: "MX";
}
export interface NaptrRecord {
flags: string;
service: string;
regexp: string;
replacement: string;
order: number;
preference: number;
}
export interface AnyNaptrRecord extends NaptrRecord {
type: "NAPTR";
}
export interface SoaRecord {
nsname: string;
hostmaster: string;
serial: number;
refresh: number;
retry: number;
expire: number;
minttl: number;
}
export interface AnySoaRecord extends SoaRecord {
type: "SOA";
}
export interface SrvRecord {
priority: number;
weight: number;
port: number;
name: string;
}
export interface AnySrvRecord extends SrvRecord {
type: "SRV";
}
export interface AnyTxtRecord {
type: "TXT";
entries: string[];
}
export interface AnyNsRecord {
type: "NS";
value: string;
}
export interface AnyPtrRecord {
type: "PTR";
value: string;
}
export interface AnyCnameRecord {
type: "CNAME";
value: string;
}
export type AnyRecord =
| AnyARecord
| AnyAaaaRecord
| AnyCnameRecord
| AnyMxRecord
| AnyNaptrRecord
| AnyNsRecord
| AnyPtrRecord
| AnySoaRecord
| AnySrvRecord
| AnyTxtRecord;
/**
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
* of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource
* records. The type and structure of individual results varies based on `rrtype`:
*
* <omitted>
*
* On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`.
* @since v0.1.27
* @param hostname Host name to resolve.
* @param [rrtype='A'] Resource record type.
*/
export function resolve(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "A",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "AAAA",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "ANY",
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "CNAME",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "MX",
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "NAPTR",
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "NS",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "PTR",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "SOA",
callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void,
): void;
export function resolve(
hostname: string,
rrtype: "SRV",
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "TXT",
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
): void;
export function resolve(
hostname: string,
rrtype: string,
callback: (
err: NodeJS.ErrnoException | null,
addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[],
) => void,
): void;
export namespace resolve {
function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function __promisify__(
hostname: string,
rrtype: string,
): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
}
/**
* Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function
* will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
* @since v0.1.16
* @param hostname Host name to resolve.
*/
export function resolve4(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve4(
hostname: string,
options: ResolveWithTtlOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
): void;
export function resolve4(
hostname: string,
options: ResolveOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
): void;
export namespace resolve4 {
function __promisify__(hostname: string): Promise<string[]>;
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
}
/**
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function
* will contain an array of IPv6 addresses.
* @since v0.1.16
* @param hostname Host name to resolve.
*/
export function resolve6(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve6(
hostname: string,
options: ResolveWithTtlOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
): void;
export function resolve6(
hostname: string,
options: ResolveOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
): void;
export namespace resolve6 {
function __promisify__(hostname: string): Promise<string[]>;
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
}
/**
* Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function
* will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`).
* @since v0.3.2
*/
export function resolveCname(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export namespace resolveCname {
function __promisify__(hostname: string): Promise<string[]>;
}
/**
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function
* will contain an array of certification authority authorization records
* available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`).
* @since v15.0.0, v14.17.0
*/
export function resolveCaa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void,
): void;
export namespace resolveCaa {
function __promisify__(hostname: string): Promise<CaaRecord[]>;
}
/**
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will
* contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
* @since v0.1.27
*/
export function resolveMx(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
): void;
export namespace resolveMx {
function __promisify__(hostname: string): Promise<MxRecord[]>;
}
/**
* Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of
* objects with the following properties:
*
* * `flags`
* * `service`
* * `regexp`
* * `replacement`
* * `order`
* * `preference`
*
* ```js
* {
* flags: 's',
* service: 'SIP+D2U',
* regexp: '',
* replacement: '_sip._udp.example.com',
* order: 30,
* preference: 100
* }
* ```
* @since v0.9.12
*/
export function resolveNaptr(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
): void;
export namespace resolveNaptr {
function __promisify__(hostname: string): Promise<NaptrRecord[]>;
}
/**
* Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will
* contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`).
* @since v0.1.90
*/
export function resolveNs(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export namespace resolveNs {
function __promisify__(hostname: string): Promise<string[]>;
}
/**
* Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will
* be an array of strings containing the reply records.
* @since v6.0.0
*/
export function resolvePtr(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export namespace resolvePtr {
function __promisify__(hostname: string): Promise<string[]>;
}
/**
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
* the `hostname`. The `address` argument passed to the `callback` function will
* be an object with the following properties:
*
* * `nsname`
* * `hostmaster`
* * `serial`
* * `refresh`
* * `retry`
* * `expire`
* * `minttl`
*
* ```js
* {
* nsname: 'ns.example.com',
* hostmaster: 'root.example.com',
* serial: 2013101809,
* refresh: 10000,
* retry: 2400,
* expire: 604800,
* minttl: 3600
* }
* ```
* @since v0.11.10
*/
export function resolveSoa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void,
): void;
export namespace resolveSoa {
function __promisify__(hostname: string): Promise<SoaRecord>;
}
/**
* Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will
* be an array of objects with the following properties:
*
* * `priority`
* * `weight`
* * `port`
* * `name`
*
* ```js
* {
* priority: 10,
* weight: 5,
* port: 21223,
* name: 'service.example.com'
* }
* ```
* @since v0.1.27
*/
export function resolveSrv(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
): void;
export namespace resolveSrv {
function __promisify__(hostname: string): Promise<SrvRecord[]>;
}
/**
* Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a
* two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
* one record. Depending on the use case, these could be either joined together or
* treated separately.
* @since v0.1.27
*/
export function resolveTxt(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
): void;
export namespace resolveTxt {
function __promisify__(hostname: string): Promise<string[][]>;
}
/**
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
* The `ret` argument passed to the `callback` function will be an array containing
* various types of records. Each object has a property `type` that indicates the
* type of the current record. And depending on the `type`, additional properties
* will be present on the object:
*
* <omitted>
*
* Here is an example of the `ret` object passed to the callback:
*
* ```js
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
* { type: 'CNAME', value: 'example.com' },
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
* { type: 'NS', value: 'ns1.example.com' },
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
* { type: 'SOA',
* nsname: 'ns1.example.com',
* hostmaster: 'admin.example.com',
* serial: 156696742,
* refresh: 900,
* retry: 900,
* expire: 1800,
* minttl: 60 } ]
* ```
*
* DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC
* 8482](https://tools.ietf.org/html/rfc8482).
*/
export function resolveAny(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
): void;
export namespace resolveAny {
function __promisify__(hostname: string): Promise<AnyRecord[]>;
}
/**
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
* array of host names.
*
* On error, `err` is an `Error` object, where `err.code` is
* one of the `DNS error codes`.
* @since v0.1.16
*/
export function reverse(
ip: string,
callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void,
): void;
/**
* Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be:
*
* * `ipv4first`: for `verbatim` defaulting to `false`.
* * `verbatim`: for `verbatim` defaulting to `true`.
* @since v20.1.0
*/
export function getDefaultResultOrder(): "ipv4first" | "verbatim";
/**
* Sets the IP address and port of servers to be used when performing DNS
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
* addresses. If the port is the IANA default DNS port (53) it can be omitted.
*
* ```js
* dns.setServers([
* '4.4.4.4',
* '[2001:4860:4860::8888]',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]);
* ```
*
* An error will be thrown if an invalid address is provided.
*
* The `dns.setServers()` method must not be called while a DNS query is in
* progress.
*
* The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}).
*
* This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
* That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
* subsequent servers provided. Fallback DNS servers will only be used if the
* earlier ones time out or result in some other error.
* @since v0.11.3
* @param servers array of `RFC 5952` formatted addresses
*/
export function setServers(servers: readonly string[]): void;
/**
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
* that are currently configured for DNS resolution. A string will include a port
* section if a custom port is used.
*
* ```js
* [
* '4.4.4.4',
* '2001:4860:4860::8888',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]
* ```
* @since v0.11.3
*/
export function getServers(): string[];
/**
* Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be:
*
* * `ipv4first`: sets default `verbatim` `false`.
* * `verbatim`: sets default `verbatim` `true`.
*
* The default is `verbatim` and {@link setDefaultResultOrder} have higher
* priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default
* dns orders in workers.
* @since v16.4.0, v14.18.0
* @param order must be `'ipv4first'` or `'verbatim'`.
*/
export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void;
// Error codes
export const NODATA: string;
export const FORMERR: string;
export const SERVFAIL: string;
export const NOTFOUND: string;
export const NOTIMP: string;
export const REFUSED: string;
export const BADQUERY: string;
export const BADNAME: string;
export const BADFAMILY: string;
export const BADRESP: string;
export const CONNREFUSED: string;
export const TIMEOUT: string;
export const EOF: string;
export const FILE: string;
export const NOMEM: string;
export const DESTRUCTION: string;
export const BADSTR: string;
export const BADFLAGS: string;
export const NONAME: string;
export const BADHINTS: string;
export const NOTINITIALIZED: string;
export const LOADIPHLPAPI: string;
export const ADDRGETNETWORKPARAMS: string;
export const CANCELLED: string;
export interface ResolverOptions {
timeout?: number | undefined;
/**
* @default 4
*/
tries?: number;
}
/**
* An independent resolver for DNS requests.
*
* Creating a new resolver uses the default server settings. Setting
* the servers used for a resolver using `resolver.setServers()` does not affect
* other resolvers:
*
* ```js
* const { Resolver } = require('node:dns');
* const resolver = new Resolver();
* resolver.setServers(['4.4.4.4']);
*
* // This request will use the server at 4.4.4.4, independent of global settings.
* resolver.resolve4('example.org', (err, addresses) => {
* // ...
* });
* ```
*
* The following methods from the `node:dns` module are available:
*
* * `resolver.getServers()`
* * `resolver.resolve()`
* * `resolver.resolve4()`
* * `resolver.resolve6()`
* * `resolver.resolveAny()`
* * `resolver.resolveCaa()`
* * `resolver.resolveCname()`
* * `resolver.resolveMx()`
* * `resolver.resolveNaptr()`
* * `resolver.resolveNs()`
* * `resolver.resolvePtr()`
* * `resolver.resolveSoa()`
* * `resolver.resolveSrv()`
* * `resolver.resolveTxt()`
* * `resolver.reverse()`
* * `resolver.setServers()`
* @since v8.3.0
*/
export class Resolver {
constructor(options?: ResolverOptions);
/**
* Cancel all outstanding DNS queries made by this resolver. The corresponding
* callbacks will be called with an error with code `ECANCELLED`.
* @since v8.3.0
*/
cancel(): void;
getServers: typeof getServers;
resolve: typeof resolve;
resolve4: typeof resolve4;
resolve6: typeof resolve6;
resolveAny: typeof resolveAny;
resolveCaa: typeof resolveCaa;
resolveCname: typeof resolveCname;
resolveMx: typeof resolveMx;
resolveNaptr: typeof resolveNaptr;
resolveNs: typeof resolveNs;
resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
/**
* The resolver instance will send its requests from the specified IP address.
* This allows programs to specify outbound interfaces when used on multi-homed
* systems.
*
* If a v4 or v6 address is not specified, it is set to the default and the
* operating system will choose a local address automatically.
*
* The resolver will use the v4 local address when making requests to IPv4 DNS
* servers, and the v6 local address when making requests to IPv6 DNS servers.
* The `rrtype` of resolution requests has no impact on the local address used.
* @since v15.1.0, v14.17.0
* @param [ipv4='0.0.0.0'] A string representation of an IPv4 address.
* @param [ipv6='::0'] A string representation of an IPv6 address.
*/
setLocalAddress(ipv4?: string, ipv6?: string): void;
setServers: typeof setServers;
}
export { dnsPromises as promises };
}
declare module "node:dns" {
export * from "dns";
}

425
node_modules/@types/node/dns/promises.d.ts generated vendored Normal file
View File

@ -0,0 +1,425 @@
/**
* The `dns.promises` API provides an alternative set of asynchronous DNS methods
* that return `Promise` objects rather than using callbacks. The API is accessible
* via `require('node:dns').promises` or `require('node:dns/promises')`.
* @since v10.6.0
*/
declare module "dns/promises" {
import {
AnyRecord,
CaaRecord,
LookupAddress,
LookupAllOptions,
LookupOneOptions,
LookupOptions,
MxRecord,
NaptrRecord,
RecordWithTtl,
ResolveOptions,
ResolverOptions,
ResolveWithTtlOptions,
SoaRecord,
SrvRecord,
} from "node:dns";
/**
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
* that are currently configured for DNS resolution. A string will include a port
* section if a custom port is used.
*
* ```js
* [
* '4.4.4.4',
* '2001:4860:4860::8888',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]
* ```
* @since v10.6.0
*/
function getServers(): string[];
/**
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an
* integer, then it must be `4` or `6` if `options` is not provided, then IPv4
* and IPv6 addresses are both returned if found.
*
* With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`.
*
* On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code.
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
* the host name does not exist but also when the lookup fails in other ways
* such as no available file descriptors.
*
* `dnsPromises.lookup()` does not necessarily have anything to do with the DNS
* protocol. The implementation uses an operating system facility that can
* associate names with addresses and vice versa. This implementation can have
* subtle but important consequences on the behavior of any Node.js program. Please
* take some time to consult the `Implementation considerations section` before
* using `dnsPromises.lookup()`.
*
* Example usage:
*
* ```js
* const dns = require('node:dns');
* const dnsPromises = dns.promises;
* const options = {
* family: 6,
* hints: dns.ADDRCONFIG | dns.V4MAPPED,
* };
*
* dnsPromises.lookup('example.com', options).then((result) => {
* console.log('address: %j family: IPv%s', result.address, result.family);
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
* });
*
* // When options.all is true, the result will be an Array.
* options.all = true;
* dnsPromises.lookup('example.com', options).then((result) => {
* console.log('addresses: %j', result);
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
* });
* ```
* @since v10.6.0
*/
function lookup(hostname: string, family: number): Promise<LookupAddress>;
function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>;
function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
function lookup(hostname: string): Promise<LookupAddress>;
/**
* Resolves the given `address` and `port` into a host name and service using
* the operating system's underlying `getnameinfo` implementation.
*
* If `address` is not a valid IP address, a `TypeError` will be thrown.
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown.
*
* On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code.
*
* ```js
* const dnsPromises = require('node:dns').promises;
* dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
* console.log(result.hostname, result.service);
* // Prints: localhost ssh
* });
* ```
* @since v10.6.0
*/
function lookupService(
address: string,
port: number,
): Promise<{
hostname: string;
service: string;
}>;
/**
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
* of the resource records. When successful, the `Promise` is resolved with an
* array of resource records. The type and structure of individual results vary
* based on `rrtype`:
*
* <omitted>
*
* On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`.
* @since v10.6.0
* @param hostname Host name to resolve.
* @param [rrtype='A'] Resource record type.
*/
function resolve(hostname: string): Promise<string[]>;
function resolve(hostname: string, rrtype: "A"): Promise<string[]>;
function resolve(hostname: string, rrtype: "AAAA"): Promise<string[]>;
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function resolve(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
function resolve(hostname: string, rrtype: "CNAME"): Promise<string[]>;
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function resolve(hostname: string, rrtype: "NS"): Promise<string[]>;
function resolve(hostname: string, rrtype: "PTR"): Promise<string[]>;
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function resolve(
hostname: string,
rrtype: string,
): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
/**
* Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4
* addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
* @since v10.6.0
* @param hostname Host name to resolve.
*/
function resolve4(hostname: string): Promise<string[]>;
function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
/**
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6
* addresses.
* @since v10.6.0
* @param hostname Host name to resolve.
*/
function resolve6(hostname: string): Promise<string[]>;
function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
/**
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
* On success, the `Promise` is resolved with an array containing various types of
* records. Each object has a property `type` that indicates the type of the
* current record. And depending on the `type`, additional properties will be
* present on the object:
*
* <omitted>
*
* Here is an example of the result object:
*
* ```js
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
* { type: 'CNAME', value: 'example.com' },
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
* { type: 'NS', value: 'ns1.example.com' },
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
* { type: 'SOA',
* nsname: 'ns1.example.com',
* hostmaster: 'admin.example.com',
* serial: 156696742,
* refresh: 900,
* retry: 900,
* expire: 1800,
* minttl: 60 } ]
* ```
* @since v10.6.0
*/
function resolveAny(hostname: string): Promise<AnyRecord[]>;
/**
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success,
* the `Promise` is resolved with an array of objects containing available
* certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`).
* @since v15.0.0, v14.17.0
*/
function resolveCaa(hostname: string): Promise<CaaRecord[]>;
/**
* Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success,
* the `Promise` is resolved with an array of canonical name records available for
* the `hostname` (e.g. `['bar.example.com']`).
* @since v10.6.0
*/
function resolveCname(hostname: string): Promise<string[]>;
/**
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects
* containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`).
* @since v10.6.0
*/
function resolveMx(hostname: string): Promise<MxRecord[]>;
/**
* Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array
* of objects with the following properties:
*
* * `flags`
* * `service`
* * `regexp`
* * `replacement`
* * `order`
* * `preference`
*
* ```js
* {
* flags: 's',
* service: 'SIP+D2U',
* regexp: '',
* replacement: '_sip._udp.example.com',
* order: 30,
* preference: 100
* }
* ```
* @since v10.6.0
*/
function resolveNaptr(hostname: string): Promise<NaptrRecord[]>;
/**
* Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server
* records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`).
* @since v10.6.0
*/
function resolveNs(hostname: string): Promise<string[]>;
/**
* Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings
* containing the reply records.
* @since v10.6.0
*/
function resolvePtr(hostname: string): Promise<string[]>;
/**
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
* the `hostname`. On success, the `Promise` is resolved with an object with the
* following properties:
*
* * `nsname`
* * `hostmaster`
* * `serial`
* * `refresh`
* * `retry`
* * `expire`
* * `minttl`
*
* ```js
* {
* nsname: 'ns.example.com',
* hostmaster: 'root.example.com',
* serial: 2013101809,
* refresh: 10000,
* retry: 2400,
* expire: 604800,
* minttl: 3600
* }
* ```
* @since v10.6.0
*/
function resolveSoa(hostname: string): Promise<SoaRecord>;
/**
* Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with
* the following properties:
*
* * `priority`
* * `weight`
* * `port`
* * `name`
*
* ```js
* {
* priority: 10,
* weight: 5,
* port: 21223,
* name: 'service.example.com'
* }
* ```
* @since v10.6.0
*/
function resolveSrv(hostname: string): Promise<SrvRecord[]>;
/**
* Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array
* of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
* one record. Depending on the use case, these could be either joined together or
* treated separately.
* @since v10.6.0
*/
function resolveTxt(hostname: string): Promise<string[][]>;
/**
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
* array of host names.
*
* On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`.
* @since v10.6.0
*/
function reverse(ip: string): Promise<string[]>;
/**
* Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be:
*
* * `ipv4first`: for `verbatim` defaulting to `false`.
* * `verbatim`: for `verbatim` defaulting to `true`.
* @since v20.1.0
*/
function getDefaultResultOrder(): "ipv4first" | "verbatim";
/**
* Sets the IP address and port of servers to be used when performing DNS
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
* addresses. If the port is the IANA default DNS port (53) it can be omitted.
*
* ```js
* dnsPromises.setServers([
* '4.4.4.4',
* '[2001:4860:4860::8888]',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]);
* ```
*
* An error will be thrown if an invalid address is provided.
*
* The `dnsPromises.setServers()` method must not be called while a DNS query is in
* progress.
*
* This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
* That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
* subsequent servers provided. Fallback DNS servers will only be used if the
* earlier ones time out or result in some other error.
* @since v10.6.0
* @param servers array of `RFC 5952` formatted addresses
*/
function setServers(servers: readonly string[]): void;
/**
* Set the default value of `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be:
*
* * `ipv4first`: sets default `verbatim` `false`.
* * `verbatim`: sets default `verbatim` `true`.
*
* The default is `verbatim` and `dnsPromises.setDefaultResultOrder()` have
* higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.setDefaultResultOrder()` from the main thread won't affect the
* default dns orders in workers.
* @since v16.4.0, v14.18.0
* @param order must be `'ipv4first'` or `'verbatim'`.
*/
function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void;
/**
* An independent resolver for DNS requests.
*
* Creating a new resolver uses the default server settings. Setting
* the servers used for a resolver using `resolver.setServers()` does not affect
* other resolvers:
*
* ```js
* const { Resolver } = require('node:dns').promises;
* const resolver = new Resolver();
* resolver.setServers(['4.4.4.4']);
*
* // This request will use the server at 4.4.4.4, independent of global settings.
* resolver.resolve4('example.org').then((addresses) => {
* // ...
* });
*
* // Alternatively, the same code can be written using async-await style.
* (async function() {
* const addresses = await resolver.resolve4('example.org');
* })();
* ```
*
* The following methods from the `dnsPromises` API are available:
*
* * `resolver.getServers()`
* * `resolver.resolve()`
* * `resolver.resolve4()`
* * `resolver.resolve6()`
* * `resolver.resolveAny()`
* * `resolver.resolveCaa()`
* * `resolver.resolveCname()`
* * `resolver.resolveMx()`
* * `resolver.resolveNaptr()`
* * `resolver.resolveNs()`
* * `resolver.resolvePtr()`
* * `resolver.resolveSoa()`
* * `resolver.resolveSrv()`
* * `resolver.resolveTxt()`
* * `resolver.reverse()`
* * `resolver.setServers()`
* @since v10.6.0
*/
class Resolver {
constructor(options?: ResolverOptions);
cancel(): void;
getServers: typeof getServers;
resolve: typeof resolve;
resolve4: typeof resolve4;
resolve6: typeof resolve6;
resolveAny: typeof resolveAny;
resolveCaa: typeof resolveCaa;
resolveCname: typeof resolveCname;
resolveMx: typeof resolveMx;
resolveNaptr: typeof resolveNaptr;
resolveNs: typeof resolveNs;
resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
setLocalAddress(ipv4?: string, ipv6?: string): void;
setServers: typeof setServers;
}
}
declare module "node:dns/promises" {
export * from "dns/promises";
}

122
node_modules/@types/node/dom-events.d.ts generated vendored Normal file
View File

@ -0,0 +1,122 @@
export {}; // Don't export anything!
//// DOM-like Events
// NB: The Event / EventTarget / EventListener implementations below were copied
// from lib.dom.d.ts, then edited to reflect Node's documentation at
// https://nodejs.org/api/events.html#class-eventtarget.
// Please read that link to understand important implementation differences.
// This conditional type will be the existing global Event in a browser, or
// the copy below in a Node environment.
type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {}
: {
/** This is not used in Node.js and is provided purely for completeness. */
readonly bubbles: boolean;
/** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */
cancelBubble: () => void;
/** True if the event was created with the cancelable option */
readonly cancelable: boolean;
/** This is not used in Node.js and is provided purely for completeness. */
readonly composed: boolean;
/** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */
composedPath(): [EventTarget?];
/** Alias for event.target. */
readonly currentTarget: EventTarget | null;
/** Is true if cancelable is true and event.preventDefault() has been called. */
readonly defaultPrevented: boolean;
/** This is not used in Node.js and is provided purely for completeness. */
readonly eventPhase: 0 | 2;
/** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */
readonly isTrusted: boolean;
/** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */
preventDefault(): void;
/** This is not used in Node.js and is provided purely for completeness. */
returnValue: boolean;
/** Alias for event.target. */
readonly srcElement: EventTarget | null;
/** Stops the invocation of event listeners after the current one completes. */
stopImmediatePropagation(): void;
/** This is not used in Node.js and is provided purely for completeness. */
stopPropagation(): void;
/** The `EventTarget` dispatching the event */
readonly target: EventTarget | null;
/** The millisecond timestamp when the Event object was created. */
readonly timeStamp: number;
/** Returns the type of event, e.g. "click", "hashchange", or "submit". */
readonly type: string;
};
// See comment above explaining conditional type
type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {}
: {
/**
* Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value.
*
* If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched.
*
* The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification.
* Specifically, the `capture` option is used as part of the key when registering a `listener`.
* Any individual `listener` may be added once with `capture = false`, and once with `capture = true`.
*/
addEventListener(
type: string,
listener: EventListener | EventListenerObject,
options?: AddEventListenerOptions | boolean,
): void;
/** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */
dispatchEvent(event: Event): boolean;
/** Removes the event listener in target's event listener list with the same type, callback, and options. */
removeEventListener(
type: string,
listener: EventListener | EventListenerObject,
options?: EventListenerOptions | boolean,
): void;
};
interface EventInit {
bubbles?: boolean;
cancelable?: boolean;
composed?: boolean;
}
interface EventListenerOptions {
/** Not directly used by Node.js. Added for API completeness. Default: `false`. */
capture?: boolean;
}
interface AddEventListenerOptions extends EventListenerOptions {
/** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */
once?: boolean;
/** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */
passive?: boolean;
}
interface EventListener {
(evt: Event): void;
}
interface EventListenerObject {
handleEvent(object: Event): void;
}
import {} from "events"; // Make this an ambient declaration
declare global {
/** An event which takes place in the DOM. */
interface Event extends __Event {}
var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T
: {
prototype: __Event;
new(type: string, eventInitDict?: EventInit): __Event;
};
/**
* EventTarget is a DOM interface implemented by objects that can
* receive events and may have listeners for them.
*/
interface EventTarget extends __EventTarget {}
var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T
: {
prototype: __EventTarget;
new(): __EventTarget;
};
}

170
node_modules/@types/node/domain.d.ts generated vendored Normal file
View File

@ -0,0 +1,170 @@
/**
* **This module is pending deprecation.** Once a replacement API has been
* finalized, this module will be fully deprecated. Most developers should
* **not** have cause to use this module. Users who absolutely must have
* the functionality that domains provide may rely on it for the time being
* but should expect to have to migrate to a different solution
* in the future.
*
* Domains provide a way to handle multiple different IO operations as a
* single group. If any of the event emitters or callbacks registered to a
* domain emit an `'error'` event, or throw an error, then the domain object
* will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to
* exit immediately with an error code.
* @deprecated Since v1.4.2 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js)
*/
declare module "domain" {
import EventEmitter = require("node:events");
/**
* The `Domain` class encapsulates the functionality of routing errors and
* uncaught exceptions to the active `Domain` object.
*
* To handle the errors that it catches, listen to its `'error'` event.
*/
class Domain extends EventEmitter {
/**
* An array of timers and event emitters that have been explicitly added
* to the domain.
*/
members: Array<EventEmitter | NodeJS.Timer>;
/**
* The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly
* pushes the domain onto the domain
* stack managed by the domain module (see {@link exit} for details on the
* domain stack). The call to `enter()` delimits the beginning of a chain of
* asynchronous calls and I/O operations bound to a domain.
*
* Calling `enter()` changes only the active domain, and does not alter the domain
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
* single domain.
*/
enter(): void;
/**
* The `exit()` method exits the current domain, popping it off the domain stack.
* Any time execution is going to switch to the context of a different chain of
* asynchronous calls, it's important to ensure that the current domain is exited.
* The call to `exit()` delimits either the end of or an interruption to the chain
* of asynchronous calls and I/O operations bound to a domain.
*
* If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain.
*
* Calling `exit()` changes only the active domain, and does not alter the domain
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
* single domain.
*/
exit(): void;
/**
* Run the supplied function in the context of the domain, implicitly
* binding all event emitters, timers, and low-level requests that are
* created in that context. Optionally, arguments can be passed to
* the function.
*
* This is the most basic way to use a domain.
*
* ```js
* const domain = require('node:domain');
* const fs = require('node:fs');
* const d = domain.create();
* d.on('error', (er) => {
* console.error('Caught error!', er);
* });
* d.run(() => {
* process.nextTick(() => {
* setTimeout(() => { // Simulating some various async stuff
* fs.open('non-existent file', 'r', (er, fd) => {
* if (er) throw er;
* // proceed...
* });
* }, 100);
* });
* });
* ```
*
* In this example, the `d.on('error')` handler will be triggered, rather
* than crashing the program.
*/
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
/**
* Explicitly adds an emitter to the domain. If any event handlers called by
* the emitter throw an error, or if the emitter emits an `'error'` event, it
* will be routed to the domain's `'error'` event, just like with implicit
* binding.
*
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by
* the domain `'error'` handler.
*
* If the Timer or `EventEmitter` was already bound to a domain, it is removed
* from that one, and bound to this one instead.
* @param emitter emitter or timer to be added to the domain
*/
add(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The opposite of {@link add}. Removes domain handling from the
* specified emitter.
* @param emitter emitter or timer to be removed from the domain
*/
remove(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The returned function will be a wrapper around the supplied callback
* function. When the returned function is called, any errors that are
* thrown will be routed to the domain's `'error'` event.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.bind((er, data) => {
* // If this throws, it will also be passed to the domain.
* return cb(er, data ? JSON.parse(data) : null);
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The bound function
*/
bind<T extends Function>(callback: T): T;
/**
* This method is almost identical to {@link bind}. However, in
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.
*
* In this way, the common `if (err) return callback(err);` pattern can be replaced
* with a single error handler in a single place.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.intercept((data) => {
* // Note, the first argument is never passed to the
* // callback since it is assumed to be the 'Error' argument
* // and thus intercepted by the domain.
*
* // If this throws, it will also be passed to the domain
* // so the error-handling logic can be moved to the 'error'
* // event on the domain instead of being repeated throughout
* // the program.
* return cb(null, JSON.parse(data));
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The intercepted function
*/
intercept<T extends Function>(callback: T): T;
}
function create(): Domain;
}
declare module "node:domain" {
export * from "domain";
}

896
node_modules/@types/node/events.d.ts generated vendored Normal file
View File

@ -0,0 +1,896 @@
/**
* Much of the Node.js core API is built around an idiomatic asynchronous
* event-driven architecture in which certain kinds of objects (called "emitters")
* emit named events that cause `Function` objects ("listeners") to be called.
*
* For instance: a `net.Server` object emits an event each time a peer
* connects to it; a `fs.ReadStream` emits an event when the file is opened;
* a `stream` emits an event whenever data is available to be read.
*
* All objects that emit events are instances of the `EventEmitter` class. These
* objects expose an `eventEmitter.on()` function that allows one or more
* functions to be attached to named events emitted by the object. Typically,
* event names are camel-cased strings but any valid JavaScript property key
* can be used.
*
* When the `EventEmitter` object emits an event, all of the functions attached
* to that specific event are called _synchronously_. Any values returned by the
* called listeners are _ignored_ and discarded.
*
* The following example shows a simple `EventEmitter` instance with a single
* listener. The `eventEmitter.on()` method is used to register listeners, while
* the `eventEmitter.emit()` method is used to trigger the event.
*
* ```js
* import { EventEmitter } from 'node:events';
*
* class MyEmitter extends EventEmitter {}
*
* const myEmitter = new MyEmitter();
* myEmitter.on('event', () => {
* console.log('an event occurred!');
* });
* myEmitter.emit('event');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/events.js)
*/
declare module "events" {
import { AsyncResource, AsyncResourceOptions } from "node:async_hooks";
// NOTE: This class is in the docs but is **not actually exported** by Node.
// If https://github.com/nodejs/node/issues/39903 gets resolved and Node
// actually starts exporting the class, uncomment below.
// import { EventListener, EventListenerObject } from '__dom-events';
// /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */
// interface NodeEventTarget extends EventTarget {
// /**
// * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API.
// * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget.
// */
// addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
// /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */
// eventNames(): string[];
// /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */
// listenerCount(type: string): number;
// /** Node.js-specific alias for `eventTarget.removeListener()`. */
// off(type: string, listener: EventListener | EventListenerObject): this;
// /** Node.js-specific alias for `eventTarget.addListener()`. */
// on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
// /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */
// once(type: string, listener: EventListener | EventListenerObject): this;
// /**
// * Node.js-specific extension to the `EventTarget` class.
// * If `type` is specified, removes all registered listeners for `type`,
// * otherwise removes all registered listeners.
// */
// removeAllListeners(type: string): this;
// /**
// * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`.
// * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`.
// */
// removeListener(type: string, listener: EventListener | EventListenerObject): this;
// }
interface EventEmitterOptions {
/**
* Enables automatic capturing of promise rejection.
*/
captureRejections?: boolean | undefined;
}
// Any EventTarget with a Node-style `once` function
interface _NodeEventTarget {
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
}
// Any EventTarget with a DOM-style `addEventListener`
interface _DOMEventTarget {
addEventListener(
eventName: string,
listener: (...args: any[]) => void,
opts?: {
once: boolean;
},
): any;
}
interface StaticEventEmitterOptions {
signal?: AbortSignal | undefined;
}
interface EventEmitter<T extends EventMap<T> = DefaultEventMap> extends NodeJS.EventEmitter<T> {}
type EventMap<T> = Record<keyof T, any[]> | DefaultEventMap;
type DefaultEventMap = [never];
type AnyRest = [...args: any[]];
type Args<K, T> = T extends DefaultEventMap ? AnyRest : (
K extends keyof T ? T[K] : never
);
type Key<K, T> = T extends DefaultEventMap ? string | symbol : K | keyof T;
type Key2<K, T> = T extends DefaultEventMap ? string | symbol : K & keyof T;
type Listener<K, T, F> = T extends DefaultEventMap ? F : (
K extends keyof T ? (
T[K] extends unknown[] ? (...args: T[K]) => void : never
)
: never
);
type Listener1<K, T> = Listener<K, T, (...args: any[]) => void>;
type Listener2<K, T> = Listener<K, T, Function>;
/**
* The `EventEmitter` class is defined and exposed by the `node:events` module:
*
* ```js
* import { EventEmitter } from 'node:events';
* ```
*
* All `EventEmitter`s emit the event `'newListener'` when new listeners are
* added and `'removeListener'` when existing listeners are removed.
*
* It supports the following option:
* @since v0.1.26
*/
class EventEmitter<T extends EventMap<T> = DefaultEventMap> {
constructor(options?: EventEmitterOptions);
[EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
/**
* Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
* event or that is rejected if the `EventEmitter` emits `'error'` while waiting.
* The `Promise` will resolve with an array of all the arguments emitted to the
* given event.
*
* This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event
* semantics and does not listen to the `'error'` event.
*
* ```js
* import { once, EventEmitter } from 'node:events';
* import process from 'node:process';
*
* const ee = new EventEmitter();
*
* process.nextTick(() => {
* ee.emit('myevent', 42);
* });
*
* const [value] = await once(ee, 'myevent');
* console.log(value);
*
* const err = new Error('kaboom');
* process.nextTick(() => {
* ee.emit('error', err);
* });
*
* try {
* await once(ee, 'myevent');
* } catch (err) {
* console.error('error happened', err);
* }
* ```
*
* The special handling of the `'error'` event is only used when `events.once()`is used to wait for another event. If `events.once()` is used to wait for the
* '`error'` event itself, then it is treated as any other kind of event without
* special handling:
*
* ```js
* import { EventEmitter, once } from 'node:events';
*
* const ee = new EventEmitter();
*
* once(ee, 'error')
* .then(([err]) => console.log('ok', err.message))
* .catch((err) => console.error('error', err.message));
*
* ee.emit('error', new Error('boom'));
*
* // Prints: ok boom
* ```
*
* An `AbortSignal` can be used to cancel waiting for the event:
*
* ```js
* import { EventEmitter, once } from 'node:events';
*
* const ee = new EventEmitter();
* const ac = new AbortController();
*
* async function foo(emitter, event, signal) {
* try {
* await once(emitter, event, { signal });
* console.log('event emitted!');
* } catch (error) {
* if (error.name === 'AbortError') {
* console.error('Waiting for the event was canceled!');
* } else {
* console.error('There was an error', error.message);
* }
* }
* }
*
* foo(ee, 'foo', ac.signal);
* ac.abort(); // Abort waiting for the event
* ee.emit('foo'); // Prints: Waiting for the event was canceled!
* ```
* @since v11.13.0, v10.16.0
*/
static once(
emitter: _NodeEventTarget,
eventName: string | symbol,
options?: StaticEventEmitterOptions,
): Promise<any[]>;
static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
/**
* ```js
* import { on, EventEmitter } from 'node:events';
* import process from 'node:process';
*
* const ee = new EventEmitter();
*
* // Emit later on
* process.nextTick(() => {
* ee.emit('foo', 'bar');
* ee.emit('foo', 42);
* });
*
* for await (const event of on(ee, 'foo')) {
* // The execution of this inner block is synchronous and it
* // processes one event at a time (even with await). Do not use
* // if concurrent execution is required.
* console.log(event); // prints ['bar'] [42]
* }
* // Unreachable here
* ```
*
* Returns an `AsyncIterator` that iterates `eventName` events. It will throw
* if the `EventEmitter` emits `'error'`. It removes all listeners when
* exiting the loop. The `value` returned by each iteration is an array
* composed of the emitted event arguments.
*
* An `AbortSignal` can be used to cancel waiting on events:
*
* ```js
* import { on, EventEmitter } from 'node:events';
* import process from 'node:process';
*
* const ac = new AbortController();
*
* (async () => {
* const ee = new EventEmitter();
*
* // Emit later on
* process.nextTick(() => {
* ee.emit('foo', 'bar');
* ee.emit('foo', 42);
* });
*
* for await (const event of on(ee, 'foo', { signal: ac.signal })) {
* // The execution of this inner block is synchronous and it
* // processes one event at a time (even with await). Do not use
* // if concurrent execution is required.
* console.log(event); // prints ['bar'] [42]
* }
* // Unreachable here
* })();
*
* process.nextTick(() => ac.abort());
* ```
* @since v13.6.0, v12.16.0
* @param eventName The name of the event being listened for
* @return that iterates `eventName` events emitted by the `emitter`
*/
static on(
emitter: NodeJS.EventEmitter,
eventName: string,
options?: StaticEventEmitterOptions,
): AsyncIterableIterator<any>;
/**
* A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`.
*
* ```js
* import { EventEmitter, listenerCount } from 'node:events';
*
* const myEmitter = new EventEmitter();
* myEmitter.on('event', () => {});
* myEmitter.on('event', () => {});
* console.log(listenerCount(myEmitter, 'event'));
* // Prints: 2
* ```
* @since v0.9.12
* @deprecated Since v3.2.0 - Use `listenerCount` instead.
* @param emitter The emitter to query
* @param eventName The event name
*/
static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
/**
* Returns a copy of the array of listeners for the event named `eventName`.
*
* For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
* the emitter.
*
* For `EventTarget`s this is the only way to get the event listeners for the
* event target. This is useful for debugging and diagnostic purposes.
*
* ```js
* import { getEventListeners, EventEmitter } from 'node:events';
*
* {
* const ee = new EventEmitter();
* const listener = () => console.log('Events are fun');
* ee.on('foo', listener);
* console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
* }
* {
* const et = new EventTarget();
* const listener = () => console.log('Events are fun');
* et.addEventListener('foo', listener);
* console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
* }
* ```
* @since v15.2.0, v14.17.0
*/
static getEventListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
/**
* Returns the currently set max amount of listeners.
*
* For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on
* the emitter.
*
* For `EventTarget`s this is the only way to get the max event listeners for the
* event target. If the number of event handlers on a single EventTarget exceeds
* the max set, the EventTarget will print a warning.
*
* ```js
* import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
*
* {
* const ee = new EventEmitter();
* console.log(getMaxListeners(ee)); // 10
* setMaxListeners(11, ee);
* console.log(getMaxListeners(ee)); // 11
* }
* {
* const et = new EventTarget();
* console.log(getMaxListeners(et)); // 10
* setMaxListeners(11, et);
* console.log(getMaxListeners(et)); // 11
* }
* ```
* @since v19.9.0
*/
static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number;
/**
* ```js
* import { setMaxListeners, EventEmitter } from 'node:events';
*
* const target = new EventTarget();
* const emitter = new EventEmitter();
*
* setMaxListeners(5, target, emitter);
* ```
* @since v15.4.0
* @param n A non-negative number. The maximum number of listeners per `EventTarget` event.
* @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
* objects.
*/
static setMaxListeners(n?: number, ...eventTargets: Array<_DOMEventTarget | NodeJS.EventEmitter>): void;
/**
* Listens once to the `abort` event on the provided `signal`.
*
* Listening to the `abort` event on abort signals is unsafe and may
* lead to resource leaks since another third party with the signal can
* call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change
* this since it would violate the web standard. Additionally, the original
* API makes it easy to forget to remove listeners.
*
* This API allows safely using `AbortSignal`s in Node.js APIs by solving these
* two issues by listening to the event such that `stopImmediatePropagation` does
* not prevent the listener from running.
*
* Returns a disposable so that it may be unsubscribed from more easily.
*
* ```js
* import { addAbortListener } from 'node:events';
*
* function example(signal) {
* let disposable;
* try {
* signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
* disposable = addAbortListener(signal, (e) => {
* // Do something when signal is aborted.
* });
* } finally {
* disposable?.[Symbol.dispose]();
* }
* }
* ```
* @since v20.5.0
* @experimental
* @return Disposable that removes the `abort` listener.
*/
static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable;
/**
* This symbol shall be used to install a listener for only monitoring `'error'`events. Listeners installed using this symbol are called before the regular`'error'` listeners are called.
*
* Installing a listener using this symbol does not change the behavior once an`'error'` event is emitted. Therefore, the process will still crash if no
* regular `'error'` listener is installed.
* @since v13.6.0, v12.17.0
*/
static readonly errorMonitor: unique symbol;
/**
* Value: `Symbol.for('nodejs.rejection')`
*
* See how to write a custom `rejection handler`.
* @since v13.4.0, v12.16.0
*/
static readonly captureRejectionSymbol: unique symbol;
/**
* Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
*
* Change the default `captureRejections` option on all new `EventEmitter` objects.
* @since v13.4.0, v12.16.0
*/
static captureRejections: boolean;
/**
* By default, a maximum of `10` listeners can be registered for any single
* event. This limit can be changed for individual `EventEmitter` instances
* using the `emitter.setMaxListeners(n)` method. To change the default
* for _all_`EventEmitter` instances, the `events.defaultMaxListeners`property can be used. If this value is not a positive number, a `RangeError`is thrown.
*
* Take caution when setting the `events.defaultMaxListeners` because the
* change affects _all_`EventEmitter` instances, including those created before
* the change is made. However, calling `emitter.setMaxListeners(n)` still has
* precedence over `events.defaultMaxListeners`.
*
* This is not a hard limit. The `EventEmitter` instance will allow
* more listeners to be added but will output a trace warning to stderr indicating
* that a "possible EventEmitter memory leak" has been detected. For any single`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`methods can be used to
* temporarily avoid this warning:
*
* ```js
* import { EventEmitter } from 'node:events';
* const emitter = new EventEmitter();
* emitter.setMaxListeners(emitter.getMaxListeners() + 1);
* emitter.once('event', () => {
* // do stuff
* emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
* });
* ```
*
* The `--trace-warnings` command-line flag can be used to display the
* stack trace for such warnings.
*
* The emitted warning can be inspected with `process.on('warning')` and will
* have the additional `emitter`, `type`, and `count` properties, referring to
* the event emitter instance, the event's name and the number of attached
* listeners, respectively.
* Its `name` property is set to `'MaxListenersExceededWarning'`.
* @since v0.11.2
*/
static defaultMaxListeners: number;
}
import internal = require("node:events");
namespace EventEmitter {
// Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
export { internal as EventEmitter };
export interface Abortable {
/**
* When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
*/
signal?: AbortSignal | undefined;
}
export interface EventEmitterReferencingAsyncResource extends AsyncResource {
readonly eventEmitter: EventEmitterAsyncResource;
}
export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions {
/**
* The type of async event, this is required when instantiating `EventEmitterAsyncResource`
* directly rather than as a child class.
* @default new.target.name if instantiated as a child class.
*/
name?: string;
}
/**
* Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that
* require manual async tracking. Specifically, all events emitted by instances
* of `events.EventEmitterAsyncResource` will run within its `async context`.
*
* ```js
* import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
* import { notStrictEqual, strictEqual } from 'node:assert';
* import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
*
* // Async tracking tooling will identify this as 'Q'.
* const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
*
* // 'foo' listeners will run in the EventEmitters async context.
* ee1.on('foo', () => {
* strictEqual(executionAsyncId(), ee1.asyncId);
* strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
* });
*
* const ee2 = new EventEmitter();
*
* // 'foo' listeners on ordinary EventEmitters that do not track async
* // context, however, run in the same async context as the emit().
* ee2.on('foo', () => {
* notStrictEqual(executionAsyncId(), ee2.asyncId);
* notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
* });
*
* Promise.resolve().then(() => {
* ee1.emit('foo');
* ee2.emit('foo');
* });
* ```
*
* The `EventEmitterAsyncResource` class has the same methods and takes the
* same options as `EventEmitter` and `AsyncResource` themselves.
* @since v17.4.0, v16.14.0
*/
export class EventEmitterAsyncResource extends EventEmitter {
/**
* @param options Only optional in child class.
*/
constructor(options?: EventEmitterAsyncResourceOptions);
/**
* 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.
*/
emitDestroy(): void;
/**
* The unique `asyncId` assigned to the resource.
*/
readonly asyncId: number;
/**
* The same triggerAsyncId that is passed to the AsyncResource constructor.
*/
readonly triggerAsyncId: number;
/**
* The returned `AsyncResource` object has an additional `eventEmitter` property
* that provides a reference to this `EventEmitterAsyncResource`.
*/
readonly asyncResource: EventEmitterReferencingAsyncResource;
}
}
global {
namespace NodeJS {
interface EventEmitter<T extends EventMap<T> = DefaultEventMap> {
[EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
/**
* Alias for `emitter.on(eventName, listener)`.
* @since v0.1.26
*/
addListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
/**
* Adds the `listener` function to the end of the listeners array for the
* event named `eventName`. No checks are made to see if the `listener` has
* already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
* times.
*
* ```js
* server.on('connection', (stream) => {
* console.log('someone connected!');
* });
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
*
* By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the
* event listener to the beginning of the listeners array.
*
* ```js
* import { EventEmitter } from 'node:events';
* const myEE = new EventEmitter();
* myEE.on('foo', () => console.log('a'));
* myEE.prependListener('foo', () => console.log('b'));
* myEE.emit('foo');
* // Prints:
* // b
* // a
* ```
* @since v0.1.101
* @param eventName The name of the event.
* @param listener The callback function
*/
on<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
/**
* Adds a **one-time**`listener` function for the event named `eventName`. The
* next time `eventName` is triggered, this listener is removed and then invoked.
*
* ```js
* server.once('connection', (stream) => {
* console.log('Ah, we have our first user!');
* });
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
*
* By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the
* event listener to the beginning of the listeners array.
*
* ```js
* import { EventEmitter } from 'node:events';
* const myEE = new EventEmitter();
* myEE.once('foo', () => console.log('a'));
* myEE.prependOnceListener('foo', () => console.log('b'));
* myEE.emit('foo');
* // Prints:
* // b
* // a
* ```
* @since v0.3.0
* @param eventName The name of the event.
* @param listener The callback function
*/
once<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
/**
* Removes the specified `listener` from the listener array for the event named`eventName`.
*
* ```js
* const callback = (stream) => {
* console.log('someone connected!');
* };
* server.on('connection', callback);
* // ...
* server.removeListener('connection', callback);
* ```
*
* `removeListener()` will remove, at most, one instance of a listener from the
* listener array. If any single listener has been added multiple times to the
* listener array for the specified `eventName`, then `removeListener()` must be
* called multiple times to remove each instance.
*
* Once an event is emitted, all listeners attached to it at the
* time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution
* will not remove them from`emit()` in progress. Subsequent events behave as expected.
*
* ```js
* import { EventEmitter } from 'node:events';
* class MyEmitter extends EventEmitter {}
* const myEmitter = new MyEmitter();
*
* const callbackA = () => {
* console.log('A');
* myEmitter.removeListener('event', callbackB);
* };
*
* const callbackB = () => {
* console.log('B');
* };
*
* myEmitter.on('event', callbackA);
*
* myEmitter.on('event', callbackB);
*
* // callbackA removes listener callbackB but it will still be called.
* // Internal listener array at time of emit [callbackA, callbackB]
* myEmitter.emit('event');
* // Prints:
* // A
* // B
*
* // callbackB is now removed.
* // Internal listener array [callbackA]
* myEmitter.emit('event');
* // Prints:
* // A
* ```
*
* Because listeners are managed using an internal array, calling this will
* change the position indices of any listener registered _after_ the listener
* being removed. This will not impact the order in which listeners are called,
* but it means that any copies of the listener array as returned by
* the `emitter.listeners()` method will need to be recreated.
*
* When a single function has been added as a handler multiple times for a single
* event (as in the example below), `removeListener()` will remove the most
* recently added instance. In the example the `once('ping')`listener is removed:
*
* ```js
* import { EventEmitter } from 'node:events';
* const ee = new EventEmitter();
*
* function pong() {
* console.log('pong');
* }
*
* ee.on('ping', pong);
* ee.once('ping', pong);
* ee.removeListener('ping', pong);
*
* ee.emit('ping');
* ee.emit('ping');
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v0.1.26
*/
removeListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
/**
* Alias for `emitter.removeListener()`.
* @since v10.0.0
*/
off<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
/**
* Removes all listeners, or those of the specified `eventName`.
*
* It is bad practice to remove listeners added elsewhere in the code,
* particularly when the `EventEmitter` instance was created by some other
* component or module (e.g. sockets or file streams).
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v0.1.26
*/
removeAllListeners(event?: Key<unknown, T>): this;
/**
* By default `EventEmitter`s will print a warning if more than `10` listeners are
* added for a particular event. This is a useful default that helps finding
* memory leaks. The `emitter.setMaxListeners()` method allows the limit to be
* modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners.
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v0.3.5
*/
setMaxListeners(n: number): this;
/**
* Returns the current max listener value for the `EventEmitter` which is either
* set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}.
* @since v1.0.0
*/
getMaxListeners(): number;
/**
* Returns a copy of the array of listeners for the event named `eventName`.
*
* ```js
* server.on('connection', (stream) => {
* console.log('someone connected!');
* });
* console.log(util.inspect(server.listeners('connection')));
* // Prints: [ [Function] ]
* ```
* @since v0.1.26
*/
listeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
/**
* Returns a copy of the array of listeners for the event named `eventName`,
* including any wrappers (such as those created by `.once()`).
*
* ```js
* import { EventEmitter } from 'node:events';
* const emitter = new EventEmitter();
* emitter.once('log', () => console.log('log once'));
*
* // Returns a new Array with a function `onceWrapper` which has a property
* // `listener` which contains the original listener bound above
* const listeners = emitter.rawListeners('log');
* const logFnWrapper = listeners[0];
*
* // Logs "log once" to the console and does not unbind the `once` event
* logFnWrapper.listener();
*
* // Logs "log once" to the console and removes the listener
* logFnWrapper();
*
* emitter.on('log', () => console.log('log persistently'));
* // Will return a new Array with a single function bound by `.on()` above
* const newListeners = emitter.rawListeners('log');
*
* // Logs "log persistently" twice
* newListeners[0]();
* emitter.emit('log');
* ```
* @since v9.4.0
*/
rawListeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
/**
* Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments
* to each.
*
* Returns `true` if the event had listeners, `false` otherwise.
*
* ```js
* import { EventEmitter } from 'node:events';
* const myEmitter = new EventEmitter();
*
* // First listener
* myEmitter.on('event', function firstListener() {
* console.log('Helloooo! first listener');
* });
* // Second listener
* myEmitter.on('event', function secondListener(arg1, arg2) {
* console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
* });
* // Third listener
* myEmitter.on('event', function thirdListener(...args) {
* const parameters = args.join(', ');
* console.log(`event with parameters ${parameters} in third listener`);
* });
*
* console.log(myEmitter.listeners('event'));
*
* myEmitter.emit('event', 1, 2, 3, 4, 5);
*
* // Prints:
* // [
* // [Function: firstListener],
* // [Function: secondListener],
* // [Function: thirdListener]
* // ]
* // Helloooo! first listener
* // event with parameters 1, 2 in second listener
* // event with parameters 1, 2, 3, 4, 5 in third listener
* ```
* @since v0.1.26
*/
emit<K>(eventName: Key<K, T>, ...args: Args<K, T>): boolean;
/**
* Returns the number of listeners listening for the event named `eventName`.
* If `listener` is provided, it will return how many times the listener is found
* in the list of the listeners of the event.
* @since v3.2.0
* @param eventName The name of the event being listened for
* @param listener The event handler function
*/
listenerCount<K>(eventName: Key<K, T>, listener?: Listener2<K, T>): number;
/**
* Adds the `listener` function to the _beginning_ of the listeners array for the
* event named `eventName`. No checks are made to see if the `listener` has
* already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple
* times.
*
* ```js
* server.prependListener('connection', (stream) => {
* console.log('someone connected!');
* });
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v6.0.0
* @param eventName The name of the event.
* @param listener The callback function
*/
prependListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
/**
* Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this
* listener is removed, and then invoked.
*
* ```js
* server.prependOnceListener('connection', (stream) => {
* console.log('Ah, we have our first user!');
* });
* ```
*
* Returns a reference to the `EventEmitter`, so that calls can be chained.
* @since v6.0.0
* @param eventName The name of the event.
* @param listener The callback function
*/
prependOnceListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
/**
* Returns an array listing the events for which the emitter has registered
* listeners. The values in the array are strings or `Symbol`s.
*
* ```js
* import { EventEmitter } from 'node:events';
*
* const myEE = new EventEmitter();
* myEE.on('foo', () => {});
* myEE.on('bar', () => {});
*
* const sym = Symbol('symbol');
* myEE.on(sym, () => {});
*
* console.log(myEE.eventNames());
* // Prints: [ 'foo', 'bar', Symbol(symbol) ]
* ```
* @since v6.0.0
*/
eventNames(): Array<(string | symbol) & Key2<unknown, T>>;
}
}
}
export = EventEmitter;
}
declare module "node:events" {
import events = require("events");
export = events;
}

4311
node_modules/@types/node/fs.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

1239
node_modules/@types/node/fs/promises.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

411
node_modules/@types/node/globals.d.ts generated vendored Normal file
View File

@ -0,0 +1,411 @@
export {}; // Make this a module
// #region Fetch and friends
// Conditional type aliases, used at the end of this file.
// Will either be empty if lib-dom is included, or the undici version otherwise.
type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request;
type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response;
type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData;
type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers;
type _RequestInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").RequestInit;
type _ResponseInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").ResponseInit;
type _File = typeof globalThis extends { onmessage: any } ? {} : import("node:buffer").File;
// #endregion Fetch and friends
declare global {
// Declare "static" methods in Error
interface ErrorConstructor {
/** Create .stack property on a target object */
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* Optional override for formatting stack traces
*
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
stackTraceLimit: number;
}
/*-----------------------------------------------*
* *
* GLOBAL *
* *
------------------------------------------------*/
// For backwards compability
interface NodeRequire extends NodeJS.Require {}
interface RequireResolve extends NodeJS.RequireResolve {}
interface NodeModule extends NodeJS.Module {}
var process: NodeJS.Process;
var console: Console;
var __filename: string;
var __dirname: string;
var require: NodeRequire;
var module: NodeModule;
// Same as module.exports
var exports: any;
/**
* Only available if `--expose-gc` is passed to the process.
*/
var gc: undefined | (() => void);
// #region borrowed
// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib
/** A controller object that allows you to abort one or more DOM requests as and when desired. */
interface AbortController {
/**
* Returns the AbortSignal object associated with this object.
*/
readonly signal: AbortSignal;
/**
* Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.
*/
abort(reason?: any): void;
}
/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
interface AbortSignal extends EventTarget {
/**
* Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
*/
readonly aborted: boolean;
readonly reason: any;
onabort: null | ((this: AbortSignal, event: Event) => any);
throwIfAborted(): void;
}
var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T
: {
prototype: AbortController;
new(): AbortController;
};
var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
: {
prototype: AbortSignal;
new(): AbortSignal;
abort(reason?: any): AbortSignal;
timeout(milliseconds: number): AbortSignal;
};
// #endregion borrowed
// #region Disposable
interface SymbolConstructor {
/**
* A method that is used to release resources held by an object. Called by the semantics of the `using` statement.
*/
readonly dispose: unique symbol;
/**
* A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement.
*/
readonly asyncDispose: unique symbol;
}
interface Disposable {
[Symbol.dispose](): void;
}
interface AsyncDisposable {
[Symbol.asyncDispose](): PromiseLike<void>;
}
// #endregion Disposable
// #region ArrayLike.at()
interface RelativeIndexable<T> {
/**
* Takes an integer value and returns the item at that index,
* allowing for positive and negative integers.
* Negative integers count back from the last item in the array.
*/
at(index: number): T | undefined;
}
interface String extends RelativeIndexable<string> {}
interface Array<T> extends RelativeIndexable<T> {}
interface ReadonlyArray<T> extends RelativeIndexable<T> {}
interface Int8Array extends RelativeIndexable<number> {}
interface Uint8Array extends RelativeIndexable<number> {}
interface Uint8ClampedArray extends RelativeIndexable<number> {}
interface Int16Array extends RelativeIndexable<number> {}
interface Uint16Array extends RelativeIndexable<number> {}
interface Int32Array extends RelativeIndexable<number> {}
interface Uint32Array extends RelativeIndexable<number> {}
interface Float32Array extends RelativeIndexable<number> {}
interface Float64Array extends RelativeIndexable<number> {}
interface BigInt64Array extends RelativeIndexable<bigint> {}
interface BigUint64Array extends RelativeIndexable<bigint> {}
// #endregion ArrayLike.at() end
/**
* @since v17.0.0
*
* Creates a deep clone of an object.
*/
function structuredClone<T>(
value: T,
transfer?: { transfer: ReadonlyArray<import("worker_threads").TransferListItem> },
): T;
/*----------------------------------------------*
* *
* GLOBAL INTERFACES *
* *
*-----------------------------------------------*/
namespace NodeJS {
interface CallSite {
/**
* Value of "this"
*/
getThis(): unknown;
/**
* Type of "this" as a string.
* This is the name of the function stored in the constructor field of
* "this", if available. Otherwise the object's [[Class]] internal
* property.
*/
getTypeName(): string | null;
/**
* Current function
*/
getFunction(): Function | undefined;
/**
* Name of the current function, typically its name property.
* If a name property is not available an attempt will be made to try
* to infer a name from the function's context.
*/
getFunctionName(): string | null;
/**
* Name of the property [of "this" or one of its prototypes] that holds
* the current function
*/
getMethodName(): string | null;
/**
* Name of the script [if this function was defined in a script]
*/
getFileName(): string | undefined;
/**
* Current line number [if this function was defined in a script]
*/
getLineNumber(): number | null;
/**
* Current column number [if this function was defined in a script]
*/
getColumnNumber(): number | null;
/**
* A call site object representing the location where eval was called
* [if this function was created using a call to eval]
*/
getEvalOrigin(): string | undefined;
/**
* Is this a toplevel invocation, that is, is "this" the global object?
*/
isToplevel(): boolean;
/**
* Does this call take place in code defined by a call to eval?
*/
isEval(): boolean;
/**
* Is this call in native V8 code?
*/
isNative(): boolean;
/**
* Is this a constructor call?
*/
isConstructor(): boolean;
/**
* is this an async call (i.e. await, Promise.all(), or Promise.any())?
*/
isAsync(): boolean;
/**
* is this an async call to Promise.all()?
*/
isPromiseAll(): boolean;
/**
* returns the index of the promise element that was followed in
* Promise.all() or Promise.any() for async stack traces, or null
* if the CallSite is not an async
*/
getPromiseIndex(): number | null;
getScriptNameOrSourceURL(): string;
getScriptHash(): string;
getEnclosingColumnNumber(): number;
getEnclosingLineNumber(): number;
getPosition(): number;
toString(): string;
}
interface ErrnoException extends Error {
errno?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
}
interface ReadableStream extends EventEmitter {
readable: boolean;
read(size?: number): string | Buffer;
setEncoding(encoding: BufferEncoding): this;
pause(): this;
resume(): this;
isPaused(): boolean;
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined }): T;
unpipe(destination?: WritableStream): this;
unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void;
wrap(oldStream: ReadableStream): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>;
}
interface WritableStream extends EventEmitter {
writable: boolean;
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
end(cb?: () => void): this;
end(data: string | Uint8Array, cb?: () => void): this;
end(str: string, encoding?: BufferEncoding, cb?: () => void): this;
}
interface ReadWriteStream extends ReadableStream, WritableStream {}
interface RefCounted {
ref(): this;
unref(): this;
}
type TypedArray =
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| BigUint64Array
| BigInt64Array
| Float32Array
| Float64Array;
type ArrayBufferView = TypedArray | DataView;
interface Require {
(id: string): any;
resolve: RequireResolve;
cache: Dict<NodeModule>;
/**
* @deprecated
*/
extensions: RequireExtensions;
main: Module | undefined;
}
interface RequireResolve {
(id: string, options?: { paths?: string[] | undefined }): string;
paths(request: string): string[] | null;
}
interface RequireExtensions extends Dict<(m: Module, filename: string) => any> {
".js": (m: Module, filename: string) => any;
".json": (m: Module, filename: string) => any;
".node": (m: Module, filename: string) => any;
}
interface Module {
/**
* `true` if the module is running during the Node.js preload
*/
isPreloading: boolean;
exports: any;
require: Require;
id: string;
filename: string;
loaded: boolean;
/** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */
parent: Module | null | undefined;
children: Module[];
/**
* @since v11.14.0
*
* The directory name of the module. This is usually the same as the path.dirname() of the module.id.
*/
path: string;
paths: string[];
}
interface Dict<T> {
[key: string]: T | undefined;
}
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
}
interface RequestInit extends _RequestInit {}
function fetch(
input: string | URL | globalThis.Request,
init?: RequestInit,
): Promise<Response>;
interface Request extends _Request {}
var Request: typeof globalThis extends {
onmessage: any;
Request: infer T;
} ? T
: typeof import("undici-types").Request;
interface ResponseInit extends _ResponseInit {}
interface Response extends _Response {}
var Response: typeof globalThis extends {
onmessage: any;
Response: infer T;
} ? T
: typeof import("undici-types").Response;
interface FormData extends _FormData {}
var FormData: typeof globalThis extends {
onmessage: any;
FormData: infer T;
} ? T
: typeof import("undici-types").FormData;
interface Headers extends _Headers {}
var Headers: typeof globalThis extends {
onmessage: any;
Headers: infer T;
} ? T
: typeof import("undici-types").Headers;
interface File extends _File {}
var File: typeof globalThis extends {
onmessage: any;
File: infer T;
} ? T
: typeof import("node:buffer").File;
}

1
node_modules/@types/node/globals.global.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
declare var global: typeof globalThis;

1889
node_modules/@types/node/http.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

2382
node_modules/@types/node/http2.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

550
node_modules/@types/node/https.d.ts generated vendored Normal file
View File

@ -0,0 +1,550 @@
/**
* HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
* separate module.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/https.js)
*/
declare module "https" {
import { Duplex } from "node:stream";
import * as tls from "node:tls";
import * as http from "node:http";
import { URL } from "node:url";
type ServerOptions<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
> = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions<Request, Response>;
type RequestOptions =
& http.RequestOptions
& tls.SecureContextOptions
& {
checkServerIdentity?: typeof tls.checkServerIdentity | undefined;
rejectUnauthorized?: boolean | undefined; // Defaults to true
servername?: string | undefined; // SNI TLS Extension
};
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
rejectUnauthorized?: boolean | undefined;
maxCachedSessions?: number | undefined;
}
/**
* An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information.
* @since v0.4.5
*/
class Agent extends http.Agent {
constructor(options?: AgentOptions);
options: AgentOptions;
}
interface Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
> extends http.Server<Request, Response> {}
/**
* See `http.Server` for more information.
* @since v0.3.4
*/
class Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
> extends tls.Server {
constructor(requestListener?: http.RequestListener<Request, Response>);
constructor(
options: ServerOptions<Request, Response>,
requestListener?: http.RequestListener<Request, Response>,
);
/**
* Closes all connections connected to this server.
* @since v18.2.0
*/
closeAllConnections(): void;
/**
* Closes all connections connected to this server which are not sending a request or waiting for a response.
* @since v18.2.0
*/
closeIdleConnections(): void;
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
addListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
addListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
addListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "connection", listener: (socket: Duplex) => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "listening", listener: () => void): this;
addListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
addListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
addListener(
event: "connect",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
addListener(event: "request", listener: http.RequestListener<Request, Response>): this;
addListener(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
emit(event: string, ...args: any[]): boolean;
emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean;
emit(
event: "newSession",
sessionId: Buffer,
sessionData: Buffer,
callback: (err: Error, resp: Buffer) => void,
): boolean;
emit(
event: "OCSPRequest",
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
): boolean;
emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean;
emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean;
emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean;
emit(event: "close"): boolean;
emit(event: "connection", socket: Duplex): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "listening"): boolean;
emit(
event: "checkContinue",
req: InstanceType<Request>,
res: InstanceType<Response> & {
req: InstanceType<Request>;
},
): boolean;
emit(
event: "checkExpectation",
req: InstanceType<Request>,
res: InstanceType<Response> & {
req: InstanceType<Request>;
},
): boolean;
emit(event: "clientError", err: Error, socket: Duplex): boolean;
emit(event: "connect", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean;
emit(
event: "request",
req: InstanceType<Request>,
res: InstanceType<Response> & {
req: InstanceType<Request>;
},
): boolean;
emit(event: "upgrade", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
on(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
on(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
on(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
on(event: "close", listener: () => void): this;
on(event: "connection", listener: (socket: Duplex) => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this;
on(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
on(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
on(event: "connect", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
on(event: "request", listener: http.RequestListener<Request, Response>): this;
on(event: "upgrade", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
once(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
once(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
once(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
once(event: "close", listener: () => void): this;
once(event: "connection", listener: (socket: Duplex) => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "listening", listener: () => void): this;
once(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
once(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
once(event: "connect", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
once(event: "request", listener: http.RequestListener<Request, Response>): this;
once(event: "upgrade", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
prependListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
prependListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
prependListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "connection", listener: (socket: Duplex) => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "listening", listener: () => void): this;
prependListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
prependListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
prependListener(
event: "connect",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
prependListener(event: "request", listener: http.RequestListener<Request, Response>): this;
prependListener(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
prependOnceListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
): this;
prependOnceListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
prependOnceListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
): this;
prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "listening", listener: () => void): this;
prependOnceListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
prependOnceListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
prependOnceListener(
event: "connect",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
prependOnceListener(event: "request", listener: http.RequestListener<Request, Response>): this;
prependOnceListener(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
): this;
}
/**
* ```js
* // curl -k https://localhost:8000/
* const https = require('node:https');
* const fs = require('node:fs');
*
* const options = {
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
* };
*
* https.createServer(options, (req, res) => {
* res.writeHead(200);
* res.end('hello world\n');
* }).listen(8000);
* ```
*
* Or
*
* ```js
* const https = require('node:https');
* const fs = require('node:fs');
*
* const options = {
* pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
* passphrase: 'sample',
* };
*
* https.createServer(options, (req, res) => {
* res.writeHead(200);
* res.end('hello world\n');
* }).listen(8000);
* ```
* @since v0.3.4
* @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`.
* @param requestListener A listener to be added to the `'request'` event.
*/
function createServer<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
>(requestListener?: http.RequestListener<Request, Response>): Server<Request, Response>;
function createServer<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse = typeof http.ServerResponse,
>(
options: ServerOptions<Request, Response>,
requestListener?: http.RequestListener<Request, Response>,
): Server<Request, Response>;
/**
* Makes a request to a secure web server.
*
* The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`,
* `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`.
*
* `options` can be an object, a string, or a `URL` object. If `options` is a
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
*
* `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to
* upload a file with a POST request, then write to the `ClientRequest` object.
*
* ```js
* const https = require('node:https');
*
* const options = {
* hostname: 'encrypted.google.com',
* port: 443,
* path: '/',
* method: 'GET',
* };
*
* const req = https.request(options, (res) => {
* console.log('statusCode:', res.statusCode);
* console.log('headers:', res.headers);
*
* res.on('data', (d) => {
* process.stdout.write(d);
* });
* });
*
* req.on('error', (e) => {
* console.error(e);
* });
* req.end();
* ```
*
* Example using options from `tls.connect()`:
*
* ```js
* const options = {
* hostname: 'encrypted.google.com',
* port: 443,
* path: '/',
* method: 'GET',
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
* };
* options.agent = new https.Agent(options);
*
* const req = https.request(options, (res) => {
* // ...
* });
* ```
*
* Alternatively, opt out of connection pooling by not using an `Agent`.
*
* ```js
* const options = {
* hostname: 'encrypted.google.com',
* port: 443,
* path: '/',
* method: 'GET',
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
* agent: false,
* };
*
* const req = https.request(options, (res) => {
* // ...
* });
* ```
*
* Example using a `URL` as `options`:
*
* ```js
* const options = new URL('https://abc:xyz@example.com');
*
* const req = https.request(options, (res) => {
* // ...
* });
* ```
*
* Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`):
*
* ```js
* const tls = require('node:tls');
* const https = require('node:https');
* const crypto = require('node:crypto');
*
* function sha256(s) {
* return crypto.createHash('sha256').update(s).digest('base64');
* }
* const options = {
* hostname: 'github.com',
* port: 443,
* path: '/',
* method: 'GET',
* checkServerIdentity: function(host, cert) {
* // Make sure the certificate is issued to the host we are connected to
* const err = tls.checkServerIdentity(host, cert);
* if (err) {
* return err;
* }
*
* // Pin the public key, similar to HPKP pin-sha256 pinning
* const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
* if (sha256(cert.pubkey) !== pubkey256) {
* const msg = 'Certificate verification error: ' +
* `The public key of '${cert.subject.CN}' ` +
* 'does not match our pinned fingerprint';
* return new Error(msg);
* }
*
* // Pin the exact certificate, rather than the pub key
* const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
* 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
* if (cert.fingerprint256 !== cert256) {
* const msg = 'Certificate verification error: ' +
* `The certificate of '${cert.subject.CN}' ` +
* 'does not match our pinned fingerprint';
* return new Error(msg);
* }
*
* // This loop is informational only.
* // Print the certificate and public key fingerprints of all certs in the
* // chain. Its common to pin the public key of the issuer on the public
* // internet, while pinning the public key of the service in sensitive
* // environments.
* do {
* console.log('Subject Common Name:', cert.subject.CN);
* console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256);
*
* hash = crypto.createHash('sha256');
* console.log(' Public key ping-sha256:', sha256(cert.pubkey));
*
* lastprint256 = cert.fingerprint256;
* cert = cert.issuerCertificate;
* } while (cert.fingerprint256 !== lastprint256);
*
* },
* };
*
* options.agent = new https.Agent(options);
* const req = https.request(options, (res) => {
* console.log('All OK. Server matched our pinned cert or public key');
* console.log('statusCode:', res.statusCode);
* // Print the HPKP values
* console.log('headers:', res.headers['public-key-pins']);
*
* res.on('data', (d) => {});
* });
*
* req.on('error', (e) => {
* console.error(e.message);
* });
* req.end();
* ```
*
* Outputs for example:
*
* ```text
* Subject Common Name: github.com
* Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
* Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
* Subject Common Name: DigiCert SHA2 Extended Validation Server CA
* Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
* Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
* Subject Common Name: DigiCert High Assurance EV Root CA
* Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
* Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
* All OK. Server matched our pinned cert or public key
* statusCode: 200
* headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=";
* pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=";
* pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains
* ```
* @since v0.3.6
* @param options Accepts all `options` from `request`, with some differences in default values:
*/
function request(
options: RequestOptions | string | URL,
callback?: (res: http.IncomingMessage) => void,
): http.ClientRequest;
function request(
url: string | URL,
options: RequestOptions,
callback?: (res: http.IncomingMessage) => void,
): http.ClientRequest;
/**
* Like `http.get()` but for HTTPS.
*
* `options` can be an object, a string, or a `URL` object. If `options` is a
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
*
* ```js
* const https = require('node:https');
*
* https.get('https://encrypted.google.com/', (res) => {
* console.log('statusCode:', res.statusCode);
* console.log('headers:', res.headers);
*
* res.on('data', (d) => {
* process.stdout.write(d);
* });
*
* }).on('error', (e) => {
* console.error(e);
* });
* ```
* @since v0.3.6
* @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`.
*/
function get(
options: RequestOptions | string | URL,
callback?: (res: http.IncomingMessage) => void,
): http.ClientRequest;
function get(
url: string | URL,
options: RequestOptions,
callback?: (res: http.IncomingMessage) => void,
): http.ClientRequest;
let globalAgent: Agent;
}
declare module "node:https" {
export * from "https";
}

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