6 Commits

Author SHA1 Message Date
Ebenezer
6a2ae56ad7 Merge origin/main into done-fixing and resolve conflicts
Made-with: Cursor
2026-03-27 17:20:05 +08:00
Ebenezer
592c503b5a done connecting coze and youwei 2026-03-27 17:05:01 +08:00
0251d5ffdb Merge pull request 'Login works' (#2) from done-with-login into main
Reviewed-on: #2
2026-03-27 15:45:58 +08:00
Ebenezer
e7816f78f3 Login works 2026-03-27 15:44:21 +08:00
d5c75c9f5c Merge pull request 'Done linking coze AI' (#1) from make-button into main
Reviewed-on: #1
2026-03-25 14:28:42 +08:00
Ebenezer
b314ac3ec7 Done linking coze AI 2026-03-25 14:28:09 +08:00
1647 changed files with 233499 additions and 31 deletions

23
backend/.env.example Normal file
View File

@@ -0,0 +1,23 @@
PORT=3000
DB_HOST=nw.sgcode.cn
DB_PORT=21434
DB_USER=root
DB_PASSWORD=root
DB_NAME=opencoze
PORT=3000
DB_HOST=nw.sgcode.cn
DB_PORT=21434
DB_USER=root
DB_PASSWORD=YOUR_DATABASE_PASSWORD
DB_NAME=opencoze
PORT=3001
JWT_SECRET=change-this-in-production
CORS_ORIGIN=*
# MySQL connection (from your screenshot)
DB_HOST=nw.sgcode.cn
DB_PORT=21434
DB_NAME=opencoze
DB_USER=root
DB_PASSWORD=your_real_password_here
DB_TABLE_USER=user

215
backend/auth-api.js Normal file
View File

@@ -0,0 +1,215 @@
import dotenv from 'dotenv';
import express from 'express';
import cors from 'cors';
import mysql from 'mysql2/promise';
import bcrypt from 'bcryptjs';
import argon2 from 'argon2';
dotenv.config();
const app = express();
const port = 3010;
app.use(
cors({
origin(origin, callback) {
if (!origin) {
callback(null, true);
return;
}
callback(null, true);
}
})
);
app.use(express.json());
const pool = mysql.createPool({
host: process.env.DB_HOST || 'nw.sgcode.cn',
port: Number(process.env.DB_PORT || 21434),
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || 'root',
database: process.env.DB_NAME || 'opencoze',
waitForConnections: true,
connectionLimit: 10
});
async function ensureUsersTable() {
await pool.query(`
CREATE TABLE IF NOT EXISTS \`user\` (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(128) NOT NULL DEFAULT '',
unique_name VARCHAR(128) NOT NULL UNIQUE,
email VARCHAR(128) NOT NULL UNIQUE,
password VARCHAR(128) NOT NULL DEFAULT '',
description VARCHAR(512) NOT NULL DEFAULT '',
icon_uri VARCHAR(512) NOT NULL DEFAULT '',
user_verified TINYINT(1) NOT NULL DEFAULT 0,
locale VARCHAR(128) NOT NULL DEFAULT '',
session_key VARCHAR(256) NOT NULL DEFAULT '',
created_at BIGINT UNSIGNED NOT NULL DEFAULT 0,
updated_at BIGINT UNSIGNED NOT NULL DEFAULT 0,
deleted_at BIGINT UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
`);
}
app.get('/api/health', async (_req, res) => {
try {
await pool.query('SELECT 1');
res.json({ ok: true });
} catch (error) {
console.error('Health check failed:', error);
res.status(500).json({ ok: false, message: 'Database connection failed' });
}
});
app.post('/api/register', async (req, res) => {
let connection;
try {
const { email, password, confirmPassword } = req.body ?? {};
if (!email || !password || !confirmPassword) {
res.status(400).json({ message: 'Email, password, and confirm password are required' });
return;
}
if (password !== confirmPassword) {
res.status(400).json({ message: 'Passwords do not match' });
return;
}
const trimmedEmail = String(email).trim().toLowerCase();
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmedEmail)) {
res.status(400).json({ message: 'Please enter a valid email address' });
return;
}
if (String(password).length < 6) {
res.status(400).json({ message: 'Password must be at least 6 characters' });
return;
}
const [existingRows] = await pool.query('SELECT id FROM `user` WHERE email = ? LIMIT 1', [trimmedEmail]);
if (existingRows.length > 0) {
res.status(409).json({ message: 'Email is already registered' });
return;
}
// New users are stored with Argon2id hashes.
const passwordHash = await argon2.hash(String(password), { type: argon2.argon2id });
const uniqueName = trimmedEmail;
const displayName = trimmedEmail.split('@')[0];
const now = Date.now();
const defaultIconUri = 'default_icon/user_default_icon.png';
const personalSpaceName = 'Personal Space';
const personalSpaceDescription = 'This is your personal space';
connection = await pool.getConnection();
await connection.beginTransaction();
await connection.query(
'INSERT INTO `user` (name, unique_name, email, password, description, icon_uri, user_verified, locale, session_key, created_at, updated_at, deleted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[displayName, uniqueName, trimmedEmail, passwordHash, '', defaultIconUri, 0, 'zh-CN', '', now, now, null]
);
const [createdUserRows] = await connection.query('SELECT CAST(id AS CHAR) AS id FROM `user` WHERE email = ? LIMIT 1', [
trimmedEmail
]);
const userId = createdUserRows[0]?.id;
if (!userId) {
throw new Error('Failed to resolve created user ID');
}
await connection.query(
'INSERT INTO `space` (owner_id, name, description, icon_uri, creator_id, created_at, updated_at, deleted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[userId, personalSpaceName, personalSpaceDescription, defaultIconUri, userId, now, now, null]
);
const [createdSpaceRows] = await connection.query(
'SELECT CAST(id AS CHAR) AS id FROM `space` WHERE owner_id = ? ORDER BY created_at DESC, id DESC LIMIT 1',
[userId]
);
const spaceId = createdSpaceRows[0]?.id;
if (!spaceId) {
throw new Error('Failed to resolve created space ID');
}
await connection.query(
'INSERT INTO `space_user` (space_id, user_id, role_type, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
[spaceId, userId, 1, now, now]
);
await connection.commit();
res.status(201).json({ message: 'Registered successfully' });
} catch (error) {
if (connection) {
await connection.rollback();
}
console.error('Register failed:', error);
res.status(500).json({ message: 'Register failed' });
} finally {
if (connection) {
connection.release();
}
}
});
app.post('/api/login', async (req, res) => {
try {
const { email, password } = req.body ?? {};
if (!email || !password) {
res.status(400).json({ message: 'Email and password are required' });
return;
}
const trimmedEmail = String(email).trim().toLowerCase();
const [rows] = await pool.query('SELECT id, email, password FROM `user` WHERE email = ? LIMIT 1', [trimmedEmail]);
const user = rows[0];
if (!user) {
res.status(401).json({ message: 'Invalid email or password' });
return;
}
const rawPassword = String(password);
const storedPassword = String(user.password || '');
let isPasswordValid = false;
if (storedPassword.startsWith('$argon2')) {
isPasswordValid = await argon2.verify(storedPassword, rawPassword);
} else if (storedPassword.startsWith('$2')) {
isPasswordValid = await bcrypt.compare(rawPassword, storedPassword);
}
if (!isPasswordValid) {
res.status(401).json({ message: 'Invalid email or password' });
return;
}
res.json({
message: 'Login successful',
user: {
id: user.id,
email: user.email
}
});
} catch (error) {
console.error('Login failed:', error);
res.status(500).json({ message: 'Login failed' });
}
});
ensureUsersTable()
.then(() => {
app.listen(port, () => {
console.log(`Auth API running at http://localhost:${port}`);
});
})
.catch((error) => {
console.error('Failed to initialize database:', error);
process.exit(1);
});

Binary file not shown.

16
backend/node_modules/.bin/cross-env generated vendored Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../cross-env/dist/bin/cross-env.js" "$@"
else
exec node "$basedir/../cross-env/dist/bin/cross-env.js" "$@"
fi

16
backend/node_modules/.bin/cross-env-shell generated vendored Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../cross-env/dist/bin/cross-env-shell.js" "$@"
else
exec node "$basedir/../cross-env/dist/bin/cross-env-shell.js" "$@"
fi

17
backend/node_modules/.bin/cross-env-shell.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%\..\cross-env\dist\bin\cross-env-shell.js" %*

28
backend/node_modules/.bin/cross-env-shell.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/../cross-env/dist/bin/cross-env-shell.js" $args
} else {
& "$basedir/node$exe" "$basedir/../cross-env/dist/bin/cross-env-shell.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../cross-env/dist/bin/cross-env-shell.js" $args
} else {
& "node$exe" "$basedir/../cross-env/dist/bin/cross-env-shell.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

17
backend/node_modules/.bin/cross-env.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%\..\cross-env\dist\bin\cross-env.js" %*

28
backend/node_modules/.bin/cross-env.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/../cross-env/dist/bin/cross-env.js" $args
} else {
& "$basedir/node$exe" "$basedir/../cross-env/dist/bin/cross-env.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../cross-env/dist/bin/cross-env.js" $args
} else {
& "node$exe" "$basedir/../cross-env/dist/bin/cross-env.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/mime generated vendored Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../mime/cli.js" "$@"
else
exec node "$basedir/../mime/cli.js" "$@"
fi

17
backend/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
backend/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

16
backend/node_modules/.bin/node-gyp-build generated vendored Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-gyp-build/bin.js" "$@"
else
exec node "$basedir/../node-gyp-build/bin.js" "$@"
fi

16
backend/node_modules/.bin/node-gyp-build-optional generated vendored Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-gyp-build/optional.js" "$@"
else
exec node "$basedir/../node-gyp-build/optional.js" "$@"
fi

17
backend/node_modules/.bin/node-gyp-build-optional.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%\..\node-gyp-build\optional.js" %*

28
backend/node_modules/.bin/node-gyp-build-optional.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/../node-gyp-build/optional.js" $args
} else {
& "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../node-gyp-build/optional.js" $args
} else {
& "node$exe" "$basedir/../node-gyp-build/optional.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/node-gyp-build-test generated vendored Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../node-gyp-build/build-test.js" "$@"
else
exec node "$basedir/../node-gyp-build/build-test.js" "$@"
fi

17
backend/node_modules/.bin/node-gyp-build-test.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%\..\node-gyp-build\build-test.js" %*

28
backend/node_modules/.bin/node-gyp-build-test.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/../node-gyp-build/build-test.js" $args
} else {
& "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
} else {
& "node$exe" "$basedir/../node-gyp-build/build-test.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

17
backend/node_modules/.bin/node-gyp-build.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%\..\node-gyp-build\bin.js" %*

28
backend/node_modules/.bin/node-gyp-build.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/../node-gyp-build/bin.js" $args
} else {
& "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../node-gyp-build/bin.js" $args
} else {
& "node$exe" "$basedir/../node-gyp-build/bin.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
backend/node_modules/.bin/node-which generated vendored Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../which/bin/node-which" "$@"
else
exec node "$basedir/../which/bin/node-which" "$@"
fi

17
backend/node_modules/.bin/node-which.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%\..\which\bin\node-which" %*

28
backend/node_modules/.bin/node-which.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/../which/bin/node-which" $args
} else {
& "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../which/bin/node-which" $args
} else {
& "node$exe" "$basedir/../which/bin/node-which" $args
}
$ret=$LASTEXITCODE
}
exit $ret

1133
backend/node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

208
backend/node_modules/@epic-web/invariant/README.md generated vendored Normal file
View File

@@ -0,0 +1,208 @@
<div>
<h1 align="center"><a href="https://npm.im/@epic-web/invariant">💥 @epic-web/invariant</a></h1>
<strong>
Throw errors when thing's aren't right.
</strong>
<p>
Type safe utilities for throwing errors (and responses) in exceptional
situations in a declarative way.
</p>
</div>
```
npm install @epic-web/invariant
```
<div align="center">
<a
alt="Epic Web logo"
href="https://www.epicweb.dev"
>
<img
width="300px"
src="https://github-production-user-asset-6210df.s3.amazonaws.com/1500684/257881576-fd66040b-679f-4f25-b0d0-ab886a14909a.png"
/>
</a>
</div>
<hr />
<!-- prettier-ignore-start -->
[![Build Status][build-badge]][build]
[![MIT License][license-badge]][license]
[![Code of Conduct][coc-badge]][coc]
<!-- prettier-ignore-end -->
## The Problem
Your application has boundaries. Network requests/responses, file system reads,
etc. When you're working with these boundaries, you need to be able to handle
errors that may occur, even in TypeScript.
TypeScript will typically make these boundaries much more obvious because it
doesn't like not knowing what the type of something is. For example:
```ts
const formData = new FormData(formElement)
const name = await formData.get('name')
// name is `File | string | null`
```
Often it's a good idea to use a proper parsing library for situations like this,
but for simple cases that can often feel like overkill. But you don't want to
just ignore TypeScript because:
> TypeScript is that brutally honest friend you put up with because they save
> you from making terrible mistakes.
> [@kentcdodds](https://twitter.com/kentcdodds/status/1715562350835855396)
So you check it:
```ts
const formData = new FormData(formElement)
const name = await formData.get('name')
// name is `File | string | null`
if (typeof name !== 'string') {
throw new Error('Name must be a string')
}
// now name is `string` (and TypeScript knows it too)
```
You're fine throwing a descriptive error here because it's just _very_ unlikely
this will ever happen and even if it does you wouldn't really know what to do
about it anyway.
It's not a big deal, but there's a tiny bit of boilerplate that would be nice to
avoid. Especially when you find yourself doing this all over the codebase. This
is the problem `@epic-web/invariant` solves.
## The Solution
Here's the diff from what we had above:
```diff
const formData = new FormData(formElement)
const name = await formData.get('name')
// name is `File | string | null`
- if (typeof name !== 'string') {
- throw new Error('Name must be a string')
- }
+ invariant(typeof name === 'string', 'Name must be a string')
// now name is `string` (and TypeScript knows it too)
```
It's pretty simple. But honestly, it's nicer to read, it throws a special
`InvariantError` object to distinguish it from other types of errors, and we
have another useful utility for throwing `Response` objects instead of `Error`
objects which is handy
[in Remix](https://remix.run/docs/en/main/route/loader#throwing-responses-in-loaders).
## Usage
### `invariant`
The `invariant` function is used to assert that a condition is true. If the
condition is false, it throws an error with the provided message.
**Basic Usage**
```ts
import { invariant } from '@epic-web/invariant'
const creature = { name: 'Dragon', type: 'Fire' }
invariant(creature.name === 'Dragon', 'Creature must be a Dragon')
```
**Throwing a Response on False Condition**
```ts
import { invariant } from '@epic-web/invariant'
const creature = { name: 'Unicorn', type: 'Magic' }
invariant(creature.type === 'Fire', 'Creature must be of type Fire')
// Throws: InvariantError: Creature must be of type Fire
```
**Using Callback for Error Message**
```ts
import { invariantResponse } from '@epic-web/invariant'
const creature = { name: 'Elf', type: 'Forest' }
invariant(creature.type === 'Water', () => 'Creature must be of type Water')
// Throws: InvariantError: Creature must be of type Water
```
### `invariantResponse`
The `invariantResponse` function works similarly to `invariant`, but instead of
throwing an `InvariantError`, it throws a Response object.
**Basic Usage**
```ts
import { invariantResponse } from '@epic-web/invariant'
const creature = { name: 'Phoenix', type: 'Fire' }
invariantResponse(creature.type === 'Fire', 'Creature must be of type Fire')
```
**Throwing a Response on False Condition**
```ts
import { invariantResponse } from '@epic-web/invariant'
const creature = { name: 'Griffin', type: 'Air' }
invariantResponse(creature.type === 'Water', 'Creature must be of type Water')
// Throws: Response { status: 400, body: 'Creature must be of type Water' }
```
The response status default if 400 (Bad Request), but you'll find how to change
that below.
**Using Callback for Response Message**
```ts
import { invariantResponse } from '@epic-web/invariant'
const creature = { name: 'Mermaid', type: 'Water' }
invariantResponse(
creature.type === 'Land',
() => `Expected a Land creature, but got a ${creature.type} creature`,
)
```
**Throwing a Response with Additional Options**
```ts
import { invariantResponse } from '@epic-web/invariant'
const creature = { name: 'Cerberus', type: 'Underworld' }
invariantResponse(
creature.type === 'Sky',
JSON.stringify({ error: 'Creature must be of type Sky' }),
{ status: 500, headers: { 'Content-Type': 'text/json' } },
)
```
## Differences from [invariant](https://www.npmjs.com/package/invariant)
There are three main differences. With `@epic-web/invariant`:
1. Error messages are the same in dev and prod
2. It's typesafe
3. We support the common case (for Remix anyway) of throwing Responses as well
with `invariantResponse`.
## License
MIT
<!-- prettier-ignore-start -->
[build-badge]: https://img.shields.io/github/actions/workflow/status/epicweb-dev/invariant/release.yml?branch=main&logo=github&style=flat-square
[build]: https://github.com/epicweb-dev/invariant/actions?query=workflow%3Arelease
[license-badge]: https://img.shields.io/badge/license-MIT%20License-blue.svg?style=flat-square
[license]: https://github.com/epicweb-dev/invariant/blob/main/LICENSE
[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
[coc]: https://kentcdodds.com/conduct
<!-- prettier-ignore-end -->

View File

@@ -0,0 +1,36 @@
export declare class InvariantError extends Error {
constructor(message: string);
}
/**
* Provide a condition and if that condition is falsey, this throws an error
* with the given message.
*
* inspired by invariant from 'tiny-invariant' except will still include the
* message in production.
*
* @example
* invariant(typeof value === 'string', `value must be a string`)
*
* @param condition The condition to check
* @param message The message to throw (or a callback to generate the message)
* @param responseInit Additional response init options if a response is thrown
*
* @throws {InvariantError} if condition is falsey
*/
export declare function invariant(condition: any, message: string | (() => string)): asserts condition;
/**
* Provide a condition and if that condition is falsey, this throws a 400
* Response with the given message.
*
* inspired by invariant from 'tiny-invariant'
*
* @example
* invariantResponse(typeof value === 'string', `value must be a string`)
*
* @param condition The condition to check
* @param message The message to throw (or a callback to generate the message)
* @param responseInit Additional response init options if a response is thrown
*
* @throws {Response} if condition is falsey
*/
export declare function invariantResponse(condition: any, message: string | (() => string), responseInit?: ResponseInit): asserts condition;

50
backend/node_modules/@epic-web/invariant/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
export class InvariantError extends Error {
constructor(message) {
super(message);
Object.setPrototypeOf(this, InvariantError.prototype);
}
}
/**
* Provide a condition and if that condition is falsey, this throws an error
* with the given message.
*
* inspired by invariant from 'tiny-invariant' except will still include the
* message in production.
*
* @example
* invariant(typeof value === 'string', `value must be a string`)
*
* @param condition The condition to check
* @param message The message to throw (or a callback to generate the message)
* @param responseInit Additional response init options if a response is thrown
*
* @throws {InvariantError} if condition is falsey
*/
export function invariant(condition, message) {
if (!condition) {
throw new InvariantError(typeof message === 'function' ? message() : message);
}
}
/**
* Provide a condition and if that condition is falsey, this throws a 400
* Response with the given message.
*
* inspired by invariant from 'tiny-invariant'
*
* @example
* invariantResponse(typeof value === 'string', `value must be a string`)
*
* @param condition The condition to check
* @param message The message to throw (or a callback to generate the message)
* @param responseInit Additional response init options if a response is thrown
*
* @throws {Response} if condition is falsey
*/
export function invariantResponse(condition, message, responseInit) {
if (!condition) {
throw new Response(typeof message === 'function' ? message() : message, {
status: 400,
...responseInit,
});
}
}

59
backend/node_modules/@epic-web/invariant/package.json generated vendored Normal file
View File

@@ -0,0 +1,59 @@
{
"name": "@epic-web/invariant",
"version": "1.0.0",
"description": "Type safe utilities for throwing errors (and responses) if things aren't quite right. Inspired by npm.im/invariant",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/epicweb-dev/invariant"
},
"bugs": {
"url": "https://github.com/epicweb-dev/invariant/issues"
},
"homepage": "https://github.com/epicweb-dev/invariant#readme",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsc",
"format": "prettier --write .",
"test": "tsx --test --test-reporter spec --experimental-test-coverage test/*.test.ts",
"test:watch": "tsx --test --test-reporter spec --watch test/*.test.ts"
},
"devDependencies": {
"@types/node": "^20.10.4",
"prettier": "^3.1.1",
"tsx": "^4.6.2",
"typescript": "^5.3.3"
},
"prettier": {
"semi": false,
"useTabs": true,
"singleQuote": true,
"proseWrap": "always",
"overrides": [
{
"files": [
"**/*.json"
],
"options": {
"useTabs": false
}
}
]
},
"keywords": [],
"author": "Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com/)",
"license": "MIT"
}

229
backend/node_modules/@phc/format/index.js generated vendored Normal file
View File

@@ -0,0 +1,229 @@
const idRegex = /^[a-z0-9-]{1,32}$/;
const nameRegex = /^[a-z0-9-]{1,32}$/;
const valueRegex = /^[a-zA-Z0-9/+.-]+$/;
const b64Regex = /^([a-zA-Z0-9/+.-]+|)$/;
const decimalRegex = /^((-)?[1-9]\d*|0)$/;
const versionRegex = /^v=(\d+)$/;
function objToKeyVal(obj) {
return objectKeys(obj)
.map(k => [k, obj[k]].join('='))
.join(',');
}
function keyValtoObj(str) {
const obj = {};
str.split(',').forEach(ps => {
const pss = ps.split('=');
if (pss.length < 2) {
throw new TypeError(`params must be in the format name=value`);
}
obj[pss.shift()] = pss.join('=');
});
return obj;
}
function objectKeys(object) {
/* istanbul ignore next */
return Object.keys(object);
}
function objectValues(object) {
/* istanbul ignore next */
if (typeof Object.values === 'function') return Object.values(object);
/* istanbul ignore next */
return objectKeys(object).map(k => object[k]);
}
/**
* Generates a PHC string using the data provided.
* @param {Object} opts Object that holds the data needed to generate the PHC
* string.
* @param {string} opts.id Symbolic name for the function.
* @param {Number} [opts.version] The version of the function.
* @param {Object} [opts.params] Parameters of the function.
* @param {Buffer} [opts.salt] The salt as a binary buffer.
* @param {Buffer} [opts.hash] The hash as a binary buffer.
* @return {string} The hash string adhering to the PHC format.
*/
function serialize(opts) {
const fields = [''];
if (typeof opts !== 'object' || opts === null) {
throw new TypeError('opts must be an object');
}
// Identifier Validation
if (typeof opts.id !== 'string') {
throw new TypeError('id must be a string');
}
if (!idRegex.test(opts.id)) {
throw new TypeError(`id must satisfy ${idRegex}`);
}
fields.push(opts.id);
if (typeof opts.version !== 'undefined') {
if (
typeof opts.version !== 'number' ||
opts.version < 0 ||
!Number.isInteger(opts.version)
) {
throw new TypeError('version must be a positive integer number');
}
fields.push(`v=${opts.version}`);
}
// Parameters Validation
if (typeof opts.params !== 'undefined') {
if (typeof opts.params !== 'object' || opts.params === null) {
throw new TypeError('params must be an object');
}
const pk = objectKeys(opts.params);
if (!pk.every(p => nameRegex.test(p))) {
throw new TypeError(`params names must satisfy ${nameRegex}`);
}
// Convert Numbers into Numeric Strings and Buffers into B64 encoded strings.
pk.forEach(k => {
if (typeof opts.params[k] === 'number') {
opts.params[k] = opts.params[k].toString();
} else if (Buffer.isBuffer(opts.params[k])) {
opts.params[k] = opts.params[k].toString('base64').split('=')[0];
}
});
const pv = objectValues(opts.params);
if (!pv.every(v => typeof v === 'string')) {
throw new TypeError('params values must be strings');
}
if (!pv.every(v => valueRegex.test(v))) {
throw new TypeError(`params values must satisfy ${valueRegex}`);
}
const strpar = objToKeyVal(opts.params);
fields.push(strpar);
}
if (typeof opts.salt !== 'undefined') {
// Salt Validation
if (!Buffer.isBuffer(opts.salt)) {
throw new TypeError('salt must be a Buffer');
}
fields.push(opts.salt.toString('base64').split('=')[0]);
if (typeof opts.hash !== 'undefined') {
// Hash Validation
if (!Buffer.isBuffer(opts.hash)) {
throw new TypeError('hash must be a Buffer');
}
fields.push(opts.hash.toString('base64').split('=')[0]);
}
}
// Create the PHC formatted string
const phcstr = fields.join('$');
return phcstr;
}
/**
* Parses data from a PHC string.
* @param {string} phcstr A PHC string to parse.
* @return {Object} The object containing the data parsed from the PHC string.
*/
function deserialize(phcstr) {
if (typeof phcstr !== 'string' || phcstr === '') {
throw new TypeError('pchstr must be a non-empty string');
}
if (phcstr[0] !== '$') {
throw new TypeError('pchstr must contain a $ as first char');
}
const fields = phcstr.split('$');
// Remove first empty $
fields.shift();
// Parse Fields
let maxf = 5;
if (!versionRegex.test(fields[1])) maxf--;
if (fields.length > maxf) {
throw new TypeError(
`pchstr contains too many fileds: ${fields.length}/${maxf}`
);
}
// Parse Identifier
const id = fields.shift();
if (!idRegex.test(id)) {
throw new TypeError(`id must satisfy ${idRegex}`);
}
let version;
// Parse Version
if (versionRegex.test(fields[0])) {
version = parseInt(fields.shift().match(versionRegex)[1], 10);
}
let hash;
let salt;
if (b64Regex.test(fields[fields.length - 1])) {
if (fields.length > 1 && b64Regex.test(fields[fields.length - 2])) {
// Parse Hash
hash = Buffer.from(fields.pop(), 'base64');
// Parse Salt
salt = Buffer.from(fields.pop(), 'base64');
} else {
// Parse Salt
salt = Buffer.from(fields.pop(), 'base64');
}
}
// Parse Parameters
let params;
if (fields.length > 0) {
const parstr = fields.pop();
params = keyValtoObj(parstr);
if (!objectKeys(params).every(p => nameRegex.test(p))) {
throw new TypeError(`params names must satisfy ${nameRegex}`);
}
const pv = objectValues(params);
if (!pv.every(v => valueRegex.test(v))) {
throw new TypeError(`params values must satisfy ${valueRegex}`);
}
const pk = objectKeys(params);
// Convert Decimal Strings into Numbers
pk.forEach(k => {
params[k] = decimalRegex.test(params[k])
? parseInt(params[k], 10)
: params[k];
});
}
if (fields.length > 0) {
throw new TypeError(`pchstr contains unrecognized fileds: ${fields}`);
}
// Build the output object
const phcobj = {id};
if (version) phcobj.version = version;
if (params) phcobj.params = params;
if (salt) phcobj.salt = salt;
if (hash) phcobj.hash = hash;
return phcobj;
}
module.exports = {
serialize,
deserialize
};

21
backend/node_modules/@phc/format/license generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018-2020 Simone Primarosa
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.

60
backend/node_modules/@phc/format/package.json generated vendored Normal file
View File

@@ -0,0 +1,60 @@
{
"name": "@phc/format",
"version": "1.0.0",
"description": "PHC string format serializer/deserializer",
"license": "MIT",
"homepage": "https://github.com/simonepri/phc-format#readme",
"repository": "github:simonepri/phc-format",
"bugs": {
"url": "https://github.com/simonepri/phc-format/issues",
"email": "simonepri@outlook.com"
},
"author": "Simone Primarosa <simonepri@outlook.com> (https://simoneprimarosa.com)",
"contributors": [
"Simone Primarosa <simonepri@outlook.com> (https://simoneprimarosa.com)"
],
"keywords": [
"mcf",
"phc",
"modular",
"crypt",
"passwords",
"hashing",
"competition",
"password",
"standard",
"crypto"
],
"main": "index.js",
"files": [
"index.js"
],
"engines": {
"node": ">=10"
},
"scripts": {
"lint": "xo",
"test": "nyc ava",
"release": "npx np",
"update": "npx npm-check -u"
},
"dependencies": {},
"devDependencies": {
"ava": "^3.9.0",
"nyc": "^15.1.0",
"xo": "~0.27.2"
},
"ava": {
"verbose": true
},
"nyc": {
"reporter": [
"lcovonly",
"text"
]
},
"xo": {
"prettier": true,
"space": true
}
}

207
backend/node_modules/@phc/format/readme.md generated vendored Normal file
View File

@@ -0,0 +1,207 @@
<h1 align="center">
<b>phc-format</b>
</h1>
<p align="center">
<!-- Version - npm -->
<a href="https://www.npmjs.com/package/@phc/format">
<img src="https://img.shields.io/npm/v/@phc/format.svg" alt="Latest version on npm" />
</a>
<!-- Downloads - npm -->
<a href="https://npm-stat.com/charts.html?package=@phc/format">
<img src="https://img.shields.io/npm/dt/@phc/format.svg" alt="Downloads on npm" />
</a>
<!-- License - MIT -->
<a href="https://github.com/simonepri/phc-format/tree/master/license">
<img src="https://img.shields.io/github/license/simonepri/phc-format.svg" alt="Project license" />
</a>
<br/>
<!-- Lint -->
<a href="https://github.com/simonepri/phc-format/actions?query=workflow:lint+branch:master">
<img src="https://github.com/simonepri/phc-format/workflows/lint/badge.svg?branch=master" alt="Lint status" />
</a>
<!-- Test - macOS -->
<a href="https://github.com/simonepri/phc-format/actions?query=workflow:test-macos+branch:master">
<img src="https://github.com/simonepri/phc-format/workflows/test-macos/badge.svg?branch=master" alt="Test macOS status" />
</a>
<!-- Test - Ubuntu -->
<a href="https://github.com/simonepri/phc-format/actions?query=workflow:test-ubuntu+branch:master">
<img src="https://github.com/simonepri/phc-format/workflows/test-ubuntu/badge.svg?branch=master" alt="Test Ubuntu status" />
</a>
<!-- Test - Windows -->
<a href="https://github.com/simonepri/phc-format/actions?query=workflow:test-windows+branch:master">
<img src="https://github.com/simonepri/phc-format/workflows/test-windows/badge.svg?branch=master" alt="Test Windows status" />
</a>
<br/>
<!-- Coverage - Codecov -->
<a href="https://codecov.io/gh/simonepri/phc-format">
<img src="https://img.shields.io/codecov/c/github/simonepri/phc-format/master.svg" alt="Codecov Coverage report" />
</a>
<!-- DM - Snyk -->
<a href="https://snyk.io/test/github/simonepri/phc-format?targetFile=package.json">
<img src="https://snyk.io/test/github/simonepri/phc-format/badge.svg?targetFile=package.json" alt="Known Vulnerabilities" />
</a>
<!-- DM - David -->
<a href="https://david-dm.org/simonepri/phc-format">
<img src="https://david-dm.org/simonepri/phc-format/status.svg" alt="Dependency Status" />
</a>
<br/>
<!-- Code Style - XO-Prettier -->
<a href="https://github.com/xojs/xo">
<img src="https://img.shields.io/badge/code_style-XO+Prettier-5ed9c7.svg" alt="XO Code Style used" />
</a>
<!-- Test Runner - AVA -->
<a href="https://github.com/avajs/ava">
<img src="https://img.shields.io/badge/test_runner-AVA-fb3170.svg" alt="AVA Test Runner used" />
</a>
<!-- Test Coverage - Istanbul -->
<a href="https://github.com/istanbuljs/nyc">
<img src="https://img.shields.io/badge/test_coverage-NYC-fec606.svg" alt="Istanbul Test Coverage used" />
</a>
<!-- Init - ni -->
<a href="https://github.com/simonepri/ni">
<img src="https://img.shields.io/badge/initialized_with-ni-e74c3c.svg" alt="NI Scaffolding System used" />
</a>
<!-- Release - np -->
<a href="https://github.com/sindresorhus/np">
<img src="https://img.shields.io/badge/released_with-np-6c8784.svg" alt="NP Release System used" />
</a>
</p>
<p align="center">
📝 PHC string format serializer/deserializer
<br/>
<sub>
Coded with ❤️ by <a href="#authors">Simone Primarosa</a>.
</sub>
</p>
## Motivation
The [PHC String Format][specs:phc] is an attempt to specify a common hash string format thats a restricted & well defined subset of the Modular Crypt Format. New hashes are strongly encouraged to adhere to the PHC specification, rather than the much looser [Modular Crypt Format][specs:mcf].
## Install
```bash
npm install --save @phc/format
```
## Usage
```js
const phc = require('@phc/format');
const phcobj = {
id: 'pbkdf2-sha256',
params: {i: 6400},
salt: Buffer.from('0ZrzXitFSGltTQnBWOsdAw', 'base64'),
hash: Buffer.from('Y11AchqV4b0sUisdZd0Xr97KWoymNE0LNNrnEgY4H9M', 'base64'),
};
const phcstr = "$pbkdf2-sha256$i=6400$0ZrzXitFSGltTQnBWOsdAw$Y11AchqV4b0sUisdZd0Xr97KWoymNE0LNNrnEgY4H9M";
phc.serialize(phcobj);
// => phcstr
phc.deserialize(phcstr);
// => phcobj
```
You can also pass an optional version parameter.
```js
const phc = require('@phc/format');
const phcobj = {
id: 'argon2i',
version: 19,
params: {
m: 120,
t: 5000,
p: 2
},
salt: Buffer.from('iHSDPHzUhPzK7rCcJgOFfg', 'base64'),
hash: Buffer.from('J4moa2MM0/6uf3HbY2Tf5Fux8JIBTwIhmhxGRbsY14qhTltQt+Vw3b7tcJNEbk8ium8AQfZeD4tabCnNqfkD1g', 'base64'),
};
const phcstr = "$argon2i$v=19$m=120,t=5000,p=2$iHSDPHzUhPzK7rCcJgOFfg$J4moa2MM0/6uf3HbY2Tf5Fux8JIBTwIhmhxGRbsY14qhTltQt+Vw3b7tcJNEbk8ium8AQfZeD4tabCnNqfkD1g";
phc.serialize(phcobj);
// => phcstr
phc.deserialize(phcstr);
// => phcobj
```
## API
#### TOC
<dl>
<dt><a href="#serialize">serialize(opts)</a> ⇒ <code>string</code></dt>
<dd><p>Generates a PHC string using the data provided.</p>
</dd>
<dt><a href="#deserialize">deserialize(phcstr)</a> ⇒ <code>Object</code></dt>
<dd><p>Parses data from a PHC string.</p>
</dd>
</dl>
<a name="serialize"></a>
### serialize(opts) ⇒ <code>string</code>
Generates a PHC string using the data provided.
**Kind**: global function
**Returns**: <code>string</code> - The hash string adhering to the PHC format.
| Param | Type | Description |
| --- | --- | --- |
| opts | <code>Object</code> | Object that holds the data needed to generate the PHC string. |
| opts.id | <code>string</code> | Symbolic name for the function. |
| [opts.version] | <code>Number</code> | The version of the function. |
| [opts.params] | <code>Object</code> | Parameters of the function. |
| [opts.salt] | <code>Buffer</code> | The salt as a binary buffer. |
| [opts.hash] | <code>Buffer</code> | The hash as a binary buffer. |
<a name="deserialize"></a>
### deserialize(phcstr) ⇒ <code>Object</code>
Parses data from a PHC string.
**Kind**: global function
**Returns**: <code>Object</code> - The object containing the data parsed from the PHC string.
| Param | Type | Description |
| --- | --- | --- |
| phcstr | <code>string</code> | A PHC string to parse. |
## Contributing
Contributions are REALLY welcome and if you find a security flaw in this code, PLEASE [report it][new issue].
Please check the [contributing guidelines][contributing] for more details. Thanks!
## Authors
- **Simone Primarosa** - *Github* ([@simonepri][github:simonepri]) • *Twitter* ([@simoneprimarosa][twitter:simoneprimarosa])
See also the list of [contributors][contributors] who participated in this project.
## License
This project is licensed under the MIT License - see the [license][license] file for details.
<!-- Links -->
[start]: https://github.com/simonepri/phc-format#start-of-content
[new issue]: https://github.com/simonepri/phc-format/issues/new
[contributors]: https://github.com/simonepri/phc-format/contributors
[license]: https://github.com/simonepri/phc-format/tree/master/license
[contributing]: https://github.com/simonepri/phc-format/tree/master/.github/contributing.md
[github:simonepri]: https://github.com/simonepri
[twitter:simoneprimarosa]: http://twitter.com/intent/user?screen_name=simoneprimarosa
[specs:mcf]: https://github.com/ademarre/binary-mcf
[specs:phc]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md

21
backend/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
backend/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, 12 Mar 2026 15:47:58 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), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [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), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig).

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

@@ -0,0 +1,955 @@
/**
* The `node:assert` module provides a set of assertion functions for verifying
* invariants.
* @see [source](https://github.com/nodejs/node/blob/v25.x/lib/assert.js)
*/
declare module "node:assert" {
import strict = require("node:assert/strict");
/**
* An alias of {@link assert.ok}.
* @since v0.5.9
* @param value The input that is checked for being truthy.
*/
function assert(value: unknown, message?: string | Error): asserts value;
const kOptions: unique symbol;
namespace assert {
type AssertMethodNames =
| "deepEqual"
| "deepStrictEqual"
| "doesNotMatch"
| "doesNotReject"
| "doesNotThrow"
| "equal"
| "fail"
| "ifError"
| "match"
| "notDeepEqual"
| "notDeepStrictEqual"
| "notEqual"
| "notStrictEqual"
| "ok"
| "partialDeepStrictEqual"
| "rejects"
| "strictEqual"
| "throws";
interface AssertOptions {
/**
* If set to `'full'`, shows the full diff in assertion errors.
* @default 'simple'
*/
diff?: "simple" | "full" | undefined;
/**
* If set to `true`, non-strict methods behave like their
* corresponding strict methods.
* @default true
*/
strict?: boolean | undefined;
/**
* If set to `true`, skips prototype and constructor
* comparison in deep equality checks.
* @since v24.9.0
* @default false
*/
skipPrototype?: boolean | undefined;
}
interface Assert extends Pick<typeof assert, AssertMethodNames> {
readonly [kOptions]: AssertOptions & { strict: false };
}
interface AssertStrict extends Pick<typeof strict, AssertMethodNames> {
readonly [kOptions]: AssertOptions & { strict: true };
}
/**
* The `Assert` class allows creating independent assertion instances with custom options.
* @since v24.6.0
*/
var Assert: {
/**
* Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages.
*
* ```js
* const { Assert } = require('node:assert');
* const assertInstance = new Assert({ diff: 'full' });
* assertInstance.deepStrictEqual({ a: 1 }, { a: 2 });
* // Shows a full diff in the error message.
* ```
*
* **Important**: When destructuring assertion methods from an `Assert` instance,
* the methods lose their connection to the instance's configuration options (such
* as `diff`, `strict`, and `skipPrototype` settings).
* The destructured methods will fall back to default behavior instead.
*
* ```js
* const myAssert = new Assert({ diff: 'full' });
*
* // This works as expected - uses 'full' diff
* myAssert.strictEqual({ a: 1 }, { b: { c: 1 } });
*
* // This loses the 'full' diff setting - falls back to default 'simple' diff
* const { strictEqual } = myAssert;
* strictEqual({ a: 1 }, { b: { c: 1 } });
* ```
*
* The `skipPrototype` option affects all deep equality methods:
*
* ```js
* class Foo {
* constructor(a) {
* this.a = a;
* }
* }
*
* class Bar {
* constructor(a) {
* this.a = a;
* }
* }
*
* const foo = new Foo(1);
* const bar = new Bar(1);
*
* // Default behavior - fails due to different constructors
* const assert1 = new Assert();
* assert1.deepStrictEqual(foo, bar); // AssertionError
*
* // Skip prototype comparison - passes if properties are equal
* const assert2 = new Assert({ skipPrototype: true });
* assert2.deepStrictEqual(foo, bar); // OK
* ```
*
* When destructured, methods lose access to the instance's `this` context and revert to default assertion behavior
* (diff: 'simple', non-strict mode).
* To maintain custom options when using destructured methods, avoid
* destructuring and call methods directly on the instance.
* @since v24.6.0
*/
new(
options?: AssertOptions & { strict?: true | undefined },
): AssertStrict;
new(
options: AssertOptions,
): Assert;
};
interface AssertionErrorOptions {
/**
* If provided, the error message is set to this value.
*/
message?: string | undefined;
/**
* The `actual` property on the error instance.
*/
actual?: unknown;
/**
* The `expected` property on the error instance.
*/
expected?: unknown;
/**
* The `operator` property on the error instance.
*/
operator?: string | undefined;
/**
* If provided, the generated stack trace omits frames before this function.
*/
stackStartFn?: Function | undefined;
/**
* If set to `'full'`, shows the full diff in assertion errors.
* @default 'simple'
*/
diff?: "simple" | "full" | undefined;
}
/**
* 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 {
constructor(options: AssertionErrorOptions);
/**
* 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;
/**
* 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";
/**
* Set to the passed in operator value.
*/
operator: string;
}
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
* ```
* @since v0.1.21
* @param [message='Failed']
*/
function fail(message?: string | Error): 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(2 + 2 > 5);;
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert(2 + 2 > 5)
* ```
* @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](https://nodejs.org/docs/latest-v25.x/api/errors.html#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 `{@link 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](https://nodejs.org/docs/latest-v25.x/api/errors.html#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 `{@link 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](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) then it will be thrown instead of the `{@link 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 `{@link 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](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`.
* @since v13.6.0, v12.16.0
*/
function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void;
/**
* Tests for partial 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. "Partial" equality means
* that only properties that exist on the `expected` parameter are going to be
* compared.
*
* This method always passes the same test cases as `assert.deepStrictEqual()`,
* behaving as a super set of it.
* @since v22.13.0
*/
function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void;
}
namespace assert {
export { strict };
}
export = assert;
}
declare module "assert" {
import assert = require("node:assert");
export = assert;
}

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

@@ -0,0 +1,105 @@
/**
* In strict assertion mode, non-strict methods behave like their corresponding
* strict methods. For example, `assert.deepEqual()` will behave like
* `assert.deepStrictEqual()`.
*
* In strict assertion mode, error messages for objects display a diff. In legacy
* assertion mode, error messages for objects display the objects, often truncated.
*
* To use strict assertion mode:
*
* ```js
* import { strict as assert } from 'node:assert';
* ```
*
* ```js
* import assert from 'node:assert/strict';
* ```
*
* Example error diff:
*
* ```js
* import { strict as assert } from 'node:assert';
*
* assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
* // AssertionError: Expected inputs to be strictly deep-equal:
* // + actual - expected ... Lines skipped
* //
* // [
* // [
* // ...
* // 2,
* // + 3
* // - '3'
* // ],
* // ...
* // 5
* // ]
* ```
*
* To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS`
* environment variables. This will also deactivate the colors in the REPL. For
* more on color support in terminal environments, read the tty
* [`getColorDepth()`](https://nodejs.org/docs/latest-v25.x/api/tty.html#writestreamgetcolordepthenv) documentation.
* @since v15.0.0
* @see [source](https://github.com/nodejs/node/blob/v25.x/lib/assert/strict.js)
*/
declare module "node:assert/strict" {
import {
Assert,
AssertionError,
AssertionErrorOptions,
AssertOptions,
AssertPredicate,
AssertStrict,
deepStrictEqual,
doesNotMatch,
doesNotReject,
doesNotThrow,
fail,
ifError,
match,
notDeepStrictEqual,
notStrictEqual,
ok,
partialDeepStrictEqual,
rejects,
strictEqual,
throws,
} from "node:assert";
function strict(value: unknown, message?: string | Error): asserts value;
namespace strict {
export {
Assert,
AssertionError,
AssertionErrorOptions,
AssertOptions,
AssertPredicate,
AssertStrict,
deepStrictEqual,
deepStrictEqual as deepEqual,
doesNotMatch,
doesNotReject,
doesNotThrow,
fail,
ifError,
match,
notDeepStrictEqual,
notDeepStrictEqual as notDeepEqual,
notStrictEqual,
notStrictEqual as notEqual,
ok,
partialDeepStrictEqual,
rejects,
strict,
strictEqual,
strictEqual as equal,
throws,
};
}
export = strict;
}
declare module "assert/strict" {
import strict = require("node:assert/strict");
export = strict;
}

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

@@ -0,0 +1,623 @@
/**
* We strongly discourage the use of the `async_hooks` API.
* Other APIs that can cover most of its use cases include:
*
* * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v25.x/api/async_context.html#class-asynclocalstorage) tracks async context
* * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v25.x/api/process.html#processgetactiveresourcesinfo) 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/v25.x/lib/async_hooks.js)
*/
declare module "node: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](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#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 'node: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](https://nodejs.org/docs/latest-v25.x/api/async_hooks.html#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.
*
* If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs.
* @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;
}
interface AsyncLocalStorageOptions {
/**
* The default value to be used when no store is provided.
*/
defaultValue?: any;
/**
* A name for the `AsyncLocalStorage` value.
*/
name?: string | undefined;
}
/**
* 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
* // 0: finish
* // 1: start
* // 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> {
/**
* Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
* `run()` call or after an `enterWith()` call.
*/
constructor(options?: AsyncLocalStorageOptions);
/**
* Binds the given function to the current execution context.
* @since v19.8.0
* @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
* @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;
/**
* The name of the `AsyncLocalStorage` instance if provided.
* @since v24.0.0
*/
readonly name: string;
/**
* 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;
}
/**
* @since v17.2.0, v16.14.0
* @return A map of provider types to the corresponding numeric id.
* This map contains all the event types that might be emitted by the `async_hooks.init()` event.
*/
namespace asyncWrapProviders {
const NONE: number;
const DIRHANDLE: number;
const DNSCHANNEL: number;
const ELDHISTOGRAM: number;
const FILEHANDLE: number;
const FILEHANDLECLOSEREQ: number;
const FIXEDSIZEBLOBCOPY: number;
const FSEVENTWRAP: number;
const FSREQCALLBACK: number;
const FSREQPROMISE: number;
const GETADDRINFOREQWRAP: number;
const GETNAMEINFOREQWRAP: number;
const HEAPSNAPSHOT: number;
const HTTP2SESSION: number;
const HTTP2STREAM: number;
const HTTP2PING: number;
const HTTP2SETTINGS: number;
const HTTPINCOMINGMESSAGE: number;
const HTTPCLIENTREQUEST: number;
const JSSTREAM: number;
const JSUDPWRAP: number;
const MESSAGEPORT: number;
const PIPECONNECTWRAP: number;
const PIPESERVERWRAP: number;
const PIPEWRAP: number;
const PROCESSWRAP: number;
const PROMISE: number;
const QUERYWRAP: number;
const SHUTDOWNWRAP: number;
const SIGNALWRAP: number;
const STATWATCHER: number;
const STREAMPIPE: number;
const TCPCONNECTWRAP: number;
const TCPSERVERWRAP: number;
const TCPWRAP: number;
const TTYWRAP: number;
const UDPSENDWRAP: number;
const UDPWRAP: number;
const SIGINTWATCHDOG: number;
const WORKER: number;
const WORKERHEAPSNAPSHOT: number;
const WRITEWRAP: number;
const ZLIB: number;
const CHECKPRIMEREQUEST: number;
const PBKDF2REQUEST: number;
const KEYPAIRGENREQUEST: number;
const KEYGENREQUEST: number;
const KEYEXPORTREQUEST: number;
const CIPHERREQUEST: number;
const DERIVEBITSREQUEST: number;
const HASHREQUEST: number;
const RANDOMBYTESREQUEST: number;
const RANDOMPRIMEREQUEST: number;
const SCRYPTREQUEST: number;
const SIGNREQUEST: number;
const TLSWRAP: number;
const VERIFYREQUEST: number;
}
}
declare module "async_hooks" {
export * from "node:async_hooks";
}

466
backend/node_modules/@types/node/buffer.buffer.d.ts generated vendored Normal file
View File

@@ -0,0 +1,466 @@
declare module "node:buffer" {
type ImplicitArrayBuffer<T extends WithImplicitCoercion<ArrayBufferLike>> = T extends
{ valueOf(): infer V extends ArrayBufferLike } ? V : T;
global {
interface BufferConstructor {
// see buffer.d.ts for implementation shared with all TypeScript versions
/**
* Allocates a new buffer containing the given {str}.
*
* @param str String to store in buffer.
* @param encoding encoding to use, optional. Default is 'utf8'
* @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead.
*/
new(str: string, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
* @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`).
*/
new(size: number): Buffer<ArrayBuffer>;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
*/
new(array: ArrayLike<number>): Buffer<ArrayBuffer>;
/**
* Produces a Buffer backed by the same allocated memory as
* the given {ArrayBuffer}/{SharedArrayBuffer}.
*
* @param arrayBuffer The ArrayBuffer with which to share memory.
* @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead.
*/
new<TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(arrayBuffer: TArrayBuffer): Buffer<TArrayBuffer>;
/**
* Allocates a new `Buffer` using an `array` of bytes in the range `0` `255`.
* Array entries outside that range will be truncated to fit into it.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
* const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
* ```
*
* If `array` is an `Array`-like object (that is, one with a `length` property of
* type `number`), it is treated as if it is an array, unless it is a `Buffer` or
* a `Uint8Array`. This means all other `TypedArray` variants get treated as an
* `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use
* `Buffer.copyBytesFrom()`.
*
* A `TypeError` will be thrown if `array` is not an `Array` or another type
* appropriate for `Buffer.from()` variants.
*
* `Buffer.from(array)` and `Buffer.from(string)` may also use the internal
* `Buffer` pool like `Buffer.allocUnsafe()` does.
* @since v5.10.0
*/
from(array: WithImplicitCoercion<ArrayLike<number>>): Buffer<ArrayBuffer>;
/**
* This creates a view of the `ArrayBuffer` without copying the underlying
* memory. For example, when passed a reference to the `.buffer` property of a
* `TypedArray` instance, the newly created `Buffer` will share the same
* allocated memory as the `TypedArray`'s underlying `ArrayBuffer`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const arr = new Uint16Array(2);
*
* arr[0] = 5000;
* arr[1] = 4000;
*
* // Shares memory with `arr`.
* const buf = Buffer.from(arr.buffer);
*
* console.log(buf);
* // Prints: <Buffer 88 13 a0 0f>
*
* // Changing the original Uint16Array changes the Buffer also.
* arr[1] = 6000;
*
* console.log(buf);
* // Prints: <Buffer 88 13 70 17>
* ```
*
* The optional `byteOffset` and `length` arguments specify a memory range within
* the `arrayBuffer` that will be shared by the `Buffer`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const ab = new ArrayBuffer(10);
* const buf = Buffer.from(ab, 0, 2);
*
* console.log(buf.length);
* // Prints: 2
* ```
*
* A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a
* `SharedArrayBuffer` or another type appropriate for `Buffer.from()`
* variants.
*
* It is important to remember that a backing `ArrayBuffer` can cover a range
* of memory that extends beyond the bounds of a `TypedArray` view. A new
* `Buffer` created using the `buffer` property of a `TypedArray` may extend
* beyond the range of the `TypedArray`:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
* const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
* console.log(arrA.buffer === arrB.buffer); // true
*
* const buf = Buffer.from(arrB.buffer);
* console.log(buf);
* // Prints: <Buffer 63 64 65 66>
* ```
* @since v5.10.0
* @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the
* `.buffer` property of a `TypedArray`.
* @param byteOffset Index of first byte to expose. **Default:** `0`.
* @param length Number of bytes to expose. **Default:**
* `arrayBuffer.byteLength - byteOffset`.
*/
from<TArrayBuffer extends WithImplicitCoercion<ArrayBufferLike>>(
arrayBuffer: TArrayBuffer,
byteOffset?: number,
length?: number,
): Buffer<ImplicitArrayBuffer<TArrayBuffer>>;
/**
* Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
* the character encoding to be used when converting `string` into bytes.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from('this is a tést');
* const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
*
* console.log(buf1.toString());
* // Prints: this is a tést
* console.log(buf2.toString());
* // Prints: this is a tést
* console.log(buf1.toString('latin1'));
* // Prints: this is a tést
* ```
*
* A `TypeError` will be thrown if `string` is not a string or another type
* appropriate for `Buffer.from()` variants.
*
* `Buffer.from(string)` may also use the internal `Buffer` pool like
* `Buffer.allocUnsafe()` does.
* @since v5.10.0
* @param string A string to encode.
* @param encoding The encoding of `string`. **Default:** `'utf8'`.
*/
from(string: WithImplicitCoercion<string>, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
from(arrayOrString: WithImplicitCoercion<ArrayLike<number> | string>): Buffer<ArrayBuffer>;
/**
* Creates a new Buffer using the passed {data}
* @param values to create a new Buffer
*/
of(...items: number[]): Buffer<ArrayBuffer>;
/**
* Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together.
*
* If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned.
*
* If `totalLength` is not provided, it is calculated from the `Buffer` instances
* in `list` by adding their lengths.
*
* If `totalLength` is provided, it is coerced to an unsigned integer. If the
* combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
* truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is
* less than `totalLength`, the remaining space is filled with zeros.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a single `Buffer` from a list of three `Buffer` instances.
*
* const buf1 = Buffer.alloc(10);
* const buf2 = Buffer.alloc(14);
* const buf3 = Buffer.alloc(18);
* const totalLength = buf1.length + buf2.length + buf3.length;
*
* console.log(totalLength);
* // Prints: 42
*
* const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
*
* console.log(bufA);
* // Prints: <Buffer 00 00 00 00 ...>
* console.log(bufA.length);
* // Prints: 42
* ```
*
* `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does.
* @since v0.7.11
* @param list List of `Buffer` or {@link Uint8Array} instances to concatenate.
* @param totalLength Total length of the `Buffer` instances in `list` when concatenated.
*/
concat(list: readonly Uint8Array[], totalLength?: number): Buffer<ArrayBuffer>;
/**
* Copies the underlying memory of `view` into a new `Buffer`.
*
* ```js
* const u16 = new Uint16Array([0, 0xffff]);
* const buf = Buffer.copyBytesFrom(u16, 1, 1);
* u16[1] = 0;
* console.log(buf.length); // 2
* console.log(buf[0]); // 255
* console.log(buf[1]); // 255
* ```
* @since v19.8.0
* @param view The {TypedArray} to copy.
* @param [offset=0] The starting offset within `view`.
* @param [length=view.length - offset] The number of elements from `view` to copy.
*/
copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer<ArrayBuffer>;
/**
* Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(5);
*
* console.log(buf);
* // Prints: <Buffer 00 00 00 00 00>
* ```
*
* If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
*
* If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(5, 'a');
*
* console.log(buf);
* // Prints: <Buffer 61 61 61 61 61>
* ```
*
* If both `fill` and `encoding` are specified, the allocated `Buffer` will be
* initialized by calling `buf.fill(fill, encoding)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
*
* console.log(buf);
* // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
* ```
*
* Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance
* contents will never contain sensitive data from previous allocations, including
* data that might not have been allocated for `Buffer`s.
*
* A `TypeError` will be thrown if `size` is not a number.
* @since v5.10.0
* @param size The desired length of the new `Buffer`.
* @param [fill=0] A value to pre-fill the new `Buffer` with.
* @param [encoding='utf8'] If `fill` is a string, this is its encoding.
*/
alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
/**
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
*
* The underlying memory for `Buffer` instances created in this way is _not_
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(10);
*
* console.log(buf);
* // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
*
* buf.fill(0);
*
* console.log(buf);
* // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
* ```
*
* A `TypeError` will be thrown if `size` is not a number.
*
* The `Buffer` module pre-allocates an internal `Buffer` instance of
* size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`,
* and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two).
*
* Use of this pre-allocated internal memory pool is a key difference between
* calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
* Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less
* than or equal to half `Buffer.poolSize`. The
* difference is subtle but can be important when an application requires the
* additional performance that `Buffer.allocUnsafe()` provides.
* @since v5.10.0
* @param size The desired length of the new `Buffer`.
*/
allocUnsafe(size: number): Buffer<ArrayBuffer>;
/**
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if
* `size` is 0.
*
* The underlying memory for `Buffer` instances created in this way is _not_
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize
* such `Buffer` instances with zeroes.
*
* When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
* allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
* allows applications to avoid the garbage collection overhead of creating many
* individually allocated `Buffer` instances. This approach improves both
* performance and memory usage by eliminating the need to track and clean up as
* many individual `ArrayBuffer` objects.
*
* However, in the case where a developer may need to retain a small chunk of
* memory from a pool for an indeterminate amount of time, it may be appropriate
* to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
* then copying out the relevant bits.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Need to keep around a few small chunks of memory.
* const store = [];
*
* socket.on('readable', () => {
* let data;
* while (null !== (data = readable.read())) {
* // Allocate for retained data.
* const sb = Buffer.allocUnsafeSlow(10);
*
* // Copy the data into the new allocation.
* data.copy(sb, 0, 0, 10);
*
* store.push(sb);
* }
* });
* ```
*
* A `TypeError` will be thrown if `size` is not a number.
* @since v5.12.0
* @param size The desired length of the new `Buffer`.
*/
allocUnsafeSlow(size: number): Buffer<ArrayBuffer>;
}
interface Buffer<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> extends Uint8Array<TArrayBuffer> {
// see buffer.d.ts for implementation shared with all TypeScript versions
/**
* Returns a new `Buffer` that references the same memory as the original, but
* offset and cropped by the `start` and `end` indices.
*
* This method is not compatible with the `Uint8Array.prototype.slice()`,
* which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* const copiedBuf = Uint8Array.prototype.slice.call(buf);
* copiedBuf[0]++;
* console.log(copiedBuf.toString());
* // Prints: cuffer
*
* console.log(buf.toString());
* // Prints: buffer
*
* // With buf.slice(), the original buffer is modified.
* const notReallyCopiedBuf = buf.slice();
* notReallyCopiedBuf[0]++;
* console.log(notReallyCopiedBuf.toString());
* // Prints: cuffer
* console.log(buf.toString());
* // Also prints: cuffer (!)
* ```
* @since v0.3.0
* @deprecated Use `subarray` instead.
* @param [start=0] Where the new `Buffer` will start.
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
*/
slice(start?: number, end?: number): Buffer<ArrayBuffer>;
/**
* Returns a new `Buffer` that references the same memory as the original, but
* offset and cropped by the `start` and `end` indices.
*
* Specifying `end` greater than `buf.length` will return the same result as
* that of `end` equal to `buf.length`.
*
* This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray).
*
* Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
* // from the original `Buffer`.
*
* const buf1 = Buffer.allocUnsafe(26);
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf1[i] = i + 97;
* }
*
* const buf2 = buf1.subarray(0, 3);
*
* console.log(buf2.toString('ascii', 0, buf2.length));
* // Prints: abc
*
* buf1[0] = 33;
*
* console.log(buf2.toString('ascii', 0, buf2.length));
* // Prints: !bc
* ```
*
* Specifying negative indexes causes the slice to be generated relative to the
* end of `buf` rather than the beginning.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* console.log(buf.subarray(-6, -1).toString());
* // Prints: buffe
* // (Equivalent to buf.subarray(0, 5).)
*
* console.log(buf.subarray(-6, -2).toString());
* // Prints: buff
* // (Equivalent to buf.subarray(0, 4).)
*
* console.log(buf.subarray(-5, -2).toString());
* // Prints: uff
* // (Equivalent to buf.subarray(1, 4).)
* ```
* @since v3.0.0
* @param [start=0] Where the new `Buffer` will start.
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
*/
subarray(start?: number, end?: number): Buffer<TArrayBuffer>;
}
// TODO: remove globals in future version
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedBuffer = Buffer<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type AllowSharedBuffer = Buffer<ArrayBufferLike>;
}
}

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

File diff suppressed because it is too large Load Diff

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

File diff suppressed because it is too large Load Diff

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

@@ -0,0 +1,486 @@
/**
* 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`](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html)
* 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/v25.x/lib/cluster.js)
*/
declare module "node:cluster" {
import * as child_process from "node:child_process";
import { EventEmitter, InternalEventEmitter } from "node:events";
class Worker implements EventEmitter {
constructor(options?: cluster.WorkerOptions);
/**
* 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()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object
* from this function is stored as `.process`. In a worker, the global `process` is stored.
*
* See: [Child Process module](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processforkmodulepath-args-options).
*
* 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_process.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()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback).
*
* 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.
*/
send(message: child_process.Serializable, callback?: (error: Error | null) => void): boolean;
send(
message: child_process.Serializable,
sendHandle: child_process.SendHandle,
callback?: (error: Error | null) => void,
): boolean;
send(
message: child_process.Serializable,
sendHandle: child_process.SendHandle,
options?: child_process.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()`](https://nodejs.org/docs/latest-v25.x/api/process.html#processkillpid-signal).
* @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
* import net from 'node:net';
*
* 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 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(): this;
/**
* 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;
}
interface Worker extends InternalEventEmitter<cluster.WorkerEventMap> {}
type _Worker = Worker;
namespace cluster {
interface Worker extends _Worker {}
interface WorkerOptions {
id?: number | undefined;
process?: child_process.ChildProcess | undefined;
state?: string | undefined;
}
interface WorkerEventMap {
"disconnect": [];
"error": [error: Error];
"exit": [code: number, signal: string];
"listening": [address: Address];
"message": [message: any, handle: child_process.SendHandle];
"online": [];
}
interface ClusterSettings {
/**
* List of string arguments passed to the Node.js executable.
* @default process.execArgv
*/
execArgv?: string[] | undefined;
/**
* File path to worker file.
* @default process.argv[1]
*/
exec?: string | undefined;
/**
* String arguments passed to worker.
* @default process.argv.slice(2)
*/
args?: readonly string[] | undefined;
/**
* Whether or not to send output to parent's stdio.
* @default false
*/
silent?: boolean | undefined;
/**
* Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must
* contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#child_processspawncommand-args-options)'s
* [`stdio`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#optionsstdio).
*/
stdio?: any[] | undefined;
/**
* Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).)
*/
uid?: number | undefined;
/**
* Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).)
*/
gid?: number | undefined;
/**
* Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number.
* By default each worker gets its own port, incremented from the primary's `process.debugPort`.
*/
inspectPort?: number | (() => number) | undefined;
/**
* Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`.
* See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v25.x/api/child_process.html#advanced-serialization) for more details.
* @default false
*/
serialization?: "json" | "advanced" | undefined;
/**
* Current working directory of the worker process.
* @default undefined (inherits from parent process)
*/
cwd?: string | undefined;
/**
* Hide the forked processes console window that would normally be created on Windows systems.
* @default false
*/
windowsHide?: boolean | undefined;
}
interface Address {
address: string;
port: number;
/**
* The `addressType` is one of:
*
* * `4` (TCPv4)
* * `6` (TCPv6)
* * `-1` (Unix domain socket)
* * `'udp4'` or `'udp6'` (UDPv4 or UDPv6)
*/
addressType: 4 | 6 | -1 | "udp4" | "udp6";
}
interface ClusterEventMap {
"disconnect": [worker: Worker];
"exit": [worker: Worker, code: number, signal: string];
"fork": [worker: Worker];
"listening": [worker: Worker, address: Address];
"message": [worker: Worker, message: any, handle: child_process.SendHandle];
"online": [worker: Worker];
"setup": [settings: ClusterSettings];
}
interface Cluster extends InternalEventEmitter<ClusterEventMap> {
/**
* 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
*/
Worker: typeof Worker;
disconnect(callback?: () => void): void;
/**
* Spawn a new worker process.
*
* This can only be called from the primary process.
* @param env Key/value pairs to add to worker process environment.
* @since v0.6.0
*/
fork(env?: any): Worker;
/** @deprecated since v16.0.0 - use isPrimary. */
readonly isMaster: boolean;
/**
* True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID`
* is undefined, then `isPrimary` is `true`.
* @since v16.0.0
*/
readonly isPrimary: boolean;
/**
* True if the process is not a primary (it is the negation of `cluster.isPrimary`).
* @since v0.6.0
*/
readonly isWorker: boolean;
/**
* The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a
* global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings)
* is called, whichever comes first.
*
* `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute
* IOCP handles without incurring a large performance hit.
*
* `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`.
* @since v0.11.2
*/
schedulingPolicy: number;
/**
* After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings)
* (or [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv)) this settings object will contain
* the settings, including the default values.
*
* This object is not intended to be changed or set manually.
* @since v0.7.1
*/
readonly settings: ClusterSettings;
/** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clustersetupprimarysettings) instead. */
setupMaster(settings?: ClusterSettings): void;
/**
* `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`.
*
* Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv)
* and have no effect on workers that are already running.
*
* The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to
* [`.fork()`](https://nodejs.org/docs/latest-v25.x/api/cluster.html#clusterforkenv).
*
* The defaults above apply to the first call only; the defaults for later calls are the current values at the time of
* `cluster.setupPrimary()` is called.
*
* ```js
* import cluster from 'node:cluster';
*
* cluster.setupPrimary({
* exec: 'worker.js',
* args: ['--use', 'https'],
* silent: true,
* });
* cluster.fork(); // https worker
* cluster.setupPrimary({
* exec: 'worker.js',
* args: ['--use', 'http'],
* });
* cluster.fork(); // http worker
* ```
*
* This can only be called from the primary process.
* @since v16.0.0
*/
setupPrimary(settings?: ClusterSettings): void;
/**
* A reference to the current worker object. Not available in the primary process.
*
* ```js
* import cluster from 'node:cluster';
*
* if (cluster.isPrimary) {
* console.log('I am primary');
* cluster.fork();
* cluster.fork();
* } else if (cluster.isWorker) {
* console.log(`I am worker #${cluster.worker.id}`);
* }
* ```
* @since v0.7.0
*/
readonly worker?: Worker;
/**
* A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process.
*
* A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it
* is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted.
*
* ```js
* import cluster from 'node:cluster';
*
* for (const worker of Object.values(cluster.workers)) {
* worker.send('big announcement to all workers');
* }
* ```
* @since v0.7.0
*/
readonly workers?: NodeJS.Dict<Worker>;
readonly SCHED_NONE: number;
readonly SCHED_RR: number;
}
}
var cluster: cluster.Cluster;
export = cluster;
}
declare module "cluster" {
import cluster = require("node:cluster");
export = cluster;
}

View File

@@ -0,0 +1,21 @@
// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6.
// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects
// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded.
// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods
// if lib.esnext.iterator is loaded.
// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn.
// Placeholders for TS <5.6
interface IteratorObject<T, TReturn, TNext> {}
interface AsyncIteratorObject<T, TReturn, TNext> {}
declare namespace NodeJS {
// Populate iterator methods for TS <5.6
interface Iterator<T, TReturn, TNext> extends globalThis.Iterator<T, TReturn, TNext> {}
interface AsyncIterator<T, TReturn, TNext> extends globalThis.AsyncIterator<T, TReturn, TNext> {}
// Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators
type BuiltinIteratorReturn = ReturnType<any[][typeof Symbol.iterator]> extends
globalThis.Iterator<any, infer TReturn> ? TReturn
: any;
}

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

@@ -0,0 +1,151 @@
/**
* 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`](https://nodejs.org/docs/latest-v25.x/api/process.html#processstdout) and
* [`process.stderr`](https://nodejs.org/docs/latest-v25.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
*
* _**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`](https://nodejs.org/docs/latest-v25.x/api/process.html#a-note-on-process-io) 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/v25.x/lib/console.js)
*/
declare module "node:console" {
import { InspectOptions } from "node:util";
namespace console {
interface ConsoleOptions {
stdout: NodeJS.WritableStream;
stderr?: NodeJS.WritableStream | undefined;
/**
* Ignore errors when writing to the underlying streams.
* @default true
*/
ignoreErrors?: boolean | undefined;
/**
* Set color support for this `Console` instance. Setting to true enables coloring while inspecting
* values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color
* support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the
* respective stream. This option can not be used, if `inspectOptions.colors` is set as well.
* @default 'auto'
*/
colorMode?: boolean | "auto" | undefined;
/**
* Specifies options that are passed along to
* [`util.inspect()`](https://nodejs.org/docs/latest-v25.x/api/util.html#utilinspectobject-options).
*/
inspectOptions?: InspectOptions | ReadonlyMap<NodeJS.WritableStream, InspectOptions> | undefined;
/**
* Set group indentation.
* @default 2
*/
groupIndentation?: number | undefined;
}
interface Console {
readonly Console: {
prototype: Console;
new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console;
new(options: ConsoleOptions): Console;
};
assert(condition?: unknown, ...data: any[]): void;
clear(): void;
count(label?: string): void;
countReset(label?: string): void;
debug(...data: any[]): void;
dir(item?: any, options?: InspectOptions): void;
dirxml(...data: any[]): void;
error(...data: any[]): void;
group(...data: any[]): void;
groupCollapsed(...data: any[]): void;
groupEnd(): void;
info(...data: any[]): void;
log(...data: any[]): void;
table(tabularData?: any, properties?: string[]): void;
time(label?: string): void;
timeEnd(label?: string): void;
timeLog(label?: string, ...data: any[]): void;
trace(...data: any[]): void;
warn(...data: any[]): void;
/**
* This method does not display anything unless used in the inspector. The `console.profile()`
* method starts a JavaScript CPU profile with an optional label until {@link profileEnd}
* is called. The profile is then added to the Profile panel of the inspector.
*
* ```js
* console.profile('MyLabel');
* // Some code
* console.profileEnd('MyLabel');
* // Adds the profile 'MyLabel' to the Profiles panel of the inspector.
* ```
* @since v8.0.0
*/
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. See {@link profile} for an example.
*
* If this method is called without a label, the most recently started profile is stopped.
* @since v8.0.0
*/
profileEnd(label?: string): void;
/**
* This method does not display anything unless used in the inspector. The `console.timeStamp()`
* method adds an event with the label `'label'` to the Timeline panel of the inspector.
* @since v8.0.0
*/
timeStamp(label?: string): void;
}
}
var console: console.Console;
export = console;
}
declare module "console" {
import console = require("node:console");
export = console;
}

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

@@ -0,0 +1,20 @@
/**
* @deprecated The `node:constants` module is deprecated. When requiring access to constants
* relevant to specific Node.js builtin modules, developers should instead refer
* to the `constants` property exposed by the relevant module. For instance,
* `require('node:fs').constants` and `require('node:os').constants`.
*/
declare module "node:constants" {
const constants:
& typeof import("node:os").constants.dlopen
& typeof import("node:os").constants.errno
& typeof import("node:os").constants.priority
& typeof import("node:os").constants.signals
& typeof import("node:fs").constants
& typeof import("node:crypto").constants;
export = constants;
}
declare module "constants" {
import constants = require("node:constants");
export = constants;
}

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

File diff suppressed because it is too large Load Diff

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

@@ -0,0 +1,564 @@
/**
* 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/v25.x/lib/dgram.js)
*/
declare module "node:dgram" {
import { NonSharedBuffer } from "node:buffer";
import * as dns from "node:dns";
import { Abortable, EventEmitter, InternalEventEmitter } from "node:events";
import { AddressInfo, BlockList } from "node:net";
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;
reusePort?: 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;
receiveBlockList?: BlockList | undefined;
sendBlockList?: BlockList | 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: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket;
function createSocket(options: SocketOptions, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket;
interface SocketEventMap {
"close": [];
"connect": [];
"error": [err: Error];
"listening": [];
"message": [msg: NonSharedBuffer, rinfo: RemoteInfo];
}
/**
* 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 implements 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 | NodeJS.ArrayBufferView | readonly any[],
port?: number,
address?: string,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | NodeJS.ArrayBufferView | readonly any[],
port?: number,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | NodeJS.ArrayBufferView | readonly any[],
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | NodeJS.ArrayBufferView,
offset: number,
length: number,
port?: number,
address?: string,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | NodeJS.ArrayBufferView,
offset: number,
length: number,
port?: number,
callback?: (error: Error | null, bytes: number) => void,
): void;
send(
msg: string | NodeJS.ArrayBufferView,
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;
/**
* Calls `socket.close()` and returns a promise that fulfills when the socket has closed.
* @since v20.5.0
*/
[Symbol.asyncDispose](): Promise<void>;
}
interface Socket extends InternalEventEmitter<SocketEventMap> {}
}
declare module "dgram" {
export * from "node:dgram";
}

View File

@@ -0,0 +1,576 @@
/**
* 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/v25.x/lib/diagnostics_channel.js)
*/
declare module "node: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
* @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
* @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: AsyncLocalStorage<StoreType>): boolean;
/**
* 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<ThisArg = any, Args extends any[] = any[], Result = any>(
context: ContextType,
fn: (this: ThisArg, ...args: Args) => Result,
thisArg?: ThisArg,
...args: Args
): Result;
}
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.
*
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
*
* ```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[], Result = any>(
fn: (this: ThisArg, ...args: Args) => Result,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): Result;
/**
* 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.
*
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
*
* ```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[], Result = any>(
fn: (this: ThisArg, ...args: Args) => Promise<Result>,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): Promise<Result>;
/**
* 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.
*
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
*
* ```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<ThisArg = any, Args extends any[] = any[], Result = any>(
fn: (this: ThisArg, ...args: Args) => Result,
position?: number,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): Result;
/**
* `true` if any of the individual channels has a subscriber, `false` if not.
*
* This is a helper method available on a {@link TracingChannel} instance to check
* if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers.
* A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise.
*
* ```js
* const diagnostics_channel = require('node:diagnostics_channel');
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* if (channels.hasSubscribers) {
* // Do something
* }
* ```
* @since v22.0.0, v20.13.0
*/
readonly hasSubscribers: boolean;
}
}
declare module "diagnostics_channel" {
export * from "node:diagnostics_channel";
}

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

@@ -0,0 +1,922 @@
/**
* 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
* import dns from '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
* import dns from '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](https://nodejs.org/docs/latest-v25.x/api/dns.html#implementation-considerations) for more information.
* @see [source](https://github.com/nodejs/node/blob/v25.x/lib/dns.js)
*/
declare module "node:dns" {
// Supported getaddrinfo flags.
/**
* Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are
* only returned if the current system has at least one IPv4 address configured.
*/
const ADDRCONFIG: number;
/**
* If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported
* on some operating systems (e.g. FreeBSD 10.1).
*/
const V4MAPPED: number;
/**
* If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
* well as IPv4 mapped IPv6 addresses.
*/
const ALL: number;
interface LookupOptions {
/**
* The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted
* as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used
* with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned.
* @default 0
*/
family?: number | "IPv4" | "IPv6" | undefined;
/**
* One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v25.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be
* passed by bitwise `OR`ing their values.
*/
hints?: number | undefined;
/**
* When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address.
* @default false
*/
all?: boolean | undefined;
/**
* When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted
* by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6
* addresses before IPv4 addresses. Default value is configurable using
* {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--dns-result-orderorder).
* @default `verbatim` (addresses are not reordered)
* @since v22.1.0
*/
order?: "ipv4first" | "ipv6first" | "verbatim" | undefined;
/**
* When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4
* addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified,
* `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder}
* @default true (addresses are not reordered)
* @deprecated Please use `order` option
*/
verbatim?: boolean | undefined;
}
interface LookupOneOptions extends LookupOptions {
all?: false | undefined;
}
interface LookupAllOptions extends LookupOptions {
all: true;
}
interface LookupAddress {
/**
* A string representation of an IPv4 or IPv6 address.
*/
address: string;
/**
* `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a
* bug in the name resolution service used by the operating system.
*/
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](https://nodejs.org/docs/latest-v25.x/api/dns.html#implementation-considerations)
* before using `dns.lookup()`.
*
* Example usage:
*
* ```js
* import dns from '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()](https://nodejs.org/docs/latest-v25.x/api/util.html#utilpromisifyoriginal) 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
*/
function lookup(
hostname: string,
family: number,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
function lookup(
hostname: string,
options: LookupOneOptions,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
function lookup(
hostname: string,
options: LookupAllOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void,
): void;
function lookup(
hostname: string,
options: LookupOptions,
callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void,
): void;
function lookup(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
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`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) object,
* where `err.code` is the error code.
*
* ```js
* import dns from '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()](https://nodejs.org/docs/latest-v25.x/api/util.html#utilpromisifyoriginal) ed
* version, it returns a `Promise` for an `Object` with `hostname` and `service` properties.
* @since v0.11.14
*/
function lookupService(
address: string,
port: number,
callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void,
): void;
namespace lookupService {
function __promisify__(
address: string,
port: number,
): Promise<{
hostname: string;
service: string;
}>;
}
interface ResolveOptions {
ttl: boolean;
}
interface ResolveWithTtlOptions extends ResolveOptions {
ttl: true;
}
interface RecordWithTtl {
address: string;
ttl: number;
}
interface AnyARecord extends RecordWithTtl {
type: "A";
}
interface AnyAaaaRecord extends RecordWithTtl {
type: "AAAA";
}
interface CaaRecord {
critical: number;
issue?: string | undefined;
issuewild?: string | undefined;
iodef?: string | undefined;
contactemail?: string | undefined;
contactphone?: string | undefined;
}
interface AnyCaaRecord extends CaaRecord {
type: "CAA";
}
interface MxRecord {
priority: number;
exchange: string;
}
interface AnyMxRecord extends MxRecord {
type: "MX";
}
interface NaptrRecord {
flags: string;
service: string;
regexp: string;
replacement: string;
order: number;
preference: number;
}
interface AnyNaptrRecord extends NaptrRecord {
type: "NAPTR";
}
interface SoaRecord {
nsname: string;
hostmaster: string;
serial: number;
refresh: number;
retry: number;
expire: number;
minttl: number;
}
interface AnySoaRecord extends SoaRecord {
type: "SOA";
}
interface SrvRecord {
priority: number;
weight: number;
port: number;
name: string;
}
interface AnySrvRecord extends SrvRecord {
type: "SRV";
}
interface TlsaRecord {
certUsage: number;
selector: number;
match: number;
data: ArrayBuffer;
}
interface AnyTlsaRecord extends TlsaRecord {
type: "TLSA";
}
interface AnyTxtRecord {
type: "TXT";
entries: string[];
}
interface AnyNsRecord {
type: "NS";
value: string;
}
interface AnyPtrRecord {
type: "PTR";
value: string;
}
interface AnyCnameRecord {
type: "CNAME";
value: string;
}
type AnyRecord =
| AnyARecord
| AnyAaaaRecord
| AnyCaaRecord
| AnyCnameRecord
| AnyMxRecord
| AnyNaptrRecord
| AnyNsRecord
| AnyPtrRecord
| AnySoaRecord
| AnySrvRecord
| AnyTlsaRecord
| 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`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-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.
*/
function resolve(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
function resolve(
hostname: string,
rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
function resolve(
hostname: string,
rrtype: "ANY",
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
): void;
function resolve(
hostname: string,
rrtype: "CAA",
callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void,
): void;
function resolve(
hostname: string,
rrtype: "MX",
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
): void;
function resolve(
hostname: string,
rrtype: "NAPTR",
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
): void;
function resolve(
hostname: string,
rrtype: "SOA",
callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void,
): void;
function resolve(
hostname: string,
rrtype: "SRV",
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
): void;
function resolve(
hostname: string,
rrtype: "TLSA",
callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void,
): void;
function resolve(
hostname: string,
rrtype: "TXT",
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
): void;
function resolve(
hostname: string,
rrtype: string,
callback: (
err: NodeJS.ErrnoException | null,
addresses:
| string[]
| CaaRecord[]
| MxRecord[]
| NaptrRecord[]
| SoaRecord
| SrvRecord[]
| TlsaRecord[]
| string[][]
| AnyRecord[],
) => void,
): void;
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: "CAA"): Promise<CaaRecord[]>;
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: "TLSA"): Promise<TlsaRecord[]>;
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function __promisify__(
hostname: string,
rrtype: string,
): Promise<
| string[]
| CaaRecord[]
| MxRecord[]
| NaptrRecord[]
| SoaRecord
| SrvRecord[]
| TlsaRecord[]
| 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.
*/
function resolve4(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
function resolve4(
hostname: string,
options: ResolveWithTtlOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
): void;
function resolve4(
hostname: string,
options: ResolveOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
): void;
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.
*/
function resolve6(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
function resolve6(
hostname: string,
options: ResolveWithTtlOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
): void;
function resolve6(
hostname: string,
options: ResolveOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
): void;
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
*/
function resolveCname(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
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
*/
function resolveCaa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void,
): void;
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
*/
function resolveMx(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
): void;
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
*/
function resolveNaptr(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
): void;
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
*/
function resolveNs(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
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
*/
function resolvePtr(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
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
*/
function resolveSoa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void,
): void;
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
*/
function resolveSrv(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
): void;
namespace resolveSrv {
function __promisify__(hostname: string): Promise<SrvRecord[]>;
}
/**
* Uses the DNS protocol to resolve certificate associations (`TLSA` records) for
* the `hostname`. The `records` argument passed to the `callback` function is an
* array of objects with these properties:
*
* * `certUsage`
* * `selector`
* * `match`
* * `data`
*
* ```js
* {
* certUsage: 3,
* selector: 1,
* match: 1,
* data: [ArrayBuffer]
* }
* ```
* @since v23.9.0, v22.15.0
*/
function resolveTlsa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void,
): void;
namespace resolveTlsa {
function __promisify__(hostname: string): Promise<TlsaRecord[]>;
}
/**
* 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
*/
function resolveTxt(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
): void;
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).
*/
function resolveAny(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
): void;
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`](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) object, where `err.code` is
* one of the [DNS error codes](https://nodejs.org/docs/latest-v25.x/api/dns.html#error-codes).
* @since v0.1.16
*/
function reverse(
ip: string,
callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void,
): void;
/**
* Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnspromiseslookuphostname-options).
* The value could be:
*
* * `ipv4first`: for `order` defaulting to `ipv4first`.
* * `ipv6first`: for `order` defaulting to `ipv6first`.
* * `verbatim`: for `order` defaulting to `verbatim`.
* @since v18.17.0
*/
function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "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](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses
*/
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
*/
function getServers(): string[];
/**
* Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnspromiseslookuphostname-options).
* The value could be:
*
* * `ipv4first`: sets default `order` to `ipv4first`.
* * `ipv6first`: sets default `order` to `ipv6first`.
* * `verbatim`: sets default `order` to `verbatim`.
*
* The default is `verbatim` and {@link setDefaultResultOrder} have higher
* priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v25.x/api/cli.html#--dns-result-orderorder). When using
* [worker threads](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html), {@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'`, `'ipv6first'` or `'verbatim'`.
*/
function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void;
// Error codes
const NODATA: "ENODATA";
const FORMERR: "EFORMERR";
const SERVFAIL: "ESERVFAIL";
const NOTFOUND: "ENOTFOUND";
const NOTIMP: "ENOTIMP";
const REFUSED: "EREFUSED";
const BADQUERY: "EBADQUERY";
const BADNAME: "EBADNAME";
const BADFAMILY: "EBADFAMILY";
const BADRESP: "EBADRESP";
const CONNREFUSED: "ECONNREFUSED";
const TIMEOUT: "ETIMEOUT";
const EOF: "EOF";
const FILE: "EFILE";
const NOMEM: "ENOMEM";
const DESTRUCTION: "EDESTRUCTION";
const BADSTR: "EBADSTR";
const BADFLAGS: "EBADFLAGS";
const NONAME: "ENONAME";
const BADHINTS: "EBADHINTS";
const NOTINITIALIZED: "ENOTINITIALIZED";
const LOADIPHLPAPI: "ELOADIPHLPAPI";
const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS";
const CANCELLED: "ECANCELLED";
interface ResolverOptions {
/**
* Query timeout in milliseconds, or `-1` to use the default timeout.
*/
timeout?: number | undefined;
/**
* The number of tries the resolver will try contacting each name server before giving up.
* @default 4
*/
tries?: number | undefined;
/**
* The max retry timeout, in milliseconds.
* @default 0
*/
maxTimeout?: number | undefined;
}
/**
* 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()`](https://nodejs.org/docs/latest-v25.x/api/dns.html#dnssetserversservers) does not affect
* other resolvers:
*
* ```js
* import { Resolver } from '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
*/
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;
resolveTlsa: typeof resolveTlsa;
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;
}
}
declare module "node:dns" {
export * as promises from "node:dns/promises";
}
declare module "dns" {
export * from "node:dns";
}

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

@@ -0,0 +1,503 @@
/**
* 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 `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`.
* @since v10.6.0
*/
declare module "node:dns/promises" {
import {
AnyRecord,
CaaRecord,
LookupAddress,
LookupAllOptions,
LookupOneOptions,
LookupOptions,
MxRecord,
NaptrRecord,
RecordWithTtl,
ResolveOptions,
ResolverOptions,
ResolveWithTtlOptions,
SoaRecord,
SrvRecord,
TlsaRecord,
} 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`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-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()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) 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](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before
* using `dnsPromises.lookup()`.
*
* Example usage:
*
* ```js
* import dns from '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`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
*
* ```js
* import dnsPromises from 'node:dns';
* 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`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
* is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#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" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function resolve(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function resolve(hostname: string, rrtype: "TLSA"): Promise<TlsaRecord[]>;
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function resolve(hostname: string, rrtype: string): Promise<
| string[]
| CaaRecord[]
| MxRecord[]
| NaptrRecord[]
| SoaRecord
| SrvRecord[]
| TlsaRecord[]
| 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 certificate associations (`TLSA` records) for
* the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions
* with these properties:
*
* * `certUsage`
* * `selector`
* * `match`
* * `data`
*
* ```js
* {
* certUsage: 3,
* selector: 1,
* match: 1,
* data: [ArrayBuffer]
* }
* ```
* @since v23.9.0, v22.15.0
*/
function resolveTlsa(hostname: string): Promise<TlsaRecord[]>;
/**
* 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`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
* is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
* @since v10.6.0
*/
function reverse(ip: string): Promise<string[]>;
/**
* Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options).
* 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 `order` in `dns.lookup()` and `{@link lookup}`. The value could be:
*
* * `ipv4first`: sets default `order` to `ipv4first`.
* * `ipv6first`: sets default `order` to `ipv6first`.
* * `verbatim`: sets default `order` to `verbatim`.
*
* The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
* have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder).
* When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
* 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'`, `'ipv6first'` or `'verbatim'`.
*/
function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void;
// Error codes
const NODATA: "ENODATA";
const FORMERR: "EFORMERR";
const SERVFAIL: "ESERVFAIL";
const NOTFOUND: "ENOTFOUND";
const NOTIMP: "ENOTIMP";
const REFUSED: "EREFUSED";
const BADQUERY: "EBADQUERY";
const BADNAME: "EBADNAME";
const BADFAMILY: "EBADFAMILY";
const BADRESP: "EBADRESP";
const CONNREFUSED: "ECONNREFUSED";
const TIMEOUT: "ETIMEOUT";
const EOF: "EOF";
const FILE: "EFILE";
const NOMEM: "ENOMEM";
const DESTRUCTION: "EDESTRUCTION";
const BADSTR: "EBADSTR";
const BADFLAGS: "EBADFLAGS";
const NONAME: "ENONAME";
const BADHINTS: "EBADHINTS";
const NOTINITIALIZED: "ENOTINITIALIZED";
const LOADIPHLPAPI: "ELOADIPHLPAPI";
const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS";
const CANCELLED: "ECANCELLED";
/**
* 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()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect
* other resolvers:
*
* ```js
* import { promises } from 'node:dns';
* const resolver = new promises.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 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;
resolveTlsa: typeof resolveTlsa;
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;
}
}
declare module "dns/promises" {
export * from "node:dns/promises";
}

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

@@ -0,0 +1,166 @@
/**
* **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/v25.x/lib/domain.js)
*/
declare module "node:domain" {
import { EventEmitter } from "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 event emitters that have been explicitly added to the domain.
*/
members: EventEmitter[];
/**
* 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
* import domain from 'node:domain';
* import fs from '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.
*
* If the `EventEmitter` was already bound to a domain, it is removed from that
* one, and bound to this one instead.
* @param emitter emitter to be added to the domain
*/
add(emitter: EventEmitter): void;
/**
* The opposite of {@link add}. Removes domain handling from the
* specified emitter.
* @param emitter emitter to be removed from the domain
*/
remove(emitter: EventEmitter): 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 "domain" {
export * from "node:domain";
}

1047
backend/node_modules/@types/node/events.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

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

File diff suppressed because it is too large Load Diff

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

File diff suppressed because it is too large Load Diff

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

@@ -0,0 +1,150 @@
declare var global: typeof globalThis;
declare var process: NodeJS.Process;
interface ErrorConstructor {
/**
* Creates a `.stack` property on `targetObject`, which when accessed returns
* a string representing the location in the code at which
* `Error.captureStackTrace()` was called.
*
* ```js
* const myObject = {};
* Error.captureStackTrace(myObject);
* myObject.stack; // Similar to `new Error().stack`
* ```
*
* The first line of the trace will be prefixed with
* `${myObject.name}: ${myObject.message}`.
*
* The optional `constructorOpt` argument accepts a function. If given, all frames
* above `constructorOpt`, including `constructorOpt`, will be omitted from the
* generated stack trace.
*
* The `constructorOpt` argument is useful for hiding implementation
* details of error generation from the user. For instance:
*
* ```js
* function a() {
* b();
* }
*
* function b() {
* c();
* }
*
* function c() {
* // Create an error without stack trace to avoid calculating the stack trace twice.
* const { stackTraceLimit } = Error;
* Error.stackTraceLimit = 0;
* const error = new Error();
* Error.stackTraceLimit = stackTraceLimit;
*
* // Capture the stack trace above function b
* Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
* throw error;
* }
*
* a();
* ```
*/
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
/**
* The `Error.stackTraceLimit` property specifies the number of stack frames
* collected by a stack trace (whether generated by `new Error().stack` or
* `Error.captureStackTrace(obj)`).
*
* The default value is `10` but may be set to any valid JavaScript number. Changes
* will affect any stack trace captured _after_ the value has been changed.
*
* If set to a non-number value, or set to a negative number, stack traces will
* not capture any frames.
*/
stackTraceLimit: number;
}
/**
* Enable this API with the `--expose-gc` CLI flag.
*/
declare var gc: NodeJS.GCFunction | undefined;
declare namespace NodeJS {
interface CallSite {
getColumnNumber(): number | null;
getEnclosingColumnNumber(): number | null;
getEnclosingLineNumber(): number | null;
getEvalOrigin(): string | undefined;
getFileName(): string | null;
getFunction(): Function | undefined;
getFunctionName(): string | null;
getLineNumber(): number | null;
getMethodName(): string | null;
getPosition(): number;
getPromiseIndex(): number | null;
getScriptHash(): string;
getScriptNameOrSourceURL(): string | null;
getThis(): unknown;
getTypeName(): string | null;
isAsync(): boolean;
isConstructor(): boolean;
isEval(): boolean;
isNative(): boolean;
isPromiseAll(): boolean;
isToplevel(): boolean;
}
interface ErrnoException extends Error {
errno?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
}
interface RefCounted {
ref(): this;
unref(): this;
}
interface Dict<T> {
[key: string]: T | undefined;
}
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
type PartialOptions<T> = { [K in keyof T]?: T[K] | undefined };
interface GCFunction {
(minor?: boolean): void;
(options: NodeJS.GCOptions & { execution: "async" }): Promise<void>;
(options: NodeJS.GCOptions): void;
}
interface GCOptions {
execution?: "sync" | "async" | undefined;
flavor?: "regular" | "last-resort" | undefined;
type?: "major-snapshot" | "major" | "minor" | undefined;
filename?: string | undefined;
}
/** An iterable iterator returned by the Node.js API. */
interface Iterator<T, TReturn = undefined, TNext = any> extends IteratorObject<T, TReturn, TNext> {
[Symbol.iterator](): NodeJS.Iterator<T, TReturn, TNext>;
}
/** An async iterable iterator returned by the Node.js API. */
interface AsyncIterator<T, TReturn = undefined, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> {
[Symbol.asyncIterator](): NodeJS.AsyncIterator<T, TReturn, TNext>;
}
/** The [`BufferSource`](https://webidl.spec.whatwg.org/#BufferSource) type from the Web IDL specification. */
type BufferSource = NonSharedArrayBufferView | ArrayBuffer;
/** The [`AllowSharedBufferSource`](https://webidl.spec.whatwg.org/#AllowSharedBufferSource) type from the Web IDL specification. */
type AllowSharedBufferSource = ArrayBufferView | ArrayBufferLike;
}

View File

@@ -0,0 +1,101 @@
export {}; // Make this a module
declare global {
namespace NodeJS {
type TypedArray<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
| Uint8Array<TArrayBuffer>
| Uint8ClampedArray<TArrayBuffer>
| Uint16Array<TArrayBuffer>
| Uint32Array<TArrayBuffer>
| Int8Array<TArrayBuffer>
| Int16Array<TArrayBuffer>
| Int32Array<TArrayBuffer>
| BigUint64Array<TArrayBuffer>
| BigInt64Array<TArrayBuffer>
| Float16Array<TArrayBuffer>
| Float32Array<TArrayBuffer>
| Float64Array<TArrayBuffer>;
type ArrayBufferView<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
| TypedArray<TArrayBuffer>
| DataView<TArrayBuffer>;
// The following aliases are required to allow use of non-shared ArrayBufferViews in @types/node
// while maintaining compatibility with TS <=5.6.
// TODO: remove once @types/node no longer supports TS 5.6, and replace with native types.
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedUint8Array = Uint8Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedUint8ClampedArray = Uint8ClampedArray<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedUint16Array = Uint16Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedUint32Array = Uint32Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedInt8Array = Int8Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedInt16Array = Int16Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedInt32Array = Int32Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedBigUint64Array = BigUint64Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedBigInt64Array = BigInt64Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedFloat16Array = Float16Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedFloat32Array = Float32Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedFloat64Array = Float64Array<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedDataView = DataView<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedTypedArray = TypedArray<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedArrayBufferView = ArrayBufferView<ArrayBuffer>;
}
}

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

File diff suppressed because it is too large Load Diff

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

File diff suppressed because it is too large Load Diff

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

@@ -0,0 +1,405 @@
/**
* 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/v25.x/lib/https.js)
*/
declare module "node:https" {
import * as http from "node:http";
import { Duplex } from "node:stream";
import * as tls from "node:tls";
import { URL } from "node:url";
interface ServerOptions<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends http.ServerOptions<Request, Response>, tls.TlsOptions {}
interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions {
checkServerIdentity?:
| ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined)
| undefined;
rejectUnauthorized?: boolean | undefined; // Defaults to true
servername?: string | undefined; // SNI TLS Extension
}
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
maxCachedSessions?: number | undefined;
}
/**
* An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information.
*
* Like `http.Agent`, the `createConnection(options[, callback])` method can be overridden
* to customize how TLS connections are established.
*
* > See `agent.createConnection()` for details on overriding this method,
* > including asynchronous socket creation with a callback.
* @since v0.4.5
*/
class Agent extends http.Agent {
constructor(options?: AgentOptions);
options: AgentOptions;
createConnection(
options: RequestOptions,
callback?: (err: Error | null, stream: Duplex) => void,
): Duplex | null | undefined;
getName(options?: RequestOptions): string;
}
interface ServerEventMap<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends http.ServerEventMap<Request, Response>, tls.ServerEventMap {}
/**
* 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<InstanceType<Request>> = 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;
// #region InternalEventEmitter
addListener<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
emit<E extends keyof ServerEventMap>(eventName: E, ...args: ServerEventMap<Request, Response>[E]): boolean;
emit(eventName: string | symbol, ...args: any[]): boolean;
listenerCount<E extends keyof ServerEventMap>(
eventName: E,
listener?: (...args: ServerEventMap<Request, Response>[E]) => void,
): number;
listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number;
listeners<E extends keyof ServerEventMap>(
eventName: E,
): ((...args: ServerEventMap<Request, Response>[E]) => void)[];
listeners(eventName: string | symbol): ((...args: any[]) => void)[];
off<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
off(eventName: string | symbol, listener: (...args: any[]) => void): this;
on<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
on(eventName: string | symbol, listener: (...args: any[]) => void): this;
once<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
prependListener<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
rawListeners<E extends keyof ServerEventMap>(
eventName: E,
): ((...args: ServerEventMap<Request, Response>[E]) => void)[];
rawListeners(eventName: string | symbol): ((...args: any[]) => void)[];
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
removeAllListeners<E extends keyof ServerEventMap>(eventName?: E): this;
removeAllListeners(eventName?: string | symbol): this;
removeListener<E extends keyof ServerEventMap>(
eventName: E,
listener: (...args: ServerEventMap<Request, Response>[E]) => void,
): this;
removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
// #endregion
}
interface Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> extends http.Server<Request, Response> {}
/**
* ```js
* // curl -k https://localhost:8000/
* import https from 'node:https';
* import fs from '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
* import https from 'node:https';
* import fs from '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<InstanceType<Request>> = 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<InstanceType<Request>> = 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
* import https from '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
* import tls from 'node:tls';
* import https from 'node:https';
* import crypto from '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
* import https from '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 "https" {
export * from "node:https";
}

115
backend/node_modules/@types/node/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,115 @@
/**
* License for programmatically and manually incorporated
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc
*
* Copyright Node.js contributors. All rights reserved.
* 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.
*/
// NOTE: These definitions support Node.js and TypeScript 5.8+.
// Reference required TypeScript libraries:
/// <reference lib="es2020" />
/// <reference lib="esnext.disposable" />
/// <reference lib="esnext.float16" />
// Iterator definitions required for compatibility with TypeScript <5.6:
/// <reference path="compatibility/iterators.d.ts" />
// Definitions for Node.js modules specific to TypeScript 5.7+:
/// <reference path="globals.typedarray.d.ts" />
/// <reference path="buffer.buffer.d.ts" />
// Definitions for Node.js modules that are not specific to any version of TypeScript:
/// <reference path="globals.d.ts" />
/// <reference path="web-globals/abortcontroller.d.ts" />
/// <reference path="web-globals/blob.d.ts" />
/// <reference path="web-globals/console.d.ts" />
/// <reference path="web-globals/crypto.d.ts" />
/// <reference path="web-globals/domexception.d.ts" />
/// <reference path="web-globals/encoding.d.ts" />
/// <reference path="web-globals/events.d.ts" />
/// <reference path="web-globals/fetch.d.ts" />
/// <reference path="web-globals/importmeta.d.ts" />
/// <reference path="web-globals/messaging.d.ts" />
/// <reference path="web-globals/navigator.d.ts" />
/// <reference path="web-globals/performance.d.ts" />
/// <reference path="web-globals/storage.d.ts" />
/// <reference path="web-globals/streams.d.ts" />
/// <reference path="web-globals/timers.d.ts" />
/// <reference path="web-globals/url.d.ts" />
/// <reference path="assert.d.ts" />
/// <reference path="assert/strict.d.ts" />
/// <reference path="async_hooks.d.ts" />
/// <reference path="buffer.d.ts" />
/// <reference path="child_process.d.ts" />
/// <reference path="cluster.d.ts" />
/// <reference path="console.d.ts" />
/// <reference path="constants.d.ts" />
/// <reference path="crypto.d.ts" />
/// <reference path="dgram.d.ts" />
/// <reference path="diagnostics_channel.d.ts" />
/// <reference path="dns.d.ts" />
/// <reference path="dns/promises.d.ts" />
/// <reference path="domain.d.ts" />
/// <reference path="events.d.ts" />
/// <reference path="fs.d.ts" />
/// <reference path="fs/promises.d.ts" />
/// <reference path="http.d.ts" />
/// <reference path="http2.d.ts" />
/// <reference path="https.d.ts" />
/// <reference path="inspector.d.ts" />
/// <reference path="inspector.generated.d.ts" />
/// <reference path="inspector/promises.d.ts" />
/// <reference path="module.d.ts" />
/// <reference path="net.d.ts" />
/// <reference path="os.d.ts" />
/// <reference path="path.d.ts" />
/// <reference path="path/posix.d.ts" />
/// <reference path="path/win32.d.ts" />
/// <reference path="perf_hooks.d.ts" />
/// <reference path="process.d.ts" />
/// <reference path="punycode.d.ts" />
/// <reference path="querystring.d.ts" />
/// <reference path="quic.d.ts" />
/// <reference path="readline.d.ts" />
/// <reference path="readline/promises.d.ts" />
/// <reference path="repl.d.ts" />
/// <reference path="sea.d.ts" />
/// <reference path="sqlite.d.ts" />
/// <reference path="stream.d.ts" />
/// <reference path="stream/consumers.d.ts" />
/// <reference path="stream/promises.d.ts" />
/// <reference path="stream/web.d.ts" />
/// <reference path="string_decoder.d.ts" />
/// <reference path="test.d.ts" />
/// <reference path="test/reporters.d.ts" />
/// <reference path="timers.d.ts" />
/// <reference path="timers/promises.d.ts" />
/// <reference path="tls.d.ts" />
/// <reference path="trace_events.d.ts" />
/// <reference path="tty.d.ts" />
/// <reference path="url.d.ts" />
/// <reference path="util.d.ts" />
/// <reference path="util/types.d.ts" />
/// <reference path="v8.d.ts" />
/// <reference path="vm.d.ts" />
/// <reference path="wasi.d.ts" />
/// <reference path="worker_threads.d.ts" />
/// <reference path="zlib.d.ts" />

269
backend/node_modules/@types/node/inspector.d.ts generated vendored Normal file
View File

@@ -0,0 +1,269 @@
/**
* The `node:inspector` module provides an API for interacting with the V8
* inspector.
* @see [source](https://github.com/nodejs/node/blob/v25.x/lib/inspector.js)
*/
declare module "node:inspector" {
import { EventEmitter } from "node:events";
/**
* The `inspector.Session` is used for dispatching messages to the V8 inspector
* back-end and receiving message responses and notifications.
*/
class Session extends EventEmitter {
/**
* Create a new instance of the inspector.Session class.
* The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend.
*/
constructor();
/**
* Connects a session to the inspector back-end.
*/
connect(): void;
/**
* Connects a session to the inspector back-end.
* An exception will be thrown if this API was not called on a Worker thread.
* @since v12.11.0
*/
connectToMainThread(): void;
/**
* Immediately close the session. All pending message callbacks will be called with an error.
* `session.connect()` will need to be called to be able to send messages again.
* Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.
*/
disconnect(): void;
}
/**
* Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has
* started.
*
* If wait is `true`, will block until a client has connected to the inspect port
* and flow control has been passed to the debugger client.
*
* See the [security warning](https://nodejs.org/docs/latest-v25.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure)
* regarding the `host` parameter usage.
* @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI.
* @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI.
* @param wait Block until a client has connected. Defaults to what was specified on the CLI.
* @returns Disposable that calls `inspector.close()`.
*/
function open(port?: number, host?: string, wait?: boolean): Disposable;
/**
* Deactivate the inspector. Blocks until there are no active connections.
*/
function close(): void;
/**
* Return the URL of the active inspector, or `undefined` if there is none.
*
* ```console
* $ node --inspect -p 'inspector.url()'
* Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
* For help, see: https://nodejs.org/en/docs/inspector
* ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
*
* $ node --inspect=localhost:3000 -p 'inspector.url()'
* Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
* For help, see: https://nodejs.org/en/docs/inspector
* ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
*
* $ node -p 'inspector.url()'
* undefined
* ```
*/
function url(): string | undefined;
/**
* Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command.
*
* An exception will be thrown if there is no active inspector.
* @since v12.7.0
*/
function waitForDebugger(): void;
// These methods are exposed by the V8 inspector console API (inspector/v8-console.h).
// The method signatures differ from those of the Node.js console, and are deliberately
// typed permissively.
interface InspectorConsole {
debug(...data: any[]): void;
error(...data: any[]): void;
info(...data: any[]): void;
log(...data: any[]): void;
warn(...data: any[]): void;
dir(...data: any[]): void;
dirxml(...data: any[]): void;
table(...data: any[]): void;
trace(...data: any[]): void;
group(...data: any[]): void;
groupCollapsed(...data: any[]): void;
groupEnd(...data: any[]): void;
clear(...data: any[]): void;
count(label?: any): void;
countReset(label?: any): void;
assert(value?: any, ...data: any[]): void;
profile(label?: any): void;
profileEnd(label?: any): void;
time(label?: any): void;
timeLog(label?: any): void;
timeStamp(label?: any): void;
}
/**
* An object to send messages to the remote inspector console.
* @since v11.0.0
*/
const console: InspectorConsole;
// DevTools protocol event broadcast methods
namespace Network {
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that
* the application is about to send an HTTP request.
* @since v22.6.0
*/
function requestWillBeSent(params: RequestWillBeSentEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if
* `Network.streamResourceContent` command was not invoked for the given request yet.
*
* Also enables `Network.getResponseBody` command to retrieve the response data.
* @since v24.2.0
*/
function dataReceived(params: DataReceivedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Enables `Network.getRequestPostData` command to retrieve the request data.
* @since v24.3.0
*/
function dataSent(params: unknown): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that
* HTTP response is available.
* @since v22.6.0
*/
function responseReceived(params: ResponseReceivedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that
* HTTP request has finished loading.
* @since v22.6.0
*/
function loadingFinished(params: LoadingFinishedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that
* HTTP request has failed to load.
* @since v22.7.0
*/
function loadingFailed(params: LoadingFailedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.webSocketCreated` event to connected frontends. This event indicates that
* a WebSocket connection has been initiated.
* @since v24.7.0
*/
function webSocketCreated(params: WebSocketCreatedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.webSocketHandshakeResponseReceived` event to connected frontends.
* This event indicates that the WebSocket handshake response has been received.
* @since v24.7.0
*/
function webSocketHandshakeResponseReceived(params: WebSocketHandshakeResponseReceivedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.webSocketClosed` event to connected frontends.
* This event indicates that a WebSocket connection has been closed.
* @since v24.7.0
*/
function webSocketClosed(params: WebSocketClosedEventDataType): void;
}
namespace NetworkResources {
/**
* This feature is only available with the `--experimental-inspector-network-resource` flag enabled.
*
* The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource
* request issued via the Chrome DevTools Protocol (CDP).
* This is typically triggered when a source map is specified by URL, and a DevTools frontend—such as
* Chrome—requests the resource to retrieve the source map.
*
* This method allows developers to predefine the resource content to be served in response to such CDP requests.
*
* ```js
* const inspector = require('node:inspector');
* // By preemptively calling put to register the resource, a source map can be resolved when
* // a loadNetworkResource request is made from the frontend.
* async function setNetworkResources() {
* const mapUrl = 'http://localhost:3000/dist/app.js.map';
* const tsUrl = 'http://localhost:3000/src/app.ts';
* const distAppJsMap = await fetch(mapUrl).then((res) => res.text());
* const srcAppTs = await fetch(tsUrl).then((res) => res.text());
* inspector.NetworkResources.put(mapUrl, distAppJsMap);
* inspector.NetworkResources.put(tsUrl, srcAppTs);
* };
* setNetworkResources().then(() => {
* require('./dist/app');
* });
* ```
*
* For more details, see the official CDP documentation: [Network.loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-loadNetworkResource)
* @since v24.5.0
* @experimental
*/
function put(url: string, data: string): void;
}
namespace DOMStorage {
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
*
* Broadcasts the `DOMStorage.domStorageItemAdded` event to connected frontends.
* This event indicates that a new item has been added to the storage.
* @since v25.5.0
*/
function domStorageItemAdded(params: DomStorageItemAddedEventDataType): void;
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
*
* Broadcasts the `DOMStorage.domStorageItemRemoved` event to connected frontends.
* This event indicates that an item has been removed from the storage.
* @since v25.5.0
*/
function domStorageItemRemoved(params: DomStorageItemRemovedEventDataType): void;
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
* Broadcasts the `DOMStorage.domStorageItemUpdated` event to connected frontends.
* This event indicates that a storage item has been updated.
* @since v25.5.0
*/
function domStorageItemUpdated(params: DomStorageItemUpdatedEventDataType): void;
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
*
* Broadcasts the `DOMStorage.domStorageItemsCleared` event to connected
* frontends. This event indicates that all items have been cleared from the
* storage.
* @since v25.5.0
*/
function domStorageItemsCleared(params: DomStorageItemsClearedEventDataType): void;
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
* @since v25.5.0
*/
function registerStorage(params: unknown): void;
}
}
declare module "inspector" {
export * from "node:inspector";
}

4401
backend/node_modules/@types/node/inspector.generated.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,41 @@
/**
* The `node:inspector/promises` module provides an API for interacting with the V8
* inspector.
* @see [source](https://github.com/nodejs/node/blob/v25.x/lib/inspector/promises.js)
* @since v19.0.0
*/
declare module "node:inspector/promises" {
import { EventEmitter } from "node:events";
export { close, console, NetworkResources, open, url, waitForDebugger } from "node:inspector";
/**
* The `inspector.Session` is used for dispatching messages to the V8 inspector
* back-end and receiving message responses and notifications.
* @since v19.0.0
*/
export class Session extends EventEmitter {
/**
* Create a new instance of the inspector.Session class.
* The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend.
*/
constructor();
/**
* Connects a session to the inspector back-end.
*/
connect(): void;
/**
* Connects a session to the inspector back-end.
* An exception will be thrown if this API was not called on a Worker thread.
* @since v12.11.0
*/
connectToMainThread(): void;
/**
* Immediately close the session. All pending message callbacks will be called with an error.
* `session.connect()` will need to be called to be able to send messages again.
* Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.
*/
disconnect(): void;
}
}
declare module "inspector/promises" {
export * from "node:inspector/promises";
}

757
backend/node_modules/@types/node/module.d.ts generated vendored Normal file
View File

@@ -0,0 +1,757 @@
/**
* @since v0.3.7
*/
declare module "node:module" {
import { URL } from "node:url";
class Module {
constructor(id: string, parent?: Module);
}
interface Module extends NodeJS.Module {}
namespace Module {
export { Module };
}
namespace Module {
/**
* A list of the names of all modules provided by Node.js. Can be used to verify
* if a module is maintained by a third party or not.
*
* Note: the list doesn't contain prefix-only modules like `node:test`.
* @since v9.3.0, v8.10.0, v6.13.0
*/
const builtinModules: readonly string[];
/**
* @since v12.2.0
* @param path Filename to be used to construct the require
* function. Must be a file URL object, file URL string, or absolute path
* string.
*/
function createRequire(path: string | URL): NodeJS.Require;
namespace constants {
/**
* The following constants are returned as the `status` field in the object returned by
* {@link enableCompileCache} to indicate the result of the attempt to enable the
* [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache).
* @since v22.8.0
*/
namespace compileCacheStatus {
/**
* Node.js has enabled the compile cache successfully. The directory used to store the
* compile cache will be returned in the `directory` field in the
* returned object.
*/
const ENABLED: number;
/**
* The compile cache has already been enabled before, either by a previous call to
* {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir`
* environment variable. The directory used to store the
* compile cache will be returned in the `directory` field in the
* returned object.
*/
const ALREADY_ENABLED: number;
/**
* Node.js fails to enable the compile cache. This can be caused by the lack of
* permission to use the specified directory, or various kinds of file system errors.
* The detail of the failure will be returned in the `message` field in the
* returned object.
*/
const FAILED: number;
/**
* Node.js cannot enable the compile cache because the environment variable
* `NODE_DISABLE_COMPILE_CACHE=1` has been set.
*/
const DISABLED: number;
}
}
interface EnableCompileCacheOptions {
/**
* Optional. Directory to store the compile cache. If not specified,
* the directory specified by the `NODE_COMPILE_CACHE=dir` environment variable
* will be used if it's set, or `path.join(os.tmpdir(), 'node-compile-cache')`
* otherwise.
* @since v25.0.0
*/
directory?: string | undefined;
/**
* Optional. If `true`, enables portable compile cache so that
* the cache can be reused even if the project directory is moved. This is a best-effort
* feature. If not specified, it will depend on whether the environment variable
* `NODE_COMPILE_CACHE_PORTABLE=1` is set.
* @since v25.0.0
*/
portable?: boolean | undefined;
}
interface EnableCompileCacheResult {
/**
* One of the {@link constants.compileCacheStatus}
*/
status: number;
/**
* If Node.js cannot enable the compile cache, this contains
* the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`.
*/
message?: string;
/**
* If the compile cache is enabled, this contains the directory
* where the compile cache is stored. Only set if `status` is
* `module.constants.compileCacheStatus.ENABLED` or
* `module.constants.compileCacheStatus.ALREADY_ENABLED`.
*/
directory?: string;
}
/**
* Enable [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache)
* in the current Node.js instance.
*
* For general use cases, it's recommended to call `module.enableCompileCache()` without
* specifying the `options.directory`, so that the directory can be overridden by the
* `NODE_COMPILE_CACHE` environment variable when necessary.
*
* Since compile cache is supposed to be a optimization that is not mission critical, this
* method is designed to not throw any exception when the compile cache cannot be enabled.
* Instead, it will return an object containing an error message in the `message` field to
* aid debugging. If compile cache is enabled successfully, the `directory` field in the
* returned object contains the path to the directory where the compile cache is stored. The
* `status` field in the returned object would be one of the `module.constants.compileCacheStatus`
* values to indicate the result of the attempt to enable the
* [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache).
*
* This method only affects the current Node.js instance. To enable it in child worker threads,
* either call this method in child worker threads too, or set the
* `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can
* be inherited into the child workers. The directory can be obtained either from the
* `directory` field returned by this method, or with {@link getCompileCacheDir}.
* @since v22.8.0
* @param options Optional. If a string is passed, it is considered to be `options.directory`.
*/
function enableCompileCache(options?: string | EnableCompileCacheOptions): EnableCompileCacheResult;
/**
* Flush the [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache)
* accumulated from modules already loaded
* in the current Node.js instance to disk. This returns after all the flushing
* file system operations come to an end, no matter they succeed or not. If there
* are any errors, this will fail silently, since compile cache misses should not
* interfere with the actual operation of the application.
* @since v22.10.0
*/
function flushCompileCache(): void;
/**
* @since v22.8.0
* @return Path to the [module compile cache](https://nodejs.org/docs/latest-v25.x/api/module.html#module-compile-cache)
* directory if it is enabled, or `undefined` otherwise.
*/
function getCompileCacheDir(): string | undefined;
/**
* ```text
* /path/to/project
* ├ packages/
* ├ bar/
* ├ bar.js
* └ package.json // name = '@foo/bar'
* └ qux/
* ├ node_modules/
* └ some-package/
* └ package.json // name = 'some-package'
* ├ qux.js
* └ package.json // name = '@foo/qux'
* ├ main.js
* └ package.json // name = '@foo'
* ```
* ```js
* // /path/to/project/packages/bar/bar.js
* import { findPackageJSON } from 'node:module';
*
* findPackageJSON('..', import.meta.url);
* // '/path/to/project/package.json'
* // Same result when passing an absolute specifier instead:
* findPackageJSON(new URL('../', import.meta.url));
* findPackageJSON(import.meta.resolve('../'));
*
* findPackageJSON('some-package', import.meta.url);
* // '/path/to/project/packages/bar/node_modules/some-package/package.json'
* // When passing an absolute specifier, you might get a different result if the
* // resolved module is inside a subfolder that has nested `package.json`.
* findPackageJSON(import.meta.resolve('some-package'));
* // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'
*
* findPackageJSON('@foo/qux', import.meta.url);
* // '/path/to/project/packages/qux/package.json'
* ```
* @since v22.14.0
* @param specifier The specifier for the module whose `package.json` to
* retrieve. When passing a _bare specifier_, the `package.json` at the root of
* the package is returned. When passing a _relative specifier_ or an _absolute specifier_,
* the closest parent `package.json` is returned.
* @param base The absolute location (`file:` URL string or FS path) of the
* containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use
* `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_.
* @returns A path if the `package.json` is found. When `startLocation`
* is a package, the package's root `package.json`; when a relative or unresolved, the closest
* `package.json` to the `startLocation`.
*/
function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined;
/**
* @since v18.6.0, v16.17.0
*/
function isBuiltin(moduleName: string): boolean;
interface RegisterOptions<Data> {
/**
* If you want to resolve `specifier` relative to a
* base URL, such as `import.meta.url`, you can pass that URL here. This
* property is ignored if the `parentURL` is supplied as the second argument.
* @default 'data:'
*/
parentURL?: string | URL | undefined;
/**
* Any arbitrary, cloneable JavaScript value to pass into the
* {@link initialize} hook.
*/
data?: Data | undefined;
/**
* [Transferable objects](https://nodejs.org/docs/latest-v25.x/api/worker_threads.html#portpostmessagevalue-transferlist)
* to be passed into the `initialize` hook.
*/
transferList?: any[] | undefined;
}
/* eslint-disable @definitelytyped/no-unnecessary-generics */
/**
* Register a module that exports hooks that customize Node.js module
* resolution and loading behavior. See
* [Customization hooks](https://nodejs.org/docs/latest-v25.x/api/module.html#customization-hooks).
*
* This feature requires `--allow-worker` if used with the
* [Permission Model](https://nodejs.org/docs/latest-v25.x/api/permissions.html#permission-model).
* @since v20.6.0, v18.19.0
* @param specifier Customization hooks to be registered; this should be
* the same string that would be passed to `import()`, except that if it is
* relative, it is resolved relative to `parentURL`.
* @param parentURL f you want to resolve `specifier` relative to a base
* URL, such as `import.meta.url`, you can pass that URL here.
*/
function register<Data = any>(
specifier: string | URL,
parentURL?: string | URL,
options?: RegisterOptions<Data>,
): void;
function register<Data = any>(specifier: string | URL, options?: RegisterOptions<Data>): void;
interface RegisterHooksOptions {
/**
* See [load hook](https://nodejs.org/docs/latest-v25.x/api/module.html#loadurl-context-nextload).
* @default undefined
*/
load?: LoadHookSync | undefined;
/**
* See [resolve hook](https://nodejs.org/docs/latest-v25.x/api/module.html#resolvespecifier-context-nextresolve).
* @default undefined
*/
resolve?: ResolveHookSync | undefined;
}
interface ModuleHooks {
/**
* Deregister the hook instance.
*/
deregister(): void;
}
/**
* Register [hooks](https://nodejs.org/docs/latest-v25.x/api/module.html#customization-hooks)
* that customize Node.js module resolution and loading behavior.
* @since v22.15.0
* @experimental
*/
function registerHooks(options: RegisterHooksOptions): ModuleHooks;
interface StripTypeScriptTypesOptions {
/**
* Possible values are:
* * `'strip'` Only strip type annotations without performing the transformation of TypeScript features.
* * `'transform'` Strip type annotations and transform TypeScript features to JavaScript.
* @default 'strip'
*/
mode?: "strip" | "transform" | undefined;
/**
* Only when `mode` is `'transform'`, if `true`, a source map
* will be generated for the transformed code.
* @default false
*/
sourceMap?: boolean | undefined;
/**
* Specifies the source url used in the source map.
*/
sourceUrl?: string | undefined;
}
/**
* `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It
* can be used to strip type annotations from TypeScript code before running it
* with `vm.runInContext()` or `vm.compileFunction()`.
* By default, it will throw an error if the code contains TypeScript features
* that require transformation such as `Enums`,
* see [type-stripping](https://nodejs.org/docs/latest-v25.x/api/typescript.md#type-stripping) for more information.
* When mode is `'transform'`, it also transforms TypeScript features to JavaScript,
* see [transform TypeScript features](https://nodejs.org/docs/latest-v25.x/api/typescript.md#typescript-features) for more information.
* When mode is `'strip'`, source maps are not generated, because locations are preserved.
* If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown.
*
* _WARNING_: The output of this function should not be considered stable across Node.js versions,
* due to changes in the TypeScript parser.
*
* ```js
* import { stripTypeScriptTypes } from 'node:module';
* const code = 'const a: number = 1;';
* const strippedCode = stripTypeScriptTypes(code);
* console.log(strippedCode);
* // Prints: const a = 1;
* ```
*
* If `sourceUrl` is provided, it will be used appended as a comment at the end of the output:
*
* ```js
* import { stripTypeScriptTypes } from 'node:module';
* const code = 'const a: number = 1;';
* const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
* console.log(strippedCode);
* // Prints: const a = 1\n\n//# sourceURL=source.ts;
* ```
*
* When `mode` is `'transform'`, the code is transformed to JavaScript:
*
* ```js
* import { stripTypeScriptTypes } from 'node:module';
* const code = `
* namespace MathUtil {
* export const add = (a: number, b: number) => a + b;
* }`;
* const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });
* console.log(strippedCode);
* // Prints:
* // var MathUtil;
* // (function(MathUtil) {
* // MathUtil.add = (a, b)=>a + b;
* // })(MathUtil || (MathUtil = {}));
* // # sourceMappingURL=data:application/json;base64, ...
* ```
* @since v22.13.0
* @param code The code to strip type annotations from.
* @returns The code with type annotations stripped.
*/
function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string;
/* eslint-enable @definitelytyped/no-unnecessary-generics */
/**
* The `module.syncBuiltinESMExports()` method updates all the live bindings for
* builtin `ES Modules` to match the properties of the `CommonJS` exports. It
* does not add or remove exported names from the `ES Modules`.
*
* ```js
* import fs from 'node:fs';
* import assert from 'node:assert';
* import { syncBuiltinESMExports } from 'node:module';
*
* fs.readFile = newAPI;
*
* delete fs.readFileSync;
*
* function newAPI() {
* // ...
* }
*
* fs.newAPI = newAPI;
*
* syncBuiltinESMExports();
*
* import('node:fs').then((esmFS) => {
* // It syncs the existing readFile property with the new value
* assert.strictEqual(esmFS.readFile, newAPI);
* // readFileSync has been deleted from the required fs
* assert.strictEqual('readFileSync' in fs, false);
* // syncBuiltinESMExports() does not remove readFileSync from esmFS
* assert.strictEqual('readFileSync' in esmFS, true);
* // syncBuiltinESMExports() does not add names
* assert.strictEqual(esmFS.newAPI, undefined);
* });
* ```
* @since v12.12.0
*/
function syncBuiltinESMExports(): void;
interface ImportAttributes extends NodeJS.Dict<string> {
type?: string | undefined;
}
type ImportPhase = "source" | "evaluation";
type ModuleFormat =
| "addon"
| "builtin"
| "commonjs"
| "commonjs-typescript"
| "json"
| "module"
| "module-typescript"
| "wasm";
type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray;
type InitializeHook<Data = any> = (data: Data) => void | Promise<void>;
interface ResolveHookContext {
conditions: string[];
importAttributes: ImportAttributes;
parentURL: string | undefined;
}
interface ResolveFnOutput {
format?: string | null | undefined;
importAttributes?: ImportAttributes | undefined;
shortCircuit?: boolean | undefined;
url: string;
}
type ResolveHook = (
specifier: string,
context: ResolveHookContext,
nextResolve: (
specifier: string,
context?: Partial<ResolveHookContext>,
) => ResolveFnOutput | Promise<ResolveFnOutput>,
) => ResolveFnOutput | Promise<ResolveFnOutput>;
type ResolveHookSync = (
specifier: string,
context: ResolveHookContext,
nextResolve: (
specifier: string,
context?: Partial<ResolveHookContext>,
) => ResolveFnOutput,
) => ResolveFnOutput;
interface LoadHookContext {
conditions: string[];
format: string | null | undefined;
importAttributes: ImportAttributes;
}
interface LoadFnOutput {
format: string | null | undefined;
shortCircuit?: boolean | undefined;
source?: ModuleSource | undefined;
}
type LoadHook = (
url: string,
context: LoadHookContext,
nextLoad: (
url: string,
context?: Partial<LoadHookContext>,
) => LoadFnOutput | Promise<LoadFnOutput>,
) => LoadFnOutput | Promise<LoadFnOutput>;
type LoadHookSync = (
url: string,
context: LoadHookContext,
nextLoad: (
url: string,
context?: Partial<LoadHookContext>,
) => LoadFnOutput,
) => LoadFnOutput;
interface SourceMapsSupport {
/**
* If the source maps support is enabled
*/
enabled: boolean;
/**
* If the support is enabled for files in `node_modules`.
*/
nodeModules: boolean;
/**
* If the support is enabled for generated code from `eval` or `new Function`.
*/
generatedCode: boolean;
}
/**
* This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack
* traces is enabled.
* @since v23.7.0, v22.14.0
*/
function getSourceMapsSupport(): SourceMapsSupport;
/**
* `path` is the resolved path for the file for which a corresponding source map
* should be fetched.
* @since v13.7.0, v12.17.0
* @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise.
*/
function findSourceMap(path: string): SourceMap | undefined;
interface SetSourceMapsSupportOptions {
/**
* If enabling the support for files in `node_modules`.
* @default false
*/
nodeModules?: boolean | undefined;
/**
* If enabling the support for generated code from `eval` or `new Function`.
* @default false
*/
generatedCode?: boolean | undefined;
}
/**
* This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for
* stack traces.
*
* It provides same features as launching Node.js process with commandline options
* `--enable-source-maps`, with additional options to alter the support for files
* in `node_modules` or generated codes.
*
* Only source maps in JavaScript files that are loaded after source maps has been
* enabled will be parsed and loaded. Preferably, use the commandline options
* `--enable-source-maps` to avoid losing track of source maps of modules loaded
* before this API call.
* @since v23.7.0, v22.14.0
*/
function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void;
interface SourceMapConstructorOptions {
/**
* @since v21.0.0, v20.5.0
*/
lineLengths?: readonly number[] | undefined;
}
interface SourceMapPayload {
file: string;
version: number;
sources: string[];
sourcesContent: string[];
names: string[];
mappings: string;
sourceRoot: string;
}
interface SourceMapping {
generatedLine: number;
generatedColumn: number;
originalSource: string;
originalLine: number;
originalColumn: number;
}
interface SourceOrigin {
/**
* The name of the range in the source map, if one was provided
*/
name: string | undefined;
/**
* The file name of the original source, as reported in the SourceMap
*/
fileName: string;
/**
* The 1-indexed lineNumber of the corresponding call site in the original source
*/
lineNumber: number;
/**
* The 1-indexed columnNumber of the corresponding call site in the original source
*/
columnNumber: number;
}
/**
* @since v13.7.0, v12.17.0
*/
class SourceMap {
constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions);
/**
* Getter for the payload used to construct the `SourceMap` instance.
*/
readonly payload: SourceMapPayload;
/**
* Given a line offset and column offset in the generated source
* file, returns an object representing the SourceMap range in the
* original file if found, or an empty object if not.
*
* The object returned contains the following keys:
*
* The returned value represents the raw range as it appears in the
* SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and
* column numbers as they appear in Error messages and CallSite
* objects.
*
* To get the corresponding 1-indexed line and column numbers from a
* lineNumber and columnNumber as they are reported by Error stacks
* and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)`
* @param lineOffset The zero-indexed line number offset in the generated source
* @param columnOffset The zero-indexed column number offset in the generated source
*/
findEntry(lineOffset: number, columnOffset: number): SourceMapping | {};
/**
* Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source,
* find the corresponding call site location in the original source.
*
* If the `lineNumber` and `columnNumber` provided are not found in any source map,
* then an empty object is returned.
* @param lineNumber The 1-indexed line number of the call site in the generated source
* @param columnNumber The 1-indexed column number of the call site in the generated source
*/
findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {};
}
function runMain(main?: string): void;
function wrap(script: string): string;
}
global {
namespace NodeJS {
interface Module {
/**
* The module objects required for the first time by this one.
* @since v0.1.16
*/
children: Module[];
/**
* The `module.exports` object is created by the `Module` system. Sometimes this is
* not acceptable; many want their module to be an instance of some class. To do
* this, assign the desired export object to `module.exports`.
* @since v0.1.16
*/
exports: any;
/**
* The fully resolved filename of the module.
* @since v0.1.16
*/
filename: string;
/**
* The identifier for the module. Typically this is the fully resolved
* filename.
* @since v0.1.16
*/
id: string;
/**
* `true` if the module is running during the Node.js preload
* phase.
* @since v15.4.0, v14.17.0
*/
isPreloading: boolean;
/**
* Whether or not the module is done loading, or is in the process of
* loading.
* @since v0.1.16
*/
loaded: boolean;
/**
* The module that first required this one, or `null` if the current module is the
* entry point of the current process, or `undefined` if the module was loaded by
* something that is not a CommonJS module (e.g. REPL or `import`).
* @since v0.1.16
* @deprecated Please use `require.main` and `module.children` instead.
*/
parent: Module | null | undefined;
/**
* The directory name of the module. This is usually the same as the
* `path.dirname()` of the `module.id`.
* @since v11.14.0
*/
path: string;
/**
* The search paths for the module.
* @since v0.4.0
*/
paths: string[];
/**
* The `module.require()` method provides a way to load a module as if
* `require()` was called from the original module.
* @since v0.5.1
*/
require(id: string): any;
}
interface Require {
/**
* Used to import modules, `JSON`, and local files.
* @since v0.1.13
*/
(id: string): any;
/**
* Modules are cached in this object when they are required. By deleting a key
* value from this object, the next `require` will reload the module.
* This does not apply to
* [native addons](https://nodejs.org/docs/latest-v25.x/api/addons.html),
* for which reloading will result in an error.
* @since v0.3.0
*/
cache: Dict<Module>;
/**
* Instruct `require` on how to handle certain file extensions.
* @since v0.3.0
* @deprecated
*/
extensions: RequireExtensions;
/**
* The `Module` object representing the entry script loaded when the Node.js
* process launched, or `undefined` if the entry point of the program is not a
* CommonJS module.
* @since v0.1.17
*/
main: Module | undefined;
/**
* @since v0.3.0
*/
resolve: RequireResolve;
}
/** @deprecated */
interface RequireExtensions extends Dict<(module: Module, filename: string) => any> {
".js": (module: Module, filename: string) => any;
".json": (module: Module, filename: string) => any;
".node": (module: Module, filename: string) => any;
}
interface RequireResolveOptions {
/**
* Paths to resolve module location from. If present, these
* paths are used instead of the default resolution paths, with the exception
* of
* [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v25.x/api/modules.html#loading-from-the-global-folders)
* like `$HOME/.node_modules`, which are
* always included. Each of these paths is used as a starting point for
* the module resolution algorithm, meaning that the `node_modules` hierarchy
* is checked from this location.
* @since v8.9.0
*/
paths?: string[] | undefined;
}
interface RequireResolve {
/**
* Use the internal `require()` machinery to look up the location of a module,
* but rather than loading the module, just return the resolved filename.
*
* If the module can not be found, a `MODULE_NOT_FOUND` error is thrown.
* @since v0.3.0
* @param request The module path to resolve.
*/
(request: string, options?: RequireResolveOptions): string;
/**
* Returns an array containing the paths searched during resolution of `request` or
* `null` if the `request` string references a core module, for example `http` or
* `fs`.
* @since v8.9.0
* @param request The module path whose lookup paths are being retrieved.
*/
paths(request: string): string[] | null;
}
}
/**
* The directory name of the current module. This is the same as the
* `path.dirname()` of the `__filename`.
* @since v0.1.27
*/
var __dirname: string;
/**
* The file name of the current module. This is the current module file's absolute
* path with symlinks resolved.
*
* For a main program this is not necessarily the same as the file name used in the
* command line.
* @since v0.0.1
*/
var __filename: string;
/**
* The `exports` variable is available within a module's file-level scope, and is
* assigned the value of `module.exports` before the module is evaluated.
* @since v0.1.16
*/
var exports: NodeJS.Module["exports"];
/**
* A reference to the current module.
* @since v0.1.16
*/
var module: NodeJS.Module;
/**
* @since v0.1.13
*/
var require: NodeJS.Require;
// Global-scope aliases for backwards compatibility with @types/node <13.0.x
// TODO: consider removing in a future major version update
/** @deprecated Use `NodeJS.Module` instead. */
interface NodeModule extends NodeJS.Module {}
/** @deprecated Use `NodeJS.Require` instead. */
interface NodeRequire extends NodeJS.Require {}
/** @deprecated Use `NodeJS.RequireResolve` instead. */
interface RequireResolve extends NodeJS.RequireResolve {}
}
export = Module;
}
declare module "module" {
import module = require("node:module");
export = module;
}

933
backend/node_modules/@types/node/net.d.ts generated vendored Normal file
View File

@@ -0,0 +1,933 @@
/**
* > Stability: 2 - Stable
*
* The `node:net` module provides an asynchronous network API for creating stream-based
* TCP or `IPC` servers ({@link createServer}) and clients
* ({@link createConnection}).
*
* It can be accessed using:
*
* ```js
* import net from 'node:net';
* ```
* @see [source](https://github.com/nodejs/node/blob/v25.x/lib/net.js)
*/
declare module "node:net" {
import { NonSharedBuffer } from "node:buffer";
import * as dns from "node:dns";
import { Abortable, EventEmitter, InternalEventEmitter } from "node:events";
import * as stream from "node:stream";
type LookupFunction = (
hostname: string,
options: dns.LookupOptions,
callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void,
) => void;
interface AddressInfo {
address: string;
family: string;
port: number;
}
interface SocketConstructorOpts {
fd?: number | undefined;
allowHalfOpen?: boolean | undefined;
onread?: OnReadOpts | undefined;
readable?: boolean | undefined;
writable?: boolean | undefined;
signal?: AbortSignal | undefined;
noDelay?: boolean | undefined;
keepAlive?: boolean | undefined;
keepAliveInitialDelay?: number | undefined;
blockList?: BlockList | undefined;
}
interface OnReadOpts {
buffer: Uint8Array | (() => Uint8Array);
/**
* This function is called for every chunk of incoming data.
* Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`.
* Return `false` from this function to implicitly `pause()` the socket.
*/
callback(bytesWritten: number, buffer: Uint8Array): boolean;
}
interface TcpSocketConnectOpts {
port: number;
host?: string | undefined;
localAddress?: string | undefined;
localPort?: number | undefined;
hints?: number | undefined;
family?: number | undefined;
lookup?: LookupFunction | undefined;
/**
* @since v18.13.0
*/
autoSelectFamily?: boolean | undefined;
/**
* @since v18.13.0
*/
autoSelectFamilyAttemptTimeout?: number | undefined;
}
interface IpcSocketConnectOpts {
path: string;
}
type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts;
type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed";
interface SocketEventMap extends Omit<stream.DuplexEventMap, "close"> {
"close": [hadError: boolean];
"connect": [];
"connectionAttempt": [ip: string, port: number, family: number];
"connectionAttemptFailed": [ip: string, port: number, family: number, error: Error];
"connectionAttemptTimeout": [ip: string, port: number, family: number];
"data": [data: string | NonSharedBuffer];
"lookup": [err: Error | null, address: string, family: number | null, host: string];
"ready": [];
"timeout": [];
}
/**
* This class is an abstraction of a TCP socket or a streaming `IPC` endpoint
* (uses named pipes on Windows, and Unix domain sockets otherwise). It is also
* an `EventEmitter`.
*
* A `net.Socket` can be created by the user and used directly to interact with
* a server. For example, it is returned by {@link createConnection},
* so the user can use it to talk to the server.
*
* It can also be created by Node.js and passed to the user when a connection
* is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use
* it to interact with the client.
* @since v0.3.4
*/
class Socket extends stream.Duplex {
constructor(options?: SocketConstructorOpts);
/**
* Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately.
* If the socket is still writable it implicitly calls `socket.end()`.
* @since v0.3.4
*/
destroySoon(): void;
/**
* Sends data on the socket. The second parameter specifies the encoding in the
* case of a string. It defaults to UTF8 encoding.
*
* Returns `true` if the entire data was flushed successfully to the kernel
* buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free.
*
* The optional `callback` parameter will be executed when the data is finally
* written out, which may not be immediately.
*
* See `Writable` stream `write()` method for more
* information.
* @since v0.1.90
* @param [encoding='utf8'] Only used when data is `string`.
*/
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
/**
* Initiate a connection on a given socket.
*
* Possible signatures:
*
* * `socket.connect(options[, connectListener])`
* * `socket.connect(path[, connectListener])` for `IPC` connections.
* * `socket.connect(port[, host][, connectListener])` for TCP connections.
* * Returns: `net.Socket` The socket itself.
*
* This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting,
* instead of a `'connect'` event, an `'error'` event will be emitted with
* the error passed to the `'error'` listener.
* The last parameter `connectListener`, if supplied, will be added as a listener
* for the `'connect'` event **once**.
*
* This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined
* behavior.
*/
connect(options: SocketConnectOpts, connectionListener?: () => void): this;
connect(port: number, host: string, connectionListener?: () => void): this;
connect(port: number, connectionListener?: () => void): this;
connect(path: string, connectionListener?: () => void): this;
/**
* Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information.
* @since v0.1.90
* @return The socket itself.
*/
setEncoding(encoding?: BufferEncoding): this;
/**
* Pauses the reading of data. That is, `'data'` events will not be emitted.
* Useful to throttle back an upload.
* @return The socket itself.
*/
pause(): this;
/**
* Close the TCP connection by sending an RST packet and destroy the stream.
* If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.
* Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error.
* If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error.
* @since v18.3.0, v16.17.0
*/
resetAndDestroy(): this;
/**
* Resumes reading after a call to `socket.pause()`.
* @return The socket itself.
*/
resume(): this;
/**
* Sets the socket to timeout after `timeout` milliseconds of inactivity on
* the socket. By default `net.Socket` do not have a timeout.
*
* When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to
* end the connection.
*
* ```js
* socket.setTimeout(3000);
* socket.on('timeout', () => {
* console.log('socket timeout');
* socket.end();
* });
* ```
*
* If `timeout` is 0, then the existing idle timeout is disabled.
*
* The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event.
* @since v0.1.90
* @return The socket itself.
*/
setTimeout(timeout: number, callback?: () => void): this;
/**
* Enable/disable the use of Nagle's algorithm.
*
* When a TCP connection is created, it will have Nagle's algorithm enabled.
*
* Nagle's algorithm delays data before it is sent via the network. It attempts
* to optimize throughput at the expense of latency.
*
* Passing `true` for `noDelay` or not passing an argument will disable Nagle's
* algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's
* algorithm.
* @since v0.1.90
* @param [noDelay=true]
* @return The socket itself.
*/
setNoDelay(noDelay?: boolean): this;
/**
* Enable/disable keep-alive functionality, and optionally set the initial
* delay before the first keepalive probe is sent on an idle socket.
*
* Set `initialDelay` (in milliseconds) to set the delay between the last
* data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default
* (or previous) setting.
*
* Enabling the keep-alive functionality will set the following socket options:
*
* * `SO_KEEPALIVE=1`
* * `TCP_KEEPIDLE=initialDelay`
* * `TCP_KEEPCNT=10`
* * `TCP_KEEPINTVL=1`
* @since v0.1.92
* @param [enable=false]
* @param [initialDelay=0]
* @return The socket itself.
*/
setKeepAlive(enable?: boolean, initialDelay?: number): this;
/**
* Returns the bound `address`, the address `family` name and `port` of the
* socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
* @since v0.1.90
*/
address(): AddressInfo | {};
/**
* Calling `unref()` on a socket will allow the program to exit if this is the only
* active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect.
* @since v0.9.1
* @return The socket itself.
*/
unref(): this;
/**
* Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior).
* If the socket is `ref`ed calling `ref` again will have no effect.
* @since v0.9.1
* @return The socket itself.
*/
ref(): this;
/**
* This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)`
* and it is an array of the addresses that have been attempted.
*
* Each address is a string in the form of `$IP:$PORT`.
* If the connection was successful, then the last address is the one that the socket is currently connected to.
* @since v19.4.0
*/
readonly autoSelectFamilyAttemptedAddresses: string[];
/**
* This property shows the number of characters buffered for writing. The buffer
* may contain strings whose length after encoding is not yet known. So this number
* is only an approximation of the number of bytes in the buffer.
*
* `net.Socket` has the property that `socket.write()` always works. This is to
* help users get up and running quickly. The computer cannot always keep up
* with the amount of data that is written to a socket. The network connection
* simply might be too slow. Node.js will internally queue up the data written to a
* socket and send it out over the wire when it is possible.
*
* The consequence of this internal buffering is that memory may grow.
* Users who experience large or growing `bufferSize` should attempt to
* "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`.
* @since v0.3.8
* @deprecated Since v14.6.0 - Use `writableLength` instead.
*/
readonly bufferSize: number;
/**
* The amount of received bytes.
* @since v0.5.3
*/
readonly bytesRead: number;
/**
* The amount of bytes sent.
* @since v0.5.3
*/
readonly bytesWritten: number;
/**
* If `true`, `socket.connect(options[, connectListener])` was
* called and has not yet finished. It will stay `true` until the socket becomes
* connected, then it is set to `false` and the `'connect'` event is emitted. Note
* that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event.
* @since v6.1.0
*/
readonly connecting: boolean;
/**
* This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting
* (see `socket.connecting`).
* @since v11.2.0, v10.16.0
*/
readonly pending: boolean;
/**
* See `writable.destroyed` for further details.
*/
readonly destroyed: boolean;
/**
* The string representation of the local IP address the remote client is
* connecting on. For example, in a server listening on `'0.0.0.0'`, if a client
* connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`.
* @since v0.9.6
*/
readonly localAddress?: string;
/**
* The numeric representation of the local port. For example, `80` or `21`.
* @since v0.9.6
*/
readonly localPort?: number;
/**
* The string representation of the local IP family. `'IPv4'` or `'IPv6'`.
* @since v18.8.0, v16.18.0
*/
readonly localFamily?: string;
/**
* This property represents the state of the connection as a string.
*
* * If the stream is connecting `socket.readyState` is `opening`.
* * If the stream is readable and writable, it is `open`.
* * If the stream is readable and not writable, it is `readOnly`.
* * If the stream is not readable and writable, it is `writeOnly`.
* @since v0.5.0
*/
readonly readyState: SocketReadyState;
/**
* The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if
* the socket is destroyed (for example, if the client disconnected).
* @since v0.5.10
*/
readonly remoteAddress: string | undefined;
/**
* The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if
* the socket is destroyed (for example, if the client disconnected).
* @since v0.11.14
*/
readonly remoteFamily: string | undefined;
/**
* The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if
* the socket is destroyed (for example, if the client disconnected).
* @since v0.5.10
*/
readonly remotePort: number | undefined;
/**
* The socket timeout in milliseconds as set by `socket.setTimeout()`.
* It is `undefined` if a timeout has not been set.
* @since v10.7.0
*/
readonly timeout?: number;
/**
* Half-closes the socket. i.e., it sends a FIN packet. It is possible the
* server will still send some data.
*
* See `writable.end()` for further details.
* @since v0.1.90
* @param [encoding='utf8'] Only used when data is `string`.
* @param callback Optional callback for when the socket is finished.
* @return The socket itself.
*/
end(callback?: () => void): this;
end(buffer: Uint8Array | string, callback?: () => void): this;
end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this;
// #region InternalEventEmitter
addListener<E extends keyof SocketEventMap>(eventName: E, listener: (...args: SocketEventMap[E]) => void): this;
addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
emit<E extends keyof SocketEventMap>(eventName: E, ...args: SocketEventMap[E]): boolean;
emit(eventName: string | symbol, ...args: any[]): boolean;
listenerCount<E extends keyof SocketEventMap>(
eventName: E,
listener?: (...args: SocketEventMap[E]) => void,
): number;
listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number;
listeners<E extends keyof SocketEventMap>(eventName: E): ((...args: SocketEventMap[E]) => void)[];
listeners(eventName: string | symbol): ((...args: any[]) => void)[];
off<E extends keyof SocketEventMap>(eventName: E, listener: (...args: SocketEventMap[E]) => void): this;
off(eventName: string | symbol, listener: (...args: any[]) => void): this;
on<E extends keyof SocketEventMap>(eventName: E, listener: (...args: SocketEventMap[E]) => void): this;
on(eventName: string | symbol, listener: (...args: any[]) => void): this;
once<E extends keyof SocketEventMap>(eventName: E, listener: (...args: SocketEventMap[E]) => void): this;
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
prependListener<E extends keyof SocketEventMap>(
eventName: E,
listener: (...args: SocketEventMap[E]) => void,
): this;
prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener<E extends keyof SocketEventMap>(
eventName: E,
listener: (...args: SocketEventMap[E]) => void,
): this;
prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
rawListeners<E extends keyof SocketEventMap>(eventName: E): ((...args: SocketEventMap[E]) => void)[];
rawListeners(eventName: string | symbol): ((...args: any[]) => void)[];
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
removeAllListeners<E extends keyof SocketEventMap>(eventName?: E): this;
removeAllListeners(eventName?: string | symbol): this;
removeListener<E extends keyof SocketEventMap>(
eventName: E,
listener: (...args: SocketEventMap[E]) => void,
): this;
removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
// #endregion
}
interface ListenOptions extends Abortable {
backlog?: number | undefined;
exclusive?: boolean | undefined;
host?: string | undefined;
/**
* @default false
*/
ipv6Only?: boolean | undefined;
reusePort?: boolean | undefined;
path?: string | undefined;
port?: number | undefined;
readableAll?: boolean | undefined;
writableAll?: boolean | undefined;
}
interface ServerOpts {
/**
* Indicates whether half-opened TCP connections are allowed.
* @default false
*/
allowHalfOpen?: boolean | undefined;
/**
* Indicates whether the socket should be paused on incoming connections.
* @default false
*/
pauseOnConnect?: boolean | undefined;
/**
* If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received.
* @default false
* @since v16.5.0
*/
noDelay?: boolean | undefined;
/**
* If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received,
* similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`.
* @default false
* @since v16.5.0
*/
keepAlive?: boolean | undefined;
/**
* If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket.
* @default 0
* @since v16.5.0
*/
keepAliveInitialDelay?: number | undefined;
/**
* Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`.
* @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode).
* @since v18.17.0, v20.1.0
*/
highWaterMark?: number | undefined;
/**
* `blockList` can be used for disabling inbound
* access to specific IP addresses, IP ranges, or IP subnets. This does not
* work if the server is behind a reverse proxy, NAT, etc. because the address
* checked against the block list is the address of the proxy, or the one
* specified by the NAT.
* @since v22.13.0
*/
blockList?: BlockList | undefined;
}
interface DropArgument {
localAddress?: string;
localPort?: number;
localFamily?: string;
remoteAddress?: string;
remotePort?: number;
remoteFamily?: string;
}
interface ServerEventMap {
"close": [];
"connection": [socket: Socket];
"error": [err: Error];
"listening": [];
"drop": [data?: DropArgument];
}
/**
* This class is used to create a TCP or `IPC` server.
* @since v0.1.90
*/
class Server implements EventEmitter {
constructor(connectionListener?: (socket: Socket) => void);
constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void);
/**
* Start a server listening for connections. A `net.Server` can be a TCP or
* an `IPC` server depending on what it listens to.
*
* Possible signatures:
*
* * `server.listen(handle[, backlog][, callback])`
* * `server.listen(options[, callback])`
* * `server.listen(path[, backlog][, callback])` for `IPC` servers
* * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers
*
* This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'`
* event.
*
* All `listen()` methods can take a `backlog` parameter to specify the maximum
* length of the queue of pending connections. The actual length will be determined
* by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512).
*
* All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for
* details).
*
* The `server.listen()` method can be called again if and only if there was an
* error during the first `server.listen()` call or `server.close()` has been
* called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown.
*
* One of the most common errors raised when listening is `EADDRINUSE`.
* This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry
* after a certain amount of time:
*
* ```js
* server.on('error', (e) => {
* if (e.code === 'EADDRINUSE') {
* console.error('Address in use, retrying...');
* setTimeout(() => {
* server.close();
* server.listen(PORT, HOST);
* }, 1000);
* }
* });
* ```
*/
listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this;
listen(port?: number, hostname?: string, listeningListener?: () => void): this;
listen(port?: number, backlog?: number, listeningListener?: () => void): this;
listen(port?: number, listeningListener?: () => void): this;
listen(path: string, backlog?: number, listeningListener?: () => void): this;
listen(path: string, listeningListener?: () => void): this;
listen(options: ListenOptions, listeningListener?: () => void): this;
listen(handle: any, backlog?: number, listeningListener?: () => void): this;
listen(handle: any, listeningListener?: () => void): this;
/**
* Stops the server from accepting new connections and keeps existing
* connections. This function is asynchronous, the server is finally closed
* when all connections are ended and the server emits a `'close'` event.
* The optional `callback` will be called once the `'close'` event occurs. Unlike
* that event, it will be called with an `Error` as its only argument if the server
* was not open when it was closed.
* @since v0.1.90
* @param callback Called when the server is closed.
*/
close(callback?: (err?: Error) => void): this;
/**
* Returns the bound `address`, the address `family` name, and `port` of the server
* as reported by the operating system if listening on an IP socket
* (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
*
* For a server listening on a pipe or Unix domain socket, the name is returned
* as a string.
*
* ```js
* const server = net.createServer((socket) => {
* socket.end('goodbye\n');
* }).on('error', (err) => {
* // Handle errors here.
* throw err;
* });
*
* // Grab an arbitrary unused port.
* server.listen(() => {
* console.log('opened server on', server.address());
* });
* ```
*
* `server.address()` returns `null` before the `'listening'` event has been
* emitted or after calling `server.close()`.
* @since v0.1.90
*/
address(): AddressInfo | string | null;
/**
* Asynchronously get the number of concurrent connections on the server. Works
* when sockets were sent to forks.
*
* Callback should take two arguments `err` and `count`.
* @since v0.9.7
*/
getConnections(cb: (error: Error | null, count: number) => void): this;
/**
* Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior).
* If the server is `ref`ed calling `ref()` again will have no effect.
* @since v0.9.1
*/
ref(): this;
/**
* Calling `unref()` on a server will allow the program to exit if this is the only
* active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect.
* @since v0.9.1
*/
unref(): this;
/**
* Set this property to reject connections when the server's connection count gets
* high.
*
* It is not recommended to use this option once a socket has been sent to a child
* with `child_process.fork()`.
* @since v0.2.0
*/
maxConnections: number;
connections: number;
/**
* Indicates whether or not the server is listening for connections.
* @since v5.7.0
*/
readonly listening: boolean;
/**
* Calls {@link Server.close()} and returns a promise that fulfills when the server has closed.
* @since v20.5.0
*/
[Symbol.asyncDispose](): Promise<void>;
}
interface Server extends InternalEventEmitter<ServerEventMap> {}
type IPVersion = "ipv4" | "ipv6";
/**
* The `BlockList` object can be used with some network APIs to specify rules for
* disabling inbound or outbound access to specific IP addresses, IP ranges, or
* IP subnets.
* @since v15.0.0, v14.18.0
*/
class BlockList {
/**
* Adds a rule to block the given IP address.
* @since v15.0.0, v14.18.0
* @param address An IPv4 or IPv6 address.
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
*/
addAddress(address: string, type?: IPVersion): void;
addAddress(address: SocketAddress): void;
/**
* Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive).
* @since v15.0.0, v14.18.0
* @param start The starting IPv4 or IPv6 address in the range.
* @param end The ending IPv4 or IPv6 address in the range.
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
*/
addRange(start: string, end: string, type?: IPVersion): void;
addRange(start: SocketAddress, end: SocketAddress): void;
/**
* Adds a rule to block a range of IP addresses specified as a subnet mask.
* @since v15.0.0, v14.18.0
* @param net The network IPv4 or IPv6 address.
* @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`.
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
*/
addSubnet(net: SocketAddress, prefix: number): void;
addSubnet(net: string, prefix: number, type?: IPVersion): void;
/**
* Returns `true` if the given IP address matches any of the rules added to the`BlockList`.
*
* ```js
* const blockList = new net.BlockList();
* blockList.addAddress('123.123.123.123');
* blockList.addRange('10.0.0.1', '10.0.0.10');
* blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');
*
* console.log(blockList.check('123.123.123.123')); // Prints: true
* console.log(blockList.check('10.0.0.3')); // Prints: true
* console.log(blockList.check('222.111.111.222')); // Prints: false
*
* // IPv6 notation for IPv4 addresses works:
* console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true
* console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true
* ```
* @since v15.0.0, v14.18.0
* @param address The IP address to check
* @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`.
*/
check(address: SocketAddress): boolean;
check(address: string, type?: IPVersion): boolean;
/**
* The list of rules added to the blocklist.
* @since v15.0.0, v14.18.0
*/
rules: readonly string[];
/**
* Returns `true` if the `value` is a `net.BlockList`.
* @since v22.13.0
* @param value Any JS value
*/
static isBlockList(value: unknown): value is BlockList;
/**
* ```js
* const blockList = new net.BlockList();
* const data = [
* 'Subnet: IPv4 192.168.1.0/24',
* 'Address: IPv4 10.0.0.5',
* 'Range: IPv4 192.168.2.1-192.168.2.10',
* 'Range: IPv4 10.0.0.1-10.0.0.10',
* ];
* blockList.fromJSON(data);
* blockList.fromJSON(JSON.stringify(data));
* ```
* @since v24.5.0
* @experimental
*/
fromJSON(data: string | readonly string[]): void;
/**
* @since v24.5.0
* @experimental
*/
toJSON(): readonly string[];
}
interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts {
timeout?: number | undefined;
}
interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts {
timeout?: number | undefined;
}
type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts;
/**
* Creates a new TCP or `IPC` server.
*
* If `allowHalfOpen` is set to `true`, when the other end of the socket
* signals the end of transmission, the server will only send back the end of
* transmission when `socket.end()` is explicitly called. For example, in the
* context of TCP, when a FIN packed is received, a FIN packed is sent
* back only when `socket.end()` is explicitly called. Until then the
* connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information.
*
* If `pauseOnConnect` is set to `true`, then the socket associated with each
* incoming connection will be paused, and no data will be read from its handle.
* This allows connections to be passed between processes without any data being
* read by the original process. To begin reading data from a paused socket, call `socket.resume()`.
*
* The server can be a TCP server or an `IPC` server, depending on what it `listen()` to.
*
* Here is an example of a TCP echo server which listens for connections
* on port 8124:
*
* ```js
* import net from 'node:net';
* const server = net.createServer((c) => {
* // 'connection' listener.
* console.log('client connected');
* c.on('end', () => {
* console.log('client disconnected');
* });
* c.write('hello\r\n');
* c.pipe(c);
* });
* server.on('error', (err) => {
* throw err;
* });
* server.listen(8124, () => {
* console.log('server bound');
* });
* ```
*
* Test this by using `telnet`:
*
* ```bash
* telnet localhost 8124
* ```
*
* To listen on the socket `/tmp/echo.sock`:
*
* ```js
* server.listen('/tmp/echo.sock', () => {
* console.log('server bound');
* });
* ```
*
* Use `nc` to connect to a Unix domain socket server:
*
* ```bash
* nc -U /tmp/echo.sock
* ```
* @since v0.5.0
* @param connectionListener Automatically set as a listener for the {@link 'connection'} event.
*/
function createServer(connectionListener?: (socket: Socket) => void): Server;
function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server;
/**
* Aliases to {@link createConnection}.
*
* Possible signatures:
*
* * {@link connect}
* * {@link connect} for `IPC` connections.
* * {@link connect} for TCP connections.
*/
function connect(options: NetConnectOpts, connectionListener?: () => void): Socket;
function connect(port: number, host?: string, connectionListener?: () => void): Socket;
function connect(path: string, connectionListener?: () => void): Socket;
/**
* A factory function, which creates a new {@link Socket},
* immediately initiates connection with `socket.connect()`,
* then returns the `net.Socket` that starts the connection.
*
* When the connection is established, a `'connect'` event will be emitted
* on the returned socket. The last parameter `connectListener`, if supplied,
* will be added as a listener for the `'connect'` event **once**.
*
* Possible signatures:
*
* * {@link createConnection}
* * {@link createConnection} for `IPC` connections.
* * {@link createConnection} for TCP connections.
*
* The {@link connect} function is an alias to this function.
*/
function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket;
function createConnection(port: number, host?: string, connectionListener?: () => void): Socket;
function createConnection(path: string, connectionListener?: () => void): Socket;
/**
* Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`.
* The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided.
* @since v19.4.0
*/
function getDefaultAutoSelectFamily(): boolean;
/**
* Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`.
* @param value The new default value.
* The initial default value is `true`, unless the command line option
* `--no-network-family-autoselection` is provided.
* @since v19.4.0
*/
function setDefaultAutoSelectFamily(value: boolean): void;
/**
* Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`.
* The initial default value is `500` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`.
* @returns The current default value of the `autoSelectFamilyAttemptTimeout` option.
* @since v19.8.0, v18.8.0
*/
function getDefaultAutoSelectFamilyAttemptTimeout(): number;
/**
* Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`.
* @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line
* option `--network-family-autoselection-attempt-timeout`.
* @since v19.8.0, v18.8.0
*/
function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void;
/**
* Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4
* address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`.
*
* ```js
* net.isIP('::1'); // returns 6
* net.isIP('127.0.0.1'); // returns 4
* net.isIP('127.000.000.001'); // returns 0
* net.isIP('127.0.0.1/24'); // returns 0
* net.isIP('fhqwhgads'); // returns 0
* ```
* @since v0.3.0
*/
function isIP(input: string): number;
/**
* Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no
* leading zeroes. Otherwise, returns `false`.
*
* ```js
* net.isIPv4('127.0.0.1'); // returns true
* net.isIPv4('127.000.000.001'); // returns false
* net.isIPv4('127.0.0.1/24'); // returns false
* net.isIPv4('fhqwhgads'); // returns false
* ```
* @since v0.3.0
*/
function isIPv4(input: string): boolean;
/**
* Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`.
*
* ```js
* net.isIPv6('::1'); // returns true
* net.isIPv6('fhqwhgads'); // returns false
* ```
* @since v0.3.0
*/
function isIPv6(input: string): boolean;
interface SocketAddressInitOptions {
/**
* The network address as either an IPv4 or IPv6 string.
* @default 127.0.0.1
*/
address?: string | undefined;
/**
* @default `'ipv4'`
*/
family?: IPVersion | undefined;
/**
* An IPv6 flow-label used only if `family` is `'ipv6'`.
* @default 0
*/
flowlabel?: number | undefined;
/**
* An IP port.
* @default 0
*/
port?: number | undefined;
}
/**
* @since v15.14.0, v14.18.0
*/
class SocketAddress {
constructor(options: SocketAddressInitOptions);
/**
* Either \`'ipv4'\` or \`'ipv6'\`.
* @since v15.14.0, v14.18.0
*/
readonly address: string;
/**
* Either \`'ipv4'\` or \`'ipv6'\`.
* @since v15.14.0, v14.18.0
*/
readonly family: IPVersion;
/**
* @since v15.14.0, v14.18.0
*/
readonly port: number;
/**
* @since v15.14.0, v14.18.0
*/
readonly flowlabel: number;
/**
* @since v22.13.0
* @param input An input string containing an IP address and optional port,
* e.g. `123.1.2.3:1234` or `[1::1]:1234`.
* @returns Returns a `SocketAddress` if parsing was successful.
* Otherwise returns `undefined`.
*/
static parse(input: string): SocketAddress | undefined;
}
}
declare module "net" {
export * from "node:net";
}

View File

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

View File

@@ -0,0 +1,6 @@
# undici-types
This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version.
- [GitHub nodejs/undici](https://github.com/nodejs/undici)
- [Undici Documentation](https://undici.nodejs.org/#/)

View File

@@ -0,0 +1,32 @@
import { URL } from 'node:url'
import Pool from './pool'
import Dispatcher from './dispatcher'
import TClientStats from './client-stats'
import TPoolStats from './pool-stats'
export default Agent
declare class Agent extends Dispatcher {
constructor (opts?: Agent.Options)
/** `true` after `dispatcher.close()` has been called. */
closed: boolean
/** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */
destroyed: boolean
/** Dispatches a request. */
dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean
/** Aggregate stats for a Agent by origin. */
readonly stats: Record<string, TClientStats | TPoolStats>
}
declare namespace Agent {
export interface Options extends Pool.Options {
/** Default: `(origin, opts) => new Pool(origin, opts)`. */
factory?(origin: string | URL, opts: Object): Dispatcher;
interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options['interceptors']
maxOrigins?: number
}
export interface DispatchOptions extends Dispatcher.DispatchOptions {
}
}

View File

@@ -0,0 +1,43 @@
import { URL, UrlObject } from 'node:url'
import { Duplex } from 'node:stream'
import Dispatcher from './dispatcher'
/** Performs an HTTP request. */
declare function request<TOpaque = null> (
url: string | URL | UrlObject,
options?: { dispatcher?: Dispatcher } & Omit<Dispatcher.RequestOptions<TOpaque>, 'origin' | 'path' | 'method'> & Partial<Pick<Dispatcher.RequestOptions, 'method'>>,
): Promise<Dispatcher.ResponseData<TOpaque>>
/** A faster version of `request`. */
declare function stream<TOpaque = null> (
url: string | URL | UrlObject,
options: { dispatcher?: Dispatcher } & Omit<Dispatcher.RequestOptions<TOpaque>, 'origin' | 'path'>,
factory: Dispatcher.StreamFactory<TOpaque>
): Promise<Dispatcher.StreamData<TOpaque>>
/** For easy use with `stream.pipeline`. */
declare function pipeline<TOpaque = null> (
url: string | URL | UrlObject,
options: { dispatcher?: Dispatcher } & Omit<Dispatcher.PipelineOptions<TOpaque>, 'origin' | 'path'>,
handler: Dispatcher.PipelineHandler<TOpaque>
): Duplex
/** Starts two-way communications with the requested resource. */
declare function connect<TOpaque = null> (
url: string | URL | UrlObject,
options?: { dispatcher?: Dispatcher } & Omit<Dispatcher.ConnectOptions<TOpaque>, 'origin' | 'path'>
): Promise<Dispatcher.ConnectData<TOpaque>>
/** Upgrade to a different protocol. */
declare function upgrade (
url: string | URL | UrlObject,
options?: { dispatcher?: Dispatcher } & Omit<Dispatcher.UpgradeOptions, 'origin' | 'path'>
): Promise<Dispatcher.UpgradeData>
export {
request,
stream,
pipeline,
connect,
upgrade
}

View File

@@ -0,0 +1,30 @@
import Pool from './pool'
import Dispatcher from './dispatcher'
import { URL } from 'node:url'
export default BalancedPool
type BalancedPoolConnectOptions = Omit<Dispatcher.ConnectOptions, 'origin'>
declare class BalancedPool extends Dispatcher {
constructor (url: string | string[] | URL | URL[], options?: Pool.Options)
addUpstream (upstream: string | URL): BalancedPool
removeUpstream (upstream: string | URL): BalancedPool
getUpstream (upstream: string | URL): Pool | undefined
upstreams: Array<string>
/** `true` after `pool.close()` has been called. */
closed: boolean
/** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */
destroyed: boolean
// Override dispatcher APIs.
override connect (
options: BalancedPoolConnectOptions
): Promise<Dispatcher.ConnectData>
override connect (
options: BalancedPoolConnectOptions,
callback: (err: Error | null, data: Dispatcher.ConnectData) => void
): void
}

View File

@@ -0,0 +1,173 @@
import { Readable, Writable } from 'node:stream'
export default CacheHandler
declare namespace CacheHandler {
export type CacheMethods = 'GET' | 'HEAD' | 'OPTIONS' | 'TRACE'
export interface CacheHandlerOptions {
store: CacheStore
cacheByDefault?: number
type?: CacheOptions['type']
}
export interface CacheOptions {
store?: CacheStore
/**
* The methods to cache
* Note we can only cache safe methods. Unsafe methods (i.e. PUT, POST)
* invalidate the cache for a origin.
* @see https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-respons
* @see https://www.rfc-editor.org/rfc/rfc9110#section-9.2.1
*/
methods?: CacheMethods[]
/**
* RFC9111 allows for caching responses that we aren't explicitly told to
* cache or to not cache.
* @see https://www.rfc-editor.org/rfc/rfc9111.html#section-3-5
* @default undefined
*/
cacheByDefault?: number
/**
* TODO docs
* @default 'shared'
*/
type?: 'shared' | 'private'
}
export interface CacheControlDirectives {
'max-stale'?: number;
'min-fresh'?: number;
'max-age'?: number;
's-maxage'?: number;
'stale-while-revalidate'?: number;
'stale-if-error'?: number;
public?: true;
private?: true | string[];
'no-store'?: true;
'no-cache'?: true | string[];
'must-revalidate'?: true;
'proxy-revalidate'?: true;
immutable?: true;
'no-transform'?: true;
'must-understand'?: true;
'only-if-cached'?: true;
}
export interface CacheKey {
origin: string
method: string
path: string
headers?: Record<string, string | string[]>
}
export interface CacheValue {
statusCode: number
statusMessage: string
headers: Record<string, string | string[]>
vary?: Record<string, string | string[] | null>
etag?: string
cacheControlDirectives?: CacheControlDirectives
cachedAt: number
staleAt: number
deleteAt: number
}
export interface DeleteByUri {
origin: string
method: string
path: string
}
type GetResult = {
statusCode: number
statusMessage: string
headers: Record<string, string | string[]>
vary?: Record<string, string | string[] | null>
etag?: string
body?: Readable | Iterable<Buffer> | AsyncIterable<Buffer> | Buffer | Iterable<string> | AsyncIterable<string> | string
cacheControlDirectives: CacheControlDirectives,
cachedAt: number
staleAt: number
deleteAt: number
}
/**
* Underlying storage provider for cached responses
*/
export interface CacheStore {
get(key: CacheKey): GetResult | Promise<GetResult | undefined> | undefined
createWriteStream(key: CacheKey, val: CacheValue): Writable | undefined
delete(key: CacheKey): void | Promise<void>
}
export interface MemoryCacheStoreOpts {
/**
* @default Infinity
*/
maxCount?: number
/**
* @default Infinity
*/
maxSize?: number
/**
* @default Infinity
*/
maxEntrySize?: number
errorCallback?: (err: Error) => void
}
export class MemoryCacheStore implements CacheStore {
constructor (opts?: MemoryCacheStoreOpts)
get (key: CacheKey): GetResult | Promise<GetResult | undefined> | undefined
createWriteStream (key: CacheKey, value: CacheValue): Writable | undefined
delete (key: CacheKey): void | Promise<void>
}
export interface SqliteCacheStoreOpts {
/**
* Location of the database
* @default ':memory:'
*/
location?: string
/**
* @default Infinity
*/
maxCount?: number
/**
* @default Infinity
*/
maxEntrySize?: number
}
export class SqliteCacheStore implements CacheStore {
constructor (opts?: SqliteCacheStoreOpts)
/**
* Closes the connection to the database
*/
close (): void
get (key: CacheKey): GetResult | Promise<GetResult | undefined> | undefined
createWriteStream (key: CacheKey, value: CacheValue): Writable | undefined
delete (key: CacheKey): void | Promise<void>
}
}

View File

@@ -0,0 +1,36 @@
import type { RequestInfo, Response, Request } from './fetch'
export interface CacheStorage {
match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise<Response | undefined>,
has (cacheName: string): Promise<boolean>,
open (cacheName: string): Promise<Cache>,
delete (cacheName: string): Promise<boolean>,
keys (): Promise<string[]>
}
declare const CacheStorage: {
prototype: CacheStorage
new(): CacheStorage
}
export interface Cache {
match (request: RequestInfo, options?: CacheQueryOptions): Promise<Response | undefined>,
matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise<readonly Response[]>,
add (request: RequestInfo): Promise<undefined>,
addAll (requests: RequestInfo[]): Promise<undefined>,
put (request: RequestInfo, response: Response): Promise<undefined>,
delete (request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>,
keys (request?: RequestInfo, options?: CacheQueryOptions): Promise<readonly Request[]>
}
export interface CacheQueryOptions {
ignoreSearch?: boolean,
ignoreMethod?: boolean,
ignoreVary?: boolean
}
export interface MultiCacheQueryOptions extends CacheQueryOptions {
cacheName?: string
}
export declare const caches: CacheStorage

View File

@@ -0,0 +1,15 @@
import Client from './client'
export default ClientStats
declare class ClientStats {
constructor (pool: Client)
/** If socket has open connection. */
connected: boolean
/** Number of open socket connections in this client that do not have an active request. */
pending: number
/** Number of currently active requests of this client. */
running: number
/** Number of active, pending, or queued requests of this client. */
size: number
}

View File

@@ -0,0 +1,108 @@
import { URL } from 'node:url'
import Dispatcher from './dispatcher'
import buildConnector from './connector'
import TClientStats from './client-stats'
type ClientConnectOptions = Omit<Dispatcher.ConnectOptions, 'origin'>
/**
* A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
*/
export class Client extends Dispatcher {
constructor (url: string | URL, options?: Client.Options)
/** Property to get and set the pipelining factor. */
pipelining: number
/** `true` after `client.close()` has been called. */
closed: boolean
/** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */
destroyed: boolean
/** Aggregate stats for a Client. */
readonly stats: TClientStats
// Override dispatcher APIs.
override connect (
options: ClientConnectOptions
): Promise<Dispatcher.ConnectData>
override connect (
options: ClientConnectOptions,
callback: (err: Error | null, data: Dispatcher.ConnectData) => void
): void
}
export declare namespace Client {
export interface OptionsInterceptors {
Client: readonly Dispatcher.DispatchInterceptor[];
}
export interface Options {
/** TODO */
interceptors?: OptionsInterceptors;
/** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */
maxHeaderSize?: number;
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */
headersTimeout?: number;
/** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */
socketTimeout?: never;
/** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */
requestTimeout?: never;
/** TODO */
connectTimeout?: number;
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */
bodyTimeout?: number;
/** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */
idleTimeout?: never;
/** @deprecated unsupported keepAlive, use pipelining=0 instead */
keepAlive?: never;
/** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */
keepAliveTimeout?: number;
/** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */
maxKeepAliveTimeout?: never;
/** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
keepAliveMaxTimeout?: number;
/** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
keepAliveTimeoutThreshold?: number;
/** TODO */
socketPath?: string;
/** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */
pipelining?: number;
/** @deprecated use the connect option instead */
tls?: never;
/** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */
strictContentLength?: boolean;
/** TODO */
maxCachedSessions?: number;
/** TODO */
connect?: Partial<buildConnector.BuildOptions> | buildConnector.connector;
/** TODO */
maxRequestsPerClient?: number;
/** TODO */
localAddress?: string;
/** Max response body size in bytes, -1 is disabled */
maxResponseSize?: number;
/** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */
autoSelectFamily?: boolean;
/** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */
autoSelectFamilyAttemptTimeout?: number;
/**
* @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation.
* @default false
*/
allowH2?: boolean;
/**
* @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
* @default 100
*/
maxConcurrentStreams?: number;
}
export interface SocketInfo {
localAddress?: string
localPort?: number
remoteAddress?: string
remotePort?: number
remoteFamily?: string
timeout?: number
bytesWritten?: number
bytesRead?: number
}
}
export default Client

View File

@@ -0,0 +1,34 @@
import { TLSSocket, ConnectionOptions } from 'node:tls'
import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'node:net'
export default buildConnector
declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector
declare namespace buildConnector {
export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & {
allowH2?: boolean;
maxCachedSessions?: number | null;
socketPath?: string | null;
timeout?: number | null;
port?: number;
keepAlive?: boolean | null;
keepAliveInitialDelay?: number | null;
}
export interface Options {
hostname: string
host?: string
protocol: string
port: string
servername?: string
localAddress?: string | null
httpSocket?: Socket
}
export type Callback = (...args: CallbackArgs) => void
type CallbackArgs = [null, Socket | TLSSocket] | [Error, null]
export interface connector {
(options: buildConnector.Options, callback: buildConnector.Callback): void
}
}

View File

@@ -0,0 +1,21 @@
/// <reference types="node" />
interface MIMEType {
type: string
subtype: string
parameters: Map<string, string>
essence: string
}
/**
* Parse a string to a {@link MIMEType} object. Returns `failure` if the string
* couldn't be parsed.
* @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type
*/
export function parseMIMEType (input: string): 'failure' | MIMEType
/**
* Convert a MIMEType object to a string.
* @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
*/
export function serializeAMimeType (mimeType: MIMEType): string

View File

@@ -0,0 +1,30 @@
/// <reference types="node" />
import type { Headers } from './fetch'
export interface Cookie {
name: string
value: string
expires?: Date | number
maxAge?: number
domain?: string
path?: string
secure?: boolean
httpOnly?: boolean
sameSite?: 'Strict' | 'Lax' | 'None'
unparsed?: string[]
}
export function deleteCookie (
headers: Headers,
name: string,
attributes?: { name?: string, domain?: string }
): void
export function getCookies (headers: Headers): Record<string, string>
export function getSetCookies (headers: Headers): Cookie[]
export function setCookie (headers: Headers, cookie: Cookie): void
export function parseCookie (cookie: string): Cookie | null

View File

@@ -0,0 +1,74 @@
import { Socket } from 'node:net'
import { URL } from 'node:url'
import buildConnector from './connector'
import Dispatcher from './dispatcher'
declare namespace DiagnosticsChannel {
interface Request {
origin?: string | URL;
completed: boolean;
method?: Dispatcher.HttpMethod;
path: string;
headers: any;
}
interface Response {
statusCode: number;
statusText: string;
headers: Array<Buffer>;
}
interface ConnectParams {
host: URL['host'];
hostname: URL['hostname'];
protocol: URL['protocol'];
port: URL['port'];
servername: string | null;
}
type Connector = buildConnector.connector
export interface RequestCreateMessage {
request: Request;
}
export interface RequestBodySentMessage {
request: Request;
}
export interface RequestBodyChunkSentMessage {
request: Request;
chunk: Uint8Array | string;
}
export interface RequestBodyChunkReceivedMessage {
request: Request;
chunk: Buffer;
}
export interface RequestHeadersMessage {
request: Request;
response: Response;
}
export interface RequestTrailersMessage {
request: Request;
trailers: Array<Buffer>;
}
export interface RequestErrorMessage {
request: Request;
error: Error;
}
export interface ClientSendHeadersMessage {
request: Request;
headers: string;
socket: Socket;
}
export interface ClientBeforeConnectMessage {
connectParams: ConnectParams;
connector: Connector;
}
export interface ClientConnectedMessage {
socket: Socket;
connectParams: ConnectParams;
connector: Connector;
}
export interface ClientConnectErrorMessage {
error: Error;
socket: Socket;
connectParams: ConnectParams;
connector: Connector;
}
}

View File

@@ -0,0 +1,276 @@
import { URL } from 'node:url'
import { Duplex, Readable, Writable } from 'node:stream'
import { EventEmitter } from 'node:events'
import { Blob } from 'node:buffer'
import { IncomingHttpHeaders } from './header'
import BodyReadable from './readable'
import { FormData } from './formdata'
import Errors from './errors'
import { Autocomplete } from './utility'
type AbortSignal = unknown
export default Dispatcher
export type UndiciHeaders = Record<string, string | string[]> | IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null
/** Dispatcher is the core API used to dispatch requests. */
declare class Dispatcher extends EventEmitter {
/** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */
dispatch (options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean
/** Starts two-way communications with the requested resource. */
connect<TOpaque = null>(options: Dispatcher.ConnectOptions<TOpaque>, callback: (err: Error | null, data: Dispatcher.ConnectData<TOpaque>) => void): void
connect<TOpaque = null>(options: Dispatcher.ConnectOptions<TOpaque>): Promise<Dispatcher.ConnectData<TOpaque>>
/** Compose a chain of dispatchers */
compose (dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher
compose (...dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher
/** Performs an HTTP request. */
request<TOpaque = null>(options: Dispatcher.RequestOptions<TOpaque>, callback: (err: Error | null, data: Dispatcher.ResponseData<TOpaque>) => void): void
request<TOpaque = null>(options: Dispatcher.RequestOptions<TOpaque>): Promise<Dispatcher.ResponseData<TOpaque>>
/** For easy use with `stream.pipeline`. */
pipeline<TOpaque = null>(options: Dispatcher.PipelineOptions<TOpaque>, handler: Dispatcher.PipelineHandler<TOpaque>): Duplex
/** A faster version of `Dispatcher.request`. */
stream<TOpaque = null>(options: Dispatcher.RequestOptions<TOpaque>, factory: Dispatcher.StreamFactory<TOpaque>, callback: (err: Error | null, data: Dispatcher.StreamData<TOpaque>) => void): void
stream<TOpaque = null>(options: Dispatcher.RequestOptions<TOpaque>, factory: Dispatcher.StreamFactory<TOpaque>): Promise<Dispatcher.StreamData<TOpaque>>
/** Upgrade to a different protocol. */
upgrade (options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void
upgrade (options: Dispatcher.UpgradeOptions): Promise<Dispatcher.UpgradeData>
/** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */
close (callback: () => void): void
close (): Promise<void>
/** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */
destroy (err: Error | null, callback: () => void): void
destroy (callback: () => void): void
destroy (err: Error | null): Promise<void>
destroy (): Promise<void>
on (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this
on (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
on (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
on (eventName: 'drain', callback: (origin: URL) => void): this
once (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this
once (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
once (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
once (eventName: 'drain', callback: (origin: URL) => void): this
off (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this
off (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
off (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
off (eventName: 'drain', callback: (origin: URL) => void): this
addListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this
addListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
addListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
addListener (eventName: 'drain', callback: (origin: URL) => void): this
removeListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this
removeListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
removeListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
removeListener (eventName: 'drain', callback: (origin: URL) => void): this
prependListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this
prependListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
prependListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
prependListener (eventName: 'drain', callback: (origin: URL) => void): this
prependOnceListener (eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this
prependOnceListener (eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
prependOnceListener (eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this
prependOnceListener (eventName: 'drain', callback: (origin: URL) => void): this
listeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[]
listeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]
listeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]
listeners (eventName: 'drain'): ((origin: URL) => void)[]
rawListeners (eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[]
rawListeners (eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]
rawListeners (eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]
rawListeners (eventName: 'drain'): ((origin: URL) => void)[]
emit (eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean
emit (eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean
emit (eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean
emit (eventName: 'drain', origin: URL): boolean
}
declare namespace Dispatcher {
export interface ComposedDispatcher extends Dispatcher {}
export type Dispatch = Dispatcher['dispatch']
export type DispatcherComposeInterceptor = (dispatch: Dispatch) => Dispatch
export interface DispatchOptions {
origin?: string | URL;
path: string;
method: HttpMethod;
/** Default: `null` */
body?: string | Buffer | Uint8Array | Readable | null | FormData;
/** Default: `null` */
headers?: UndiciHeaders;
/** Query string params to be embedded in the request URL. Default: `null` */
query?: Record<string, any>;
/** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */
idempotent?: boolean;
/** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. Defaults to `method !== 'HEAD'`. */
blocking?: boolean;
/** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */
upgrade?: boolean | string | null;
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */
headersTimeout?: number | null;
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */
bodyTimeout?: number | null;
/** Whether the request should stablish a keep-alive or not. Default `false` */
reset?: boolean;
/** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */
throwOnError?: boolean;
/** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server */
expectContinue?: boolean;
}
export interface ConnectOptions<TOpaque = null> {
origin: string | URL;
path: string;
/** Default: `null` */
headers?: UndiciHeaders;
/** Default: `null` */
signal?: AbortSignal | EventEmitter | null;
/** This argument parameter is passed through to `ConnectData` */
opaque?: TOpaque;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
responseHeaders?: 'raw' | null;
}
export interface RequestOptions<TOpaque = null> extends DispatchOptions {
/** Default: `null` */
opaque?: TOpaque;
/** Default: `null` */
signal?: AbortSignal | EventEmitter | null;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
onInfo?: (info: { statusCode: number, headers: Record<string, string | string[]> }) => void;
/** Default: `null` */
responseHeaders?: 'raw' | null;
/** Default: `64 KiB` */
highWaterMark?: number;
}
export interface PipelineOptions<TOpaque = null> extends RequestOptions<TOpaque> {
/** `true` if the `handler` will return an object stream. Default: `false` */
objectMode?: boolean;
}
export interface UpgradeOptions {
path: string;
/** Default: `'GET'` */
method?: string;
/** Default: `null` */
headers?: UndiciHeaders;
/** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */
protocol?: string;
/** Default: `null` */
signal?: AbortSignal | EventEmitter | null;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
responseHeaders?: 'raw' | null;
}
export interface ConnectData<TOpaque = null> {
statusCode: number;
headers: IncomingHttpHeaders;
socket: Duplex;
opaque: TOpaque;
}
export interface ResponseData<TOpaque = null> {
statusCode: number;
headers: IncomingHttpHeaders;
body: BodyReadable & BodyMixin;
trailers: Record<string, string>;
opaque: TOpaque;
context: object;
}
export interface PipelineHandlerData<TOpaque = null> {
statusCode: number;
headers: IncomingHttpHeaders;
opaque: TOpaque;
body: BodyReadable;
context: object;
}
export interface StreamData<TOpaque = null> {
opaque: TOpaque;
trailers: Record<string, string>;
}
export interface UpgradeData<TOpaque = null> {
headers: IncomingHttpHeaders;
socket: Duplex;
opaque: TOpaque;
}
export interface StreamFactoryData<TOpaque = null> {
statusCode: number;
headers: IncomingHttpHeaders;
opaque: TOpaque;
context: object;
}
export type StreamFactory<TOpaque = null> = (data: StreamFactoryData<TOpaque>) => Writable
export interface DispatchController {
get aborted () : boolean
get paused () : boolean
get reason () : Error | null
abort (reason: Error): void
pause(): void
resume(): void
}
export interface DispatchHandler {
onRequestStart?(controller: DispatchController, context: any): void;
onRequestUpgrade?(controller: DispatchController, statusCode: number, headers: IncomingHttpHeaders, socket: Duplex): void;
onResponseStart?(controller: DispatchController, statusCode: number, headers: IncomingHttpHeaders, statusMessage?: string): void;
onResponseData?(controller: DispatchController, chunk: Buffer): void;
onResponseEnd?(controller: DispatchController, trailers: IncomingHttpHeaders): void;
onResponseError?(controller: DispatchController, error: Error): void;
/** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */
/** @deprecated */
onConnect?(abort: (err?: Error) => void): void;
/** Invoked when an error has occurred. */
/** @deprecated */
onError?(err: Error): void;
/** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */
/** @deprecated */
onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void;
/** Invoked when response is received, before headers have been read. **/
/** @deprecated */
onResponseStarted?(): void;
/** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */
/** @deprecated */
onHeaders?(statusCode: number, headers: Buffer[], resume: () => void, statusText: string): boolean;
/** Invoked when response payload data is received. */
/** @deprecated */
onData?(chunk: Buffer): boolean;
/** Invoked when response payload and trailers have been received and the request has completed. */
/** @deprecated */
onComplete?(trailers: string[] | null): void;
/** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */
/** @deprecated */
onBodySent?(chunkSize: number, totalBytesSent: number): void;
}
export type PipelineHandler<TOpaque = null> = (data: PipelineHandlerData<TOpaque>) => Readable
export type HttpMethod = Autocomplete<'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'>
/**
* @link https://fetch.spec.whatwg.org/#body-mixin
*/
interface BodyMixin {
readonly body?: never;
readonly bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
bytes(): Promise<Uint8Array>;
formData(): Promise<never>;
json(): Promise<unknown>;
text(): Promise<string>;
}
export interface DispatchInterceptor {
(dispatch: Dispatch): Dispatch
}
}

View File

@@ -0,0 +1,22 @@
import Agent from './agent'
import ProxyAgent from './proxy-agent'
import Dispatcher from './dispatcher'
export default EnvHttpProxyAgent
declare class EnvHttpProxyAgent extends Dispatcher {
constructor (opts?: EnvHttpProxyAgent.Options)
dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean
}
declare namespace EnvHttpProxyAgent {
export interface Options extends Omit<ProxyAgent.Options, 'uri'> {
/** Overrides the value of the HTTP_PROXY environment variable */
httpProxy?: string;
/** Overrides the value of the HTTPS_PROXY environment variable */
httpsProxy?: string;
/** Overrides the value of the NO_PROXY environment variable */
noProxy?: string;
}
}

View File

@@ -0,0 +1,161 @@
import { IncomingHttpHeaders } from './header'
import Client from './client'
export default Errors
declare namespace Errors {
export class UndiciError extends Error {
name: string
code: string
}
/** Connect timeout error. */
export class ConnectTimeoutError extends UndiciError {
name: 'ConnectTimeoutError'
code: 'UND_ERR_CONNECT_TIMEOUT'
}
/** A header exceeds the `headersTimeout` option. */
export class HeadersTimeoutError extends UndiciError {
name: 'HeadersTimeoutError'
code: 'UND_ERR_HEADERS_TIMEOUT'
}
/** Headers overflow error. */
export class HeadersOverflowError extends UndiciError {
name: 'HeadersOverflowError'
code: 'UND_ERR_HEADERS_OVERFLOW'
}
/** A body exceeds the `bodyTimeout` option. */
export class BodyTimeoutError extends UndiciError {
name: 'BodyTimeoutError'
code: 'UND_ERR_BODY_TIMEOUT'
}
export class ResponseError extends UndiciError {
constructor (
message: string,
code: number,
options: {
headers?: IncomingHttpHeaders | string[] | null,
body?: null | Record<string, any> | string
}
)
name: 'ResponseError'
code: 'UND_ERR_RESPONSE'
statusCode: number
body: null | Record<string, any> | string
headers: IncomingHttpHeaders | string[] | null
}
/** Passed an invalid argument. */
export class InvalidArgumentError extends UndiciError {
name: 'InvalidArgumentError'
code: 'UND_ERR_INVALID_ARG'
}
/** Returned an invalid value. */
export class InvalidReturnValueError extends UndiciError {
name: 'InvalidReturnValueError'
code: 'UND_ERR_INVALID_RETURN_VALUE'
}
/** The request has been aborted by the user. */
export class RequestAbortedError extends UndiciError {
name: 'AbortError'
code: 'UND_ERR_ABORTED'
}
/** Expected error with reason. */
export class InformationalError extends UndiciError {
name: 'InformationalError'
code: 'UND_ERR_INFO'
}
/** Request body length does not match content-length header. */
export class RequestContentLengthMismatchError extends UndiciError {
name: 'RequestContentLengthMismatchError'
code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
}
/** Response body length does not match content-length header. */
export class ResponseContentLengthMismatchError extends UndiciError {
name: 'ResponseContentLengthMismatchError'
code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
}
/** Trying to use a destroyed client. */
export class ClientDestroyedError extends UndiciError {
name: 'ClientDestroyedError'
code: 'UND_ERR_DESTROYED'
}
/** Trying to use a closed client. */
export class ClientClosedError extends UndiciError {
name: 'ClientClosedError'
code: 'UND_ERR_CLOSED'
}
/** There is an error with the socket. */
export class SocketError extends UndiciError {
name: 'SocketError'
code: 'UND_ERR_SOCKET'
socket: Client.SocketInfo | null
}
/** Encountered unsupported functionality. */
export class NotSupportedError extends UndiciError {
name: 'NotSupportedError'
code: 'UND_ERR_NOT_SUPPORTED'
}
/** No upstream has been added to the BalancedPool. */
export class BalancedPoolMissingUpstreamError extends UndiciError {
name: 'MissingUpstreamError'
code: 'UND_ERR_BPL_MISSING_UPSTREAM'
}
export class HTTPParserError extends UndiciError {
name: 'HTTPParserError'
code: string
}
/** The response exceed the length allowed. */
export class ResponseExceededMaxSizeError extends UndiciError {
name: 'ResponseExceededMaxSizeError'
code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
}
export class RequestRetryError extends UndiciError {
constructor (
message: string,
statusCode: number,
headers?: IncomingHttpHeaders | string[] | null,
body?: null | Record<string, any> | string
)
name: 'RequestRetryError'
code: 'UND_ERR_REQ_RETRY'
statusCode: number
data: {
count: number;
}
headers: Record<string, string | string[]>
}
export class SecureProxyConnectionError extends UndiciError {
constructor (
cause?: Error,
message?: string,
options?: Record<any, any>
)
name: 'SecureProxyConnectionError'
code: 'UND_ERR_PRX_TLS'
}
class MaxOriginsReachedError extends UndiciError {
name: 'MaxOriginsReachedError'
code: 'UND_ERR_MAX_ORIGINS_REACHED'
}
}

View File

@@ -0,0 +1,66 @@
import { MessageEvent, ErrorEvent } from './websocket'
import Dispatcher from './dispatcher'
import {
EventListenerOptions,
AddEventListenerOptions,
EventListenerOrEventListenerObject
} from './patch'
interface EventSourceEventMap {
error: ErrorEvent
message: MessageEvent
open: Event
}
interface EventSource extends EventTarget {
close(): void
readonly CLOSED: 2
readonly CONNECTING: 0
readonly OPEN: 1
onerror: ((this: EventSource, ev: ErrorEvent) => any) | null
onmessage: ((this: EventSource, ev: MessageEvent) => any) | null
onopen: ((this: EventSource, ev: Event) => any) | null
readonly readyState: 0 | 1 | 2
readonly url: string
readonly withCredentials: boolean
addEventListener<K extends keyof EventSourceEventMap>(
type: K,
listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
options?: boolean | AddEventListenerOptions
): void
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions
): void
removeEventListener<K extends keyof EventSourceEventMap>(
type: K,
listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
options?: boolean | EventListenerOptions
): void
removeEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions
): void
}
export declare const EventSource: {
prototype: EventSource
new (url: string | URL, init?: EventSourceInit): EventSource
readonly CLOSED: 2
readonly CONNECTING: 0
readonly OPEN: 1
}
interface EventSourceInit {
withCredentials?: boolean
// @deprecated use `node.dispatcher` instead
dispatcher?: Dispatcher
node?: {
dispatcher?: Dispatcher
reconnectionTime?: number
}
}

View File

@@ -0,0 +1,211 @@
// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license)
// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license)
/// <reference types="node" />
import { Blob } from 'node:buffer'
import { URL, URLSearchParams } from 'node:url'
import { ReadableStream } from 'node:stream/web'
import { FormData } from './formdata'
import { HeaderRecord } from './header'
import Dispatcher from './dispatcher'
export type RequestInfo = string | URL | Request
export declare function fetch (
input: RequestInfo,
init?: RequestInit
): Promise<Response>
export type BodyInit =
| ArrayBuffer
| AsyncIterable<Uint8Array>
| Blob
| FormData
| Iterable<Uint8Array>
| NodeJS.ArrayBufferView
| URLSearchParams
| null
| string
export class BodyMixin {
readonly body: ReadableStream | null
readonly bodyUsed: boolean
readonly arrayBuffer: () => Promise<ArrayBuffer>
readonly blob: () => Promise<Blob>
readonly bytes: () => Promise<Uint8Array>
/**
* @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments.
* It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows:
*
* @example
* ```js
* import { Busboy } from '@fastify/busboy'
* import { Readable } from 'node:stream'
*
* const response = await fetch('...')
* const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } })
*
* // handle events emitted from `busboy`
*
* Readable.fromWeb(response.body).pipe(busboy)
* ```
*/
readonly formData: () => Promise<FormData>
readonly json: () => Promise<unknown>
readonly text: () => Promise<string>
}
export interface SpecIterator<T, TReturn = any, TNext = undefined> {
next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
}
export interface SpecIterableIterator<T> extends SpecIterator<T> {
[Symbol.iterator](): SpecIterableIterator<T>;
}
export interface SpecIterable<T> {
[Symbol.iterator](): SpecIterator<T>;
}
export type HeadersInit = [string, string][] | HeaderRecord | Headers
export declare class Headers implements SpecIterable<[string, string]> {
constructor (init?: HeadersInit)
readonly append: (name: string, value: string) => void
readonly delete: (name: string) => void
readonly get: (name: string) => string | null
readonly has: (name: string) => boolean
readonly set: (name: string, value: string) => void
readonly getSetCookie: () => string[]
readonly forEach: (
callbackfn: (value: string, key: string, iterable: Headers) => void,
thisArg?: unknown
) => void
readonly keys: () => SpecIterableIterator<string>
readonly values: () => SpecIterableIterator<string>
readonly entries: () => SpecIterableIterator<[string, string]>
readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]>
}
export type RequestCache =
| 'default'
| 'force-cache'
| 'no-cache'
| 'no-store'
| 'only-if-cached'
| 'reload'
export type RequestCredentials = 'omit' | 'include' | 'same-origin'
type RequestDestination =
| ''
| 'audio'
| 'audioworklet'
| 'document'
| 'embed'
| 'font'
| 'image'
| 'manifest'
| 'object'
| 'paintworklet'
| 'report'
| 'script'
| 'sharedworker'
| 'style'
| 'track'
| 'video'
| 'worker'
| 'xslt'
export interface RequestInit {
body?: BodyInit | null
cache?: RequestCache
credentials?: RequestCredentials
dispatcher?: Dispatcher
duplex?: RequestDuplex
headers?: HeadersInit
integrity?: string
keepalive?: boolean
method?: string
mode?: RequestMode
redirect?: RequestRedirect
referrer?: string
referrerPolicy?: ReferrerPolicy
signal?: AbortSignal | null
window?: null
}
export type ReferrerPolicy =
| ''
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin'
export type RequestRedirect = 'error' | 'follow' | 'manual'
export type RequestDuplex = 'half'
export declare class Request extends BodyMixin {
constructor (input: RequestInfo, init?: RequestInit)
readonly cache: RequestCache
readonly credentials: RequestCredentials
readonly destination: RequestDestination
readonly headers: Headers
readonly integrity: string
readonly method: string
readonly mode: RequestMode
readonly redirect: RequestRedirect
readonly referrer: string
readonly referrerPolicy: ReferrerPolicy
readonly url: string
readonly keepalive: boolean
readonly signal: AbortSignal
readonly duplex: RequestDuplex
readonly clone: () => Request
}
export interface ResponseInit {
readonly status?: number
readonly statusText?: string
readonly headers?: HeadersInit
}
export type ResponseType =
| 'basic'
| 'cors'
| 'default'
| 'error'
| 'opaque'
| 'opaqueredirect'
export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308
export declare class Response extends BodyMixin {
constructor (body?: BodyInit, init?: ResponseInit)
readonly headers: Headers
readonly ok: boolean
readonly status: number
readonly statusText: string
readonly type: ResponseType
readonly url: string
readonly redirected: boolean
readonly clone: () => Response
static error (): Response
static json (data: any, init?: ResponseInit): Response
static redirect (url: string | URL, status?: ResponseRedirectStatus): Response
}

View File

@@ -0,0 +1,108 @@
// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT)
/// <reference types="node" />
import { File } from 'node:buffer'
import { SpecIterableIterator } from './fetch'
/**
* A `string` or `File` that represents a single value from a set of `FormData` key-value pairs.
*/
declare type FormDataEntryValue = string | File
/**
* Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch().
*/
export declare class FormData {
/**
* Appends a new value onto an existing key inside a FormData object,
* or adds the key if it does not already exist.
*
* The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
*
* @param name The name of the field whose data is contained in `value`.
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
*/
append (name: string, value: unknown, fileName?: string): void
/**
* Set a new value for an existing key inside FormData,
* or add the new field if it does not already exist.
*
* @param name The name of the field whose data is contained in `value`.
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
*
*/
set (name: string, value: unknown, fileName?: string): void
/**
* Returns the first value associated with a given key from within a `FormData` object.
* If you expect multiple values and want all of them, use the `getAll()` method instead.
*
* @param {string} name A name of the value you want to retrieve.
*
* @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null.
*/
get (name: string): FormDataEntryValue | null
/**
* Returns all the values associated with a given key from within a `FormData` object.
*
* @param {string} name A name of the value you want to retrieve.
*
* @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list.
*/
getAll (name: string): FormDataEntryValue[]
/**
* Returns a boolean stating whether a `FormData` object contains a certain key.
*
* @param name A string representing the name of the key you want to test for.
*
* @return A boolean value.
*/
has (name: string): boolean
/**
* Deletes a key and its value(s) from a `FormData` object.
*
* @param name The name of the key you want to delete.
*/
delete (name: string): void
/**
* Executes given callback function for each field of the FormData instance
*/
forEach: (
callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void,
thisArg?: unknown
) => void
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
* Each key is a `string`.
*/
keys: () => SpecIterableIterator<string>
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
* Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
*/
values: () => SpecIterableIterator<FormDataEntryValue>
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs.
* The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
*/
entries: () => SpecIterableIterator<[string, FormDataEntryValue]>
/**
* An alias for FormData#entries()
*/
[Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]>
readonly [Symbol.toStringTag]: string
}

View File

@@ -0,0 +1,9 @@
import Dispatcher from './dispatcher'
declare function setGlobalDispatcher<DispatcherImplementation extends Dispatcher> (dispatcher: DispatcherImplementation): void
declare function getGlobalDispatcher (): Dispatcher
export {
getGlobalDispatcher,
setGlobalDispatcher
}

View File

@@ -0,0 +1,7 @@
declare function setGlobalOrigin (origin: string | URL | undefined): void
declare function getGlobalOrigin (): URL | undefined
export {
setGlobalOrigin,
getGlobalOrigin
}

View File

@@ -0,0 +1,73 @@
import { URL } from 'node:url'
import Dispatcher from './dispatcher'
import buildConnector from './connector'
type H2ClientOptions = Omit<Dispatcher.ConnectOptions, 'origin'>
/**
* A basic H2C client, mapped on top a single TCP connection. Pipelining is disabled by default.
*/
export class H2CClient extends Dispatcher {
constructor (url: string | URL, options?: H2CClient.Options)
/** Property to get and set the pipelining factor. */
pipelining: number
/** `true` after `client.close()` has been called. */
closed: boolean
/** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */
destroyed: boolean
// Override dispatcher APIs.
override connect (
options: H2ClientOptions
): Promise<Dispatcher.ConnectData>
override connect (
options: H2ClientOptions,
callback: (err: Error | null, data: Dispatcher.ConnectData) => void
): void
}
export declare namespace H2CClient {
export interface Options {
/** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */
maxHeaderSize?: number;
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */
headersTimeout?: number;
/** TODO */
connectTimeout?: number;
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */
bodyTimeout?: number;
/** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */
keepAliveTimeout?: number;
/** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
keepAliveMaxTimeout?: number;
/** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
keepAliveTimeoutThreshold?: number;
/** TODO */
socketPath?: string;
/** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */
pipelining?: number;
/** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */
strictContentLength?: boolean;
/** TODO */
maxCachedSessions?: number;
/** TODO */
connect?: Omit<Partial<buildConnector.BuildOptions>, 'allowH2'> | buildConnector.connector;
/** TODO */
maxRequestsPerClient?: number;
/** TODO */
localAddress?: string;
/** Max response body size in bytes, -1 is disabled */
maxResponseSize?: number;
/** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */
autoSelectFamily?: boolean;
/** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */
autoSelectFamilyAttemptTimeout?: number;
/**
* @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
* @default 100
*/
maxConcurrentStreams?: number
}
}
export default H2CClient

View File

@@ -0,0 +1,15 @@
import Dispatcher from './dispatcher'
export declare class RedirectHandler implements Dispatcher.DispatchHandler {
constructor (
dispatch: Dispatcher.Dispatch,
maxRedirections: number,
opts: Dispatcher.DispatchOptions,
handler: Dispatcher.DispatchHandler,
redirectionLimitReached: boolean
)
}
export declare class DecoratorHandler implements Dispatcher.DispatchHandler {
constructor (handler: Dispatcher.DispatchHandler)
}

View File

@@ -0,0 +1,160 @@
import { Autocomplete } from './utility'
/**
* The header type declaration of `undici`.
*/
export type IncomingHttpHeaders = Record<string, string | string[] | undefined>
type HeaderNames = Autocomplete<
| 'Accept'
| 'Accept-CH'
| 'Accept-Charset'
| 'Accept-Encoding'
| 'Accept-Language'
| 'Accept-Patch'
| 'Accept-Post'
| 'Accept-Ranges'
| 'Access-Control-Allow-Credentials'
| 'Access-Control-Allow-Headers'
| 'Access-Control-Allow-Methods'
| 'Access-Control-Allow-Origin'
| 'Access-Control-Expose-Headers'
| 'Access-Control-Max-Age'
| 'Access-Control-Request-Headers'
| 'Access-Control-Request-Method'
| 'Age'
| 'Allow'
| 'Alt-Svc'
| 'Alt-Used'
| 'Authorization'
| 'Cache-Control'
| 'Clear-Site-Data'
| 'Connection'
| 'Content-Disposition'
| 'Content-Encoding'
| 'Content-Language'
| 'Content-Length'
| 'Content-Location'
| 'Content-Range'
| 'Content-Security-Policy'
| 'Content-Security-Policy-Report-Only'
| 'Content-Type'
| 'Cookie'
| 'Cross-Origin-Embedder-Policy'
| 'Cross-Origin-Opener-Policy'
| 'Cross-Origin-Resource-Policy'
| 'Date'
| 'Device-Memory'
| 'ETag'
| 'Expect'
| 'Expect-CT'
| 'Expires'
| 'Forwarded'
| 'From'
| 'Host'
| 'If-Match'
| 'If-Modified-Since'
| 'If-None-Match'
| 'If-Range'
| 'If-Unmodified-Since'
| 'Keep-Alive'
| 'Last-Modified'
| 'Link'
| 'Location'
| 'Max-Forwards'
| 'Origin'
| 'Permissions-Policy'
| 'Priority'
| 'Proxy-Authenticate'
| 'Proxy-Authorization'
| 'Range'
| 'Referer'
| 'Referrer-Policy'
| 'Retry-After'
| 'Sec-Fetch-Dest'
| 'Sec-Fetch-Mode'
| 'Sec-Fetch-Site'
| 'Sec-Fetch-User'
| 'Sec-Purpose'
| 'Sec-WebSocket-Accept'
| 'Server'
| 'Server-Timing'
| 'Service-Worker-Navigation-Preload'
| 'Set-Cookie'
| 'SourceMap'
| 'Strict-Transport-Security'
| 'TE'
| 'Timing-Allow-Origin'
| 'Trailer'
| 'Transfer-Encoding'
| 'Upgrade'
| 'Upgrade-Insecure-Requests'
| 'User-Agent'
| 'Vary'
| 'Via'
| 'WWW-Authenticate'
| 'X-Content-Type-Options'
| 'X-Frame-Options'
>
type IANARegisteredMimeType = Autocomplete<
| 'audio/aac'
| 'video/x-msvideo'
| 'image/avif'
| 'video/av1'
| 'application/octet-stream'
| 'image/bmp'
| 'text/css'
| 'text/csv'
| 'application/vnd.ms-fontobject'
| 'application/epub+zip'
| 'image/gif'
| 'application/gzip'
| 'text/html'
| 'image/x-icon'
| 'text/calendar'
| 'image/jpeg'
| 'text/javascript'
| 'application/json'
| 'application/ld+json'
| 'audio/x-midi'
| 'audio/mpeg'
| 'video/mp4'
| 'video/mpeg'
| 'audio/ogg'
| 'video/ogg'
| 'application/ogg'
| 'audio/opus'
| 'font/otf'
| 'application/pdf'
| 'image/png'
| 'application/rtf'
| 'image/svg+xml'
| 'image/tiff'
| 'video/mp2t'
| 'font/ttf'
| 'text/plain'
| 'application/wasm'
| 'video/webm'
| 'audio/webm'
| 'image/webp'
| 'font/woff'
| 'font/woff2'
| 'application/xhtml+xml'
| 'application/xml'
| 'application/zip'
| 'video/3gpp'
| 'video/3gpp2'
| 'model/gltf+json'
| 'model/gltf-binary'
>
type KnownHeaderValues = {
'content-type': IANARegisteredMimeType
}
export type HeaderRecord = {
[K in HeaderNames | Lowercase<HeaderNames>]?: Lowercase<K> extends keyof KnownHeaderValues
? KnownHeaderValues[Lowercase<K>]
: string
}

View File

@@ -0,0 +1,88 @@
import Dispatcher from './dispatcher'
import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher'
import { setGlobalOrigin, getGlobalOrigin } from './global-origin'
import Pool from './pool'
import { RedirectHandler, DecoratorHandler } from './handlers'
import BalancedPool from './balanced-pool'
import RoundRobinPool from './round-robin-pool'
import Client from './client'
import H2CClient from './h2c-client'
import buildConnector from './connector'
import errors from './errors'
import Agent from './agent'
import MockClient from './mock-client'
import MockPool from './mock-pool'
import MockAgent from './mock-agent'
import { SnapshotAgent } from './snapshot-agent'
import { MockCallHistory, MockCallHistoryLog } from './mock-call-history'
import mockErrors from './mock-errors'
import ProxyAgent from './proxy-agent'
import EnvHttpProxyAgent from './env-http-proxy-agent'
import RetryHandler from './retry-handler'
import RetryAgent from './retry-agent'
import { request, pipeline, stream, connect, upgrade } from './api'
import interceptors from './interceptors'
import CacheInterceptor from './cache-interceptor'
declare const cacheStores: {
MemoryCacheStore: typeof CacheInterceptor.MemoryCacheStore;
SqliteCacheStore: typeof CacheInterceptor.SqliteCacheStore;
}
export * from './util'
export * from './cookies'
export * from './eventsource'
export * from './fetch'
export * from './formdata'
export * from './diagnostics-channel'
export * from './websocket'
export * from './content-type'
export * from './cache'
export { Interceptable } from './mock-interceptor'
declare function globalThisInstall (): void
export { Dispatcher, BalancedPool, RoundRobinPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, cacheStores, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install }
export default Undici
declare namespace Undici {
const Dispatcher: typeof import('./dispatcher').default
const Pool: typeof import('./pool').default
const RedirectHandler: typeof import ('./handlers').RedirectHandler
const DecoratorHandler: typeof import ('./handlers').DecoratorHandler
const RetryHandler: typeof import ('./retry-handler').default
const BalancedPool: typeof import('./balanced-pool').default
const RoundRobinPool: typeof import('./round-robin-pool').default
const Client: typeof import('./client').default
const H2CClient: typeof import('./h2c-client').default
const buildConnector: typeof import('./connector').default
const errors: typeof import('./errors').default
const Agent: typeof import('./agent').default
const setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher
const getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher
const request: typeof import('./api').request
const stream: typeof import('./api').stream
const pipeline: typeof import('./api').pipeline
const connect: typeof import('./api').connect
const upgrade: typeof import('./api').upgrade
const MockClient: typeof import('./mock-client').default
const MockPool: typeof import('./mock-pool').default
const MockAgent: typeof import('./mock-agent').default
const SnapshotAgent: typeof import('./snapshot-agent').SnapshotAgent
const MockCallHistory: typeof import('./mock-call-history').MockCallHistory
const MockCallHistoryLog: typeof import('./mock-call-history').MockCallHistoryLog
const mockErrors: typeof import('./mock-errors').default
const fetch: typeof import('./fetch').fetch
const Headers: typeof import('./fetch').Headers
const Response: typeof import('./fetch').Response
const Request: typeof import('./fetch').Request
const FormData: typeof import('./formdata').FormData
const caches: typeof import('./cache').caches
const interceptors: typeof import('./interceptors').default
const cacheStores: {
MemoryCacheStore: typeof import('./cache-interceptor').default.MemoryCacheStore,
SqliteCacheStore: typeof import('./cache-interceptor').default.SqliteCacheStore
}
const install: typeof globalThisInstall
}

View File

@@ -0,0 +1,73 @@
import CacheHandler from './cache-interceptor'
import Dispatcher from './dispatcher'
import RetryHandler from './retry-handler'
import { LookupOptions } from 'node:dns'
export default Interceptors
declare namespace Interceptors {
export type DumpInterceptorOpts = { maxSize?: number }
export type RetryInterceptorOpts = RetryHandler.RetryOptions
export type RedirectInterceptorOpts = { maxRedirections?: number }
export type DecompressInterceptorOpts = {
skipErrorResponses?: boolean
skipStatusCodes?: number[]
}
export type ResponseErrorInterceptorOpts = { throwOnError: boolean }
export type CacheInterceptorOpts = CacheHandler.CacheOptions
// DNS interceptor
export type DNSInterceptorRecord = { address: string, ttl: number, family: 4 | 6 }
export type DNSInterceptorOriginRecords = { records: { 4: { ips: DNSInterceptorRecord[] } | null, 6: { ips: DNSInterceptorRecord[] } | null } }
export type DNSStorage = {
size: number
get(origin: string): DNSInterceptorOriginRecords | null
set(origin: string, records: DNSInterceptorOriginRecords | null, options: { ttl: number }): void
delete(origin: string): void
full(): boolean
}
export type DNSInterceptorOpts = {
maxTTL?: number
maxItems?: number
lookup?: (origin: URL, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void
pick?: (origin: URL, records: DNSInterceptorOriginRecords, affinity: 4 | 6) => DNSInterceptorRecord
dualStack?: boolean
affinity?: 4 | 6
storage?: DNSStorage
}
// Deduplicate interceptor
export type DeduplicateMethods = 'GET' | 'HEAD' | 'OPTIONS' | 'TRACE'
export type DeduplicateInterceptorOpts = {
/**
* The HTTP methods to deduplicate.
* Note: Only safe HTTP methods can be deduplicated.
* @default ['GET']
*/
methods?: DeduplicateMethods[]
/**
* Header names that, if present in a request, will cause the request to skip deduplication.
* Header name matching is case-insensitive.
* @default []
*/
skipHeaderNames?: string[]
/**
* Header names to exclude from the deduplication key.
* Requests with different values for these headers will still be deduplicated together.
* Useful for headers like `x-request-id` that vary per request but shouldn't affect deduplication.
* Header name matching is case-insensitive.
* @default []
*/
excludeHeaderNames?: string[]
}
export function dump (opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function retry (opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function redirect (opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function decompress (opts?: DecompressInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function responseError (opts?: ResponseErrorInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function dns (opts?: DNSInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function cache (opts?: CacheInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function deduplicate (opts?: DeduplicateInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
}

View File

@@ -0,0 +1,68 @@
import Agent from './agent'
import Dispatcher from './dispatcher'
import { Interceptable, MockInterceptor } from './mock-interceptor'
import MockDispatch = MockInterceptor.MockDispatch
import { MockCallHistory } from './mock-call-history'
export default MockAgent
interface PendingInterceptor extends MockDispatch {
origin: string;
}
/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */
declare class MockAgent<TMockAgentOptions extends MockAgent.Options = MockAgent.Options> extends Dispatcher {
constructor (options?: TMockAgentOptions)
/** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */
get<TInterceptable extends Interceptable>(origin: string): TInterceptable
get<TInterceptable extends Interceptable>(origin: RegExp): TInterceptable
get<TInterceptable extends Interceptable>(origin: ((origin: string) => boolean)): TInterceptable
/** Dispatches a mocked request. */
dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean
/** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */
close (): Promise<void>
/** Disables mocking in MockAgent. */
deactivate (): void
/** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */
activate (): void
/** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */
enableNetConnect (): void
enableNetConnect (host: string): void
enableNetConnect (host: RegExp): void
enableNetConnect (host: ((host: string) => boolean)): void
/** Causes all requests to throw when requests are not matched in a MockAgent intercept. */
disableNetConnect (): void
/** get call history. returns the MockAgent call history or undefined if the option is not enabled. */
getCallHistory (): MockCallHistory | undefined
/** clear every call history. Any MockCallHistoryLog will be deleted on the MockCallHistory instance */
clearCallHistory (): void
/** Enable call history. Any subsequence calls will then be registered. */
enableCallHistory (): this
/** Disable call history. Any subsequence calls will then not be registered. */
disableCallHistory (): this
pendingInterceptors (): PendingInterceptor[]
assertNoPendingInterceptors (options?: {
pendingInterceptorsFormatter?: PendingInterceptorsFormatter;
}): void
}
interface PendingInterceptorsFormatter {
format(pendingInterceptors: readonly PendingInterceptor[]): string;
}
declare namespace MockAgent {
/** MockAgent options. */
export interface Options extends Agent.Options {
/** A custom agent to be encapsulated by the MockAgent. */
agent?: Dispatcher;
/** Ignore trailing slashes in the path */
ignoreTrailingSlash?: boolean;
/** Accept URLs with search parameters using non standard syntaxes. default false */
acceptNonStandardSearchParameters?: boolean;
/** Enable call history. you can either call MockAgent.enableCallHistory(). default false */
enableCallHistory?: boolean
}
}

View File

@@ -0,0 +1,111 @@
import Dispatcher from './dispatcher'
declare namespace MockCallHistoryLog {
/** request's configuration properties */
export type MockCallHistoryLogProperties = 'protocol' | 'host' | 'port' | 'origin' | 'path' | 'hash' | 'fullUrl' | 'method' | 'searchParams' | 'body' | 'headers'
}
/** a log reflecting request configuration */
declare class MockCallHistoryLog {
constructor (requestInit: Dispatcher.DispatchOptions)
/** protocol used. ie. 'https:' or 'http:' etc... */
protocol: string
/** request's host. */
host: string
/** request's port. */
port: string
/** request's origin. ie. https://localhost:3000. */
origin: string
/** path. never contains searchParams. */
path: string
/** request's hash. */
hash: string
/** the full url requested. */
fullUrl: string
/** request's method. */
method: string
/** search params. */
searchParams: Record<string, string>
/** request's body */
body: string | null | undefined
/** request's headers */
headers: Record<string, string | string[]> | null | undefined
/** returns an Map of property / value pair */
toMap (): Map<MockCallHistoryLog.MockCallHistoryLogProperties, string | Record<string, string | string[]> | null | undefined>
/** returns a string computed with all key value pair */
toString (): string
}
declare namespace MockCallHistory {
export type FilterCallsOperator = 'AND' | 'OR'
/** modify the filtering behavior */
export interface FilterCallsOptions {
/** the operator to apply when filtering. 'OR' will adds any MockCallHistoryLog matching any criteria given. 'AND' will adds only MockCallHistoryLog matching every criteria given. (default 'OR') */
operator?: FilterCallsOperator | Lowercase<FilterCallsOperator>
}
/** a function to be executed for filtering MockCallHistoryLog */
export type FilterCallsFunctionCriteria = (log: MockCallHistoryLog) => boolean
/** parameter to filter MockCallHistoryLog */
export type FilterCallsParameter = string | RegExp | undefined | null
/** an object to execute multiple filtering at once */
export interface FilterCallsObjectCriteria extends Record<string, FilterCallsParameter> {
/** filter by request protocol. ie https: */
protocol?: FilterCallsParameter;
/** filter by request host. */
host?: FilterCallsParameter;
/** filter by request port. */
port?: FilterCallsParameter;
/** filter by request origin. */
origin?: FilterCallsParameter;
/** filter by request path. */
path?: FilterCallsParameter;
/** filter by request hash. */
hash?: FilterCallsParameter;
/** filter by request fullUrl. */
fullUrl?: FilterCallsParameter;
/** filter by request method. */
method?: FilterCallsParameter;
}
}
/** a call history to track requests configuration */
declare class MockCallHistory {
constructor (name: string)
/** returns an array of MockCallHistoryLog. */
calls (): Array<MockCallHistoryLog>
/** returns the first MockCallHistoryLog */
firstCall (): MockCallHistoryLog | undefined
/** returns the last MockCallHistoryLog. */
lastCall (): MockCallHistoryLog | undefined
/** returns the nth MockCallHistoryLog. */
nthCall (position: number): MockCallHistoryLog | undefined
/** return all MockCallHistoryLog matching any of criteria given. if an object is used with multiple properties, you can change the operator to apply during filtering on options */
filterCalls (criteria: MockCallHistory.FilterCallsFunctionCriteria | MockCallHistory.FilterCallsObjectCriteria | RegExp, options?: MockCallHistory.FilterCallsOptions): Array<MockCallHistoryLog>
/** return all MockCallHistoryLog matching the given protocol. if a string is given, it is matched with includes */
filterCallsByProtocol (protocol: MockCallHistory.FilterCallsParameter): Array<MockCallHistoryLog>
/** return all MockCallHistoryLog matching the given host. if a string is given, it is matched with includes */
filterCallsByHost (host: MockCallHistory.FilterCallsParameter): Array<MockCallHistoryLog>
/** return all MockCallHistoryLog matching the given port. if a string is given, it is matched with includes */
filterCallsByPort (port: MockCallHistory.FilterCallsParameter): Array<MockCallHistoryLog>
/** return all MockCallHistoryLog matching the given origin. if a string is given, it is matched with includes */
filterCallsByOrigin (origin: MockCallHistory.FilterCallsParameter): Array<MockCallHistoryLog>
/** return all MockCallHistoryLog matching the given path. if a string is given, it is matched with includes */
filterCallsByPath (path: MockCallHistory.FilterCallsParameter): Array<MockCallHistoryLog>
/** return all MockCallHistoryLog matching the given hash. if a string is given, it is matched with includes */
filterCallsByHash (hash: MockCallHistory.FilterCallsParameter): Array<MockCallHistoryLog>
/** return all MockCallHistoryLog matching the given fullUrl. if a string is given, it is matched with includes */
filterCallsByFullUrl (fullUrl: MockCallHistory.FilterCallsParameter): Array<MockCallHistoryLog>
/** return all MockCallHistoryLog matching the given method. if a string is given, it is matched with includes */
filterCallsByMethod (method: MockCallHistory.FilterCallsParameter): Array<MockCallHistoryLog>
/** clear all MockCallHistoryLog on this MockCallHistory. */
clear (): void
/** use it with for..of loop or spread operator */
[Symbol.iterator]: () => Generator<MockCallHistoryLog>
}
export { MockCallHistoryLog, MockCallHistory }

View File

@@ -0,0 +1,27 @@
import Client from './client'
import Dispatcher from './dispatcher'
import MockAgent from './mock-agent'
import { MockInterceptor, Interceptable } from './mock-interceptor'
export default MockClient
/** MockClient extends the Client API and allows one to mock requests. */
declare class MockClient extends Client implements Interceptable {
constructor (origin: string, options: MockClient.Options)
/** Intercepts any matching requests that use the same origin as this mock client. */
intercept (options: MockInterceptor.Options): MockInterceptor
/** Dispatches a mocked request. */
dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandler): boolean
/** Closes the mock client and gracefully waits for enqueued requests to complete. */
close (): Promise<void>
/** Clean up all the prepared mocks. */
cleanMocks (): void
}
declare namespace MockClient {
/** MockClient options. */
export interface Options extends Client.Options {
/** The agent to associate this MockClient with. */
agent: MockAgent;
}
}

View File

@@ -0,0 +1,12 @@
import Errors from './errors'
export default MockErrors
declare namespace MockErrors {
/** The request does not match any registered mock dispatches. */
export class MockNotMatchedError extends Errors.UndiciError {
constructor (message?: string)
name: 'MockNotMatchedError'
code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
}
}

View File

@@ -0,0 +1,94 @@
import { IncomingHttpHeaders } from './header'
import Dispatcher from './dispatcher'
import { BodyInit, Headers } from './fetch'
/** The scope associated with a mock dispatch. */
declare class MockScope<TData extends object = object> {
constructor (mockDispatch: MockInterceptor.MockDispatch<TData>)
/** Delay a reply by a set amount of time in ms. */
delay (waitInMs: number): MockScope<TData>
/** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */
persist (): MockScope<TData>
/** Define a reply for a set amount of matching requests. */
times (repeatTimes: number): MockScope<TData>
}
/** The interceptor for a Mock. */
declare class MockInterceptor {
constructor (options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[])
/** Mock an undici request with the defined reply. */
reply<TData extends object = object>(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback<TData>): MockScope<TData>
reply<TData extends object = object>(
statusCode: number,
data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler<TData>,
responseOptions?: MockInterceptor.MockResponseOptions
): MockScope<TData>
/** Mock an undici request by throwing the defined reply error. */
replyWithError<TError extends Error = Error>(error: TError): MockScope
/** Set default reply headers on the interceptor for subsequent mocked replies. */
defaultReplyHeaders (headers: IncomingHttpHeaders): MockInterceptor
/** Set default reply trailers on the interceptor for subsequent mocked replies. */
defaultReplyTrailers (trailers: Record<string, string>): MockInterceptor
/** Set automatically calculated content-length header on subsequent mocked replies. */
replyContentLength (): MockInterceptor
}
declare namespace MockInterceptor {
/** MockInterceptor options. */
export interface Options {
/** Path to intercept on. */
path: string | RegExp | ((path: string) => boolean);
/** Method to intercept on. Defaults to GET. */
method?: string | RegExp | ((method: string) => boolean);
/** Body to intercept on. */
body?: string | RegExp | ((body: string) => boolean);
/** Headers to intercept on. */
headers?: Record<string, string | RegExp | ((body: string) => boolean)> | ((headers: Record<string, string>) => boolean);
/** Query params to intercept on */
query?: Record<string, any>;
}
export interface MockDispatch<TData extends object = object, TError extends Error = Error> extends Options {
times: number | null;
persist: boolean;
consumed: boolean;
data: MockDispatchData<TData, TError>;
}
export interface MockDispatchData<TData extends object = object, TError extends Error = Error> extends MockResponseOptions {
error: TError | null;
statusCode?: number;
data?: TData | string;
}
export interface MockResponseOptions {
headers?: IncomingHttpHeaders;
trailers?: Record<string, string>;
}
export interface MockResponseCallbackOptions {
path: string;
method: string;
headers?: Headers | Record<string, string>;
origin?: string;
body?: BodyInit | Dispatcher.DispatchOptions['body'] | null;
}
export type MockResponseDataHandler<TData extends object = object> = (
opts: MockResponseCallbackOptions
) => TData | Buffer | string
export type MockReplyOptionsCallback<TData extends object = object> = (
opts: MockResponseCallbackOptions
) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions }
}
interface Interceptable extends Dispatcher {
/** Intercepts any matching requests that use the same origin as this mock client. */
intercept(options: MockInterceptor.Options): MockInterceptor;
/** Clean up all the prepared mocks. */
cleanMocks (): void
}
export {
Interceptable,
MockInterceptor,
MockScope
}

View File

@@ -0,0 +1,27 @@
import Pool from './pool'
import MockAgent from './mock-agent'
import { Interceptable, MockInterceptor } from './mock-interceptor'
import Dispatcher from './dispatcher'
export default MockPool
/** MockPool extends the Pool API and allows one to mock requests. */
declare class MockPool extends Pool implements Interceptable {
constructor (origin: string, options: MockPool.Options)
/** Intercepts any matching requests that use the same origin as this mock pool. */
intercept (options: MockInterceptor.Options): MockInterceptor
/** Dispatches a mocked request. */
dispatch (options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandler): boolean
/** Closes the mock pool and gracefully waits for enqueued requests to complete. */
close (): Promise<void>
/** Clean up all the prepared mocks. */
cleanMocks (): void
}
declare namespace MockPool {
/** MockPool options. */
export interface Options extends Pool.Options {
/** The agent to associate this MockPool with. */
agent: MockAgent;
}
}

View File

@@ -0,0 +1,55 @@
{
"name": "undici-types",
"version": "7.18.2",
"description": "A stand-alone types package for Undici",
"homepage": "https://undici.nodejs.org",
"bugs": {
"url": "https://github.com/nodejs/undici/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/nodejs/undici.git"
},
"license": "MIT",
"types": "index.d.ts",
"files": [
"*.d.ts"
],
"contributors": [
{
"name": "Daniele Belardi",
"url": "https://github.com/dnlup",
"author": true
},
{
"name": "Ethan Arrowood",
"url": "https://github.com/ethan-arrowood",
"author": true
},
{
"name": "Matteo Collina",
"url": "https://github.com/mcollina",
"author": true
},
{
"name": "Matthew Aitken",
"url": "https://github.com/KhafraDev",
"author": true
},
{
"name": "Robert Nagy",
"url": "https://github.com/ronag",
"author": true
},
{
"name": "Szymon Marczak",
"url": "https://github.com/szmarczak",
"author": true
},
{
"name": "Tomas Della Vedova",
"url": "https://github.com/delvedor",
"author": true
}
]
}

View File

@@ -0,0 +1,29 @@
/// <reference types="node" />
// See https://github.com/nodejs/undici/issues/1740
export interface EventInit {
bubbles?: boolean
cancelable?: boolean
composed?: boolean
}
export interface EventListenerOptions {
capture?: boolean
}
export interface AddEventListenerOptions extends EventListenerOptions {
once?: boolean
passive?: boolean
signal?: AbortSignal
}
export type EventListenerOrEventListenerObject = EventListener | EventListenerObject
export interface EventListenerObject {
handleEvent (object: Event): void
}
export interface EventListener {
(evt: Event): void
}

View File

@@ -0,0 +1,19 @@
import Pool from './pool'
export default PoolStats
declare class PoolStats {
constructor (pool: Pool)
/** Number of open socket connections in this pool. */
connected: number
/** Number of open socket connections in this pool that do not have an active request. */
free: number
/** Number of pending requests across all clients in this pool. */
pending: number
/** Number of queued requests across all clients in this pool. */
queued: number
/** Number of currently active requests across all clients in this pool. */
running: number
/** Number of active, pending, or queued requests across all clients in this pool. */
size: number
}

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