lab3(+catalog)
This commit is contained in:
parent
0d9eff0c49
commit
42cead50e5
110
addElement.html
Normal file
110
addElement.html
Normal file
@ -0,0 +1,110 @@
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://fonts.cdnfonts.com/css/correction-tape" rel="stylesheet">
|
||||
<title>Admin</title>
|
||||
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
|
||||
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
|
||||
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
|
||||
<link rel="stylesheet" href="./style.css">
|
||||
|
||||
<script>
|
||||
function toggleMenu() {
|
||||
var menuWrapper = document.getElementById("menu-wrapper");
|
||||
menuWrapper.classList.toggle("open");
|
||||
}
|
||||
</script>
|
||||
|
||||
</head>
|
||||
<body class="h-100 d-flex flex-column">
|
||||
<div id="menu-wrapper">
|
||||
<div id="menu">
|
||||
<ul>
|
||||
<li><a href="/">Главная</a></li>
|
||||
<li><a href="./page2(cinema).html">Кино</a></li>
|
||||
<li><a href="./page2(concerts).html">Концерты</a></li>
|
||||
<li><a href="./page2(theatre).html">Театр</a></li>
|
||||
<li><a href="./about.html">О сайте</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<header>
|
||||
<nav class="navbar navbar-expand-md navbar-dark">
|
||||
<div class="container-fluid">
|
||||
<a id="toggle-menu" onclick="toggleMenu()">
|
||||
<h1>TicketsBook</h1>
|
||||
</a>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
|
||||
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="navbar-collapse collapse justify-content-end" id="navbarNav">
|
||||
<div class="navbar-nav">
|
||||
<a class="nav-link" href="./signingIn.html">вход/регистрация</a>
|
||||
<a class="nav-link" href="./lkAdmin.html">админ</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="container-fluid p-2">
|
||||
<div class="d-flex justify-content-center">
|
||||
<div class="info" style="max-height: 90vh; overflow-y: auto;">
|
||||
<h1>Добавить событие</h1>
|
||||
<form class="needs-validation" method="get" novalidate>
|
||||
<div class="mb-1">
|
||||
<label for="name" class="form-label">Название</label>
|
||||
<input type="text" class="form-control" id="name" placeholder="Введите название" required>
|
||||
<div class="invalid-feedback">Название не заполнено</div>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="type" class="form-label">Тип</label>
|
||||
<select class="form-control" id="type" name="type" placeholder="Выберите тип" required>
|
||||
<option value="option1">Концерт</option>
|
||||
<option value="option2">Кино</option>
|
||||
<option value="option3">Театр</option>
|
||||
</select>
|
||||
<div class="invalid-feedback">Тип не выбран</div>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="date" class="form-label">Дата</label>
|
||||
<input type="date" class="form-control" id="date" required>
|
||||
<div class="invalid-feedback">Дата не заполнена</div>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="price" class="form-label">Стоимость</label>
|
||||
<input id="price" name="price" class="form-control" type="number" value="0.00" min="1000.00"
|
||||
step="0.50" required placeholder="Введите стоимость" required>
|
||||
<div class="invalid-feedback">Стоимость не заполнена</div>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="description" class="form-label">Описание</label>
|
||||
<textarea class="form-control" id="description" rows="3" placeholder="Введите описание" required></textarea>
|
||||
<div class="invalid-feedback">Описание не заполнено</div>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="photo" class="form-label">Фото</label>
|
||||
<input type="file" class="form-control" id="photo" required>
|
||||
<div class="valid-feedback">Изображение загружено</div>
|
||||
<div class="invalid-feedback">Изображение не загружено</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Добавить</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
|
||||
Иевлева Милана, 2023
|
||||
</footer>
|
||||
<script type="module">
|
||||
import validation from "./js/validation";
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
validation();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
63
js/lines-modal.js
Normal file
63
js/lines-modal.js
Normal file
@ -0,0 +1,63 @@
|
||||
// Модуль для работы с модальным окном
|
||||
|
||||
// импорт компонента Modal из bootstrap
|
||||
import { Modal } from "bootstrap";
|
||||
import { cntrls, imagePlaceholder } from "./lines-ui";
|
||||
|
||||
// поиск модального окна на странице
|
||||
const modal = document.getElementById("items-update");
|
||||
// если он найден, то создается экземпляр компонента Modal
|
||||
// для программного управления модальным окном
|
||||
const myModal = modal ? new Modal(modal, {}) : null;
|
||||
|
||||
// поиск тега с заголовком модального кона для его смены
|
||||
const modalTitle = document.getElementById("items-update-title");
|
||||
|
||||
// обнуление значений модального окна, т. к.
|
||||
// используется одно окно для всех операций
|
||||
function resetValues() {
|
||||
cntrls.lineId.value = "";
|
||||
cntrls.ItName.value = "";
|
||||
cntrls.itemsType.value = "";
|
||||
cntrls.date.value = "";
|
||||
cntrls.price.value = parseFloat(0).toFixed(2);
|
||||
cntrls.place.value = "";
|
||||
cntrls.image.value = "";
|
||||
cntrls.imagePreview.src = imagePlaceholder;
|
||||
}
|
||||
|
||||
// функция для показа модального окна
|
||||
// перед показом происходит заполнение формы для редактирования
|
||||
// если объект item не пуст
|
||||
export function showUpdateModal(item) {
|
||||
modalTitle.innerHTML = item === null ? "Добавить" : "Изменить";
|
||||
console.info(item);
|
||||
|
||||
if (item) {
|
||||
cntrls.lineId.value = item.id;
|
||||
cntrls.ItName.value = item.ItName;
|
||||
cntrls.itemsType.value = item.itemsId;
|
||||
cntrls.date.value = item.date;
|
||||
cntrls.price.value = item.price;
|
||||
cntrls.place.value = item.placesId;
|
||||
// заполнение превью
|
||||
// Если пользователь выбрал изображение, то оно загружается
|
||||
// в тэг image с id image - preview
|
||||
// иначе устанавливается заглушка, адрес которой указан в imagePlaceholder
|
||||
cntrls.imagePreview.src = item.image ? item.image : imagePlaceholder;
|
||||
} else {
|
||||
resetValues();
|
||||
}
|
||||
|
||||
myModal.show();
|
||||
}
|
||||
|
||||
// функция для скрытия модального окна
|
||||
export function hideUpdateModal() {
|
||||
resetValues();
|
||||
|
||||
// удаление класса was-validated для скрытия результатов валидации
|
||||
cntrls.form.classList.remove("was-validated");
|
||||
|
||||
myModal.hide();
|
||||
}
|
110
js/lines-rest-api.js
Normal file
110
js/lines-rest-api.js
Normal file
@ -0,0 +1,110 @@
|
||||
// модуль для работы с REST API сервера
|
||||
|
||||
// адрес сервера
|
||||
const serverUrl = "http://localhost:8081";
|
||||
|
||||
// функция возвращает объект нужной структуры для отправки на сервер
|
||||
function createLineObject(ItName, item, date, price, place, image) {
|
||||
return {
|
||||
ItName: ItName,
|
||||
itemsId: item,
|
||||
date: date,
|
||||
price: parseFloat(price).toFixed(2),
|
||||
placesId: place,
|
||||
image,
|
||||
};
|
||||
}
|
||||
|
||||
// обращение к серверу для получения всех типов товара (get)
|
||||
export async function getAllItemTypes() {
|
||||
const response = await fetch(`${serverUrl}/items`);
|
||||
if (!response.ok) {
|
||||
throw response.statusText;
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// обращение к серверу для получения всех типов товара (get)
|
||||
export async function getAllItemPlaces() {
|
||||
const response = await fetch(`${serverUrl}/places`);
|
||||
if (!response.ok) {
|
||||
throw response.statusText;
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// обращение к серверу для получения всех записей (get)
|
||||
export async function getAllLines() {
|
||||
const response = await fetch(`${serverUrl}/lines?_expand=items&_expand=places`);
|
||||
if (!response.ok) {
|
||||
throw response.statusText;
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// обращение к серверу для получения записи по первичному ключу (id) (get)
|
||||
// id передается в качестве части пути URL get-запроса
|
||||
export async function getLine(id) {
|
||||
const response = await fetch(`${serverUrl}/lines/${id}?_expand=items&_expand=places`);
|
||||
if (!response.ok) {
|
||||
throw response.statusText;
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// обращение к серверу для создания записи (post)
|
||||
// объект отправляется в теле запроса (body)
|
||||
export async function createLine(ItName, item, date, price, place, image) {
|
||||
const itemObject = createLineObject(ItName, item, date, price, place, image);
|
||||
|
||||
const options = {
|
||||
method: "POST",
|
||||
body: JSON.stringify(itemObject),
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
};
|
||||
|
||||
const response = await fetch(`${serverUrl}/lines`, options);
|
||||
if (!response.ok) {
|
||||
throw response.statusText;
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// обращение к серверу для обновления записи по id (put)
|
||||
// объект отправляется в теле запроса (body)
|
||||
// id передается в качестве части пути URL get-запроса
|
||||
export async function updateLine(id, ItName, item, date, price, place, image) {
|
||||
const itemObject = createLineObject(ItName, item, date, price, place, image);
|
||||
|
||||
const options = {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(itemObject),
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
};
|
||||
|
||||
const response = await fetch(`${serverUrl}/lines/${id}`, options);
|
||||
if (!response.ok) {
|
||||
throw response.statusText;
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// обращение к серверу для удаления записи по id (delete)
|
||||
// id передается в качестве части пути URL get-запроса
|
||||
export async function deleteLine(id) {
|
||||
const options = {
|
||||
method: "DELETE",
|
||||
};
|
||||
|
||||
const response = await fetch(`${serverUrl}/lines/${id}`, options);
|
||||
if (!response.ok) {
|
||||
throw response.statusText;
|
||||
}
|
||||
return response.json();
|
||||
}
|
95
js/lines-ui.js
Normal file
95
js/lines-ui.js
Normal file
@ -0,0 +1,95 @@
|
||||
// модуль для работы с элементами управления
|
||||
|
||||
// объект для удобного получения элементов
|
||||
// при обращении к атрибуту объекта вызывается
|
||||
// нужная функция для поиска элемента
|
||||
export const cntrls = {
|
||||
button: document.getElementById("items-add"),
|
||||
table: document.querySelector("#items-table tbody"),
|
||||
form: document.getElementById("items-form"),
|
||||
lineId: document.getElementById("items-line-id"),
|
||||
ItName: document.getElementById("ItName"),
|
||||
itemsType: document.getElementById("item"),
|
||||
date: document.getElementById("date"),
|
||||
price: document.getElementById("price"),
|
||||
place: document.getElementById("place"),
|
||||
image: document.getElementById("image"),
|
||||
imagePreview: document.getElementById("image-preview"),
|
||||
};
|
||||
|
||||
// Дефолтное превью
|
||||
export const imagePlaceholder = "https://via.placeholder.com/200";
|
||||
|
||||
// функция создает тег option для select
|
||||
// <option value="" selected>name</option>
|
||||
export function createItemsOption(name, value = "", isSelected = false) {
|
||||
const option = document.createElement("option");
|
||||
option.value = value || "";
|
||||
option.selected = isSelected;
|
||||
option.text = name;
|
||||
return option;
|
||||
}
|
||||
|
||||
// функция создает ссылку (a) для таблицы
|
||||
// содержимое тега a заполняется необходимой иконкой (icon)
|
||||
// при нажатии вызывается callback
|
||||
// ссылка "оборачивается" тегом td
|
||||
// <td><a href="#" onclick="callback()"><i class="fa-solid icon"></i></a></td>
|
||||
function createTableAnchor(icon, callback) {
|
||||
const i = document.createElement("i");
|
||||
i.classList.add("fa-solid", icon);
|
||||
|
||||
const a = document.createElement("a");
|
||||
a.href = "#";
|
||||
a.appendChild(i);
|
||||
a.onclick = (event) => {
|
||||
// чтобы в URL не добавлялась решетка
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
callback();
|
||||
};
|
||||
|
||||
const td = document.createElement("td");
|
||||
td.appendChild(a);
|
||||
return td;
|
||||
}
|
||||
|
||||
// функция создает колонку таблицы с текстом value
|
||||
// <td>value</td>
|
||||
function createTableColumn(value) {
|
||||
const td = document.createElement("td");
|
||||
td.textContent = value;
|
||||
return td;
|
||||
}
|
||||
|
||||
// функция создает строку таблицы
|
||||
// <tr>
|
||||
// <th scope="row">index + 1</th>
|
||||
// <td>item.items.name</td>
|
||||
// <td>parseFloat(item.price).toFixed(2))</td>
|
||||
// <td>item.count</td>
|
||||
// <td>parseFloat(item.sum).toFixed(2))</td>
|
||||
// <td><a href="#" onclick="editCallback()"><i class="fa-solid fa-pencil"></i></a></td>
|
||||
// <td><a href="#" onclick="editPageCallback()"><i class="fa-solid fa-pen-to-square"></i></a></td>
|
||||
// <td><a href="#" onclick="deleteCallback()"><i class="fa-solid fa-trash"></i></a></td>
|
||||
// </tr>
|
||||
export function createTableRow(item, index, editCallback, editPageCallback, deleteCallback) {
|
||||
const rowNumber = document.createElement("th");
|
||||
rowNumber.scope = "row";
|
||||
rowNumber.textContent = index + 1;
|
||||
|
||||
const row = document.createElement("tr");
|
||||
row.id = `line-${item.id}`;
|
||||
|
||||
row.appendChild(rowNumber);
|
||||
row.appendChild(createTableColumn(item.ItName));
|
||||
row.appendChild(createTableColumn(item.items.name));
|
||||
row.appendChild(createTableColumn(item.date));
|
||||
row.appendChild(createTableColumn(parseFloat(item.price).toFixed(2)));
|
||||
row.appendChild(createTableColumn(item.places.name));
|
||||
// редактировать в модальном окне
|
||||
row.appendChild(createTableAnchor("fa-pencil", editCallback));
|
||||
// удаление
|
||||
row.appendChild(createTableAnchor("fa-trash", deleteCallback));
|
||||
return row;
|
||||
}
|
334
js/lines.js
Normal file
334
js/lines.js
Normal file
@ -0,0 +1,334 @@
|
||||
// модуль с логикой
|
||||
|
||||
import { hideUpdateModal, showUpdateModal } from "./lines-modal";
|
||||
import {
|
||||
createLine, deleteLine, getAllItemTypes, getAllItemPlaces, getAllLines, getLine, updateLine,
|
||||
} from "./lines-rest-api";
|
||||
import {
|
||||
cntrls, createItemsOption, createTableRow, imagePlaceholder,
|
||||
} from "./lines-ui";
|
||||
|
||||
async function drawItemsSelect() {
|
||||
// вызов метода REST API для получения списка типов товаров
|
||||
const data = await getAllItemTypes();
|
||||
// очистка содержимого select
|
||||
// удаляется все, что находится между тегами <select></select>
|
||||
// но не атрибуты
|
||||
cntrls.itemsType.innerHTML = "";
|
||||
// пустое значение
|
||||
cntrls.itemsType.appendChild(createItemsOption("Выберите значение", "", true));
|
||||
// цикл по результату ответа от сервера
|
||||
// используется лямбда-выражение
|
||||
// (item) => {} аналогично function(item) {}
|
||||
data.forEach((item) => {
|
||||
cntrls.itemsType.appendChild(createItemsOption(item.name, item.id));
|
||||
});
|
||||
}
|
||||
|
||||
async function drawPlacesSelect() {
|
||||
// вызов метода REST API для получения списка типов товаров
|
||||
const data = await getAllItemPlaces();
|
||||
// очистка содержимого select
|
||||
// удаляется все, что находится между тегами <select></select>
|
||||
// но не атрибуты
|
||||
cntrls.place.innerHTML = "";
|
||||
// пустое значение
|
||||
cntrls.place.appendChild(createItemsOption("Выберите значение", "", true));
|
||||
// цикл по результату ответа от сервера
|
||||
// используется лямбда-выражение
|
||||
// (item) => {} аналогично function(item) {}
|
||||
data.forEach((item) => {
|
||||
cntrls.place.appendChild(createItemsOption(item.name, item.id));
|
||||
});
|
||||
}
|
||||
|
||||
async function drawLinesTable() {
|
||||
console.info("Try to load data");
|
||||
if (!cntrls.table) {
|
||||
return;
|
||||
}
|
||||
// вызов метода REST API для получения всех записей
|
||||
const data = await getAllLines();
|
||||
// очистка содержимого table
|
||||
// удаляется все, что находится между тегами <table></table>
|
||||
// но не атрибуты
|
||||
cntrls.table.innerHTML = "";
|
||||
// цикл по результату ответа от сервера
|
||||
// используется лямбда-выражение
|
||||
// (item, index) => {} аналогично function(item, index) {}
|
||||
data.forEach((item, index) => {
|
||||
cntrls.table.appendChild(
|
||||
createTableRow(
|
||||
item,
|
||||
index,
|
||||
// функции передаются в качестве параметра
|
||||
// это очень удобно, так как аргументы функций доступны только
|
||||
// в данном месте кода и не передаются в сервисные модули
|
||||
() => showUpdateModal(item),
|
||||
() => location.assign(`page-edit.html?id=${item.id}`),
|
||||
() => removeLine(item.id),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function addLine(ItName, item, date, price, place, image) {
|
||||
console.info("Try to add item");
|
||||
// вызов метода REST API для добавления записи
|
||||
const data = await createLine(ItName, item, date, price, place, image);
|
||||
console.info("Added");
|
||||
console.info(data);
|
||||
// загрузка и заполнение table
|
||||
drawLinesTable();
|
||||
}
|
||||
|
||||
async function editLine(id, ItName, item, date, price, place, image) {
|
||||
console.info("Try to update item");
|
||||
// вызов метода REST API для обновления записи
|
||||
const data = await updateLine(id, ItName, item, date, price, place, image);
|
||||
console.info("Updated");
|
||||
console.info(data);
|
||||
// загрузка и заполнение table
|
||||
drawLinesTable();
|
||||
}
|
||||
|
||||
async function removeLine(id) {
|
||||
if (!confirm("Do you really want to remove this item?")) {
|
||||
console.info("Canceled");
|
||||
return;
|
||||
}
|
||||
console.info("Try to remove item");
|
||||
// вызов метода REST API для удаления записи
|
||||
const data = await deleteLine(id);
|
||||
console.info(data);
|
||||
// загрузка и заполнение table
|
||||
drawLinesTable();
|
||||
}
|
||||
|
||||
// функция для получения содержимого файла в виде base64 строки
|
||||
// https://ru.wikipedia.org/wiki/Base64
|
||||
async function readFile(file) {
|
||||
const reader = new FileReader();
|
||||
|
||||
// создание Promise-объекта для использования функции
|
||||
// с помощью await (асинхронно) без коллбэков (callback)
|
||||
// https://learn.javascript.ru/promise
|
||||
return new Promise((resolve, reject) => {
|
||||
// 2. "Возвращаем" содержимое когда файл прочитан
|
||||
// через вызов resolve
|
||||
// Если не использовать Promise, то всю работу по взаимодействию
|
||||
// с REST API пришлось бы делать в обработчике (callback) функции
|
||||
// onloadend
|
||||
reader.onloadend = () => {
|
||||
const fileContent = reader.result;
|
||||
// Здесь могла бы быть работа с REST API
|
||||
// Чтение заканчивает выполняться здесь
|
||||
resolve(fileContent);
|
||||
};
|
||||
// 3. Возвращаем ошибку
|
||||
reader.onerror = () => {
|
||||
// Или здесь в случае ошибки
|
||||
reject(new Error("oops, something went wrong with the file reader."));
|
||||
};
|
||||
// Шаг 1. Сначала читаем файл
|
||||
// Чтение начинает выполняться здесь
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
// функция для обновления блока с превью выбранного изображения
|
||||
async function updateImagePreview() {
|
||||
// получение выбранного файла
|
||||
// возможен выбор нескольких файлов, поэтому необходимо получить только первый
|
||||
const file = cntrls.image.files[0];
|
||||
// чтение содержимого файла в виде base64 строки
|
||||
const fileContent = await readFile(file);
|
||||
console.info("base64 ", fileContent);
|
||||
// обновление атрибута src для тега img с id image-preview
|
||||
cntrls.imagePreview.src = fileContent;
|
||||
}
|
||||
|
||||
// Функция для обработки создания и редактирования элементов таблицы через модальное окно
|
||||
// Если хотите делать через страницу, то удалите эту функцию
|
||||
export function linesForm() {
|
||||
console.info("linesForm");
|
||||
|
||||
// загрузка и заполнение select со списком товаров
|
||||
drawItemsSelect();
|
||||
drawPlacesSelect();
|
||||
// загрузка и заполнение table
|
||||
drawLinesTable();
|
||||
|
||||
// Вызов функции обновления превью изображения при возникновении
|
||||
// события oncahnge в тэге input с id image
|
||||
cntrls.image.addEventListener("change", () => updateImagePreview());
|
||||
|
||||
// обработчик события нажатия на кнопку для показа модального окна
|
||||
cntrls.button.addEventListener("click", () => showUpdateModal(null));
|
||||
|
||||
// обработчик события отправки формы
|
||||
// возникает при нажатии на кнопку (button) с типом submit
|
||||
// кнопка должна находится внутри тега form
|
||||
cntrls.form.addEventListener("submit", async (event) => {
|
||||
console.info("Form onSubmit");
|
||||
// отключение стандартного поведения формы при отправке
|
||||
// при отправке страница обновляется и JS перестает работать
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// если форма не прошла валидацию, то ничего делать не нужно
|
||||
if (!cntrls.form.checkValidity()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let imageBase64 = "";
|
||||
// Получение выбранного пользователем изображения в виде base64 строки
|
||||
// Если пользователь ничего не выбрал, то не нужно сохранять в БД
|
||||
// дефолтное изображение
|
||||
if (cntrls.imagePreview.src !== imagePlaceholder) {
|
||||
// Загрузка содержимого атрибута src тэга img с id image-preview
|
||||
// Здесь выполняется HTTP запрос с типом GET
|
||||
const result = await fetch(cntrls.imagePreview.src);
|
||||
// Получение из HTTP-ответа бинарного содержимого
|
||||
const blob = await result.blob();
|
||||
// Получение base64 строки для файла
|
||||
// Здесь выполняется Promise из функции readFile
|
||||
// Promise позволяет писать линейный код для работы с асинхронными методами
|
||||
// без использования обработчиков (callback) с помощью await
|
||||
imageBase64 = await readFile(blob);
|
||||
}
|
||||
|
||||
// получение id строки для редактирования
|
||||
// это значение содержится в скрытом input
|
||||
const currentId = cntrls.lineId.value;
|
||||
// если значение id не задано,
|
||||
// то необходимо выполнить добавление записи
|
||||
// иначе обновление записи
|
||||
if (!currentId) {
|
||||
await addLine(
|
||||
cntrls.ItName.value,
|
||||
cntrls.itemsType.value,
|
||||
cntrls.date.value,
|
||||
cntrls.price.value,
|
||||
cntrls.place.value,
|
||||
imageBase64,
|
||||
);
|
||||
} else {
|
||||
await editLine(
|
||||
currentId,
|
||||
cntrls.ItName.value,
|
||||
cntrls.itemsType.value,
|
||||
cntrls.date.value,
|
||||
cntrls.price.value,
|
||||
cntrls.place.value,
|
||||
imageBase64,
|
||||
);
|
||||
}
|
||||
|
||||
// после выполнения добавления/обновления модальное окно скрывается
|
||||
hideUpdateModal();
|
||||
});
|
||||
}
|
||||
|
||||
// Функция для обработки создания и редактирования элементов таблицы через страницу page-edit.html
|
||||
// Если хотите делать через модальное окно, то удалите эту функцию
|
||||
export async function linesPageForm() {
|
||||
console.info("linesPageForm");
|
||||
|
||||
// загрузка и заполнение select со списком товаров
|
||||
drawItemsSelect();
|
||||
drawPlacesSelect();
|
||||
|
||||
// func1 = (id) => {} аналогично function func1(id) {}
|
||||
const goBack = () => location.assign("/lkAdmin.html");
|
||||
|
||||
// Вызов функции обновления превью изображения при возникновении
|
||||
// события onchange в тэге input с id image
|
||||
cntrls.image.addEventListener("change", () => updateImagePreview());
|
||||
|
||||
// получение параметров GET-запроса из URL
|
||||
// параметры перечислены после символа ? (?id=1&color=black&...)
|
||||
const urlParams = new URLSearchParams(location.search);
|
||||
|
||||
// получение значения конкретного параметра (id)
|
||||
// указан только при редактировании
|
||||
const currentId = urlParams.get("id");
|
||||
// если id задан
|
||||
if (currentId) {
|
||||
try {
|
||||
// вызов метода REST API для получения записи по первичному ключу(id)
|
||||
const line = await getLine(currentId);
|
||||
// заполнение формы для редактирования
|
||||
cntrls.ItName.value = line.ItName;
|
||||
cntrls.itemsType.value = line.itemsId;
|
||||
cntrls.date.value = line.date;
|
||||
cntrls.price.value = line.price;
|
||||
cntrls.place.value = line.placesId;
|
||||
// заполнение превью
|
||||
// Если пользователь выбрал изображение, то оно загружается
|
||||
// в тэг image с id image - preview
|
||||
// иначе устанавливается заглушка, адрес которой указан в imagePlaceholder
|
||||
cntrls.imagePreview.src = line.image ? line.image : imagePlaceholder;
|
||||
} catch {
|
||||
// в случае ошибки происходит возврат к page4
|
||||
goBack();
|
||||
}
|
||||
}
|
||||
|
||||
// обработчик события отправки формы
|
||||
// возникает при нажатии на кнопку (button) с типом submit
|
||||
// кнопка должна находится внутри тега form
|
||||
cntrls.form.addEventListener("submit", async (event) => {
|
||||
console.info("Form onSubmit");
|
||||
// отключение стандартного поведения формы при отправке
|
||||
// при отправке страница обновляется и JS перестает работать
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// если форма не прошла валидацию, то ничего делать не нужно
|
||||
if (!cntrls.form.checkValidity()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let imageBase64 = "";
|
||||
// Получение выбранного пользователем изображения в виде base64 строки
|
||||
// Если пользователь ничего не выбрал, то не нужно сохранять в БД
|
||||
// дефолтное изображение
|
||||
if (cntrls.imagePreview.src !== imagePlaceholder) {
|
||||
// Загрузка содержимого атрибута src тэга img с id image-preview
|
||||
// Здесь выполняется HTTP запрос с типом GET
|
||||
const result = await fetch(cntrls.imagePreview.src);
|
||||
// Получение из HTTP-ответа бинарного содержимого
|
||||
const blob = await result.blob();
|
||||
// Получение base64 строки для файла
|
||||
// Здесь выполняется Promise из функции readFile
|
||||
// Promise позволяет писать линейный код для работы с асинхронными методами
|
||||
// без использования обработчиков (callback) с помощью await
|
||||
imageBase64 = await readFile(blob);
|
||||
}
|
||||
|
||||
// если значение параметра запроса не задано,
|
||||
// то необходимо выполнить добавление записи
|
||||
// иначе обновление записи
|
||||
if (!currentId) {
|
||||
await addLine(
|
||||
cntrls.ItName.value,
|
||||
cntrls.itemsType.value,
|
||||
cntrls.date.value,
|
||||
cntrls.price.value,
|
||||
cntrls.place.value,
|
||||
imageBase64,
|
||||
);
|
||||
} else {
|
||||
await editLine(
|
||||
currentId,
|
||||
cntrls.ItName.value,
|
||||
cntrls.itemsType.value,
|
||||
cntrls.date.value,
|
||||
cntrls.price.value,
|
||||
cntrls.place.value,
|
||||
imageBase64,
|
||||
);
|
||||
}
|
||||
// возврат к странице page4
|
||||
goBack();
|
||||
});
|
||||
}
|
25
js/validation.js
Normal file
25
js/validation.js
Normal file
@ -0,0 +1,25 @@
|
||||
// модуль используется для валидации форма на странице
|
||||
|
||||
function validation() {
|
||||
// поиск всех форма с классом .needs-validation
|
||||
const forms = document.querySelectorAll("form.needs-validation");
|
||||
|
||||
for (let i = 0; i < forms.length; i += 1) {
|
||||
const form = forms[i];
|
||||
// для каждой формы добавляется обработчик события отправки
|
||||
form.addEventListener("submit", (event) => {
|
||||
// если форма не прошла валидацию
|
||||
// то выключить стандартное действие
|
||||
if (!form.checkValidity()) {
|
||||
event.preventDefault();
|
||||
// предотвращает распространение preventDefault
|
||||
// на другие объекты
|
||||
event.stopPropagation();
|
||||
}
|
||||
// добавляет к форме класс was-validated
|
||||
form.classList.add("was-validated");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default validation;
|
177
lkAdmin.html
177
lkAdmin.html
@ -4,7 +4,7 @@
|
||||
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://fonts.cdnfonts.com/css/correction-tape" rel="stylesheet">
|
||||
<title>Admin</title>
|
||||
<title>ADMIN</title>
|
||||
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
|
||||
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
|
||||
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
|
||||
@ -18,6 +18,7 @@
|
||||
</script>
|
||||
|
||||
</head>
|
||||
|
||||
<body class="h-100 d-flex flex-column">
|
||||
<div id="menu-wrapper">
|
||||
<div id="menu">
|
||||
@ -49,108 +50,96 @@
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main class="container-fluid p-2">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-8">
|
||||
<div class="info">
|
||||
<h1>Таблица событий</h1>
|
||||
<div class="info-text container" style="max-height: 25vh; overflow-y: auto;">
|
||||
<table class="table" style="color: aliceblue;">
|
||||
<div>
|
||||
<table id="items-table" class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Дата покупки</th>
|
||||
<th>Название</th>
|
||||
<th>Дата проведения</th>
|
||||
<th>Стоимость</th>
|
||||
<th>Место проведения</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
<th scope="col">№</th>
|
||||
<th scope="col">Название</th>
|
||||
<th scope="col">Тип события</th>
|
||||
<th scope="col">Дата проведения</th>
|
||||
<th scope="col">Стоимость</th>
|
||||
<th scope="col">Место проведения</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Ячейка 1</td>
|
||||
<td>Ячейка 2</td>
|
||||
<td>Ячейка 3</td>
|
||||
<td>Ячейка 4</td>
|
||||
<td>Ячейка 5</td>
|
||||
<td><button class="btn btn-primary" onclick="">отменить</button></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info">
|
||||
<h1>Таблица пользователей</h1>
|
||||
<div class="info-text container" style="max-height: 25vh; overflow-y: auto;">
|
||||
<table class="table" style="color: aliceblue;">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Дата покупки</th>
|
||||
<th>Название</th>
|
||||
<th>Дата проведения</th>
|
||||
<th>Стоимость</th>
|
||||
<th>Место проведения</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Ячейка 1</td>
|
||||
<td>Ячейка 2</td>
|
||||
<td>Ячейка 3</td>
|
||||
<td>Ячейка 4</td>
|
||||
<td>Ячейка 5</td>
|
||||
<td><button class="btn btn-primary" onclick="">отменить</button></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="info" style="max-height: 90vh; overflow-y: auto;">
|
||||
<h1>Добавить событие</h1>
|
||||
<form>
|
||||
<div class="mb-1">
|
||||
<label for="name" class="form-label">Название</label>
|
||||
<input type="text" class="form-control" id="name" placeholder="Введите название">
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="type" class="form-label">Тип</label>
|
||||
<select class="form-control" id="type" name="type" placeholder="Выберите тип">
|
||||
<option value="option1">Концерт</option>
|
||||
<option value="option2">Кино</option>
|
||||
<option value="option3">Театр</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="date" class="form-label">Дата</label>
|
||||
<input type="date" class="form-control" id="date">
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="price" class="form-label">Стоимость</label>
|
||||
<input id="price" name="price" class="form-control" type="number" value="0.00" min="1000.00"
|
||||
step="0.50" required placeholder="Введите стоимость">
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="description" class="form-label">Описание</label>
|
||||
<textarea class="form-control" id="description" rows="3" placeholder="Введите описание"></textarea>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label for="photo" class="form-label">Фото</label>
|
||||
<input type="file" class="form-control" id="photo">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Добавить</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-center" role="group">
|
||||
<button id="items-add" class="btn btn-primary" style="font-size: 30px;">Добавить</button>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
|
||||
Иевлева Милана, 2023
|
||||
</footer>
|
||||
<div id="items-update" class="modal fade" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
|
||||
<div class="modal-dialog">
|
||||
<form id="items-form" class="needs-validation" novalidate>
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h1 class="modal-title fs-5" id="items-update-title"></h1>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="text-center">
|
||||
<img id="image-preview" src="https://pic.onlinewebfonts.com/svg/img_351184.svg" class="rounded rounded-circle"
|
||||
alt="placeholder">
|
||||
</div>
|
||||
|
||||
<input id="items-line-id" type="number" hidden>
|
||||
|
||||
<div class="mb-1">
|
||||
<label for="ItName" class="form-label">Название</label>
|
||||
<input id="ItName" name="ItName" class="form-control" type="text" placeholder="Название" required>
|
||||
</div>
|
||||
|
||||
<div class="mb-1">
|
||||
<label for="item" class="form-label">Тип мероприятия</label>
|
||||
<select id="item" class="form-select" name="selected" placeholder="Тип мероприятия" required>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="mb-1">
|
||||
<label for="date" class="form-label">Дата проведения</label>
|
||||
<input type="date" class="form-control" id="date" placeholder="Дата проведения" required>
|
||||
</div>
|
||||
|
||||
<div class="mb-1">
|
||||
<label class="form-label" for="price">Стоимость</label>
|
||||
<input id="price" name="price" class="form-control" type="number" value="0.00" min="1000.00"
|
||||
step="100" placeholder="Стоимость" required>
|
||||
</div>
|
||||
|
||||
<div class="mb-1">
|
||||
<label for="place" class="form-label">Место проведения</label>
|
||||
<select id="place" class="form-select" name="selected" placeholder="Место проведения" required>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="mb-1">
|
||||
<label class="form-label" for="image">Изображение</label>
|
||||
<input id="image" type="file" name="image" class="form-control" accept="image/*">
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
|
||||
<button type="submit" class="btn btn-primary">Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<script type="module">
|
||||
import validation from "./js/validation";
|
||||
import { linesForm } from "./js/lines";
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
validation();
|
||||
linesForm();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
4
node_modules/npm-run-all/node_modules/.bin/semver → node_modules/.bin/json-server
generated
vendored
4
node_modules/npm-run-all/node_modules/.bin/semver → node_modules/.bin/json-server
generated
vendored
@ -10,7 +10,7 @@ case `uname` in
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../semver/bin/semver" "$@"
|
||||
exec "$basedir/node" "$basedir/../json-server/lib/cli/bin.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../semver/bin/semver" "$@"
|
||||
exec node "$basedir/../json-server/lib/cli/bin.js" "$@"
|
||||
fi
|
@ -14,4 +14,4 @@ IF EXIST "%dp0%\node.exe" (
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver" %*
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\json-server\lib\cli\bin.js" %*
|
@ -11,17 +11,17 @@ $ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver" $args
|
||||
$input | & "$basedir/node$exe" "$basedir/../json-server/lib/cli/bin.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../semver/bin/semver" $args
|
||||
& "$basedir/node$exe" "$basedir/../json-server/lib/cli/bin.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../semver/bin/semver" $args
|
||||
$input | & "node$exe" "$basedir/../json-server/lib/cli/bin.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../semver/bin/semver" $args
|
||||
& "node$exe" "$basedir/../json-server/lib/cli/bin.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
0
node_modules/npm-run-all/node_modules/.bin/which → node_modules/.bin/which
generated
vendored
0
node_modules/npm-run-all/node_modules/.bin/which → node_modules/.bin/which
generated
vendored
0
node_modules/npm-run-all/node_modules/.bin/which.cmd → node_modules/.bin/which.cmd
generated
vendored
0
node_modules/npm-run-all/node_modules/.bin/which.cmd → node_modules/.bin/which.cmd
generated
vendored
0
node_modules/npm-run-all/node_modules/.bin/which.ps1 → node_modules/.bin/which.ps1
generated
vendored
0
node_modules/npm-run-all/node_modules/.bin/which.ps1 → node_modules/.bin/which.ps1
generated
vendored
1189
node_modules/.package-lock.json
generated
vendored
1189
node_modules/.package-lock.json
generated
vendored
File diff suppressed because it is too large
Load Diff
1504
node_modules/.vite/deps/@popperjs_core.js
generated
vendored
1504
node_modules/.vite/deps/@popperjs_core.js
generated
vendored
File diff suppressed because it is too large
Load Diff
8
node_modules/.vite/deps/@popperjs_core.js.map
generated
vendored
8
node_modules/.vite/deps/@popperjs_core.js.map
generated
vendored
File diff suppressed because one or more lines are too long
18
node_modules/.vite/deps/_metadata.json
generated
vendored
18
node_modules/.vite/deps/_metadata.json
generated
vendored
@ -1,13 +1,23 @@
|
||||
{
|
||||
"hash": "6ab68219",
|
||||
"browserHash": "d57d5172",
|
||||
"hash": "b01d275e",
|
||||
"browserHash": "4dc28aa6",
|
||||
"optimized": {
|
||||
"@popperjs/core": {
|
||||
"src": "../../@popperjs/core/lib/index.js",
|
||||
"file": "@popperjs_core.js",
|
||||
"fileHash": "0bea50e2",
|
||||
"fileHash": "c8c53402",
|
||||
"needsInterop": false
|
||||
},
|
||||
"bootstrap": {
|
||||
"src": "../../bootstrap/dist/js/bootstrap.esm.js",
|
||||
"file": "bootstrap.js",
|
||||
"fileHash": "c05ae548",
|
||||
"needsInterop": false
|
||||
}
|
||||
},
|
||||
"chunks": {}
|
||||
"chunks": {
|
||||
"chunk-IOJ6CEWC": {
|
||||
"file": "chunk-IOJ6CEWC.js"
|
||||
}
|
||||
}
|
||||
}
|
3676
node_modules/.vite/deps/bootstrap.js
generated
vendored
Normal file
3676
node_modules/.vite/deps/bootstrap.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
7
node_modules/.vite/deps/bootstrap.js.map
generated
vendored
Normal file
7
node_modules/.vite/deps/bootstrap.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1556
node_modules/.vite/deps/chunk-IOJ6CEWC.js
generated
vendored
Normal file
1556
node_modules/.vite/deps/chunk-IOJ6CEWC.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
7
node_modules/.vite/deps/chunk-IOJ6CEWC.js.map
generated
vendored
Normal file
7
node_modules/.vite/deps/chunk-IOJ6CEWC.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
243
node_modules/accepts/HISTORY.md
generated
vendored
Normal file
243
node_modules/accepts/HISTORY.md
generated
vendored
Normal file
@ -0,0 +1,243 @@
|
||||
1.3.8 / 2022-02-02
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.34
|
||||
- deps: mime-db@~1.51.0
|
||||
* deps: negotiator@0.6.3
|
||||
|
||||
1.3.7 / 2019-04-29
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.6.2
|
||||
- Fix sorting charset, encoding, and language with extra parameters
|
||||
|
||||
1.3.6 / 2019-04-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.24
|
||||
- deps: mime-db@~1.40.0
|
||||
|
||||
1.3.5 / 2018-02-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.18
|
||||
- deps: mime-db@~1.33.0
|
||||
|
||||
1.3.4 / 2017-08-22
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.16
|
||||
- deps: mime-db@~1.29.0
|
||||
|
||||
1.3.3 / 2016-05-02
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.11
|
||||
- deps: mime-db@~1.23.0
|
||||
* deps: negotiator@0.6.1
|
||||
- perf: improve `Accept` parsing speed
|
||||
- perf: improve `Accept-Charset` parsing speed
|
||||
- perf: improve `Accept-Encoding` parsing speed
|
||||
- perf: improve `Accept-Language` parsing speed
|
||||
|
||||
1.3.2 / 2016-03-08
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.10
|
||||
- Fix extension of `application/dash+xml`
|
||||
- Update primary extension for `audio/mp4`
|
||||
- deps: mime-db@~1.22.0
|
||||
|
||||
1.3.1 / 2016-01-19
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.9
|
||||
- deps: mime-db@~1.21.0
|
||||
|
||||
1.3.0 / 2015-09-29
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.7
|
||||
- deps: mime-db@~1.19.0
|
||||
* deps: negotiator@0.6.0
|
||||
- Fix including type extensions in parameters in `Accept` parsing
|
||||
- Fix parsing `Accept` parameters with quoted equals
|
||||
- Fix parsing `Accept` parameters with quoted semicolons
|
||||
- Lazy-load modules from main entry point
|
||||
- perf: delay type concatenation until needed
|
||||
- perf: enable strict mode
|
||||
- perf: hoist regular expressions
|
||||
- perf: remove closures getting spec properties
|
||||
- perf: remove a closure from media type parsing
|
||||
- perf: remove property delete from media type parsing
|
||||
|
||||
1.2.13 / 2015-09-06
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.6
|
||||
- deps: mime-db@~1.18.0
|
||||
|
||||
1.2.12 / 2015-07-30
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.4
|
||||
- deps: mime-db@~1.16.0
|
||||
|
||||
1.2.11 / 2015-07-16
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.3
|
||||
- deps: mime-db@~1.15.0
|
||||
|
||||
1.2.10 / 2015-07-01
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.2
|
||||
- deps: mime-db@~1.14.0
|
||||
|
||||
1.2.9 / 2015-06-08
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.1
|
||||
- perf: fix deopt during mapping
|
||||
|
||||
1.2.8 / 2015-06-07
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.0
|
||||
- deps: mime-db@~1.13.0
|
||||
* perf: avoid argument reassignment & argument slice
|
||||
* perf: avoid negotiator recursive construction
|
||||
* perf: enable strict mode
|
||||
* perf: remove unnecessary bitwise operator
|
||||
|
||||
1.2.7 / 2015-05-10
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.5.3
|
||||
- Fix media type parameter matching to be case-insensitive
|
||||
|
||||
1.2.6 / 2015-05-07
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.11
|
||||
- deps: mime-db@~1.9.1
|
||||
* deps: negotiator@0.5.2
|
||||
- Fix comparing media types with quoted values
|
||||
- Fix splitting media types with quoted commas
|
||||
|
||||
1.2.5 / 2015-03-13
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.10
|
||||
- deps: mime-db@~1.8.0
|
||||
|
||||
1.2.4 / 2015-02-14
|
||||
==================
|
||||
|
||||
* Support Node.js 0.6
|
||||
* deps: mime-types@~2.0.9
|
||||
- deps: mime-db@~1.7.0
|
||||
* deps: negotiator@0.5.1
|
||||
- Fix preference sorting to be stable for long acceptable lists
|
||||
|
||||
1.2.3 / 2015-01-31
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.8
|
||||
- deps: mime-db@~1.6.0
|
||||
|
||||
1.2.2 / 2014-12-30
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.7
|
||||
- deps: mime-db@~1.5.0
|
||||
|
||||
1.2.1 / 2014-12-30
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.5
|
||||
- deps: mime-db@~1.3.1
|
||||
|
||||
1.2.0 / 2014-12-19
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.5.0
|
||||
- Fix list return order when large accepted list
|
||||
- Fix missing identity encoding when q=0 exists
|
||||
- Remove dynamic building of Negotiator class
|
||||
|
||||
1.1.4 / 2014-12-10
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.4
|
||||
- deps: mime-db@~1.3.0
|
||||
|
||||
1.1.3 / 2014-11-09
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.3
|
||||
- deps: mime-db@~1.2.0
|
||||
|
||||
1.1.2 / 2014-10-14
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.9
|
||||
- Fix error when media type has invalid parameter
|
||||
|
||||
1.1.1 / 2014-09-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.2
|
||||
- deps: mime-db@~1.1.0
|
||||
* deps: negotiator@0.4.8
|
||||
- Fix all negotiations to be case-insensitive
|
||||
- Stable sort preferences of same quality according to client order
|
||||
|
||||
1.1.0 / 2014-09-02
|
||||
==================
|
||||
|
||||
* update `mime-types`
|
||||
|
||||
1.0.7 / 2014-07-04
|
||||
==================
|
||||
|
||||
* Fix wrong type returned from `type` when match after unknown extension
|
||||
|
||||
1.0.6 / 2014-06-24
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.7
|
||||
|
||||
1.0.5 / 2014-06-20
|
||||
==================
|
||||
|
||||
* fix crash when unknown extension given
|
||||
|
||||
1.0.4 / 2014-06-19
|
||||
==================
|
||||
|
||||
* use `mime-types`
|
||||
|
||||
1.0.3 / 2014-06-11
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.6
|
||||
- Order by specificity when quality is the same
|
||||
|
||||
1.0.2 / 2014-05-29
|
||||
==================
|
||||
|
||||
* Fix interpretation when header not in request
|
||||
* deps: pin negotiator@0.4.5
|
||||
|
||||
1.0.1 / 2014-01-18
|
||||
==================
|
||||
|
||||
* Identity encoding isn't always acceptable
|
||||
* deps: negotiator@~0.4.0
|
||||
|
||||
1.0.0 / 2013-12-27
|
||||
==================
|
||||
|
||||
* Genesis
|
23
node_modules/accepts/LICENSE
generated
vendored
Normal file
23
node_modules/accepts/LICENSE
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
|
||||
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.
|
140
node_modules/accepts/README.md
generated
vendored
Normal file
140
node_modules/accepts/README.md
generated
vendored
Normal file
@ -0,0 +1,140 @@
|
||||
# accepts
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Node.js Version][node-version-image]][node-version-url]
|
||||
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
|
||||
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
|
||||
|
||||
In addition to negotiator, it allows:
|
||||
|
||||
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
|
||||
as well as `('text/html', 'application/json')`.
|
||||
- Allows type shorthands such as `json`.
|
||||
- Returns `false` when no types match
|
||||
- Treats non-existent headers as `*`
|
||||
|
||||
## Installation
|
||||
|
||||
This is a [Node.js](https://nodejs.org/en/) module available through the
|
||||
[npm registry](https://www.npmjs.com/). Installation is done using the
|
||||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
||||
|
||||
```sh
|
||||
$ npm install accepts
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
var accepts = require('accepts')
|
||||
```
|
||||
|
||||
### accepts(req)
|
||||
|
||||
Create a new `Accepts` object for the given `req`.
|
||||
|
||||
#### .charset(charsets)
|
||||
|
||||
Return the first accepted charset. If nothing in `charsets` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .charsets()
|
||||
|
||||
Return the charsets that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .encoding(encodings)
|
||||
|
||||
Return the first accepted encoding. If nothing in `encodings` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .encodings()
|
||||
|
||||
Return the encodings that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .language(languages)
|
||||
|
||||
Return the first accepted language. If nothing in `languages` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .languages()
|
||||
|
||||
Return the languages that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .type(types)
|
||||
|
||||
Return the first accepted type (and it is returned as the same text as what
|
||||
appears in the `types` array). If nothing in `types` is accepted, then `false`
|
||||
is returned.
|
||||
|
||||
The `types` array can contain full MIME types or file extensions. Any value
|
||||
that is not a full MIME types is passed to `require('mime-types').lookup`.
|
||||
|
||||
#### .types()
|
||||
|
||||
Return the types that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
## Examples
|
||||
|
||||
### Simple type negotiation
|
||||
|
||||
This simple example shows how to use `accepts` to return a different typed
|
||||
respond body based on what the client wants to accept. The server lists it's
|
||||
preferences in order and will get back the best match between the client and
|
||||
server.
|
||||
|
||||
```js
|
||||
var accepts = require('accepts')
|
||||
var http = require('http')
|
||||
|
||||
function app (req, res) {
|
||||
var accept = accepts(req)
|
||||
|
||||
// the order of this list is significant; should be server preferred order
|
||||
switch (accept.type(['json', 'html'])) {
|
||||
case 'json':
|
||||
res.setHeader('Content-Type', 'application/json')
|
||||
res.write('{"hello":"world!"}')
|
||||
break
|
||||
case 'html':
|
||||
res.setHeader('Content-Type', 'text/html')
|
||||
res.write('<b>hello, world!</b>')
|
||||
break
|
||||
default:
|
||||
// the fallback is text/plain, so no need to specify it above
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.write('hello, world!')
|
||||
break
|
||||
}
|
||||
|
||||
res.end()
|
||||
}
|
||||
|
||||
http.createServer(app).listen(3000)
|
||||
```
|
||||
|
||||
You can test this out with the cURL program:
|
||||
```sh
|
||||
curl -I -H'Accept: text/html' http://localhost:3000/
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
|
||||
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
|
||||
[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
|
||||
[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
|
||||
[node-version-image]: https://badgen.net/npm/node/accepts
|
||||
[node-version-url]: https://nodejs.org/en/download
|
||||
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
|
||||
[npm-url]: https://npmjs.org/package/accepts
|
||||
[npm-version-image]: https://badgen.net/npm/v/accepts
|
238
node_modules/accepts/index.js
generated
vendored
Normal file
238
node_modules/accepts/index.js
generated
vendored
Normal file
@ -0,0 +1,238 @@
|
||||
/*!
|
||||
* accepts
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var Negotiator = require('negotiator')
|
||||
var mime = require('mime-types')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = Accepts
|
||||
|
||||
/**
|
||||
* Create a new Accepts object for the given req.
|
||||
*
|
||||
* @param {object} req
|
||||
* @public
|
||||
*/
|
||||
|
||||
function Accepts (req) {
|
||||
if (!(this instanceof Accepts)) {
|
||||
return new Accepts(req)
|
||||
}
|
||||
|
||||
this.headers = req.headers
|
||||
this.negotiator = new Negotiator(req)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given `type(s)` is acceptable, returning
|
||||
* the best match when true, otherwise `undefined`, in which
|
||||
* case you should respond with 406 "Not Acceptable".
|
||||
*
|
||||
* The `type` value may be a single mime type string
|
||||
* such as "application/json", the extension name
|
||||
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
|
||||
* or array is given the _best_ match, if any is returned.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* // Accept: text/html
|
||||
* this.types('html');
|
||||
* // => "html"
|
||||
*
|
||||
* // Accept: text/*, application/json
|
||||
* this.types('html');
|
||||
* // => "html"
|
||||
* this.types('text/html');
|
||||
* // => "text/html"
|
||||
* this.types('json', 'text');
|
||||
* // => "json"
|
||||
* this.types('application/json');
|
||||
* // => "application/json"
|
||||
*
|
||||
* // Accept: text/*, application/json
|
||||
* this.types('image/png');
|
||||
* this.types('png');
|
||||
* // => undefined
|
||||
*
|
||||
* // Accept: text/*;q=.5, application/json
|
||||
* this.types(['html', 'json']);
|
||||
* this.types('html', 'json');
|
||||
* // => "json"
|
||||
*
|
||||
* @param {String|Array} types...
|
||||
* @return {String|Array|Boolean}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.type =
|
||||
Accepts.prototype.types = function (types_) {
|
||||
var types = types_
|
||||
|
||||
// support flattened arguments
|
||||
if (types && !Array.isArray(types)) {
|
||||
types = new Array(arguments.length)
|
||||
for (var i = 0; i < types.length; i++) {
|
||||
types[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no types, return all requested types
|
||||
if (!types || types.length === 0) {
|
||||
return this.negotiator.mediaTypes()
|
||||
}
|
||||
|
||||
// no accept header, return first given type
|
||||
if (!this.headers.accept) {
|
||||
return types[0]
|
||||
}
|
||||
|
||||
var mimes = types.map(extToMime)
|
||||
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
|
||||
var first = accepts[0]
|
||||
|
||||
return first
|
||||
? types[mimes.indexOf(first)]
|
||||
: false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted encodings or best fit based on `encodings`.
|
||||
*
|
||||
* Given `Accept-Encoding: gzip, deflate`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['gzip', 'deflate']
|
||||
*
|
||||
* @param {String|Array} encodings...
|
||||
* @return {String|Array}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.encoding =
|
||||
Accepts.prototype.encodings = function (encodings_) {
|
||||
var encodings = encodings_
|
||||
|
||||
// support flattened arguments
|
||||
if (encodings && !Array.isArray(encodings)) {
|
||||
encodings = new Array(arguments.length)
|
||||
for (var i = 0; i < encodings.length; i++) {
|
||||
encodings[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no encodings, return all requested encodings
|
||||
if (!encodings || encodings.length === 0) {
|
||||
return this.negotiator.encodings()
|
||||
}
|
||||
|
||||
return this.negotiator.encodings(encodings)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted charsets or best fit based on `charsets`.
|
||||
*
|
||||
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['utf-8', 'utf-7', 'iso-8859-1']
|
||||
*
|
||||
* @param {String|Array} charsets...
|
||||
* @return {String|Array}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.charset =
|
||||
Accepts.prototype.charsets = function (charsets_) {
|
||||
var charsets = charsets_
|
||||
|
||||
// support flattened arguments
|
||||
if (charsets && !Array.isArray(charsets)) {
|
||||
charsets = new Array(arguments.length)
|
||||
for (var i = 0; i < charsets.length; i++) {
|
||||
charsets[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no charsets, return all requested charsets
|
||||
if (!charsets || charsets.length === 0) {
|
||||
return this.negotiator.charsets()
|
||||
}
|
||||
|
||||
return this.negotiator.charsets(charsets)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted languages or best fit based on `langs`.
|
||||
*
|
||||
* Given `Accept-Language: en;q=0.8, es, pt`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['es', 'pt', 'en']
|
||||
*
|
||||
* @param {String|Array} langs...
|
||||
* @return {Array|String}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.lang =
|
||||
Accepts.prototype.langs =
|
||||
Accepts.prototype.language =
|
||||
Accepts.prototype.languages = function (languages_) {
|
||||
var languages = languages_
|
||||
|
||||
// support flattened arguments
|
||||
if (languages && !Array.isArray(languages)) {
|
||||
languages = new Array(arguments.length)
|
||||
for (var i = 0; i < languages.length; i++) {
|
||||
languages[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no languages, return all requested languages
|
||||
if (!languages || languages.length === 0) {
|
||||
return this.negotiator.languages()
|
||||
}
|
||||
|
||||
return this.negotiator.languages(languages)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert extnames to mime.
|
||||
*
|
||||
* @param {String} type
|
||||
* @return {String}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function extToMime (type) {
|
||||
return type.indexOf('/') === -1
|
||||
? mime.lookup(type)
|
||||
: type
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if mime is valid.
|
||||
*
|
||||
* @param {String} type
|
||||
* @return {String}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function validMime (type) {
|
||||
return typeof type === 'string'
|
||||
}
|
47
node_modules/accepts/package.json
generated
vendored
Normal file
47
node_modules/accepts/package.json
generated
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "accepts",
|
||||
"description": "Higher-level content negotiation",
|
||||
"version": "1.3.8",
|
||||
"contributors": [
|
||||
"Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "jshttp/accepts",
|
||||
"dependencies": {
|
||||
"mime-types": "~2.1.34",
|
||||
"negotiator": "0.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"deep-equal": "1.0.1",
|
||||
"eslint": "7.32.0",
|
||||
"eslint-config-standard": "14.1.1",
|
||||
"eslint-plugin-import": "2.25.4",
|
||||
"eslint-plugin-markdown": "2.2.1",
|
||||
"eslint-plugin-node": "11.1.0",
|
||||
"eslint-plugin-promise": "4.3.1",
|
||||
"eslint-plugin-standard": "4.1.0",
|
||||
"mocha": "9.2.0",
|
||||
"nyc": "15.1.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"HISTORY.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --reporter spec --check-leaks --bail test/",
|
||||
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
},
|
||||
"keywords": [
|
||||
"content",
|
||||
"negotiation",
|
||||
"accept",
|
||||
"accepts"
|
||||
]
|
||||
}
|
37
node_modules/ansi-regex/index.d.ts
generated
vendored
Normal file
37
node_modules/ansi-regex/index.d.ts
generated
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
declare namespace ansiRegex {
|
||||
interface Options {
|
||||
/**
|
||||
Match only the first ANSI escape.
|
||||
|
||||
@default false
|
||||
*/
|
||||
onlyFirst: boolean;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Regular expression for matching ANSI escape codes.
|
||||
|
||||
@example
|
||||
```
|
||||
import ansiRegex = require('ansi-regex');
|
||||
|
||||
ansiRegex().test('\u001B[4mcake\u001B[0m');
|
||||
//=> true
|
||||
|
||||
ansiRegex().test('cake');
|
||||
//=> false
|
||||
|
||||
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
|
||||
//=> ['\u001B[4m', '\u001B[0m']
|
||||
|
||||
'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
|
||||
//=> ['\u001B[4m']
|
||||
|
||||
'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex());
|
||||
//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007']
|
||||
```
|
||||
*/
|
||||
declare function ansiRegex(options?: ansiRegex.Options): RegExp;
|
||||
|
||||
export = ansiRegex;
|
10
node_modules/ansi-regex/index.js
generated
vendored
Normal file
10
node_modules/ansi-regex/index.js
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = ({onlyFirst = false} = {}) => {
|
||||
const pattern = [
|
||||
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
|
||||
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
|
||||
].join('|');
|
||||
|
||||
return new RegExp(pattern, onlyFirst ? undefined : 'g');
|
||||
};
|
9
node_modules/ansi-regex/license
generated
vendored
Normal file
9
node_modules/ansi-regex/license
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
|
||||
|
||||
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.
|
55
node_modules/ansi-regex/package.json
generated
vendored
Normal file
55
node_modules/ansi-regex/package.json
generated
vendored
Normal file
@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "ansi-regex",
|
||||
"version": "5.0.1",
|
||||
"description": "Regular expression for matching ANSI escape codes",
|
||||
"license": "MIT",
|
||||
"repository": "chalk/ansi-regex",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "sindresorhus.com"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && ava && tsd",
|
||||
"view-supported": "node fixtures/view-codes.js"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts"
|
||||
],
|
||||
"keywords": [
|
||||
"ansi",
|
||||
"styles",
|
||||
"color",
|
||||
"colour",
|
||||
"colors",
|
||||
"terminal",
|
||||
"console",
|
||||
"cli",
|
||||
"string",
|
||||
"tty",
|
||||
"escape",
|
||||
"formatting",
|
||||
"rgb",
|
||||
"256",
|
||||
"shell",
|
||||
"xterm",
|
||||
"command-line",
|
||||
"text",
|
||||
"regex",
|
||||
"regexp",
|
||||
"re",
|
||||
"match",
|
||||
"test",
|
||||
"find",
|
||||
"pattern"
|
||||
],
|
||||
"devDependencies": {
|
||||
"ava": "^2.4.0",
|
||||
"tsd": "^0.9.0",
|
||||
"xo": "^0.25.3"
|
||||
}
|
||||
}
|
78
node_modules/ansi-regex/readme.md
generated
vendored
Normal file
78
node_modules/ansi-regex/readme.md
generated
vendored
Normal file
@ -0,0 +1,78 @@
|
||||
# ansi-regex
|
||||
|
||||
> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install ansi-regex
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const ansiRegex = require('ansi-regex');
|
||||
|
||||
ansiRegex().test('\u001B[4mcake\u001B[0m');
|
||||
//=> true
|
||||
|
||||
ansiRegex().test('cake');
|
||||
//=> false
|
||||
|
||||
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
|
||||
//=> ['\u001B[4m', '\u001B[0m']
|
||||
|
||||
'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
|
||||
//=> ['\u001B[4m']
|
||||
|
||||
'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex());
|
||||
//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007']
|
||||
```
|
||||
|
||||
|
||||
## API
|
||||
|
||||
### ansiRegex(options?)
|
||||
|
||||
Returns a regex for matching ANSI escape codes.
|
||||
|
||||
#### options
|
||||
|
||||
Type: `object`
|
||||
|
||||
##### onlyFirst
|
||||
|
||||
Type: `boolean`<br>
|
||||
Default: `false` *(Matches any ANSI escape codes in a string)*
|
||||
|
||||
Match only the first ANSI escape.
|
||||
|
||||
|
||||
## FAQ
|
||||
|
||||
### Why do you test for codes not in the ECMA 48 standard?
|
||||
|
||||
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
|
||||
|
||||
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
|
||||
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||
- [Josh Junon](https://github.com/qix-)
|
||||
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<b>
|
||||
<a href="https://tidelift.com/subscription/pkg/npm-ansi-regex?utm_source=npm-ansi-regex&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
|
||||
</b>
|
||||
<br>
|
||||
<sub>
|
||||
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
|
||||
</sub>
|
||||
</div>
|
21
node_modules/array-flatten/LICENSE
generated
vendored
Normal file
21
node_modules/array-flatten/LICENSE
generated
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com)
|
||||
|
||||
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.
|
43
node_modules/array-flatten/README.md
generated
vendored
Normal file
43
node_modules/array-flatten/README.md
generated
vendored
Normal file
@ -0,0 +1,43 @@
|
||||
# Array Flatten
|
||||
|
||||
[![NPM version][npm-image]][npm-url]
|
||||
[![NPM downloads][downloads-image]][downloads-url]
|
||||
[![Build status][travis-image]][travis-url]
|
||||
[![Test coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
> Flatten an array of nested arrays into a single flat array. Accepts an optional depth.
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
npm install array-flatten --save
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```javascript
|
||||
var flatten = require('array-flatten')
|
||||
|
||||
flatten([1, [2, [3, [4, [5], 6], 7], 8], 9])
|
||||
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
|
||||
flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2)
|
||||
//=> [1, 2, 3, [4, [5], 6], 7, 8, 9]
|
||||
|
||||
(function () {
|
||||
flatten(arguments) //=> [1, 2, 3]
|
||||
})(1, [2, 3])
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat
|
||||
[npm-url]: https://npmjs.org/package/array-flatten
|
||||
[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat
|
||||
[downloads-url]: https://npmjs.org/package/array-flatten
|
||||
[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat
|
||||
[travis-url]: https://travis-ci.org/blakeembrey/array-flatten
|
||||
[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat
|
||||
[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master
|
64
node_modules/array-flatten/array-flatten.js
generated
vendored
Normal file
64
node_modules/array-flatten/array-flatten.js
generated
vendored
Normal file
@ -0,0 +1,64 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Expose `arrayFlatten`.
|
||||
*/
|
||||
module.exports = arrayFlatten
|
||||
|
||||
/**
|
||||
* Recursive flatten function with depth.
|
||||
*
|
||||
* @param {Array} array
|
||||
* @param {Array} result
|
||||
* @param {Number} depth
|
||||
* @return {Array}
|
||||
*/
|
||||
function flattenWithDepth (array, result, depth) {
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
var value = array[i]
|
||||
|
||||
if (depth > 0 && Array.isArray(value)) {
|
||||
flattenWithDepth(value, result, depth - 1)
|
||||
} else {
|
||||
result.push(value)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive flatten function. Omitting depth is slightly faster.
|
||||
*
|
||||
* @param {Array} array
|
||||
* @param {Array} result
|
||||
* @return {Array}
|
||||
*/
|
||||
function flattenForever (array, result) {
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
var value = array[i]
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
flattenForever(value, result)
|
||||
} else {
|
||||
result.push(value)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Flatten an array, with the ability to define a depth.
|
||||
*
|
||||
* @param {Array} array
|
||||
* @param {Number} depth
|
||||
* @return {Array}
|
||||
*/
|
||||
function arrayFlatten (array, depth) {
|
||||
if (depth == null) {
|
||||
return flattenForever(array, [])
|
||||
}
|
||||
|
||||
return flattenWithDepth(array, [], depth)
|
||||
}
|
39
node_modules/array-flatten/package.json
generated
vendored
Normal file
39
node_modules/array-flatten/package.json
generated
vendored
Normal file
@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "array-flatten",
|
||||
"version": "1.1.1",
|
||||
"description": "Flatten an array of nested arrays into a single flat array",
|
||||
"main": "array-flatten.js",
|
||||
"files": [
|
||||
"array-flatten.js",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "istanbul cover _mocha -- -R spec"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/blakeembrey/array-flatten.git"
|
||||
},
|
||||
"keywords": [
|
||||
"array",
|
||||
"flatten",
|
||||
"arguments",
|
||||
"depth"
|
||||
],
|
||||
"author": {
|
||||
"name": "Blake Embrey",
|
||||
"email": "hello@blakeembrey.com",
|
||||
"url": "http://blakeembrey.me"
|
||||
},
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/blakeembrey/array-flatten/issues"
|
||||
},
|
||||
"homepage": "https://github.com/blakeembrey/array-flatten",
|
||||
"devDependencies": {
|
||||
"istanbul": "^0.3.13",
|
||||
"mocha": "^2.2.4",
|
||||
"pre-commit": "^1.0.7",
|
||||
"standard": "^3.7.3"
|
||||
}
|
||||
}
|
665
node_modules/body-parser/HISTORY.md
generated
vendored
Normal file
665
node_modules/body-parser/HISTORY.md
generated
vendored
Normal file
@ -0,0 +1,665 @@
|
||||
1.20.2 / 2023-02-21
|
||||
===================
|
||||
|
||||
* Fix strict json error message on Node.js 19+
|
||||
* deps: content-type@~1.0.5
|
||||
- perf: skip value escaping when unnecessary
|
||||
* deps: raw-body@2.5.2
|
||||
|
||||
1.20.1 / 2022-10-06
|
||||
===================
|
||||
|
||||
* deps: qs@6.11.0
|
||||
* perf: remove unnecessary object clone
|
||||
|
||||
1.20.0 / 2022-04-02
|
||||
===================
|
||||
|
||||
* Fix error message for json parse whitespace in `strict`
|
||||
* Fix internal error when inflated body exceeds limit
|
||||
* Prevent loss of async hooks context
|
||||
* Prevent hanging when request already read
|
||||
* deps: depd@2.0.0
|
||||
- Replace internal `eval` usage with `Function` constructor
|
||||
- Use instance methods on `process` to check for listeners
|
||||
* deps: http-errors@2.0.0
|
||||
- deps: depd@2.0.0
|
||||
- deps: statuses@2.0.1
|
||||
* deps: on-finished@2.4.1
|
||||
* deps: qs@6.10.3
|
||||
* deps: raw-body@2.5.1
|
||||
- deps: http-errors@2.0.0
|
||||
|
||||
1.19.2 / 2022-02-15
|
||||
===================
|
||||
|
||||
* deps: bytes@3.1.2
|
||||
* deps: qs@6.9.7
|
||||
* Fix handling of `__proto__` keys
|
||||
* deps: raw-body@2.4.3
|
||||
- deps: bytes@3.1.2
|
||||
|
||||
1.19.1 / 2021-12-10
|
||||
===================
|
||||
|
||||
* deps: bytes@3.1.1
|
||||
* deps: http-errors@1.8.1
|
||||
- deps: inherits@2.0.4
|
||||
- deps: toidentifier@1.0.1
|
||||
- deps: setprototypeof@1.2.0
|
||||
* deps: qs@6.9.6
|
||||
* deps: raw-body@2.4.2
|
||||
- deps: bytes@3.1.1
|
||||
- deps: http-errors@1.8.1
|
||||
* deps: safe-buffer@5.2.1
|
||||
* deps: type-is@~1.6.18
|
||||
|
||||
1.19.0 / 2019-04-25
|
||||
===================
|
||||
|
||||
* deps: bytes@3.1.0
|
||||
- Add petabyte (`pb`) support
|
||||
* deps: http-errors@1.7.2
|
||||
- Set constructor name when possible
|
||||
- deps: setprototypeof@1.1.1
|
||||
- deps: statuses@'>= 1.5.0 < 2'
|
||||
* deps: iconv-lite@0.4.24
|
||||
- Added encoding MIK
|
||||
* deps: qs@6.7.0
|
||||
- Fix parsing array brackets after index
|
||||
* deps: raw-body@2.4.0
|
||||
- deps: bytes@3.1.0
|
||||
- deps: http-errors@1.7.2
|
||||
- deps: iconv-lite@0.4.24
|
||||
* deps: type-is@~1.6.17
|
||||
- deps: mime-types@~2.1.24
|
||||
- perf: prevent internal `throw` on invalid type
|
||||
|
||||
1.18.3 / 2018-05-14
|
||||
===================
|
||||
|
||||
* Fix stack trace for strict json parse error
|
||||
* deps: depd@~1.1.2
|
||||
- perf: remove argument reassignment
|
||||
* deps: http-errors@~1.6.3
|
||||
- deps: depd@~1.1.2
|
||||
- deps: setprototypeof@1.1.0
|
||||
- deps: statuses@'>= 1.3.1 < 2'
|
||||
* deps: iconv-lite@0.4.23
|
||||
- Fix loading encoding with year appended
|
||||
- Fix deprecation warnings on Node.js 10+
|
||||
* deps: qs@6.5.2
|
||||
* deps: raw-body@2.3.3
|
||||
- deps: http-errors@1.6.3
|
||||
- deps: iconv-lite@0.4.23
|
||||
* deps: type-is@~1.6.16
|
||||
- deps: mime-types@~2.1.18
|
||||
|
||||
1.18.2 / 2017-09-22
|
||||
===================
|
||||
|
||||
* deps: debug@2.6.9
|
||||
* perf: remove argument reassignment
|
||||
|
||||
1.18.1 / 2017-09-12
|
||||
===================
|
||||
|
||||
* deps: content-type@~1.0.4
|
||||
- perf: remove argument reassignment
|
||||
- perf: skip parameter parsing when no parameters
|
||||
* deps: iconv-lite@0.4.19
|
||||
- Fix ISO-8859-1 regression
|
||||
- Update Windows-1255
|
||||
* deps: qs@6.5.1
|
||||
- Fix parsing & compacting very deep objects
|
||||
* deps: raw-body@2.3.2
|
||||
- deps: iconv-lite@0.4.19
|
||||
|
||||
1.18.0 / 2017-09-08
|
||||
===================
|
||||
|
||||
* Fix JSON strict violation error to match native parse error
|
||||
* Include the `body` property on verify errors
|
||||
* Include the `type` property on all generated errors
|
||||
* Use `http-errors` to set status code on errors
|
||||
* deps: bytes@3.0.0
|
||||
* deps: debug@2.6.8
|
||||
* deps: depd@~1.1.1
|
||||
- Remove unnecessary `Buffer` loading
|
||||
* deps: http-errors@~1.6.2
|
||||
- deps: depd@1.1.1
|
||||
* deps: iconv-lite@0.4.18
|
||||
- Add support for React Native
|
||||
- Add a warning if not loaded as utf-8
|
||||
- Fix CESU-8 decoding in Node.js 8
|
||||
- Improve speed of ISO-8859-1 encoding
|
||||
* deps: qs@6.5.0
|
||||
* deps: raw-body@2.3.1
|
||||
- Use `http-errors` for standard emitted errors
|
||||
- deps: bytes@3.0.0
|
||||
- deps: iconv-lite@0.4.18
|
||||
- perf: skip buffer decoding on overage chunk
|
||||
* perf: prevent internal `throw` when missing charset
|
||||
|
||||
1.17.2 / 2017-05-17
|
||||
===================
|
||||
|
||||
* deps: debug@2.6.7
|
||||
- Fix `DEBUG_MAX_ARRAY_LENGTH`
|
||||
- deps: ms@2.0.0
|
||||
* deps: type-is@~1.6.15
|
||||
- deps: mime-types@~2.1.15
|
||||
|
||||
1.17.1 / 2017-03-06
|
||||
===================
|
||||
|
||||
* deps: qs@6.4.0
|
||||
- Fix regression parsing keys starting with `[`
|
||||
|
||||
1.17.0 / 2017-03-01
|
||||
===================
|
||||
|
||||
* deps: http-errors@~1.6.1
|
||||
- Make `message` property enumerable for `HttpError`s
|
||||
- deps: setprototypeof@1.0.3
|
||||
* deps: qs@6.3.1
|
||||
- Fix compacting nested arrays
|
||||
|
||||
1.16.1 / 2017-02-10
|
||||
===================
|
||||
|
||||
* deps: debug@2.6.1
|
||||
- Fix deprecation messages in WebStorm and other editors
|
||||
- Undeprecate `DEBUG_FD` set to `1` or `2`
|
||||
|
||||
1.16.0 / 2017-01-17
|
||||
===================
|
||||
|
||||
* deps: debug@2.6.0
|
||||
- Allow colors in workers
|
||||
- Deprecated `DEBUG_FD` environment variable
|
||||
- Fix error when running under React Native
|
||||
- Use same color for same namespace
|
||||
- deps: ms@0.7.2
|
||||
* deps: http-errors@~1.5.1
|
||||
- deps: inherits@2.0.3
|
||||
- deps: setprototypeof@1.0.2
|
||||
- deps: statuses@'>= 1.3.1 < 2'
|
||||
* deps: iconv-lite@0.4.15
|
||||
- Added encoding MS-31J
|
||||
- Added encoding MS-932
|
||||
- Added encoding MS-936
|
||||
- Added encoding MS-949
|
||||
- Added encoding MS-950
|
||||
- Fix GBK/GB18030 handling of Euro character
|
||||
* deps: qs@6.2.1
|
||||
- Fix array parsing from skipping empty values
|
||||
* deps: raw-body@~2.2.0
|
||||
- deps: iconv-lite@0.4.15
|
||||
* deps: type-is@~1.6.14
|
||||
- deps: mime-types@~2.1.13
|
||||
|
||||
1.15.2 / 2016-06-19
|
||||
===================
|
||||
|
||||
* deps: bytes@2.4.0
|
||||
* deps: content-type@~1.0.2
|
||||
- perf: enable strict mode
|
||||
* deps: http-errors@~1.5.0
|
||||
- Use `setprototypeof` module to replace `__proto__` setting
|
||||
- deps: statuses@'>= 1.3.0 < 2'
|
||||
- perf: enable strict mode
|
||||
* deps: qs@6.2.0
|
||||
* deps: raw-body@~2.1.7
|
||||
- deps: bytes@2.4.0
|
||||
- perf: remove double-cleanup on happy path
|
||||
* deps: type-is@~1.6.13
|
||||
- deps: mime-types@~2.1.11
|
||||
|
||||
1.15.1 / 2016-05-05
|
||||
===================
|
||||
|
||||
* deps: bytes@2.3.0
|
||||
- Drop partial bytes on all parsed units
|
||||
- Fix parsing byte string that looks like hex
|
||||
* deps: raw-body@~2.1.6
|
||||
- deps: bytes@2.3.0
|
||||
* deps: type-is@~1.6.12
|
||||
- deps: mime-types@~2.1.10
|
||||
|
||||
1.15.0 / 2016-02-10
|
||||
===================
|
||||
|
||||
* deps: http-errors@~1.4.0
|
||||
- Add `HttpError` export, for `err instanceof createError.HttpError`
|
||||
- deps: inherits@2.0.1
|
||||
- deps: statuses@'>= 1.2.1 < 2'
|
||||
* deps: qs@6.1.0
|
||||
* deps: type-is@~1.6.11
|
||||
- deps: mime-types@~2.1.9
|
||||
|
||||
1.14.2 / 2015-12-16
|
||||
===================
|
||||
|
||||
* deps: bytes@2.2.0
|
||||
* deps: iconv-lite@0.4.13
|
||||
* deps: qs@5.2.0
|
||||
* deps: raw-body@~2.1.5
|
||||
- deps: bytes@2.2.0
|
||||
- deps: iconv-lite@0.4.13
|
||||
* deps: type-is@~1.6.10
|
||||
- deps: mime-types@~2.1.8
|
||||
|
||||
1.14.1 / 2015-09-27
|
||||
===================
|
||||
|
||||
* Fix issue where invalid charset results in 400 when `verify` used
|
||||
* deps: iconv-lite@0.4.12
|
||||
- Fix CESU-8 decoding in Node.js 4.x
|
||||
* deps: raw-body@~2.1.4
|
||||
- Fix masking critical errors from `iconv-lite`
|
||||
- deps: iconv-lite@0.4.12
|
||||
* deps: type-is@~1.6.9
|
||||
- deps: mime-types@~2.1.7
|
||||
|
||||
1.14.0 / 2015-09-16
|
||||
===================
|
||||
|
||||
* Fix JSON strict parse error to match syntax errors
|
||||
* Provide static `require` analysis in `urlencoded` parser
|
||||
* deps: depd@~1.1.0
|
||||
- Support web browser loading
|
||||
* deps: qs@5.1.0
|
||||
* deps: raw-body@~2.1.3
|
||||
- Fix sync callback when attaching data listener causes sync read
|
||||
* deps: type-is@~1.6.8
|
||||
- Fix type error when given invalid type to match against
|
||||
- deps: mime-types@~2.1.6
|
||||
|
||||
1.13.3 / 2015-07-31
|
||||
===================
|
||||
|
||||
* deps: type-is@~1.6.6
|
||||
- deps: mime-types@~2.1.4
|
||||
|
||||
1.13.2 / 2015-07-05
|
||||
===================
|
||||
|
||||
* deps: iconv-lite@0.4.11
|
||||
* deps: qs@4.0.0
|
||||
- Fix dropping parameters like `hasOwnProperty`
|
||||
- Fix user-visible incompatibilities from 3.1.0
|
||||
- Fix various parsing edge cases
|
||||
* deps: raw-body@~2.1.2
|
||||
- Fix error stack traces to skip `makeError`
|
||||
- deps: iconv-lite@0.4.11
|
||||
* deps: type-is@~1.6.4
|
||||
- deps: mime-types@~2.1.2
|
||||
- perf: enable strict mode
|
||||
- perf: remove argument reassignment
|
||||
|
||||
1.13.1 / 2015-06-16
|
||||
===================
|
||||
|
||||
* deps: qs@2.4.2
|
||||
- Downgraded from 3.1.0 because of user-visible incompatibilities
|
||||
|
||||
1.13.0 / 2015-06-14
|
||||
===================
|
||||
|
||||
* Add `statusCode` property on `Error`s, in addition to `status`
|
||||
* Change `type` default to `application/json` for JSON parser
|
||||
* Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser
|
||||
* Provide static `require` analysis
|
||||
* Use the `http-errors` module to generate errors
|
||||
* deps: bytes@2.1.0
|
||||
- Slight optimizations
|
||||
* deps: iconv-lite@0.4.10
|
||||
- The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails
|
||||
- Leading BOM is now removed when decoding
|
||||
* deps: on-finished@~2.3.0
|
||||
- Add defined behavior for HTTP `CONNECT` requests
|
||||
- Add defined behavior for HTTP `Upgrade` requests
|
||||
- deps: ee-first@1.1.1
|
||||
* deps: qs@3.1.0
|
||||
- Fix dropping parameters like `hasOwnProperty`
|
||||
- Fix various parsing edge cases
|
||||
- Parsed object now has `null` prototype
|
||||
* deps: raw-body@~2.1.1
|
||||
- Use `unpipe` module for unpiping requests
|
||||
- deps: iconv-lite@0.4.10
|
||||
* deps: type-is@~1.6.3
|
||||
- deps: mime-types@~2.1.1
|
||||
- perf: reduce try block size
|
||||
- perf: remove bitwise operations
|
||||
* perf: enable strict mode
|
||||
* perf: remove argument reassignment
|
||||
* perf: remove delete call
|
||||
|
||||
1.12.4 / 2015-05-10
|
||||
===================
|
||||
|
||||
* deps: debug@~2.2.0
|
||||
* deps: qs@2.4.2
|
||||
- Fix allowing parameters like `constructor`
|
||||
* deps: on-finished@~2.2.1
|
||||
* deps: raw-body@~2.0.1
|
||||
- Fix a false-positive when unpiping in Node.js 0.8
|
||||
- deps: bytes@2.0.1
|
||||
* deps: type-is@~1.6.2
|
||||
- deps: mime-types@~2.0.11
|
||||
|
||||
1.12.3 / 2015-04-15
|
||||
===================
|
||||
|
||||
* Slight efficiency improvement when not debugging
|
||||
* deps: depd@~1.0.1
|
||||
* deps: iconv-lite@0.4.8
|
||||
- Add encoding alias UNICODE-1-1-UTF-7
|
||||
* deps: raw-body@1.3.4
|
||||
- Fix hanging callback if request aborts during read
|
||||
- deps: iconv-lite@0.4.8
|
||||
|
||||
1.12.2 / 2015-03-16
|
||||
===================
|
||||
|
||||
* deps: qs@2.4.1
|
||||
- Fix error when parameter `hasOwnProperty` is present
|
||||
|
||||
1.12.1 / 2015-03-15
|
||||
===================
|
||||
|
||||
* deps: debug@~2.1.3
|
||||
- Fix high intensity foreground color for bold
|
||||
- deps: ms@0.7.0
|
||||
* deps: type-is@~1.6.1
|
||||
- deps: mime-types@~2.0.10
|
||||
|
||||
1.12.0 / 2015-02-13
|
||||
===================
|
||||
|
||||
* add `debug` messages
|
||||
* accept a function for the `type` option
|
||||
* use `content-type` to parse `Content-Type` headers
|
||||
* deps: iconv-lite@0.4.7
|
||||
- Gracefully support enumerables on `Object.prototype`
|
||||
* deps: raw-body@1.3.3
|
||||
- deps: iconv-lite@0.4.7
|
||||
* deps: type-is@~1.6.0
|
||||
- fix argument reassignment
|
||||
- fix false-positives in `hasBody` `Transfer-Encoding` check
|
||||
- support wildcard for both type and subtype (`*/*`)
|
||||
- deps: mime-types@~2.0.9
|
||||
|
||||
1.11.0 / 2015-01-30
|
||||
===================
|
||||
|
||||
* make internal `extended: true` depth limit infinity
|
||||
* deps: type-is@~1.5.6
|
||||
- deps: mime-types@~2.0.8
|
||||
|
||||
1.10.2 / 2015-01-20
|
||||
===================
|
||||
|
||||
* deps: iconv-lite@0.4.6
|
||||
- Fix rare aliases of single-byte encodings
|
||||
* deps: raw-body@1.3.2
|
||||
- deps: iconv-lite@0.4.6
|
||||
|
||||
1.10.1 / 2015-01-01
|
||||
===================
|
||||
|
||||
* deps: on-finished@~2.2.0
|
||||
* deps: type-is@~1.5.5
|
||||
- deps: mime-types@~2.0.7
|
||||
|
||||
1.10.0 / 2014-12-02
|
||||
===================
|
||||
|
||||
* make internal `extended: true` array limit dynamic
|
||||
|
||||
1.9.3 / 2014-11-21
|
||||
==================
|
||||
|
||||
* deps: iconv-lite@0.4.5
|
||||
- Fix Windows-31J and X-SJIS encoding support
|
||||
* deps: qs@2.3.3
|
||||
- Fix `arrayLimit` behavior
|
||||
* deps: raw-body@1.3.1
|
||||
- deps: iconv-lite@0.4.5
|
||||
* deps: type-is@~1.5.3
|
||||
- deps: mime-types@~2.0.3
|
||||
|
||||
1.9.2 / 2014-10-27
|
||||
==================
|
||||
|
||||
* deps: qs@2.3.2
|
||||
- Fix parsing of mixed objects and values
|
||||
|
||||
1.9.1 / 2014-10-22
|
||||
==================
|
||||
|
||||
* deps: on-finished@~2.1.1
|
||||
- Fix handling of pipelined requests
|
||||
* deps: qs@2.3.0
|
||||
- Fix parsing of mixed implicit and explicit arrays
|
||||
* deps: type-is@~1.5.2
|
||||
- deps: mime-types@~2.0.2
|
||||
|
||||
1.9.0 / 2014-09-24
|
||||
==================
|
||||
|
||||
* include the charset in "unsupported charset" error message
|
||||
* include the encoding in "unsupported content encoding" error message
|
||||
* deps: depd@~1.0.0
|
||||
|
||||
1.8.4 / 2014-09-23
|
||||
==================
|
||||
|
||||
* fix content encoding to be case-insensitive
|
||||
|
||||
1.8.3 / 2014-09-19
|
||||
==================
|
||||
|
||||
* deps: qs@2.2.4
|
||||
- Fix issue with object keys starting with numbers truncated
|
||||
|
||||
1.8.2 / 2014-09-15
|
||||
==================
|
||||
|
||||
* deps: depd@0.4.5
|
||||
|
||||
1.8.1 / 2014-09-07
|
||||
==================
|
||||
|
||||
* deps: media-typer@0.3.0
|
||||
* deps: type-is@~1.5.1
|
||||
|
||||
1.8.0 / 2014-09-05
|
||||
==================
|
||||
|
||||
* make empty-body-handling consistent between chunked requests
|
||||
- empty `json` produces `{}`
|
||||
- empty `raw` produces `new Buffer(0)`
|
||||
- empty `text` produces `''`
|
||||
- empty `urlencoded` produces `{}`
|
||||
* deps: qs@2.2.3
|
||||
- Fix issue where first empty value in array is discarded
|
||||
* deps: type-is@~1.5.0
|
||||
- fix `hasbody` to be true for `content-length: 0`
|
||||
|
||||
1.7.0 / 2014-09-01
|
||||
==================
|
||||
|
||||
* add `parameterLimit` option to `urlencoded` parser
|
||||
* change `urlencoded` extended array limit to 100
|
||||
* respond with 413 when over `parameterLimit` in `urlencoded`
|
||||
|
||||
1.6.7 / 2014-08-29
|
||||
==================
|
||||
|
||||
* deps: qs@2.2.2
|
||||
- Remove unnecessary cloning
|
||||
|
||||
1.6.6 / 2014-08-27
|
||||
==================
|
||||
|
||||
* deps: qs@2.2.0
|
||||
- Array parsing fix
|
||||
- Performance improvements
|
||||
|
||||
1.6.5 / 2014-08-16
|
||||
==================
|
||||
|
||||
* deps: on-finished@2.1.0
|
||||
|
||||
1.6.4 / 2014-08-14
|
||||
==================
|
||||
|
||||
* deps: qs@1.2.2
|
||||
|
||||
1.6.3 / 2014-08-10
|
||||
==================
|
||||
|
||||
* deps: qs@1.2.1
|
||||
|
||||
1.6.2 / 2014-08-07
|
||||
==================
|
||||
|
||||
* deps: qs@1.2.0
|
||||
- Fix parsing array of objects
|
||||
|
||||
1.6.1 / 2014-08-06
|
||||
==================
|
||||
|
||||
* deps: qs@1.1.0
|
||||
- Accept urlencoded square brackets
|
||||
- Accept empty values in implicit array notation
|
||||
|
||||
1.6.0 / 2014-08-05
|
||||
==================
|
||||
|
||||
* deps: qs@1.0.2
|
||||
- Complete rewrite
|
||||
- Limits array length to 20
|
||||
- Limits object depth to 5
|
||||
- Limits parameters to 1,000
|
||||
|
||||
1.5.2 / 2014-07-27
|
||||
==================
|
||||
|
||||
* deps: depd@0.4.4
|
||||
- Work-around v8 generating empty stack traces
|
||||
|
||||
1.5.1 / 2014-07-26
|
||||
==================
|
||||
|
||||
* deps: depd@0.4.3
|
||||
- Fix exception when global `Error.stackTraceLimit` is too low
|
||||
|
||||
1.5.0 / 2014-07-20
|
||||
==================
|
||||
|
||||
* deps: depd@0.4.2
|
||||
- Add `TRACE_DEPRECATION` environment variable
|
||||
- Remove non-standard grey color from color output
|
||||
- Support `--no-deprecation` argument
|
||||
- Support `--trace-deprecation` argument
|
||||
* deps: iconv-lite@0.4.4
|
||||
- Added encoding UTF-7
|
||||
* deps: raw-body@1.3.0
|
||||
- deps: iconv-lite@0.4.4
|
||||
- Added encoding UTF-7
|
||||
- Fix `Cannot switch to old mode now` error on Node.js 0.10+
|
||||
* deps: type-is@~1.3.2
|
||||
|
||||
1.4.3 / 2014-06-19
|
||||
==================
|
||||
|
||||
* deps: type-is@1.3.1
|
||||
- fix global variable leak
|
||||
|
||||
1.4.2 / 2014-06-19
|
||||
==================
|
||||
|
||||
* deps: type-is@1.3.0
|
||||
- improve type parsing
|
||||
|
||||
1.4.1 / 2014-06-19
|
||||
==================
|
||||
|
||||
* fix urlencoded extended deprecation message
|
||||
|
||||
1.4.0 / 2014-06-19
|
||||
==================
|
||||
|
||||
* add `text` parser
|
||||
* add `raw` parser
|
||||
* check accepted charset in content-type (accepts utf-8)
|
||||
* check accepted encoding in content-encoding (accepts identity)
|
||||
* deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed
|
||||
* deprecate `urlencoded()` without provided `extended` option
|
||||
* lazy-load urlencoded parsers
|
||||
* parsers split into files for reduced mem usage
|
||||
* support gzip and deflate bodies
|
||||
- set `inflate: false` to turn off
|
||||
* deps: raw-body@1.2.2
|
||||
- Support all encodings from `iconv-lite`
|
||||
|
||||
1.3.1 / 2014-06-11
|
||||
==================
|
||||
|
||||
* deps: type-is@1.2.1
|
||||
- Switch dependency from mime to mime-types@1.0.0
|
||||
|
||||
1.3.0 / 2014-05-31
|
||||
==================
|
||||
|
||||
* add `extended` option to urlencoded parser
|
||||
|
||||
1.2.2 / 2014-05-27
|
||||
==================
|
||||
|
||||
* deps: raw-body@1.1.6
|
||||
- assert stream encoding on node.js 0.8
|
||||
- assert stream encoding on node.js < 0.10.6
|
||||
- deps: bytes@1
|
||||
|
||||
1.2.1 / 2014-05-26
|
||||
==================
|
||||
|
||||
* invoke `next(err)` after request fully read
|
||||
- prevents hung responses and socket hang ups
|
||||
|
||||
1.2.0 / 2014-05-11
|
||||
==================
|
||||
|
||||
* add `verify` option
|
||||
* deps: type-is@1.2.0
|
||||
- support suffix matching
|
||||
|
||||
1.1.2 / 2014-05-11
|
||||
==================
|
||||
|
||||
* improve json parser speed
|
||||
|
||||
1.1.1 / 2014-05-11
|
||||
==================
|
||||
|
||||
* fix repeated limit parsing with every request
|
||||
|
||||
1.1.0 / 2014-05-10
|
||||
==================
|
||||
|
||||
* add `type` option
|
||||
* deps: pin for safety and consistency
|
||||
|
||||
1.0.2 / 2014-04-14
|
||||
==================
|
||||
|
||||
* use `type-is` module
|
||||
|
||||
1.0.1 / 2014-03-20
|
||||
==================
|
||||
|
||||
* lower default limits to 100kb
|
23
node_modules/body-parser/LICENSE
generated
vendored
Normal file
23
node_modules/body-parser/LICENSE
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
|
||||
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.
|
465
node_modules/body-parser/README.md
generated
vendored
Normal file
465
node_modules/body-parser/README.md
generated
vendored
Normal file
@ -0,0 +1,465 @@
|
||||
# body-parser
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Build Status][ci-image]][ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Node.js body parsing middleware.
|
||||
|
||||
Parse incoming request bodies in a middleware before your handlers, available
|
||||
under the `req.body` property.
|
||||
|
||||
**Note** As `req.body`'s shape is based on user-controlled input, all
|
||||
properties and values in this object are untrusted and should be validated
|
||||
before trusting. For example, `req.body.foo.toString()` may fail in multiple
|
||||
ways, for example the `foo` property may not be there or may not be a string,
|
||||
and `toString` may not be a function and instead a string or other user input.
|
||||
|
||||
[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).
|
||||
|
||||
_This does not handle multipart bodies_, due to their complex and typically
|
||||
large nature. For multipart bodies, you may be interested in the following
|
||||
modules:
|
||||
|
||||
* [busboy](https://www.npmjs.org/package/busboy#readme) and
|
||||
[connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)
|
||||
* [multiparty](https://www.npmjs.org/package/multiparty#readme) and
|
||||
[connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)
|
||||
* [formidable](https://www.npmjs.org/package/formidable#readme)
|
||||
* [multer](https://www.npmjs.org/package/multer#readme)
|
||||
|
||||
This module provides the following parsers:
|
||||
|
||||
* [JSON body parser](#bodyparserjsonoptions)
|
||||
* [Raw body parser](#bodyparserrawoptions)
|
||||
* [Text body parser](#bodyparsertextoptions)
|
||||
* [URL-encoded form body parser](#bodyparserurlencodedoptions)
|
||||
|
||||
Other body parsers you might be interested in:
|
||||
|
||||
- [body](https://www.npmjs.org/package/body#readme)
|
||||
- [co-body](https://www.npmjs.org/package/co-body#readme)
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ npm install body-parser
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
var bodyParser = require('body-parser')
|
||||
```
|
||||
|
||||
The `bodyParser` object exposes various factories to create middlewares. All
|
||||
middlewares will populate the `req.body` property with the parsed body when
|
||||
the `Content-Type` request header matches the `type` option, or an empty
|
||||
object (`{}`) if there was no body to parse, the `Content-Type` was not matched,
|
||||
or an error occurred.
|
||||
|
||||
The various errors returned by this module are described in the
|
||||
[errors section](#errors).
|
||||
|
||||
### bodyParser.json([options])
|
||||
|
||||
Returns middleware that only parses `json` and only looks at requests where
|
||||
the `Content-Type` header matches the `type` option. This parser accepts any
|
||||
Unicode encoding of the body and supports automatic inflation of `gzip` and
|
||||
`deflate` encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`).
|
||||
|
||||
#### Options
|
||||
|
||||
The `json` function takes an optional `options` object that may contain any of
|
||||
the following keys:
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
##### reviver
|
||||
|
||||
The `reviver` option is passed directly to `JSON.parse` as the second
|
||||
argument. You can find more information on this argument
|
||||
[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
|
||||
|
||||
##### strict
|
||||
|
||||
When set to `true`, will only accept arrays and objects; when `false` will
|
||||
accept anything `JSON.parse` accepts. Defaults to `true`.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not a
|
||||
function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
|
||||
be an extension name (like `json`), a mime type (like `application/json`), or
|
||||
a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`
|
||||
option is called as `fn(req)` and the request is parsed if it returns a truthy
|
||||
value. Defaults to `application/json`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
|
||||
where `buf` is a `Buffer` of the raw request body and `encoding` is the
|
||||
encoding of the request. The parsing can be aborted by throwing an error.
|
||||
|
||||
### bodyParser.raw([options])
|
||||
|
||||
Returns middleware that parses all bodies as a `Buffer` and only looks at
|
||||
requests where the `Content-Type` header matches the `type` option. This
|
||||
parser supports automatic inflation of `gzip` and `deflate` encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`). This will be a `Buffer` object
|
||||
of the body.
|
||||
|
||||
#### Options
|
||||
|
||||
The `raw` function takes an optional `options` object that may contain any of
|
||||
the following keys:
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function.
|
||||
If not a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.org/package/type-is#readme) library and this
|
||||
can be an extension name (like `bin`), a mime type (like
|
||||
`application/octet-stream`), or a mime type with a wildcard (like `*/*` or
|
||||
`application/*`). If a function, the `type` option is called as `fn(req)`
|
||||
and the request is parsed if it returns a truthy value. Defaults to
|
||||
`application/octet-stream`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
|
||||
where `buf` is a `Buffer` of the raw request body and `encoding` is the
|
||||
encoding of the request. The parsing can be aborted by throwing an error.
|
||||
|
||||
### bodyParser.text([options])
|
||||
|
||||
Returns middleware that parses all bodies as a string and only looks at
|
||||
requests where the `Content-Type` header matches the `type` option. This
|
||||
parser supports automatic inflation of `gzip` and `deflate` encodings.
|
||||
|
||||
A new `body` string containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`). This will be a string of the
|
||||
body.
|
||||
|
||||
#### Options
|
||||
|
||||
The `text` function takes an optional `options` object that may contain any of
|
||||
the following keys:
|
||||
|
||||
##### defaultCharset
|
||||
|
||||
Specify the default character set for the text content if the charset is not
|
||||
specified in the `Content-Type` header of the request. Defaults to `utf-8`.
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not
|
||||
a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
|
||||
be an extension name (like `txt`), a mime type (like `text/plain`), or a mime
|
||||
type with a wildcard (like `*/*` or `text/*`). If a function, the `type`
|
||||
option is called as `fn(req)` and the request is parsed if it returns a
|
||||
truthy value. Defaults to `text/plain`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
|
||||
where `buf` is a `Buffer` of the raw request body and `encoding` is the
|
||||
encoding of the request. The parsing can be aborted by throwing an error.
|
||||
|
||||
### bodyParser.urlencoded([options])
|
||||
|
||||
Returns middleware that only parses `urlencoded` bodies and only looks at
|
||||
requests where the `Content-Type` header matches the `type` option. This
|
||||
parser accepts only UTF-8 encoding of the body and supports automatic
|
||||
inflation of `gzip` and `deflate` encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`). This object will contain
|
||||
key-value pairs, where the value can be a string or array (when `extended` is
|
||||
`false`), or any type (when `extended` is `true`).
|
||||
|
||||
#### Options
|
||||
|
||||
The `urlencoded` function takes an optional `options` object that may contain
|
||||
any of the following keys:
|
||||
|
||||
##### extended
|
||||
|
||||
The `extended` option allows to choose between parsing the URL-encoded data
|
||||
with the `querystring` library (when `false`) or the `qs` library (when
|
||||
`true`). The "extended" syntax allows for rich objects and arrays to be
|
||||
encoded into the URL-encoded format, allowing for a JSON-like experience
|
||||
with URL-encoded. For more information, please
|
||||
[see the qs library](https://www.npmjs.org/package/qs#readme).
|
||||
|
||||
Defaults to `true`, but using the default has been deprecated. Please
|
||||
research into the difference between `qs` and `querystring` and choose the
|
||||
appropriate setting.
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
##### parameterLimit
|
||||
|
||||
The `parameterLimit` option controls the maximum number of parameters that
|
||||
are allowed in the URL-encoded data. If a request contains more parameters
|
||||
than this value, a 413 will be returned to the client. Defaults to `1000`.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not
|
||||
a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
|
||||
be an extension name (like `urlencoded`), a mime type (like
|
||||
`application/x-www-form-urlencoded`), or a mime type with a wildcard (like
|
||||
`*/x-www-form-urlencoded`). If a function, the `type` option is called as
|
||||
`fn(req)` and the request is parsed if it returns a truthy value. Defaults
|
||||
to `application/x-www-form-urlencoded`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
|
||||
where `buf` is a `Buffer` of the raw request body and `encoding` is the
|
||||
encoding of the request. The parsing can be aborted by throwing an error.
|
||||
|
||||
## Errors
|
||||
|
||||
The middlewares provided by this module create errors using the
|
||||
[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors
|
||||
will typically have a `status`/`statusCode` property that contains the suggested
|
||||
HTTP response code, an `expose` property to determine if the `message` property
|
||||
should be displayed to the client, a `type` property to determine the type of
|
||||
error without matching against the `message`, and a `body` property containing
|
||||
the read body, if available.
|
||||
|
||||
The following are the common errors created, though any error can come through
|
||||
for various reasons.
|
||||
|
||||
### content encoding unsupported
|
||||
|
||||
This error will occur when the request had a `Content-Encoding` header that
|
||||
contained an encoding but the "inflation" option was set to `false`. The
|
||||
`status` property is set to `415`, the `type` property is set to
|
||||
`'encoding.unsupported'`, and the `charset` property will be set to the
|
||||
encoding that is unsupported.
|
||||
|
||||
### entity parse failed
|
||||
|
||||
This error will occur when the request contained an entity that could not be
|
||||
parsed by the middleware. The `status` property is set to `400`, the `type`
|
||||
property is set to `'entity.parse.failed'`, and the `body` property is set to
|
||||
the entity value that failed parsing.
|
||||
|
||||
### entity verify failed
|
||||
|
||||
This error will occur when the request contained an entity that could not be
|
||||
failed verification by the defined `verify` option. The `status` property is
|
||||
set to `403`, the `type` property is set to `'entity.verify.failed'`, and the
|
||||
`body` property is set to the entity value that failed verification.
|
||||
|
||||
### request aborted
|
||||
|
||||
This error will occur when the request is aborted by the client before reading
|
||||
the body has finished. The `received` property will be set to the number of
|
||||
bytes received before the request was aborted and the `expected` property is
|
||||
set to the number of expected bytes. The `status` property is set to `400`
|
||||
and `type` property is set to `'request.aborted'`.
|
||||
|
||||
### request entity too large
|
||||
|
||||
This error will occur when the request body's size is larger than the "limit"
|
||||
option. The `limit` property will be set to the byte limit and the `length`
|
||||
property will be set to the request body's length. The `status` property is
|
||||
set to `413` and the `type` property is set to `'entity.too.large'`.
|
||||
|
||||
### request size did not match content length
|
||||
|
||||
This error will occur when the request's length did not match the length from
|
||||
the `Content-Length` header. This typically occurs when the request is malformed,
|
||||
typically when the `Content-Length` header was calculated based on characters
|
||||
instead of bytes. The `status` property is set to `400` and the `type` property
|
||||
is set to `'request.size.invalid'`.
|
||||
|
||||
### stream encoding should not be set
|
||||
|
||||
This error will occur when something called the `req.setEncoding` method prior
|
||||
to this middleware. This module operates directly on bytes only and you cannot
|
||||
call `req.setEncoding` when using this module. The `status` property is set to
|
||||
`500` and the `type` property is set to `'stream.encoding.set'`.
|
||||
|
||||
### stream is not readable
|
||||
|
||||
This error will occur when the request is no longer readable when this middleware
|
||||
attempts to read it. This typically means something other than a middleware from
|
||||
this module read the request body already and the middleware was also configured to
|
||||
read the same request. The `status` property is set to `500` and the `type`
|
||||
property is set to `'stream.not.readable'`.
|
||||
|
||||
### too many parameters
|
||||
|
||||
This error will occur when the content of the request exceeds the configured
|
||||
`parameterLimit` for the `urlencoded` parser. The `status` property is set to
|
||||
`413` and the `type` property is set to `'parameters.too.many'`.
|
||||
|
||||
### unsupported charset "BOGUS"
|
||||
|
||||
This error will occur when the request had a charset parameter in the
|
||||
`Content-Type` header, but the `iconv-lite` module does not support it OR the
|
||||
parser does not support it. The charset is contained in the message as well
|
||||
as in the `charset` property. The `status` property is set to `415`, the
|
||||
`type` property is set to `'charset.unsupported'`, and the `charset` property
|
||||
is set to the charset that is unsupported.
|
||||
|
||||
### unsupported content encoding "bogus"
|
||||
|
||||
This error will occur when the request had a `Content-Encoding` header that
|
||||
contained an unsupported encoding. The encoding is contained in the message
|
||||
as well as in the `encoding` property. The `status` property is set to `415`,
|
||||
the `type` property is set to `'encoding.unsupported'`, and the `encoding`
|
||||
property is set to the encoding that is unsupported.
|
||||
|
||||
## Examples
|
||||
|
||||
### Express/Connect top-level generic
|
||||
|
||||
This example demonstrates adding a generic JSON and URL-encoded parser as a
|
||||
top-level middleware, which will parse the bodies of all incoming requests.
|
||||
This is the simplest setup.
|
||||
|
||||
```js
|
||||
var express = require('express')
|
||||
var bodyParser = require('body-parser')
|
||||
|
||||
var app = express()
|
||||
|
||||
// parse application/x-www-form-urlencoded
|
||||
app.use(bodyParser.urlencoded({ extended: false }))
|
||||
|
||||
// parse application/json
|
||||
app.use(bodyParser.json())
|
||||
|
||||
app.use(function (req, res) {
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.write('you posted:\n')
|
||||
res.end(JSON.stringify(req.body, null, 2))
|
||||
})
|
||||
```
|
||||
|
||||
### Express route-specific
|
||||
|
||||
This example demonstrates adding body parsers specifically to the routes that
|
||||
need them. In general, this is the most recommended way to use body-parser with
|
||||
Express.
|
||||
|
||||
```js
|
||||
var express = require('express')
|
||||
var bodyParser = require('body-parser')
|
||||
|
||||
var app = express()
|
||||
|
||||
// create application/json parser
|
||||
var jsonParser = bodyParser.json()
|
||||
|
||||
// create application/x-www-form-urlencoded parser
|
||||
var urlencodedParser = bodyParser.urlencoded({ extended: false })
|
||||
|
||||
// POST /login gets urlencoded bodies
|
||||
app.post('/login', urlencodedParser, function (req, res) {
|
||||
res.send('welcome, ' + req.body.username)
|
||||
})
|
||||
|
||||
// POST /api/users gets JSON bodies
|
||||
app.post('/api/users', jsonParser, function (req, res) {
|
||||
// create user in req.body
|
||||
})
|
||||
```
|
||||
|
||||
### Change accepted type for parsers
|
||||
|
||||
All the parsers accept a `type` option which allows you to change the
|
||||
`Content-Type` that the middleware will parse.
|
||||
|
||||
```js
|
||||
var express = require('express')
|
||||
var bodyParser = require('body-parser')
|
||||
|
||||
var app = express()
|
||||
|
||||
// parse various different custom JSON types as JSON
|
||||
app.use(bodyParser.json({ type: 'application/*+json' }))
|
||||
|
||||
// parse some custom thing into a Buffer
|
||||
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
|
||||
|
||||
// parse an HTML body into a string
|
||||
app.use(bodyParser.text({ type: 'text/html' }))
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci
|
||||
[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master
|
||||
[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
|
||||
[node-version-image]: https://badgen.net/npm/node/body-parser
|
||||
[node-version-url]: https://nodejs.org/en/download
|
||||
[npm-downloads-image]: https://badgen.net/npm/dm/body-parser
|
||||
[npm-url]: https://npmjs.org/package/body-parser
|
||||
[npm-version-image]: https://badgen.net/npm/v/body-parser
|
25
node_modules/body-parser/SECURITY.md
generated
vendored
Normal file
25
node_modules/body-parser/SECURITY.md
generated
vendored
Normal file
@ -0,0 +1,25 @@
|
||||
# Security Policies and Procedures
|
||||
|
||||
## Reporting a Bug
|
||||
|
||||
The Express team and community take all security bugs seriously. Thank you
|
||||
for improving the security of Express. We appreciate your efforts and
|
||||
responsible disclosure and will make every effort to acknowledge your
|
||||
contributions.
|
||||
|
||||
Report security bugs by emailing the current owner(s) of `body-parser`. This
|
||||
information can be found in the npm registry using the command
|
||||
`npm owner ls body-parser`.
|
||||
If unsure or unable to get the information from the above, open an issue
|
||||
in the [project issue tracker](https://github.com/expressjs/body-parser/issues)
|
||||
asking for the current contact information.
|
||||
|
||||
To ensure the timely response to your report, please ensure that the entirety
|
||||
of the report is contained within the email body and not solely behind a web
|
||||
link or an attachment.
|
||||
|
||||
At least one owner will acknowledge your email within 48 hours, and will send a
|
||||
more detailed response within 48 hours indicating the next steps in handling
|
||||
your report. After the initial reply to your report, the owners will
|
||||
endeavor to keep you informed of the progress towards a fix and full
|
||||
announcement, and may ask for additional information or guidance.
|
156
node_modules/body-parser/index.js
generated
vendored
Normal file
156
node_modules/body-parser/index.js
generated
vendored
Normal file
@ -0,0 +1,156 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var deprecate = require('depd')('body-parser')
|
||||
|
||||
/**
|
||||
* Cache of loaded parsers.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var parsers = Object.create(null)
|
||||
|
||||
/**
|
||||
* @typedef Parsers
|
||||
* @type {function}
|
||||
* @property {function} json
|
||||
* @property {function} raw
|
||||
* @property {function} text
|
||||
* @property {function} urlencoded
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @type {Parsers}
|
||||
*/
|
||||
|
||||
exports = module.exports = deprecate.function(bodyParser,
|
||||
'bodyParser: use individual json/urlencoded middlewares')
|
||||
|
||||
/**
|
||||
* JSON parser.
|
||||
* @public
|
||||
*/
|
||||
|
||||
Object.defineProperty(exports, 'json', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: createParserGetter('json')
|
||||
})
|
||||
|
||||
/**
|
||||
* Raw parser.
|
||||
* @public
|
||||
*/
|
||||
|
||||
Object.defineProperty(exports, 'raw', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: createParserGetter('raw')
|
||||
})
|
||||
|
||||
/**
|
||||
* Text parser.
|
||||
* @public
|
||||
*/
|
||||
|
||||
Object.defineProperty(exports, 'text', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: createParserGetter('text')
|
||||
})
|
||||
|
||||
/**
|
||||
* URL-encoded parser.
|
||||
* @public
|
||||
*/
|
||||
|
||||
Object.defineProperty(exports, 'urlencoded', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: createParserGetter('urlencoded')
|
||||
})
|
||||
|
||||
/**
|
||||
* Create a middleware to parse json and urlencoded bodies.
|
||||
*
|
||||
* @param {object} [options]
|
||||
* @return {function}
|
||||
* @deprecated
|
||||
* @public
|
||||
*/
|
||||
|
||||
function bodyParser (options) {
|
||||
// use default type for parsers
|
||||
var opts = Object.create(options || null, {
|
||||
type: {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
value: undefined,
|
||||
writable: true
|
||||
}
|
||||
})
|
||||
|
||||
var _urlencoded = exports.urlencoded(opts)
|
||||
var _json = exports.json(opts)
|
||||
|
||||
return function bodyParser (req, res, next) {
|
||||
_json(req, res, function (err) {
|
||||
if (err) return next(err)
|
||||
_urlencoded(req, res, next)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a getter for loading a parser.
|
||||
* @private
|
||||
*/
|
||||
|
||||
function createParserGetter (name) {
|
||||
return function get () {
|
||||
return loadParser(name)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a parser module.
|
||||
* @private
|
||||
*/
|
||||
|
||||
function loadParser (parserName) {
|
||||
var parser = parsers[parserName]
|
||||
|
||||
if (parser !== undefined) {
|
||||
return parser
|
||||
}
|
||||
|
||||
// this uses a switch for static require analysis
|
||||
switch (parserName) {
|
||||
case 'json':
|
||||
parser = require('./lib/types/json')
|
||||
break
|
||||
case 'raw':
|
||||
parser = require('./lib/types/raw')
|
||||
break
|
||||
case 'text':
|
||||
parser = require('./lib/types/text')
|
||||
break
|
||||
case 'urlencoded':
|
||||
parser = require('./lib/types/urlencoded')
|
||||
break
|
||||
}
|
||||
|
||||
// store to prevent invoking require()
|
||||
return (parsers[parserName] = parser)
|
||||
}
|
205
node_modules/body-parser/lib/read.js
generated
vendored
Normal file
205
node_modules/body-parser/lib/read.js
generated
vendored
Normal file
@ -0,0 +1,205 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var createError = require('http-errors')
|
||||
var destroy = require('destroy')
|
||||
var getBody = require('raw-body')
|
||||
var iconv = require('iconv-lite')
|
||||
var onFinished = require('on-finished')
|
||||
var unpipe = require('unpipe')
|
||||
var zlib = require('zlib')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = read
|
||||
|
||||
/**
|
||||
* Read a request into a buffer and parse.
|
||||
*
|
||||
* @param {object} req
|
||||
* @param {object} res
|
||||
* @param {function} next
|
||||
* @param {function} parse
|
||||
* @param {function} debug
|
||||
* @param {object} options
|
||||
* @private
|
||||
*/
|
||||
|
||||
function read (req, res, next, parse, debug, options) {
|
||||
var length
|
||||
var opts = options
|
||||
var stream
|
||||
|
||||
// flag as parsed
|
||||
req._body = true
|
||||
|
||||
// read options
|
||||
var encoding = opts.encoding !== null
|
||||
? opts.encoding
|
||||
: null
|
||||
var verify = opts.verify
|
||||
|
||||
try {
|
||||
// get the content stream
|
||||
stream = contentstream(req, debug, opts.inflate)
|
||||
length = stream.length
|
||||
stream.length = undefined
|
||||
} catch (err) {
|
||||
return next(err)
|
||||
}
|
||||
|
||||
// set raw-body options
|
||||
opts.length = length
|
||||
opts.encoding = verify
|
||||
? null
|
||||
: encoding
|
||||
|
||||
// assert charset is supported
|
||||
if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
|
||||
return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
|
||||
charset: encoding.toLowerCase(),
|
||||
type: 'charset.unsupported'
|
||||
}))
|
||||
}
|
||||
|
||||
// read body
|
||||
debug('read body')
|
||||
getBody(stream, opts, function (error, body) {
|
||||
if (error) {
|
||||
var _error
|
||||
|
||||
if (error.type === 'encoding.unsupported') {
|
||||
// echo back charset
|
||||
_error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
|
||||
charset: encoding.toLowerCase(),
|
||||
type: 'charset.unsupported'
|
||||
})
|
||||
} else {
|
||||
// set status code on error
|
||||
_error = createError(400, error)
|
||||
}
|
||||
|
||||
// unpipe from stream and destroy
|
||||
if (stream !== req) {
|
||||
unpipe(req)
|
||||
destroy(stream, true)
|
||||
}
|
||||
|
||||
// read off entire request
|
||||
dump(req, function onfinished () {
|
||||
next(createError(400, _error))
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// verify
|
||||
if (verify) {
|
||||
try {
|
||||
debug('verify body')
|
||||
verify(req, res, body, encoding)
|
||||
} catch (err) {
|
||||
next(createError(403, err, {
|
||||
body: body,
|
||||
type: err.type || 'entity.verify.failed'
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// parse
|
||||
var str = body
|
||||
try {
|
||||
debug('parse body')
|
||||
str = typeof body !== 'string' && encoding !== null
|
||||
? iconv.decode(body, encoding)
|
||||
: body
|
||||
req.body = parse(str)
|
||||
} catch (err) {
|
||||
next(createError(400, err, {
|
||||
body: str,
|
||||
type: err.type || 'entity.parse.failed'
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
next()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the content stream of the request.
|
||||
*
|
||||
* @param {object} req
|
||||
* @param {function} debug
|
||||
* @param {boolean} [inflate=true]
|
||||
* @return {object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function contentstream (req, debug, inflate) {
|
||||
var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
|
||||
var length = req.headers['content-length']
|
||||
var stream
|
||||
|
||||
debug('content-encoding "%s"', encoding)
|
||||
|
||||
if (inflate === false && encoding !== 'identity') {
|
||||
throw createError(415, 'content encoding unsupported', {
|
||||
encoding: encoding,
|
||||
type: 'encoding.unsupported'
|
||||
})
|
||||
}
|
||||
|
||||
switch (encoding) {
|
||||
case 'deflate':
|
||||
stream = zlib.createInflate()
|
||||
debug('inflate body')
|
||||
req.pipe(stream)
|
||||
break
|
||||
case 'gzip':
|
||||
stream = zlib.createGunzip()
|
||||
debug('gunzip body')
|
||||
req.pipe(stream)
|
||||
break
|
||||
case 'identity':
|
||||
stream = req
|
||||
stream.length = length
|
||||
break
|
||||
default:
|
||||
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
|
||||
encoding: encoding,
|
||||
type: 'encoding.unsupported'
|
||||
})
|
||||
}
|
||||
|
||||
return stream
|
||||
}
|
||||
|
||||
/**
|
||||
* Dump the contents of a request.
|
||||
*
|
||||
* @param {object} req
|
||||
* @param {function} callback
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function dump (req, callback) {
|
||||
if (onFinished.isFinished(req)) {
|
||||
callback(null)
|
||||
} else {
|
||||
onFinished(req, callback)
|
||||
req.resume()
|
||||
}
|
||||
}
|
247
node_modules/body-parser/lib/types/json.js
generated
vendored
Normal file
247
node_modules/body-parser/lib/types/json.js
generated
vendored
Normal file
@ -0,0 +1,247 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var bytes = require('bytes')
|
||||
var contentType = require('content-type')
|
||||
var createError = require('http-errors')
|
||||
var debug = require('debug')('body-parser:json')
|
||||
var read = require('../read')
|
||||
var typeis = require('type-is')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = json
|
||||
|
||||
/**
|
||||
* RegExp to match the first non-space in a string.
|
||||
*
|
||||
* Allowed whitespace is defined in RFC 7159:
|
||||
*
|
||||
* ws = *(
|
||||
* %x20 / ; Space
|
||||
* %x09 / ; Horizontal tab
|
||||
* %x0A / ; Line feed or New line
|
||||
* %x0D ) ; Carriage return
|
||||
*/
|
||||
|
||||
var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex
|
||||
|
||||
var JSON_SYNTAX_CHAR = '#'
|
||||
var JSON_SYNTAX_REGEXP = /#+/g
|
||||
|
||||
/**
|
||||
* Create a middleware to parse JSON bodies.
|
||||
*
|
||||
* @param {object} [options]
|
||||
* @return {function}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function json (options) {
|
||||
var opts = options || {}
|
||||
|
||||
var limit = typeof opts.limit !== 'number'
|
||||
? bytes.parse(opts.limit || '100kb')
|
||||
: opts.limit
|
||||
var inflate = opts.inflate !== false
|
||||
var reviver = opts.reviver
|
||||
var strict = opts.strict !== false
|
||||
var type = opts.type || 'application/json'
|
||||
var verify = opts.verify || false
|
||||
|
||||
if (verify !== false && typeof verify !== 'function') {
|
||||
throw new TypeError('option verify must be function')
|
||||
}
|
||||
|
||||
// create the appropriate type checking function
|
||||
var shouldParse = typeof type !== 'function'
|
||||
? typeChecker(type)
|
||||
: type
|
||||
|
||||
function parse (body) {
|
||||
if (body.length === 0) {
|
||||
// special-case empty json body, as it's a common client-side mistake
|
||||
// TODO: maybe make this configurable or part of "strict" option
|
||||
return {}
|
||||
}
|
||||
|
||||
if (strict) {
|
||||
var first = firstchar(body)
|
||||
|
||||
if (first !== '{' && first !== '[') {
|
||||
debug('strict violation')
|
||||
throw createStrictSyntaxError(body, first)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
debug('parse json')
|
||||
return JSON.parse(body, reviver)
|
||||
} catch (e) {
|
||||
throw normalizeJsonSyntaxError(e, {
|
||||
message: e.message,
|
||||
stack: e.stack
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return function jsonParser (req, res, next) {
|
||||
if (req._body) {
|
||||
debug('body already parsed')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
req.body = req.body || {}
|
||||
|
||||
// skip requests without bodies
|
||||
if (!typeis.hasBody(req)) {
|
||||
debug('skip empty body')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
debug('content-type %j', req.headers['content-type'])
|
||||
|
||||
// determine if request should be parsed
|
||||
if (!shouldParse(req)) {
|
||||
debug('skip parsing')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// assert charset per RFC 7159 sec 8.1
|
||||
var charset = getCharset(req) || 'utf-8'
|
||||
if (charset.slice(0, 4) !== 'utf-') {
|
||||
debug('invalid charset')
|
||||
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
|
||||
charset: charset,
|
||||
type: 'charset.unsupported'
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
// read
|
||||
read(req, res, next, parse, debug, {
|
||||
encoding: charset,
|
||||
inflate: inflate,
|
||||
limit: limit,
|
||||
verify: verify
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create strict violation syntax error matching native error.
|
||||
*
|
||||
* @param {string} str
|
||||
* @param {string} char
|
||||
* @return {Error}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function createStrictSyntaxError (str, char) {
|
||||
var index = str.indexOf(char)
|
||||
var partial = ''
|
||||
|
||||
if (index !== -1) {
|
||||
partial = str.substring(0, index) + JSON_SYNTAX_CHAR
|
||||
|
||||
for (var i = index + 1; i < str.length; i++) {
|
||||
partial += JSON_SYNTAX_CHAR
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
|
||||
} catch (e) {
|
||||
return normalizeJsonSyntaxError(e, {
|
||||
message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) {
|
||||
return str.substring(index, index + placeholder.length)
|
||||
}),
|
||||
stack: e.stack
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first non-whitespace character in a string.
|
||||
*
|
||||
* @param {string} str
|
||||
* @return {function}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function firstchar (str) {
|
||||
var match = FIRST_CHAR_REGEXP.exec(str)
|
||||
|
||||
return match
|
||||
? match[1]
|
||||
: undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the charset of a request.
|
||||
*
|
||||
* @param {object} req
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function getCharset (req) {
|
||||
try {
|
||||
return (contentType.parse(req).parameters.charset || '').toLowerCase()
|
||||
} catch (e) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a SyntaxError for JSON.parse.
|
||||
*
|
||||
* @param {SyntaxError} error
|
||||
* @param {object} obj
|
||||
* @return {SyntaxError}
|
||||
*/
|
||||
|
||||
function normalizeJsonSyntaxError (error, obj) {
|
||||
var keys = Object.getOwnPropertyNames(error)
|
||||
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
var key = keys[i]
|
||||
if (key !== 'stack' && key !== 'message') {
|
||||
delete error[key]
|
||||
}
|
||||
}
|
||||
|
||||
// replace stack before message for Node.js 0.10 and below
|
||||
error.stack = obj.stack.replace(error.message, obj.message)
|
||||
error.message = obj.message
|
||||
|
||||
return error
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the simple type checker.
|
||||
*
|
||||
* @param {string} type
|
||||
* @return {function}
|
||||
*/
|
||||
|
||||
function typeChecker (type) {
|
||||
return function checkType (req) {
|
||||
return Boolean(typeis(req, type))
|
||||
}
|
||||
}
|
101
node_modules/body-parser/lib/types/raw.js
generated
vendored
Normal file
101
node_modules/body-parser/lib/types/raw.js
generated
vendored
Normal file
@ -0,0 +1,101 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var bytes = require('bytes')
|
||||
var debug = require('debug')('body-parser:raw')
|
||||
var read = require('../read')
|
||||
var typeis = require('type-is')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = raw
|
||||
|
||||
/**
|
||||
* Create a middleware to parse raw bodies.
|
||||
*
|
||||
* @param {object} [options]
|
||||
* @return {function}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function raw (options) {
|
||||
var opts = options || {}
|
||||
|
||||
var inflate = opts.inflate !== false
|
||||
var limit = typeof opts.limit !== 'number'
|
||||
? bytes.parse(opts.limit || '100kb')
|
||||
: opts.limit
|
||||
var type = opts.type || 'application/octet-stream'
|
||||
var verify = opts.verify || false
|
||||
|
||||
if (verify !== false && typeof verify !== 'function') {
|
||||
throw new TypeError('option verify must be function')
|
||||
}
|
||||
|
||||
// create the appropriate type checking function
|
||||
var shouldParse = typeof type !== 'function'
|
||||
? typeChecker(type)
|
||||
: type
|
||||
|
||||
function parse (buf) {
|
||||
return buf
|
||||
}
|
||||
|
||||
return function rawParser (req, res, next) {
|
||||
if (req._body) {
|
||||
debug('body already parsed')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
req.body = req.body || {}
|
||||
|
||||
// skip requests without bodies
|
||||
if (!typeis.hasBody(req)) {
|
||||
debug('skip empty body')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
debug('content-type %j', req.headers['content-type'])
|
||||
|
||||
// determine if request should be parsed
|
||||
if (!shouldParse(req)) {
|
||||
debug('skip parsing')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// read
|
||||
read(req, res, next, parse, debug, {
|
||||
encoding: null,
|
||||
inflate: inflate,
|
||||
limit: limit,
|
||||
verify: verify
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the simple type checker.
|
||||
*
|
||||
* @param {string} type
|
||||
* @return {function}
|
||||
*/
|
||||
|
||||
function typeChecker (type) {
|
||||
return function checkType (req) {
|
||||
return Boolean(typeis(req, type))
|
||||
}
|
||||
}
|
121
node_modules/body-parser/lib/types/text.js
generated
vendored
Normal file
121
node_modules/body-parser/lib/types/text.js
generated
vendored
Normal file
@ -0,0 +1,121 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var bytes = require('bytes')
|
||||
var contentType = require('content-type')
|
||||
var debug = require('debug')('body-parser:text')
|
||||
var read = require('../read')
|
||||
var typeis = require('type-is')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = text
|
||||
|
||||
/**
|
||||
* Create a middleware to parse text bodies.
|
||||
*
|
||||
* @param {object} [options]
|
||||
* @return {function}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function text (options) {
|
||||
var opts = options || {}
|
||||
|
||||
var defaultCharset = opts.defaultCharset || 'utf-8'
|
||||
var inflate = opts.inflate !== false
|
||||
var limit = typeof opts.limit !== 'number'
|
||||
? bytes.parse(opts.limit || '100kb')
|
||||
: opts.limit
|
||||
var type = opts.type || 'text/plain'
|
||||
var verify = opts.verify || false
|
||||
|
||||
if (verify !== false && typeof verify !== 'function') {
|
||||
throw new TypeError('option verify must be function')
|
||||
}
|
||||
|
||||
// create the appropriate type checking function
|
||||
var shouldParse = typeof type !== 'function'
|
||||
? typeChecker(type)
|
||||
: type
|
||||
|
||||
function parse (buf) {
|
||||
return buf
|
||||
}
|
||||
|
||||
return function textParser (req, res, next) {
|
||||
if (req._body) {
|
||||
debug('body already parsed')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
req.body = req.body || {}
|
||||
|
||||
// skip requests without bodies
|
||||
if (!typeis.hasBody(req)) {
|
||||
debug('skip empty body')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
debug('content-type %j', req.headers['content-type'])
|
||||
|
||||
// determine if request should be parsed
|
||||
if (!shouldParse(req)) {
|
||||
debug('skip parsing')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// get charset
|
||||
var charset = getCharset(req) || defaultCharset
|
||||
|
||||
// read
|
||||
read(req, res, next, parse, debug, {
|
||||
encoding: charset,
|
||||
inflate: inflate,
|
||||
limit: limit,
|
||||
verify: verify
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the charset of a request.
|
||||
*
|
||||
* @param {object} req
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function getCharset (req) {
|
||||
try {
|
||||
return (contentType.parse(req).parameters.charset || '').toLowerCase()
|
||||
} catch (e) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the simple type checker.
|
||||
*
|
||||
* @param {string} type
|
||||
* @return {function}
|
||||
*/
|
||||
|
||||
function typeChecker (type) {
|
||||
return function checkType (req) {
|
||||
return Boolean(typeis(req, type))
|
||||
}
|
||||
}
|
284
node_modules/body-parser/lib/types/urlencoded.js
generated
vendored
Normal file
284
node_modules/body-parser/lib/types/urlencoded.js
generated
vendored
Normal file
@ -0,0 +1,284 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var bytes = require('bytes')
|
||||
var contentType = require('content-type')
|
||||
var createError = require('http-errors')
|
||||
var debug = require('debug')('body-parser:urlencoded')
|
||||
var deprecate = require('depd')('body-parser')
|
||||
var read = require('../read')
|
||||
var typeis = require('type-is')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = urlencoded
|
||||
|
||||
/**
|
||||
* Cache of parser modules.
|
||||
*/
|
||||
|
||||
var parsers = Object.create(null)
|
||||
|
||||
/**
|
||||
* Create a middleware to parse urlencoded bodies.
|
||||
*
|
||||
* @param {object} [options]
|
||||
* @return {function}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function urlencoded (options) {
|
||||
var opts = options || {}
|
||||
|
||||
// notice because option default will flip in next major
|
||||
if (opts.extended === undefined) {
|
||||
deprecate('undefined extended: provide extended option')
|
||||
}
|
||||
|
||||
var extended = opts.extended !== false
|
||||
var inflate = opts.inflate !== false
|
||||
var limit = typeof opts.limit !== 'number'
|
||||
? bytes.parse(opts.limit || '100kb')
|
||||
: opts.limit
|
||||
var type = opts.type || 'application/x-www-form-urlencoded'
|
||||
var verify = opts.verify || false
|
||||
|
||||
if (verify !== false && typeof verify !== 'function') {
|
||||
throw new TypeError('option verify must be function')
|
||||
}
|
||||
|
||||
// create the appropriate query parser
|
||||
var queryparse = extended
|
||||
? extendedparser(opts)
|
||||
: simpleparser(opts)
|
||||
|
||||
// create the appropriate type checking function
|
||||
var shouldParse = typeof type !== 'function'
|
||||
? typeChecker(type)
|
||||
: type
|
||||
|
||||
function parse (body) {
|
||||
return body.length
|
||||
? queryparse(body)
|
||||
: {}
|
||||
}
|
||||
|
||||
return function urlencodedParser (req, res, next) {
|
||||
if (req._body) {
|
||||
debug('body already parsed')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
req.body = req.body || {}
|
||||
|
||||
// skip requests without bodies
|
||||
if (!typeis.hasBody(req)) {
|
||||
debug('skip empty body')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
debug('content-type %j', req.headers['content-type'])
|
||||
|
||||
// determine if request should be parsed
|
||||
if (!shouldParse(req)) {
|
||||
debug('skip parsing')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// assert charset
|
||||
var charset = getCharset(req) || 'utf-8'
|
||||
if (charset !== 'utf-8') {
|
||||
debug('invalid charset')
|
||||
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
|
||||
charset: charset,
|
||||
type: 'charset.unsupported'
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
// read
|
||||
read(req, res, next, parse, debug, {
|
||||
debug: debug,
|
||||
encoding: charset,
|
||||
inflate: inflate,
|
||||
limit: limit,
|
||||
verify: verify
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the extended query parser.
|
||||
*
|
||||
* @param {object} options
|
||||
*/
|
||||
|
||||
function extendedparser (options) {
|
||||
var parameterLimit = options.parameterLimit !== undefined
|
||||
? options.parameterLimit
|
||||
: 1000
|
||||
var parse = parser('qs')
|
||||
|
||||
if (isNaN(parameterLimit) || parameterLimit < 1) {
|
||||
throw new TypeError('option parameterLimit must be a positive number')
|
||||
}
|
||||
|
||||
if (isFinite(parameterLimit)) {
|
||||
parameterLimit = parameterLimit | 0
|
||||
}
|
||||
|
||||
return function queryparse (body) {
|
||||
var paramCount = parameterCount(body, parameterLimit)
|
||||
|
||||
if (paramCount === undefined) {
|
||||
debug('too many parameters')
|
||||
throw createError(413, 'too many parameters', {
|
||||
type: 'parameters.too.many'
|
||||
})
|
||||
}
|
||||
|
||||
var arrayLimit = Math.max(100, paramCount)
|
||||
|
||||
debug('parse extended urlencoding')
|
||||
return parse(body, {
|
||||
allowPrototypes: true,
|
||||
arrayLimit: arrayLimit,
|
||||
depth: Infinity,
|
||||
parameterLimit: parameterLimit
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the charset of a request.
|
||||
*
|
||||
* @param {object} req
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function getCharset (req) {
|
||||
try {
|
||||
return (contentType.parse(req).parameters.charset || '').toLowerCase()
|
||||
} catch (e) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the number of parameters, stopping once limit reached
|
||||
*
|
||||
* @param {string} body
|
||||
* @param {number} limit
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function parameterCount (body, limit) {
|
||||
var count = 0
|
||||
var index = 0
|
||||
|
||||
while ((index = body.indexOf('&', index)) !== -1) {
|
||||
count++
|
||||
index++
|
||||
|
||||
if (count === limit) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* Get parser for module name dynamically.
|
||||
*
|
||||
* @param {string} name
|
||||
* @return {function}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function parser (name) {
|
||||
var mod = parsers[name]
|
||||
|
||||
if (mod !== undefined) {
|
||||
return mod.parse
|
||||
}
|
||||
|
||||
// this uses a switch for static require analysis
|
||||
switch (name) {
|
||||
case 'qs':
|
||||
mod = require('qs')
|
||||
break
|
||||
case 'querystring':
|
||||
mod = require('querystring')
|
||||
break
|
||||
}
|
||||
|
||||
// store to prevent invoking require()
|
||||
parsers[name] = mod
|
||||
|
||||
return mod.parse
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the simple query parser.
|
||||
*
|
||||
* @param {object} options
|
||||
*/
|
||||
|
||||
function simpleparser (options) {
|
||||
var parameterLimit = options.parameterLimit !== undefined
|
||||
? options.parameterLimit
|
||||
: 1000
|
||||
var parse = parser('querystring')
|
||||
|
||||
if (isNaN(parameterLimit) || parameterLimit < 1) {
|
||||
throw new TypeError('option parameterLimit must be a positive number')
|
||||
}
|
||||
|
||||
if (isFinite(parameterLimit)) {
|
||||
parameterLimit = parameterLimit | 0
|
||||
}
|
||||
|
||||
return function queryparse (body) {
|
||||
var paramCount = parameterCount(body, parameterLimit)
|
||||
|
||||
if (paramCount === undefined) {
|
||||
debug('too many parameters')
|
||||
throw createError(413, 'too many parameters', {
|
||||
type: 'parameters.too.many'
|
||||
})
|
||||
}
|
||||
|
||||
debug('parse urlencoding')
|
||||
return parse(body, undefined, undefined, { maxKeys: parameterLimit })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the simple type checker.
|
||||
*
|
||||
* @param {string} type
|
||||
* @return {function}
|
||||
*/
|
||||
|
||||
function typeChecker (type) {
|
||||
return function checkType (req) {
|
||||
return Boolean(typeis(req, type))
|
||||
}
|
||||
}
|
56
node_modules/body-parser/package.json
generated
vendored
Normal file
56
node_modules/body-parser/package.json
generated
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "body-parser",
|
||||
"description": "Node.js body parsing middleware",
|
||||
"version": "1.20.2",
|
||||
"contributors": [
|
||||
"Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "expressjs/body-parser",
|
||||
"dependencies": {
|
||||
"bytes": "3.1.2",
|
||||
"content-type": "~1.0.5",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "1.2.0",
|
||||
"http-errors": "2.0.0",
|
||||
"iconv-lite": "0.4.24",
|
||||
"on-finished": "2.4.1",
|
||||
"qs": "6.11.0",
|
||||
"raw-body": "2.5.2",
|
||||
"type-is": "~1.6.18",
|
||||
"unpipe": "1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "8.34.0",
|
||||
"eslint-config-standard": "14.1.1",
|
||||
"eslint-plugin-import": "2.27.5",
|
||||
"eslint-plugin-markdown": "3.0.0",
|
||||
"eslint-plugin-node": "11.1.0",
|
||||
"eslint-plugin-promise": "6.1.1",
|
||||
"eslint-plugin-standard": "4.1.0",
|
||||
"methods": "1.1.2",
|
||||
"mocha": "10.2.0",
|
||||
"nyc": "15.1.0",
|
||||
"safe-buffer": "5.2.1",
|
||||
"supertest": "6.3.3"
|
||||
},
|
||||
"files": [
|
||||
"lib/",
|
||||
"LICENSE",
|
||||
"HISTORY.md",
|
||||
"SECURITY.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/",
|
||||
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
}
|
||||
}
|
97
node_modules/bytes/History.md
generated
vendored
Normal file
97
node_modules/bytes/History.md
generated
vendored
Normal file
@ -0,0 +1,97 @@
|
||||
3.1.2 / 2022-01-27
|
||||
==================
|
||||
|
||||
* Fix return value for un-parsable strings
|
||||
|
||||
3.1.1 / 2021-11-15
|
||||
==================
|
||||
|
||||
* Fix "thousandsSeparator" incorrecting formatting fractional part
|
||||
|
||||
3.1.0 / 2019-01-22
|
||||
==================
|
||||
|
||||
* Add petabyte (`pb`) support
|
||||
|
||||
3.0.0 / 2017-08-31
|
||||
==================
|
||||
|
||||
* Change "kB" to "KB" in format output
|
||||
* Remove support for Node.js 0.6
|
||||
* Remove support for ComponentJS
|
||||
|
||||
2.5.0 / 2017-03-24
|
||||
==================
|
||||
|
||||
* Add option "unit"
|
||||
|
||||
2.4.0 / 2016-06-01
|
||||
==================
|
||||
|
||||
* Add option "unitSeparator"
|
||||
|
||||
2.3.0 / 2016-02-15
|
||||
==================
|
||||
|
||||
* Drop partial bytes on all parsed units
|
||||
* Fix non-finite numbers to `.format` to return `null`
|
||||
* Fix parsing byte string that looks like hex
|
||||
* perf: hoist regular expressions
|
||||
|
||||
2.2.0 / 2015-11-13
|
||||
==================
|
||||
|
||||
* add option "decimalPlaces"
|
||||
* add option "fixedDecimals"
|
||||
|
||||
2.1.0 / 2015-05-21
|
||||
==================
|
||||
|
||||
* add `.format` export
|
||||
* add `.parse` export
|
||||
|
||||
2.0.2 / 2015-05-20
|
||||
==================
|
||||
|
||||
* remove map recreation
|
||||
* remove unnecessary object construction
|
||||
|
||||
2.0.1 / 2015-05-07
|
||||
==================
|
||||
|
||||
* fix browserify require
|
||||
* remove node.extend dependency
|
||||
|
||||
2.0.0 / 2015-04-12
|
||||
==================
|
||||
|
||||
* add option "case"
|
||||
* add option "thousandsSeparator"
|
||||
* return "null" on invalid parse input
|
||||
* support proper round-trip: bytes(bytes(num)) === num
|
||||
* units no longer case sensitive when parsing
|
||||
|
||||
1.0.0 / 2014-05-05
|
||||
==================
|
||||
|
||||
* add negative support. fixes #6
|
||||
|
||||
0.3.0 / 2014-03-19
|
||||
==================
|
||||
|
||||
* added terabyte support
|
||||
|
||||
0.2.1 / 2013-04-01
|
||||
==================
|
||||
|
||||
* add .component
|
||||
|
||||
0.2.0 / 2012-10-28
|
||||
==================
|
||||
|
||||
* bytes(200).should.eql('200b')
|
||||
|
||||
0.1.0 / 2012-07-04
|
||||
==================
|
||||
|
||||
* add bytes to string conversion [yields]
|
23
node_modules/bytes/LICENSE
generated
vendored
Normal file
23
node_modules/bytes/LICENSE
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2012-2014 TJ Holowaychuk <tj@vision-media.ca>
|
||||
Copyright (c) 2015 Jed Watson <jed.watson@me.com>
|
||||
|
||||
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.
|
152
node_modules/bytes/Readme.md
generated
vendored
Normal file
152
node_modules/bytes/Readme.md
generated
vendored
Normal file
@ -0,0 +1,152 @@
|
||||
# Bytes utility
|
||||
|
||||
[![NPM Version][npm-image]][npm-url]
|
||||
[![NPM Downloads][downloads-image]][downloads-url]
|
||||
[![Build Status][ci-image]][ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa.
|
||||
|
||||
## Installation
|
||||
|
||||
This is a [Node.js](https://nodejs.org/en/) module available through the
|
||||
[npm registry](https://www.npmjs.com/). Installation is done using the
|
||||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
||||
|
||||
```bash
|
||||
$ npm install bytes
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
var bytes = require('bytes');
|
||||
```
|
||||
|
||||
#### bytes(number|string value, [options]): number|string|null
|
||||
|
||||
Default export function. Delegates to either `bytes.format` or `bytes.parse` based on the type of `value`.
|
||||
|
||||
**Arguments**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|--------------------|
|
||||
| value | `number`|`string` | Number value to format or string value to parse |
|
||||
| options | `Object` | Conversion options for `format` |
|
||||
|
||||
**Returns**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|------------------|-------------------------------------------------|
|
||||
| results | `string`|`number`|`null` | Return null upon error. Numeric value in bytes, or string value otherwise. |
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
bytes(1024);
|
||||
// output: '1KB'
|
||||
|
||||
bytes('1KB');
|
||||
// output: 1024
|
||||
```
|
||||
|
||||
#### bytes.format(number value, [options]): string|null
|
||||
|
||||
Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is
|
||||
rounded.
|
||||
|
||||
**Arguments**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|--------------------|
|
||||
| value | `number` | Value in bytes |
|
||||
| options | `Object` | Conversion options |
|
||||
|
||||
**Options**
|
||||
|
||||
| Property | Type | Description |
|
||||
|-------------------|--------|-----------------------------------------------------------------------------------------|
|
||||
| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. |
|
||||
| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` |
|
||||
| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `'.'`... Default value to `''`. |
|
||||
| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). |
|
||||
| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. |
|
||||
|
||||
**Returns**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|------------------|-------------------------------------------------|
|
||||
| results | `string`|`null` | Return null upon error. String value otherwise. |
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
bytes.format(1024);
|
||||
// output: '1KB'
|
||||
|
||||
bytes.format(1000);
|
||||
// output: '1000B'
|
||||
|
||||
bytes.format(1000, {thousandsSeparator: ' '});
|
||||
// output: '1 000B'
|
||||
|
||||
bytes.format(1024 * 1.7, {decimalPlaces: 0});
|
||||
// output: '2KB'
|
||||
|
||||
bytes.format(1024, {unitSeparator: ' '});
|
||||
// output: '1 KB'
|
||||
```
|
||||
|
||||
#### bytes.parse(string|number value): number|null
|
||||
|
||||
Parse the string value into an integer in bytes. If no unit is given, or `value`
|
||||
is a number, it is assumed the value is in bytes.
|
||||
|
||||
Supported units and abbreviations are as follows and are case-insensitive:
|
||||
|
||||
* `b` for bytes
|
||||
* `kb` for kilobytes
|
||||
* `mb` for megabytes
|
||||
* `gb` for gigabytes
|
||||
* `tb` for terabytes
|
||||
* `pb` for petabytes
|
||||
|
||||
The units are in powers of two, not ten. This means 1kb = 1024b according to this parser.
|
||||
|
||||
**Arguments**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------------|--------|--------------------|
|
||||
| value | `string`|`number` | String to parse, or number in bytes. |
|
||||
|
||||
**Returns**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|-------------|-------------------------|
|
||||
| results | `number`|`null` | Return null upon error. Value in bytes otherwise. |
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
bytes.parse('1KB');
|
||||
// output: 1024
|
||||
|
||||
bytes.parse('1024');
|
||||
// output: 1024
|
||||
|
||||
bytes.parse(1024);
|
||||
// output: 1024
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[ci-image]: https://badgen.net/github/checks/visionmedia/bytes.js/master?label=ci
|
||||
[ci-url]: https://github.com/visionmedia/bytes.js/actions?query=workflow%3Aci
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master
|
||||
[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master
|
||||
[downloads-image]: https://badgen.net/npm/dm/bytes
|
||||
[downloads-url]: https://npmjs.org/package/bytes
|
||||
[npm-image]: https://badgen.net/npm/v/bytes
|
||||
[npm-url]: https://npmjs.org/package/bytes
|
170
node_modules/bytes/index.js
generated
vendored
Normal file
170
node_modules/bytes/index.js
generated
vendored
Normal file
@ -0,0 +1,170 @@
|
||||
/*!
|
||||
* bytes
|
||||
* Copyright(c) 2012-2014 TJ Holowaychuk
|
||||
* Copyright(c) 2015 Jed Watson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = bytes;
|
||||
module.exports.format = format;
|
||||
module.exports.parse = parse;
|
||||
|
||||
/**
|
||||
* Module variables.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
|
||||
|
||||
var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
|
||||
|
||||
var map = {
|
||||
b: 1,
|
||||
kb: 1 << 10,
|
||||
mb: 1 << 20,
|
||||
gb: 1 << 30,
|
||||
tb: Math.pow(1024, 4),
|
||||
pb: Math.pow(1024, 5),
|
||||
};
|
||||
|
||||
var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;
|
||||
|
||||
/**
|
||||
* Convert the given value in bytes into a string or parse to string to an integer in bytes.
|
||||
*
|
||||
* @param {string|number} value
|
||||
* @param {{
|
||||
* case: [string],
|
||||
* decimalPlaces: [number]
|
||||
* fixedDecimals: [boolean]
|
||||
* thousandsSeparator: [string]
|
||||
* unitSeparator: [string]
|
||||
* }} [options] bytes options.
|
||||
*
|
||||
* @returns {string|number|null}
|
||||
*/
|
||||
|
||||
function bytes(value, options) {
|
||||
if (typeof value === 'string') {
|
||||
return parse(value);
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return format(value, options);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given value in bytes into a string.
|
||||
*
|
||||
* If the value is negative, it is kept as such. If it is a float,
|
||||
* it is rounded.
|
||||
*
|
||||
* @param {number} value
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.decimalPlaces=2]
|
||||
* @param {number} [options.fixedDecimals=false]
|
||||
* @param {string} [options.thousandsSeparator=]
|
||||
* @param {string} [options.unit=]
|
||||
* @param {string} [options.unitSeparator=]
|
||||
*
|
||||
* @returns {string|null}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function format(value, options) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var mag = Math.abs(value);
|
||||
var thousandsSeparator = (options && options.thousandsSeparator) || '';
|
||||
var unitSeparator = (options && options.unitSeparator) || '';
|
||||
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
|
||||
var fixedDecimals = Boolean(options && options.fixedDecimals);
|
||||
var unit = (options && options.unit) || '';
|
||||
|
||||
if (!unit || !map[unit.toLowerCase()]) {
|
||||
if (mag >= map.pb) {
|
||||
unit = 'PB';
|
||||
} else if (mag >= map.tb) {
|
||||
unit = 'TB';
|
||||
} else if (mag >= map.gb) {
|
||||
unit = 'GB';
|
||||
} else if (mag >= map.mb) {
|
||||
unit = 'MB';
|
||||
} else if (mag >= map.kb) {
|
||||
unit = 'KB';
|
||||
} else {
|
||||
unit = 'B';
|
||||
}
|
||||
}
|
||||
|
||||
var val = value / map[unit.toLowerCase()];
|
||||
var str = val.toFixed(decimalPlaces);
|
||||
|
||||
if (!fixedDecimals) {
|
||||
str = str.replace(formatDecimalsRegExp, '$1');
|
||||
}
|
||||
|
||||
if (thousandsSeparator) {
|
||||
str = str.split('.').map(function (s, i) {
|
||||
return i === 0
|
||||
? s.replace(formatThousandsRegExp, thousandsSeparator)
|
||||
: s
|
||||
}).join('.');
|
||||
}
|
||||
|
||||
return str + unitSeparator + unit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the string value into an integer in bytes.
|
||||
*
|
||||
* If no unit is given, it is assumed the value is in bytes.
|
||||
*
|
||||
* @param {number|string} val
|
||||
*
|
||||
* @returns {number|null}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function parse(val) {
|
||||
if (typeof val === 'number' && !isNaN(val)) {
|
||||
return val;
|
||||
}
|
||||
|
||||
if (typeof val !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Test if the string passed is valid
|
||||
var results = parseRegExp.exec(val);
|
||||
var floatValue;
|
||||
var unit = 'b';
|
||||
|
||||
if (!results) {
|
||||
// Nothing could be extracted from the given string
|
||||
floatValue = parseInt(val, 10);
|
||||
unit = 'b'
|
||||
} else {
|
||||
// Retrieve the value and the unit
|
||||
floatValue = parseFloat(results[1]);
|
||||
unit = results[4].toLowerCase();
|
||||
}
|
||||
|
||||
if (isNaN(floatValue)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Math.floor(map[unit] * floatValue);
|
||||
}
|
42
node_modules/bytes/package.json
generated
vendored
Normal file
42
node_modules/bytes/package.json
generated
vendored
Normal file
@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "bytes",
|
||||
"description": "Utility to parse a string bytes to bytes and vice-versa",
|
||||
"version": "3.1.2",
|
||||
"author": "TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)",
|
||||
"contributors": [
|
||||
"Jed Watson <jed.watson@me.com>",
|
||||
"Théo FIDRY <theo.fidry@gmail.com>"
|
||||
],
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"byte",
|
||||
"bytes",
|
||||
"utility",
|
||||
"parse",
|
||||
"parser",
|
||||
"convert",
|
||||
"converter"
|
||||
],
|
||||
"repository": "visionmedia/bytes.js",
|
||||
"devDependencies": {
|
||||
"eslint": "7.32.0",
|
||||
"eslint-plugin-markdown": "2.2.1",
|
||||
"mocha": "9.2.0",
|
||||
"nyc": "15.1.0"
|
||||
},
|
||||
"files": [
|
||||
"History.md",
|
||||
"LICENSE",
|
||||
"Readme.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --check-leaks --reporter spec",
|
||||
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
}
|
||||
}
|
139
node_modules/cliui/CHANGELOG.md
generated
vendored
Normal file
139
node_modules/cliui/CHANGELOG.md
generated
vendored
Normal file
@ -0,0 +1,139 @@
|
||||
# Change Log
|
||||
|
||||
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
|
||||
|
||||
## [8.0.1](https://github.com/yargs/cliui/compare/v8.0.0...v8.0.1) (2022-10-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **deps:** move rollup-plugin-ts to dev deps ([#124](https://github.com/yargs/cliui/issues/124)) ([7c8bd6b](https://github.com/yargs/cliui/commit/7c8bd6ba024d61e4eeae310c7959ab8ab6829081))
|
||||
|
||||
## [8.0.0](https://github.com/yargs/cliui/compare/v7.0.4...v8.0.0) (2022-09-30)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **deps:** drop Node 10 to release CVE-2021-3807 patch (#122)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **deps:** drop Node 10 to release CVE-2021-3807 patch ([#122](https://github.com/yargs/cliui/issues/122)) ([f156571](https://github.com/yargs/cliui/commit/f156571ce4f2ebf313335e3a53ad905589da5a30))
|
||||
|
||||
### [7.0.4](https://www.github.com/yargs/cliui/compare/v7.0.3...v7.0.4) (2020-11-08)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **deno:** import UIOptions from definitions ([#97](https://www.github.com/yargs/cliui/issues/97)) ([f04f343](https://www.github.com/yargs/cliui/commit/f04f3439bc78114c7e90f82ff56f5acf16268ea8))
|
||||
|
||||
### [7.0.3](https://www.github.com/yargs/cliui/compare/v7.0.2...v7.0.3) (2020-10-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#93](https://www.github.com/yargs/cliui/issues/93)) ([eca16fc](https://www.github.com/yargs/cliui/commit/eca16fc05d26255df3280906c36d7f0e5b05c6e9))
|
||||
|
||||
### [7.0.2](https://www.github.com/yargs/cliui/compare/v7.0.1...v7.0.2) (2020-10-14)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **exports:** node 13.0-13.6 require a string fallback ([#91](https://www.github.com/yargs/cliui/issues/91)) ([b529d7e](https://www.github.com/yargs/cliui/commit/b529d7e432901af1af7848b23ed6cf634497d961))
|
||||
|
||||
### [7.0.1](https://www.github.com/yargs/cliui/compare/v7.0.0...v7.0.1) (2020-08-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **build:** main should be build/index.cjs ([dc29a3c](https://www.github.com/yargs/cliui/commit/dc29a3cc617a410aa850e06337b5954b04f2cb4d))
|
||||
|
||||
## [7.0.0](https://www.github.com/yargs/cliui/compare/v6.0.0...v7.0.0) (2020-08-16)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* tsc/ESM/Deno support (#82)
|
||||
* modernize deps and build (#80)
|
||||
|
||||
### Build System
|
||||
|
||||
* modernize deps and build ([#80](https://www.github.com/yargs/cliui/issues/80)) ([339d08d](https://www.github.com/yargs/cliui/commit/339d08dc71b15a3928aeab09042af94db2f43743))
|
||||
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
* tsc/ESM/Deno support ([#82](https://www.github.com/yargs/cliui/issues/82)) ([4b777a5](https://www.github.com/yargs/cliui/commit/4b777a5fe01c5d8958c6708695d6aab7dbe5706c))
|
||||
|
||||
## [6.0.0](https://www.github.com/yargs/cliui/compare/v5.0.0...v6.0.0) (2019-11-10)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* update deps, drop Node 6
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
* update deps, drop Node 6 ([62056df](https://www.github.com/yargs/cliui/commit/62056df))
|
||||
|
||||
## [5.0.0](https://github.com/yargs/cliui/compare/v4.1.0...v5.0.0) (2019-04-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Update wrap-ansi to fix compatibility with latest versions of chalk. ([#60](https://github.com/yargs/cliui/issues/60)) ([7bf79ae](https://github.com/yargs/cliui/commit/7bf79ae))
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Drop support for node < 6.
|
||||
|
||||
|
||||
|
||||
<a name="4.1.0"></a>
|
||||
## [4.1.0](https://github.com/yargs/cliui/compare/v4.0.0...v4.1.0) (2018-04-23)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add resetOutput method ([#57](https://github.com/yargs/cliui/issues/57)) ([7246902](https://github.com/yargs/cliui/commit/7246902))
|
||||
|
||||
|
||||
|
||||
<a name="4.0.0"></a>
|
||||
## [4.0.0](https://github.com/yargs/cliui/compare/v3.2.0...v4.0.0) (2017-12-18)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* downgrades strip-ansi to version 3.0.1 ([#54](https://github.com/yargs/cliui/issues/54)) ([5764c46](https://github.com/yargs/cliui/commit/5764c46))
|
||||
* set env variable FORCE_COLOR. ([#56](https://github.com/yargs/cliui/issues/56)) ([7350e36](https://github.com/yargs/cliui/commit/7350e36))
|
||||
|
||||
|
||||
### Chores
|
||||
|
||||
* drop support for node < 4 ([#53](https://github.com/yargs/cliui/issues/53)) ([b105376](https://github.com/yargs/cliui/commit/b105376))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add fallback for window width ([#45](https://github.com/yargs/cliui/issues/45)) ([d064922](https://github.com/yargs/cliui/commit/d064922))
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* officially drop support for Node < 4
|
||||
|
||||
|
||||
|
||||
<a name="3.2.0"></a>
|
||||
## [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33))
|
||||
|
||||
### Features
|
||||
|
||||
* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32))
|
14
node_modules/cliui/LICENSE.txt
generated
vendored
Normal file
14
node_modules/cliui/LICENSE.txt
generated
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
Copyright (c) 2015, Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software
|
||||
for any purpose with or without fee is hereby granted, provided
|
||||
that the above copyright notice and this permission notice
|
||||
appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
|
||||
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
|
||||
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
|
||||
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
141
node_modules/cliui/README.md
generated
vendored
Normal file
141
node_modules/cliui/README.md
generated
vendored
Normal file
@ -0,0 +1,141 @@
|
||||
# cliui
|
||||
|
||||
![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg)
|
||||
[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui)
|
||||
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
|
||||
![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui)
|
||||
|
||||
easily create complex multi-column command-line-interfaces.
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
const ui = require('cliui')()
|
||||
|
||||
ui.div('Usage: $0 [command] [options]')
|
||||
|
||||
ui.div({
|
||||
text: 'Options:',
|
||||
padding: [2, 0, 1, 0]
|
||||
})
|
||||
|
||||
ui.div(
|
||||
{
|
||||
text: "-f, --file",
|
||||
width: 20,
|
||||
padding: [0, 4, 0, 4]
|
||||
},
|
||||
{
|
||||
text: "the file to load." +
|
||||
chalk.green("(if this description is long it wraps).")
|
||||
,
|
||||
width: 20
|
||||
},
|
||||
{
|
||||
text: chalk.red("[required]"),
|
||||
align: 'right'
|
||||
}
|
||||
)
|
||||
|
||||
console.log(ui.toString())
|
||||
```
|
||||
|
||||
## Deno/ESM Support
|
||||
|
||||
As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and
|
||||
[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules):
|
||||
|
||||
```typescript
|
||||
import cliui from "https://deno.land/x/cliui/deno.ts";
|
||||
|
||||
const ui = cliui({})
|
||||
|
||||
ui.div('Usage: $0 [command] [options]')
|
||||
|
||||
ui.div({
|
||||
text: 'Options:',
|
||||
padding: [2, 0, 1, 0]
|
||||
})
|
||||
|
||||
ui.div({
|
||||
text: "-f, --file",
|
||||
width: 20,
|
||||
padding: [0, 4, 0, 4]
|
||||
})
|
||||
|
||||
console.log(ui.toString())
|
||||
```
|
||||
|
||||
<img width="500" src="screenshot.png">
|
||||
|
||||
## Layout DSL
|
||||
|
||||
cliui exposes a simple layout DSL:
|
||||
|
||||
If you create a single `ui.div`, passing a string rather than an
|
||||
object:
|
||||
|
||||
* `\n`: characters will be interpreted as new rows.
|
||||
* `\t`: characters will be interpreted as new columns.
|
||||
* `\s`: characters will be interpreted as padding.
|
||||
|
||||
**as an example...**
|
||||
|
||||
```js
|
||||
var ui = require('./')({
|
||||
width: 60
|
||||
})
|
||||
|
||||
ui.div(
|
||||
'Usage: node ./bin/foo.js\n' +
|
||||
' <regex>\t provide a regex\n' +
|
||||
' <glob>\t provide a glob\t [required]'
|
||||
)
|
||||
|
||||
console.log(ui.toString())
|
||||
```
|
||||
|
||||
**will output:**
|
||||
|
||||
```shell
|
||||
Usage: node ./bin/foo.js
|
||||
<regex> provide a regex
|
||||
<glob> provide a glob [required]
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
```js
|
||||
cliui = require('cliui')
|
||||
```
|
||||
|
||||
### cliui({width: integer})
|
||||
|
||||
Specify the maximum width of the UI being generated.
|
||||
If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`.
|
||||
|
||||
### cliui({wrap: boolean})
|
||||
|
||||
Enable or disable the wrapping of text in a column.
|
||||
|
||||
### cliui.div(column, column, column)
|
||||
|
||||
Create a row with any number of columns, a column
|
||||
can either be a string, or an object with the following
|
||||
options:
|
||||
|
||||
* **text:** some text to place in the column.
|
||||
* **width:** the width of a column.
|
||||
* **align:** alignment, `right` or `center`.
|
||||
* **padding:** `[top, right, bottom, left]`.
|
||||
* **border:** should a border be placed around the div?
|
||||
|
||||
### cliui.span(column, column, column)
|
||||
|
||||
Similar to `div`, except the next row will be appended without
|
||||
a new line being created.
|
||||
|
||||
### cliui.resetOutput()
|
||||
|
||||
Resets the UI elements of the current cliui instance, maintaining the values
|
||||
set for `width` and `wrap`.
|
302
node_modules/cliui/build/index.cjs
generated
vendored
Normal file
302
node_modules/cliui/build/index.cjs
generated
vendored
Normal file
@ -0,0 +1,302 @@
|
||||
'use strict';
|
||||
|
||||
const align = {
|
||||
right: alignRight,
|
||||
center: alignCenter
|
||||
};
|
||||
const top = 0;
|
||||
const right = 1;
|
||||
const bottom = 2;
|
||||
const left = 3;
|
||||
class UI {
|
||||
constructor(opts) {
|
||||
var _a;
|
||||
this.width = opts.width;
|
||||
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
|
||||
this.rows = [];
|
||||
}
|
||||
span(...args) {
|
||||
const cols = this.div(...args);
|
||||
cols.span = true;
|
||||
}
|
||||
resetOutput() {
|
||||
this.rows = [];
|
||||
}
|
||||
div(...args) {
|
||||
if (args.length === 0) {
|
||||
this.div('');
|
||||
}
|
||||
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
|
||||
return this.applyLayoutDSL(args[0]);
|
||||
}
|
||||
const cols = args.map(arg => {
|
||||
if (typeof arg === 'string') {
|
||||
return this.colFromString(arg);
|
||||
}
|
||||
return arg;
|
||||
});
|
||||
this.rows.push(cols);
|
||||
return cols;
|
||||
}
|
||||
shouldApplyLayoutDSL(...args) {
|
||||
return args.length === 1 && typeof args[0] === 'string' &&
|
||||
/[\t\n]/.test(args[0]);
|
||||
}
|
||||
applyLayoutDSL(str) {
|
||||
const rows = str.split('\n').map(row => row.split('\t'));
|
||||
let leftColumnWidth = 0;
|
||||
// simple heuristic for layout, make sure the
|
||||
// second column lines up along the left-hand.
|
||||
// don't allow the first column to take up more
|
||||
// than 50% of the screen.
|
||||
rows.forEach(columns => {
|
||||
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
|
||||
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
|
||||
}
|
||||
});
|
||||
// generate a table:
|
||||
// replacing ' ' with padding calculations.
|
||||
// using the algorithmically generated width.
|
||||
rows.forEach(columns => {
|
||||
this.div(...columns.map((r, i) => {
|
||||
return {
|
||||
text: r.trim(),
|
||||
padding: this.measurePadding(r),
|
||||
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
|
||||
};
|
||||
}));
|
||||
});
|
||||
return this.rows[this.rows.length - 1];
|
||||
}
|
||||
colFromString(text) {
|
||||
return {
|
||||
text,
|
||||
padding: this.measurePadding(text)
|
||||
};
|
||||
}
|
||||
measurePadding(str) {
|
||||
// measure padding without ansi escape codes
|
||||
const noAnsi = mixin.stripAnsi(str);
|
||||
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
|
||||
}
|
||||
toString() {
|
||||
const lines = [];
|
||||
this.rows.forEach(row => {
|
||||
this.rowToString(row, lines);
|
||||
});
|
||||
// don't display any lines with the
|
||||
// hidden flag set.
|
||||
return lines
|
||||
.filter(line => !line.hidden)
|
||||
.map(line => line.text)
|
||||
.join('\n');
|
||||
}
|
||||
rowToString(row, lines) {
|
||||
this.rasterize(row).forEach((rrow, r) => {
|
||||
let str = '';
|
||||
rrow.forEach((col, c) => {
|
||||
const { width } = row[c]; // the width with padding.
|
||||
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
|
||||
let ts = col; // temporary string used during alignment/padding.
|
||||
if (wrapWidth > mixin.stringWidth(col)) {
|
||||
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
|
||||
}
|
||||
// align the string within its column.
|
||||
if (row[c].align && row[c].align !== 'left' && this.wrap) {
|
||||
const fn = align[row[c].align];
|
||||
ts = fn(ts, wrapWidth);
|
||||
if (mixin.stringWidth(ts) < wrapWidth) {
|
||||
ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
|
||||
}
|
||||
}
|
||||
// apply border and padding to string.
|
||||
const padding = row[c].padding || [0, 0, 0, 0];
|
||||
if (padding[left]) {
|
||||
str += ' '.repeat(padding[left]);
|
||||
}
|
||||
str += addBorder(row[c], ts, '| ');
|
||||
str += ts;
|
||||
str += addBorder(row[c], ts, ' |');
|
||||
if (padding[right]) {
|
||||
str += ' '.repeat(padding[right]);
|
||||
}
|
||||
// if prior row is span, try to render the
|
||||
// current row on the prior line.
|
||||
if (r === 0 && lines.length > 0) {
|
||||
str = this.renderInline(str, lines[lines.length - 1]);
|
||||
}
|
||||
});
|
||||
// remove trailing whitespace.
|
||||
lines.push({
|
||||
text: str.replace(/ +$/, ''),
|
||||
span: row.span
|
||||
});
|
||||
});
|
||||
return lines;
|
||||
}
|
||||
// if the full 'source' can render in
|
||||
// the target line, do so.
|
||||
renderInline(source, previousLine) {
|
||||
const match = source.match(/^ */);
|
||||
const leadingWhitespace = match ? match[0].length : 0;
|
||||
const target = previousLine.text;
|
||||
const targetTextWidth = mixin.stringWidth(target.trimRight());
|
||||
if (!previousLine.span) {
|
||||
return source;
|
||||
}
|
||||
// if we're not applying wrapping logic,
|
||||
// just always append to the span.
|
||||
if (!this.wrap) {
|
||||
previousLine.hidden = true;
|
||||
return target + source;
|
||||
}
|
||||
if (leadingWhitespace < targetTextWidth) {
|
||||
return source;
|
||||
}
|
||||
previousLine.hidden = true;
|
||||
return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
|
||||
}
|
||||
rasterize(row) {
|
||||
const rrows = [];
|
||||
const widths = this.columnWidths(row);
|
||||
let wrapped;
|
||||
// word wrap all columns, and create
|
||||
// a data-structure that is easy to rasterize.
|
||||
row.forEach((col, c) => {
|
||||
// leave room for left and right padding.
|
||||
col.width = widths[c];
|
||||
if (this.wrap) {
|
||||
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
|
||||
}
|
||||
else {
|
||||
wrapped = col.text.split('\n');
|
||||
}
|
||||
if (col.border) {
|
||||
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
|
||||
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
|
||||
}
|
||||
// add top and bottom padding.
|
||||
if (col.padding) {
|
||||
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
|
||||
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
|
||||
}
|
||||
wrapped.forEach((str, r) => {
|
||||
if (!rrows[r]) {
|
||||
rrows.push([]);
|
||||
}
|
||||
const rrow = rrows[r];
|
||||
for (let i = 0; i < c; i++) {
|
||||
if (rrow[i] === undefined) {
|
||||
rrow.push('');
|
||||
}
|
||||
}
|
||||
rrow.push(str);
|
||||
});
|
||||
});
|
||||
return rrows;
|
||||
}
|
||||
negatePadding(col) {
|
||||
let wrapWidth = col.width || 0;
|
||||
if (col.padding) {
|
||||
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
|
||||
}
|
||||
if (col.border) {
|
||||
wrapWidth -= 4;
|
||||
}
|
||||
return wrapWidth;
|
||||
}
|
||||
columnWidths(row) {
|
||||
if (!this.wrap) {
|
||||
return row.map(col => {
|
||||
return col.width || mixin.stringWidth(col.text);
|
||||
});
|
||||
}
|
||||
let unset = row.length;
|
||||
let remainingWidth = this.width;
|
||||
// column widths can be set in config.
|
||||
const widths = row.map(col => {
|
||||
if (col.width) {
|
||||
unset--;
|
||||
remainingWidth -= col.width;
|
||||
return col.width;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
// any unset widths should be calculated.
|
||||
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
|
||||
return widths.map((w, i) => {
|
||||
if (w === undefined) {
|
||||
return Math.max(unsetWidth, _minWidth(row[i]));
|
||||
}
|
||||
return w;
|
||||
});
|
||||
}
|
||||
}
|
||||
function addBorder(col, ts, style) {
|
||||
if (col.border) {
|
||||
if (/[.']-+[.']/.test(ts)) {
|
||||
return '';
|
||||
}
|
||||
if (ts.trim().length !== 0) {
|
||||
return style;
|
||||
}
|
||||
return ' ';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
// calculates the minimum width of
|
||||
// a column, based on padding preferences.
|
||||
function _minWidth(col) {
|
||||
const padding = col.padding || [];
|
||||
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
|
||||
if (col.border) {
|
||||
return minWidth + 4;
|
||||
}
|
||||
return minWidth;
|
||||
}
|
||||
function getWindowWidth() {
|
||||
/* istanbul ignore next: depends on terminal */
|
||||
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
|
||||
return process.stdout.columns;
|
||||
}
|
||||
return 80;
|
||||
}
|
||||
function alignRight(str, width) {
|
||||
str = str.trim();
|
||||
const strWidth = mixin.stringWidth(str);
|
||||
if (strWidth < width) {
|
||||
return ' '.repeat(width - strWidth) + str;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
function alignCenter(str, width) {
|
||||
str = str.trim();
|
||||
const strWidth = mixin.stringWidth(str);
|
||||
/* istanbul ignore next */
|
||||
if (strWidth >= width) {
|
||||
return str;
|
||||
}
|
||||
return ' '.repeat((width - strWidth) >> 1) + str;
|
||||
}
|
||||
let mixin;
|
||||
function cliui(opts, _mixin) {
|
||||
mixin = _mixin;
|
||||
return new UI({
|
||||
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
|
||||
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
|
||||
});
|
||||
}
|
||||
|
||||
// Bootstrap cliui with CommonJS dependencies:
|
||||
const stringWidth = require('string-width');
|
||||
const stripAnsi = require('strip-ansi');
|
||||
const wrap = require('wrap-ansi');
|
||||
function ui(opts) {
|
||||
return cliui(opts, {
|
||||
stringWidth,
|
||||
stripAnsi,
|
||||
wrap
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = ui;
|
43
node_modules/cliui/build/index.d.cts
generated
vendored
Normal file
43
node_modules/cliui/build/index.d.cts
generated
vendored
Normal file
@ -0,0 +1,43 @@
|
||||
interface UIOptions {
|
||||
width: number;
|
||||
wrap?: boolean;
|
||||
rows?: string[];
|
||||
}
|
||||
interface Column {
|
||||
text: string;
|
||||
width?: number;
|
||||
align?: "right" | "left" | "center";
|
||||
padding: number[];
|
||||
border?: boolean;
|
||||
}
|
||||
interface ColumnArray extends Array<Column> {
|
||||
span: boolean;
|
||||
}
|
||||
interface Line {
|
||||
hidden?: boolean;
|
||||
text: string;
|
||||
span?: boolean;
|
||||
}
|
||||
declare class UI {
|
||||
width: number;
|
||||
wrap: boolean;
|
||||
rows: ColumnArray[];
|
||||
constructor(opts: UIOptions);
|
||||
span(...args: ColumnArray): void;
|
||||
resetOutput(): void;
|
||||
div(...args: (Column | string)[]): ColumnArray;
|
||||
private shouldApplyLayoutDSL;
|
||||
private applyLayoutDSL;
|
||||
private colFromString;
|
||||
private measurePadding;
|
||||
toString(): string;
|
||||
rowToString(row: ColumnArray, lines: Line[]): Line[];
|
||||
// if the full 'source' can render in
|
||||
// the target line, do so.
|
||||
private renderInline;
|
||||
private rasterize;
|
||||
private negatePadding;
|
||||
private columnWidths;
|
||||
}
|
||||
declare function ui(opts: UIOptions): UI;
|
||||
export { ui as default };
|
287
node_modules/cliui/build/lib/index.js
generated
vendored
Normal file
287
node_modules/cliui/build/lib/index.js
generated
vendored
Normal file
@ -0,0 +1,287 @@
|
||||
'use strict';
|
||||
const align = {
|
||||
right: alignRight,
|
||||
center: alignCenter
|
||||
};
|
||||
const top = 0;
|
||||
const right = 1;
|
||||
const bottom = 2;
|
||||
const left = 3;
|
||||
export class UI {
|
||||
constructor(opts) {
|
||||
var _a;
|
||||
this.width = opts.width;
|
||||
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
|
||||
this.rows = [];
|
||||
}
|
||||
span(...args) {
|
||||
const cols = this.div(...args);
|
||||
cols.span = true;
|
||||
}
|
||||
resetOutput() {
|
||||
this.rows = [];
|
||||
}
|
||||
div(...args) {
|
||||
if (args.length === 0) {
|
||||
this.div('');
|
||||
}
|
||||
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
|
||||
return this.applyLayoutDSL(args[0]);
|
||||
}
|
||||
const cols = args.map(arg => {
|
||||
if (typeof arg === 'string') {
|
||||
return this.colFromString(arg);
|
||||
}
|
||||
return arg;
|
||||
});
|
||||
this.rows.push(cols);
|
||||
return cols;
|
||||
}
|
||||
shouldApplyLayoutDSL(...args) {
|
||||
return args.length === 1 && typeof args[0] === 'string' &&
|
||||
/[\t\n]/.test(args[0]);
|
||||
}
|
||||
applyLayoutDSL(str) {
|
||||
const rows = str.split('\n').map(row => row.split('\t'));
|
||||
let leftColumnWidth = 0;
|
||||
// simple heuristic for layout, make sure the
|
||||
// second column lines up along the left-hand.
|
||||
// don't allow the first column to take up more
|
||||
// than 50% of the screen.
|
||||
rows.forEach(columns => {
|
||||
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
|
||||
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
|
||||
}
|
||||
});
|
||||
// generate a table:
|
||||
// replacing ' ' with padding calculations.
|
||||
// using the algorithmically generated width.
|
||||
rows.forEach(columns => {
|
||||
this.div(...columns.map((r, i) => {
|
||||
return {
|
||||
text: r.trim(),
|
||||
padding: this.measurePadding(r),
|
||||
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
|
||||
};
|
||||
}));
|
||||
});
|
||||
return this.rows[this.rows.length - 1];
|
||||
}
|
||||
colFromString(text) {
|
||||
return {
|
||||
text,
|
||||
padding: this.measurePadding(text)
|
||||
};
|
||||
}
|
||||
measurePadding(str) {
|
||||
// measure padding without ansi escape codes
|
||||
const noAnsi = mixin.stripAnsi(str);
|
||||
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
|
||||
}
|
||||
toString() {
|
||||
const lines = [];
|
||||
this.rows.forEach(row => {
|
||||
this.rowToString(row, lines);
|
||||
});
|
||||
// don't display any lines with the
|
||||
// hidden flag set.
|
||||
return lines
|
||||
.filter(line => !line.hidden)
|
||||
.map(line => line.text)
|
||||
.join('\n');
|
||||
}
|
||||
rowToString(row, lines) {
|
||||
this.rasterize(row).forEach((rrow, r) => {
|
||||
let str = '';
|
||||
rrow.forEach((col, c) => {
|
||||
const { width } = row[c]; // the width with padding.
|
||||
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
|
||||
let ts = col; // temporary string used during alignment/padding.
|
||||
if (wrapWidth > mixin.stringWidth(col)) {
|
||||
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
|
||||
}
|
||||
// align the string within its column.
|
||||
if (row[c].align && row[c].align !== 'left' && this.wrap) {
|
||||
const fn = align[row[c].align];
|
||||
ts = fn(ts, wrapWidth);
|
||||
if (mixin.stringWidth(ts) < wrapWidth) {
|
||||
ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
|
||||
}
|
||||
}
|
||||
// apply border and padding to string.
|
||||
const padding = row[c].padding || [0, 0, 0, 0];
|
||||
if (padding[left]) {
|
||||
str += ' '.repeat(padding[left]);
|
||||
}
|
||||
str += addBorder(row[c], ts, '| ');
|
||||
str += ts;
|
||||
str += addBorder(row[c], ts, ' |');
|
||||
if (padding[right]) {
|
||||
str += ' '.repeat(padding[right]);
|
||||
}
|
||||
// if prior row is span, try to render the
|
||||
// current row on the prior line.
|
||||
if (r === 0 && lines.length > 0) {
|
||||
str = this.renderInline(str, lines[lines.length - 1]);
|
||||
}
|
||||
});
|
||||
// remove trailing whitespace.
|
||||
lines.push({
|
||||
text: str.replace(/ +$/, ''),
|
||||
span: row.span
|
||||
});
|
||||
});
|
||||
return lines;
|
||||
}
|
||||
// if the full 'source' can render in
|
||||
// the target line, do so.
|
||||
renderInline(source, previousLine) {
|
||||
const match = source.match(/^ */);
|
||||
const leadingWhitespace = match ? match[0].length : 0;
|
||||
const target = previousLine.text;
|
||||
const targetTextWidth = mixin.stringWidth(target.trimRight());
|
||||
if (!previousLine.span) {
|
||||
return source;
|
||||
}
|
||||
// if we're not applying wrapping logic,
|
||||
// just always append to the span.
|
||||
if (!this.wrap) {
|
||||
previousLine.hidden = true;
|
||||
return target + source;
|
||||
}
|
||||
if (leadingWhitespace < targetTextWidth) {
|
||||
return source;
|
||||
}
|
||||
previousLine.hidden = true;
|
||||
return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
|
||||
}
|
||||
rasterize(row) {
|
||||
const rrows = [];
|
||||
const widths = this.columnWidths(row);
|
||||
let wrapped;
|
||||
// word wrap all columns, and create
|
||||
// a data-structure that is easy to rasterize.
|
||||
row.forEach((col, c) => {
|
||||
// leave room for left and right padding.
|
||||
col.width = widths[c];
|
||||
if (this.wrap) {
|
||||
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
|
||||
}
|
||||
else {
|
||||
wrapped = col.text.split('\n');
|
||||
}
|
||||
if (col.border) {
|
||||
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
|
||||
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
|
||||
}
|
||||
// add top and bottom padding.
|
||||
if (col.padding) {
|
||||
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
|
||||
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
|
||||
}
|
||||
wrapped.forEach((str, r) => {
|
||||
if (!rrows[r]) {
|
||||
rrows.push([]);
|
||||
}
|
||||
const rrow = rrows[r];
|
||||
for (let i = 0; i < c; i++) {
|
||||
if (rrow[i] === undefined) {
|
||||
rrow.push('');
|
||||
}
|
||||
}
|
||||
rrow.push(str);
|
||||
});
|
||||
});
|
||||
return rrows;
|
||||
}
|
||||
negatePadding(col) {
|
||||
let wrapWidth = col.width || 0;
|
||||
if (col.padding) {
|
||||
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
|
||||
}
|
||||
if (col.border) {
|
||||
wrapWidth -= 4;
|
||||
}
|
||||
return wrapWidth;
|
||||
}
|
||||
columnWidths(row) {
|
||||
if (!this.wrap) {
|
||||
return row.map(col => {
|
||||
return col.width || mixin.stringWidth(col.text);
|
||||
});
|
||||
}
|
||||
let unset = row.length;
|
||||
let remainingWidth = this.width;
|
||||
// column widths can be set in config.
|
||||
const widths = row.map(col => {
|
||||
if (col.width) {
|
||||
unset--;
|
||||
remainingWidth -= col.width;
|
||||
return col.width;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
// any unset widths should be calculated.
|
||||
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
|
||||
return widths.map((w, i) => {
|
||||
if (w === undefined) {
|
||||
return Math.max(unsetWidth, _minWidth(row[i]));
|
||||
}
|
||||
return w;
|
||||
});
|
||||
}
|
||||
}
|
||||
function addBorder(col, ts, style) {
|
||||
if (col.border) {
|
||||
if (/[.']-+[.']/.test(ts)) {
|
||||
return '';
|
||||
}
|
||||
if (ts.trim().length !== 0) {
|
||||
return style;
|
||||
}
|
||||
return ' ';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
// calculates the minimum width of
|
||||
// a column, based on padding preferences.
|
||||
function _minWidth(col) {
|
||||
const padding = col.padding || [];
|
||||
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
|
||||
if (col.border) {
|
||||
return minWidth + 4;
|
||||
}
|
||||
return minWidth;
|
||||
}
|
||||
function getWindowWidth() {
|
||||
/* istanbul ignore next: depends on terminal */
|
||||
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
|
||||
return process.stdout.columns;
|
||||
}
|
||||
return 80;
|
||||
}
|
||||
function alignRight(str, width) {
|
||||
str = str.trim();
|
||||
const strWidth = mixin.stringWidth(str);
|
||||
if (strWidth < width) {
|
||||
return ' '.repeat(width - strWidth) + str;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
function alignCenter(str, width) {
|
||||
str = str.trim();
|
||||
const strWidth = mixin.stringWidth(str);
|
||||
/* istanbul ignore next */
|
||||
if (strWidth >= width) {
|
||||
return str;
|
||||
}
|
||||
return ' '.repeat((width - strWidth) >> 1) + str;
|
||||
}
|
||||
let mixin;
|
||||
export function cliui(opts, _mixin) {
|
||||
mixin = _mixin;
|
||||
return new UI({
|
||||
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
|
||||
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
|
||||
});
|
||||
}
|
27
node_modules/cliui/build/lib/string-utils.js
generated
vendored
Normal file
27
node_modules/cliui/build/lib/string-utils.js
generated
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
// Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi".
|
||||
// to facilitate ESM and Deno modules.
|
||||
// TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM.
|
||||
// The npm application
|
||||
// Copyright (c) npm, Inc. and Contributors
|
||||
// Licensed on the terms of The Artistic License 2.0
|
||||
// See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js
|
||||
const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' +
|
||||
'\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g');
|
||||
export function stripAnsi(str) {
|
||||
return str.replace(ansi, '');
|
||||
}
|
||||
export function wrap(str, width) {
|
||||
const [start, end] = str.match(ansi) || ['', ''];
|
||||
str = stripAnsi(str);
|
||||
let wrapped = '';
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
if (i !== 0 && (i % width) === 0) {
|
||||
wrapped += '\n';
|
||||
}
|
||||
wrapped += str.charAt(i);
|
||||
}
|
||||
if (start && end) {
|
||||
wrapped = `${start}${wrapped}${end}`;
|
||||
}
|
||||
return wrapped;
|
||||
}
|
13
node_modules/cliui/index.mjs
generated
vendored
Normal file
13
node_modules/cliui/index.mjs
generated
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
// Bootstrap cliui with CommonJS dependencies:
|
||||
import { cliui } from './build/lib/index.js'
|
||||
import { wrap, stripAnsi } from './build/lib/string-utils.js'
|
||||
|
||||
export default function ui (opts) {
|
||||
return cliui(opts, {
|
||||
stringWidth: (str) => {
|
||||
return [...str].length
|
||||
},
|
||||
stripAnsi,
|
||||
wrap
|
||||
})
|
||||
}
|
83
node_modules/cliui/package.json
generated
vendored
Normal file
83
node_modules/cliui/package.json
generated
vendored
Normal file
@ -0,0 +1,83 @@
|
||||
{
|
||||
"name": "cliui",
|
||||
"version": "8.0.1",
|
||||
"description": "easily create complex multi-column command-line-interfaces",
|
||||
"main": "build/index.cjs",
|
||||
"exports": {
|
||||
".": [
|
||||
{
|
||||
"import": "./index.mjs",
|
||||
"require": "./build/index.cjs"
|
||||
},
|
||||
"./build/index.cjs"
|
||||
]
|
||||
},
|
||||
"type": "module",
|
||||
"module": "./index.mjs",
|
||||
"scripts": {
|
||||
"check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'",
|
||||
"fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'",
|
||||
"pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs",
|
||||
"test": "c8 mocha ./test/*.cjs",
|
||||
"test:esm": "c8 mocha ./test/esm/cliui-test.mjs",
|
||||
"postest": "check",
|
||||
"coverage": "c8 report --check-coverage",
|
||||
"precompile": "rimraf build",
|
||||
"compile": "tsc",
|
||||
"postcompile": "npm run build:cjs",
|
||||
"build:cjs": "rollup -c",
|
||||
"prepare": "npm run compile"
|
||||
},
|
||||
"repository": "yargs/cliui",
|
||||
"standard": {
|
||||
"ignore": [
|
||||
"**/example/**"
|
||||
],
|
||||
"globals": [
|
||||
"it"
|
||||
]
|
||||
},
|
||||
"keywords": [
|
||||
"cli",
|
||||
"command-line",
|
||||
"layout",
|
||||
"design",
|
||||
"console",
|
||||
"wrap",
|
||||
"table"
|
||||
],
|
||||
"author": "Ben Coe <ben@npmjs.com>",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.1",
|
||||
"wrap-ansi": "^7.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^14.0.27",
|
||||
"@typescript-eslint/eslint-plugin": "^4.0.0",
|
||||
"@typescript-eslint/parser": "^4.0.0",
|
||||
"c8": "^7.3.0",
|
||||
"chai": "^4.2.0",
|
||||
"chalk": "^4.1.0",
|
||||
"cross-env": "^7.0.2",
|
||||
"eslint": "^7.6.0",
|
||||
"eslint-plugin-import": "^2.22.0",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"gts": "^3.0.0",
|
||||
"mocha": "^10.0.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"rollup": "^2.23.1",
|
||||
"rollup-plugin-ts": "^3.0.2",
|
||||
"standardx": "^7.0.0",
|
||||
"typescript": "^4.0.0"
|
||||
},
|
||||
"files": [
|
||||
"build",
|
||||
"index.mjs",
|
||||
"!*.d.ts"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
}
|
111
node_modules/compressible/HISTORY.md
generated
vendored
Normal file
111
node_modules/compressible/HISTORY.md
generated
vendored
Normal file
@ -0,0 +1,111 @@
|
||||
2.0.18 / 2020-01-05
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.43.0 < 2'
|
||||
- Mark `font/ttf` as compressible
|
||||
- Remove compressible from `multipart/mixed`
|
||||
|
||||
2.0.17 / 2019-04-24
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.40.0 < 2'
|
||||
|
||||
2.0.16 / 2019-02-18
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.38.0 < 2'
|
||||
- Mark `text/less` as compressible
|
||||
|
||||
2.0.15 / 2018-09-17
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.36.0 < 2'
|
||||
|
||||
2.0.14 / 2018-06-05
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.34.0 < 2'
|
||||
- Mark all XML-derived types as compressible
|
||||
|
||||
2.0.13 / 2018-02-17
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.33.0 < 2'
|
||||
|
||||
2.0.12 / 2017-10-20
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.30.0 < 2'
|
||||
|
||||
2.0.11 / 2017-07-27
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.29.0 < 2'
|
||||
|
||||
2.0.10 / 2017-03-23
|
||||
===================
|
||||
|
||||
* deps: mime-db@'>= 1.27.0 < 2'
|
||||
|
||||
2.0.9 / 2016-10-31
|
||||
==================
|
||||
|
||||
* Fix regex fallback to not override `compressible: false` in db
|
||||
* deps: mime-db@'>= 1.24.0 < 2'
|
||||
|
||||
2.0.8 / 2016-05-12
|
||||
==================
|
||||
|
||||
* deps: mime-db@'>= 1.23.0 < 2'
|
||||
|
||||
2.0.7 / 2016-01-18
|
||||
==================
|
||||
|
||||
* deps: mime-db@'>= 1.21.0 < 2'
|
||||
|
||||
2.0.6 / 2015-09-29
|
||||
==================
|
||||
|
||||
* deps: mime-db@'>= 1.19.0 < 2'
|
||||
|
||||
2.0.5 / 2015-07-30
|
||||
==================
|
||||
|
||||
* deps: mime-db@'>= 1.16.0 < 2'
|
||||
|
||||
2.0.4 / 2015-07-01
|
||||
==================
|
||||
|
||||
* deps: mime-db@'>= 1.14.0 < 2'
|
||||
* perf: enable strict mode
|
||||
|
||||
2.0.3 / 2015-06-08
|
||||
==================
|
||||
|
||||
* Fix regex fallback to work if type exists, but is undefined
|
||||
* perf: hoist regex declaration
|
||||
* perf: use regex to extract mime
|
||||
* deps: mime-db@'>= 1.13.0 < 2'
|
||||
|
||||
2.0.2 / 2015-01-31
|
||||
==================
|
||||
|
||||
* deps: mime-db@'>= 1.1.2 < 2'
|
||||
|
||||
2.0.1 / 2014-09-28
|
||||
==================
|
||||
|
||||
* deps: mime-db@1.x
|
||||
- Add new mime types
|
||||
- Add additional compressible
|
||||
- Update charsets
|
||||
|
||||
|
||||
2.0.0 / 2014-09-02
|
||||
==================
|
||||
|
||||
* use mime-db
|
||||
* remove .get()
|
||||
* specifications are now private
|
||||
* regex is now private
|
||||
* stricter regex
|
24
node_modules/compressible/LICENSE
generated
vendored
Normal file
24
node_modules/compressible/LICENSE
generated
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2013 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2014 Jeremiah Senkpiel <fishrock123@rocketmail.com>
|
||||
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
|
||||
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.
|
61
node_modules/compressible/README.md
generated
vendored
Normal file
61
node_modules/compressible/README.md
generated
vendored
Normal file
@ -0,0 +1,61 @@
|
||||
# compressible
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Node.js Version][node-version-image]][node-version-url]
|
||||
[![Build Status][travis-image]][travis-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Compressible `Content-Type` / `mime` checking.
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ npm install compressible
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
<!-- eslint-disable no-unused-vars -->
|
||||
|
||||
```js
|
||||
var compressible = require('compressible')
|
||||
```
|
||||
|
||||
### compressible(type)
|
||||
|
||||
Checks if the given `Content-Type` is compressible. The `type` argument is expected
|
||||
to be a value MIME type or `Content-Type` string, though no validation is performed.
|
||||
|
||||
The MIME is looked up in the [`mime-db`](https://www.npmjs.com/package/mime-db) and
|
||||
if there is compressible information in the database entry, that is returned. Otherwise,
|
||||
this module will fallback to `true` for the following types:
|
||||
|
||||
* `text/*`
|
||||
* `*/*+json`
|
||||
* `*/*+text`
|
||||
* `*/*+xml`
|
||||
|
||||
If this module is not sure if a type is specifically compressible or specifically
|
||||
uncompressible, `undefined` is returned.
|
||||
|
||||
<!-- eslint-disable no-undef -->
|
||||
|
||||
```js
|
||||
compressible('text/html') // => true
|
||||
compressible('image/png') // => false
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/compressible/master
|
||||
[coveralls-url]: https://coveralls.io/r/jshttp/compressible?branch=master
|
||||
[node-version-image]: https://badgen.net/npm/node/compressible
|
||||
[node-version-url]: https://nodejs.org/en/download
|
||||
[npm-downloads-image]: https://badgen.net/npm/dm/compressible
|
||||
[npm-url]: https://npmjs.org/package/compressible
|
||||
[npm-version-image]: https://badgen.net/npm/v/compressible
|
||||
[travis-image]: https://badgen.net/travis/jshttp/compressible/master
|
||||
[travis-url]: https://travis-ci.org/jshttp/compressible
|
58
node_modules/compressible/index.js
generated
vendored
Normal file
58
node_modules/compressible/index.js
generated
vendored
Normal file
@ -0,0 +1,58 @@
|
||||
/*!
|
||||
* compressible
|
||||
* Copyright(c) 2013 Jonathan Ong
|
||||
* Copyright(c) 2014 Jeremiah Senkpiel
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var db = require('mime-db')
|
||||
|
||||
/**
|
||||
* Module variables.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var COMPRESSIBLE_TYPE_REGEXP = /^text\/|\+(?:json|text|xml)$/i
|
||||
var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = compressible
|
||||
|
||||
/**
|
||||
* Checks if a type is compressible.
|
||||
*
|
||||
* @param {string} type
|
||||
* @return {Boolean} compressible
|
||||
* @public
|
||||
*/
|
||||
|
||||
function compressible (type) {
|
||||
if (!type || typeof type !== 'string') {
|
||||
return false
|
||||
}
|
||||
|
||||
// strip parameters
|
||||
var match = EXTRACT_TYPE_REGEXP.exec(type)
|
||||
var mime = match && match[1].toLowerCase()
|
||||
var data = db[mime]
|
||||
|
||||
// return database information
|
||||
if (data && data.compressible !== undefined) {
|
||||
return data.compressible
|
||||
}
|
||||
|
||||
// fallback to regexp or unknown
|
||||
return COMPRESSIBLE_TYPE_REGEXP.test(mime) || undefined
|
||||
}
|
48
node_modules/compressible/package.json
generated
vendored
Normal file
48
node_modules/compressible/package.json
generated
vendored
Normal file
@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "compressible",
|
||||
"description": "Compressible Content-Type / mime checking",
|
||||
"version": "2.0.18",
|
||||
"contributors": [
|
||||
"Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)",
|
||||
"Jeremiah Senkpiel <fishrock123@rocketmail.com> (https://searchbeam.jit.su)"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "jshttp/compressible",
|
||||
"keywords": [
|
||||
"compress",
|
||||
"gzip",
|
||||
"mime",
|
||||
"content-type"
|
||||
],
|
||||
"dependencies": {
|
||||
"mime-db": ">= 1.43.0 < 2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "6.8.0",
|
||||
"eslint-config-standard": "14.1.0",
|
||||
"eslint-plugin-import": "2.19.1",
|
||||
"eslint-plugin-markdown": "1.0.1",
|
||||
"eslint-plugin-node": "11.0.0",
|
||||
"eslint-plugin-promise": "4.2.1",
|
||||
"eslint-plugin-standard": "4.0.1",
|
||||
"mocha": "7.0.0",
|
||||
"nyc": "15.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
},
|
||||
"files": [
|
||||
"HISTORY.md",
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"index.js"
|
||||
],
|
||||
"scripts": {
|
||||
"lint": "eslint --plugin markdown --ext js,md .",
|
||||
"test": "mocha --reporter spec --bail --check-leaks test/",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test",
|
||||
"test-travis": "nyc --reporter=text npm test",
|
||||
"version": "node scripts/version-history.js && git add HISTORY.md"
|
||||
}
|
||||
}
|
307
node_modules/compression/HISTORY.md
generated
vendored
Normal file
307
node_modules/compression/HISTORY.md
generated
vendored
Normal file
@ -0,0 +1,307 @@
|
||||
1.7.4 / 2019-03-18
|
||||
==================
|
||||
|
||||
* deps: compressible@~2.0.16
|
||||
- Mark `text/less` as compressible
|
||||
- deps: mime-db@'>= 1.38.0 < 2'
|
||||
* deps: on-headers@~1.0.2
|
||||
- Fix `res.writeHead` patch missing return value
|
||||
* perf: prevent unnecessary buffer copy
|
||||
|
||||
1.7.3 / 2018-07-15
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.3.5
|
||||
- deps: mime-types@~2.1.18
|
||||
* deps: compressible@~2.0.14
|
||||
- Mark all XML-derived types as compressible
|
||||
- deps: mime-db@'>= 1.34.0 < 2'
|
||||
* deps: safe-buffer@5.1.2
|
||||
|
||||
1.7.2 / 2018-02-18
|
||||
==================
|
||||
|
||||
* deps: compressible@~2.0.13
|
||||
- deps: mime-db@'>= 1.33.0 < 2'
|
||||
|
||||
1.7.1 / 2017-09-26
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.3.4
|
||||
- deps: mime-types@~2.1.16
|
||||
* deps: bytes@3.0.0
|
||||
* deps: compressible@~2.0.11
|
||||
- deps: mime-db@'>= 1.29.0 < 2'
|
||||
* deps: debug@2.6.9
|
||||
* deps: vary@~1.1.2
|
||||
- perf: improve header token parsing speed
|
||||
|
||||
1.7.0 / 2017-07-10
|
||||
==================
|
||||
|
||||
* Use `safe-buffer` for improved Buffer API
|
||||
* deps: bytes@2.5.0
|
||||
* deps: compressible@~2.0.10
|
||||
- Fix regex fallback to not override `compressible: false` in db
|
||||
- deps: mime-db@'>= 1.27.0 < 2'
|
||||
* deps: debug@2.6.8
|
||||
- Allow colors in workers
|
||||
- Deprecated `DEBUG_FD` environment variable set to `3` or higher
|
||||
- Fix error when running under React Native
|
||||
- Fix `DEBUG_MAX_ARRAY_LENGTH`
|
||||
- Use same color for same namespace
|
||||
- deps: ms@2.0.0
|
||||
* deps: vary@~1.1.1
|
||||
- perf: hoist regular expression
|
||||
|
||||
1.6.2 / 2016-05-12
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.3.3
|
||||
- deps: mime-types@~2.1.11
|
||||
- deps: negotiator@0.6.1
|
||||
* deps: bytes@2.3.0
|
||||
- Drop partial bytes on all parsed units
|
||||
- Fix parsing byte string that looks like hex
|
||||
- perf: hoist regular expressions
|
||||
* deps: compressible@~2.0.8
|
||||
- deps: mime-db@'>= 1.23.0 < 2'
|
||||
|
||||
1.6.1 / 2016-01-19
|
||||
==================
|
||||
|
||||
* deps: bytes@2.2.0
|
||||
* deps: compressible@~2.0.7
|
||||
- deps: mime-db@'>= 1.21.0 < 2'
|
||||
* deps: accepts@~1.3.1
|
||||
- deps: mime-types@~2.1.9
|
||||
|
||||
1.6.0 / 2015-09-29
|
||||
==================
|
||||
|
||||
* Skip compression when response has `Cache-Control: no-transform`
|
||||
* deps: accepts@~1.3.0
|
||||
- deps: mime-types@~2.1.7
|
||||
- deps: negotiator@0.6.0
|
||||
* deps: compressible@~2.0.6
|
||||
- deps: mime-db@'>= 1.19.0 < 2'
|
||||
* deps: on-headers@~1.0.1
|
||||
- perf: enable strict mode
|
||||
* deps: vary@~1.1.0
|
||||
- Only accept valid field names in the `field` argument
|
||||
|
||||
1.5.2 / 2015-07-30
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.2.12
|
||||
- deps: mime-types@~2.1.4
|
||||
* deps: compressible@~2.0.5
|
||||
- deps: mime-db@'>= 1.16.0 < 2'
|
||||
* deps: vary@~1.0.1
|
||||
- Fix setting empty header from empty `field`
|
||||
- perf: enable strict mode
|
||||
- perf: remove argument reassignments
|
||||
|
||||
1.5.1 / 2015-07-05
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.2.10
|
||||
- deps: mime-types@~2.1.2
|
||||
* deps: compressible@~2.0.4
|
||||
- deps: mime-db@'>= 1.14.0 < 2'
|
||||
- perf: enable strict mode
|
||||
|
||||
1.5.0 / 2015-06-09
|
||||
==================
|
||||
|
||||
* Fix return value from `.end` and `.write` after end
|
||||
* Improve detection of zero-length body without `Content-Length`
|
||||
* deps: accepts@~1.2.9
|
||||
- deps: mime-types@~2.1.1
|
||||
- perf: avoid argument reassignment & argument slice
|
||||
- perf: avoid negotiator recursive construction
|
||||
- perf: enable strict mode
|
||||
- perf: remove unnecessary bitwise operator
|
||||
* deps: bytes@2.1.0
|
||||
- Slight optimizations
|
||||
- Units no longer case sensitive when parsing
|
||||
* deps: compressible@~2.0.3
|
||||
- Fix regex fallback to work if type exists, but is undefined
|
||||
- deps: mime-db@'>= 1.13.0 < 2'
|
||||
- perf: hoist regex declaration
|
||||
- perf: use regex to extract mime
|
||||
* perf: enable strict mode
|
||||
* perf: remove flush reassignment
|
||||
* perf: simplify threshold detection
|
||||
|
||||
1.4.4 / 2015-05-11
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.2.7
|
||||
- deps: mime-types@~2.0.11
|
||||
- deps: negotiator@0.5.3
|
||||
* deps: debug@~2.2.0
|
||||
- deps: ms@0.7.1
|
||||
|
||||
1.4.3 / 2015-03-14
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.2.5
|
||||
- deps: mime-types@~2.0.10
|
||||
* deps: debug@~2.1.3
|
||||
- Fix high intensity foreground color for bold
|
||||
- deps: ms@0.7.0
|
||||
|
||||
1.4.2 / 2015-03-11
|
||||
==================
|
||||
|
||||
* Fix error when code calls `res.end(str, encoding)`
|
||||
- Specific to Node.js 0.8
|
||||
* deps: debug@~2.1.2
|
||||
- deps: ms@0.7.0
|
||||
|
||||
1.4.1 / 2015-02-15
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.2.4
|
||||
- deps: mime-types@~2.0.9
|
||||
- deps: negotiator@0.5.1
|
||||
|
||||
1.4.0 / 2015-02-01
|
||||
==================
|
||||
|
||||
* Prefer `gzip` over `deflate` on the server
|
||||
- Not all clients agree on what "deflate" coding means
|
||||
|
||||
1.3.1 / 2015-01-31
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.2.3
|
||||
- deps: mime-types@~2.0.8
|
||||
* deps: compressible@~2.0.2
|
||||
- deps: mime-db@'>= 1.1.2 < 2'
|
||||
|
||||
1.3.0 / 2014-12-30
|
||||
==================
|
||||
|
||||
* Export the default `filter` function for wrapping
|
||||
* deps: accepts@~1.2.2
|
||||
- deps: mime-types@~2.0.7
|
||||
- deps: negotiator@0.5.0
|
||||
* deps: debug@~2.1.1
|
||||
|
||||
1.2.2 / 2014-12-10
|
||||
==================
|
||||
|
||||
* Fix `.end` to only proxy to `.end`
|
||||
- Fixes an issue with Node.js 0.11.14
|
||||
* deps: accepts@~1.1.4
|
||||
- deps: mime-types@~2.0.4
|
||||
|
||||
1.2.1 / 2014-11-23
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.1.3
|
||||
- deps: mime-types@~2.0.3
|
||||
|
||||
1.2.0 / 2014-10-16
|
||||
==================
|
||||
|
||||
* deps: debug@~2.1.0
|
||||
- Implement `DEBUG_FD` env variable support
|
||||
|
||||
1.1.2 / 2014-10-15
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.1.2
|
||||
- Fix error when media type has invalid parameter
|
||||
- deps: negotiator@0.4.9
|
||||
|
||||
1.1.1 / 2014-10-12
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.1.1
|
||||
- deps: mime-types@~2.0.2
|
||||
- deps: negotiator@0.4.8
|
||||
* deps: compressible@~2.0.1
|
||||
- deps: mime-db@1.x
|
||||
|
||||
1.1.0 / 2014-09-07
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.1.0
|
||||
* deps: compressible@~2.0.0
|
||||
* deps: debug@~2.0.0
|
||||
|
||||
1.0.11 / 2014-08-10
|
||||
===================
|
||||
|
||||
* deps: on-headers@~1.0.0
|
||||
* deps: vary@~1.0.0
|
||||
|
||||
1.0.10 / 2014-08-05
|
||||
===================
|
||||
|
||||
* deps: compressible@~1.1.1
|
||||
- Fix upper-case Content-Type characters prevent compression
|
||||
|
||||
1.0.9 / 2014-07-20
|
||||
==================
|
||||
|
||||
* Add `debug` messages
|
||||
* deps: accepts@~1.0.7
|
||||
- deps: negotiator@0.4.7
|
||||
|
||||
1.0.8 / 2014-06-20
|
||||
==================
|
||||
|
||||
* deps: accepts@~1.0.5
|
||||
- use `mime-types`
|
||||
|
||||
1.0.7 / 2014-06-11
|
||||
==================
|
||||
|
||||
* use vary module for better `Vary` behavior
|
||||
* deps: accepts@1.0.3
|
||||
* deps: compressible@1.1.0
|
||||
|
||||
1.0.6 / 2014-06-03
|
||||
==================
|
||||
|
||||
* fix regression when negotiation fails
|
||||
|
||||
1.0.5 / 2014-06-03
|
||||
==================
|
||||
|
||||
* fix listeners for delayed stream creation
|
||||
- fixes regression for certain `stream.pipe(res)` situations
|
||||
|
||||
1.0.4 / 2014-06-03
|
||||
==================
|
||||
|
||||
* fix adding `Vary` when value stored as array
|
||||
* fix back-pressure behavior
|
||||
* fix length check for `res.end`
|
||||
|
||||
1.0.3 / 2014-05-29
|
||||
==================
|
||||
|
||||
* use `accepts` for negotiation
|
||||
* use `on-headers` to handle header checking
|
||||
* deps: bytes@1.0.0
|
||||
|
||||
1.0.2 / 2014-04-29
|
||||
==================
|
||||
|
||||
* only version compatible with node.js 0.8
|
||||
* support headers given to `res.writeHead`
|
||||
* deps: bytes@0.3.0
|
||||
* deps: negotiator@0.4.3
|
||||
|
||||
1.0.1 / 2014-03-08
|
||||
==================
|
||||
|
||||
* bump negotiator
|
||||
* use compressible
|
||||
* use .headersSent (drops 0.8 support)
|
||||
* handle identity;q=0 case
|
23
node_modules/compression/LICENSE
generated
vendored
Normal file
23
node_modules/compression/LICENSE
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
|
||||
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.
|
240
node_modules/compression/README.md
generated
vendored
Normal file
240
node_modules/compression/README.md
generated
vendored
Normal file
@ -0,0 +1,240 @@
|
||||
# compression
|
||||
|
||||
[![NPM Version][npm-image]][npm-url]
|
||||
[![NPM Downloads][downloads-image]][downloads-url]
|
||||
[![Build Status][travis-image]][travis-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Node.js compression middleware.
|
||||
|
||||
The following compression codings are supported:
|
||||
|
||||
- deflate
|
||||
- gzip
|
||||
|
||||
## Install
|
||||
|
||||
This is a [Node.js](https://nodejs.org/en/) module available through the
|
||||
[npm registry](https://www.npmjs.com/). Installation is done using the
|
||||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
||||
|
||||
```bash
|
||||
$ npm install compression
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
<!-- eslint-disable no-unused-vars -->
|
||||
|
||||
```js
|
||||
var compression = require('compression')
|
||||
```
|
||||
|
||||
### compression([options])
|
||||
|
||||
Returns the compression middleware using the given `options`. The middleware
|
||||
will attempt to compress response bodies for all request that traverse through
|
||||
the middleware, based on the given `options`.
|
||||
|
||||
This middleware will never compress responses that include a `Cache-Control`
|
||||
header with the [`no-transform` directive](https://tools.ietf.org/html/rfc7234#section-5.2.2.4),
|
||||
as compressing will transform the body.
|
||||
|
||||
#### Options
|
||||
|
||||
`compression()` accepts these properties in the options object. In addition to
|
||||
those listed below, [zlib](http://nodejs.org/api/zlib.html) options may be
|
||||
passed in to the options object.
|
||||
|
||||
##### chunkSize
|
||||
|
||||
The default value is `zlib.Z_DEFAULT_CHUNK`, or `16384`.
|
||||
|
||||
See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
|
||||
regarding the usage.
|
||||
|
||||
##### filter
|
||||
|
||||
A function to decide if the response should be considered for compression.
|
||||
This function is called as `filter(req, res)` and is expected to return
|
||||
`true` to consider the response for compression, or `false` to not compress
|
||||
the response.
|
||||
|
||||
The default filter function uses the [compressible](https://www.npmjs.com/package/compressible)
|
||||
module to determine if `res.getHeader('Content-Type')` is compressible.
|
||||
|
||||
##### level
|
||||
|
||||
The level of zlib compression to apply to responses. A higher level will result
|
||||
in better compression, but will take longer to complete. A lower level will
|
||||
result in less compression, but will be much faster.
|
||||
|
||||
This is an integer in the range of `0` (no compression) to `9` (maximum
|
||||
compression). The special value `-1` can be used to mean the "default
|
||||
compression level", which is a default compromise between speed and
|
||||
compression (currently equivalent to level 6).
|
||||
|
||||
- `-1` Default compression level (also `zlib.Z_DEFAULT_COMPRESSION`).
|
||||
- `0` No compression (also `zlib.Z_NO_COMPRESSION`).
|
||||
- `1` Fastest compression (also `zlib.Z_BEST_SPEED`).
|
||||
- `2`
|
||||
- `3`
|
||||
- `4`
|
||||
- `5`
|
||||
- `6` (currently what `zlib.Z_DEFAULT_COMPRESSION` points to).
|
||||
- `7`
|
||||
- `8`
|
||||
- `9` Best compression (also `zlib.Z_BEST_COMPRESSION`).
|
||||
|
||||
The default value is `zlib.Z_DEFAULT_COMPRESSION`, or `-1`.
|
||||
|
||||
**Note** in the list above, `zlib` is from `zlib = require('zlib')`.
|
||||
|
||||
##### memLevel
|
||||
|
||||
This specifies how much memory should be allocated for the internal compression
|
||||
state and is an integer in the range of `1` (minimum level) and `9` (maximum
|
||||
level).
|
||||
|
||||
The default value is `zlib.Z_DEFAULT_MEMLEVEL`, or `8`.
|
||||
|
||||
See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
|
||||
regarding the usage.
|
||||
|
||||
##### strategy
|
||||
|
||||
This is used to tune the compression algorithm. This value only affects the
|
||||
compression ratio, not the correctness of the compressed output, even if it
|
||||
is not set appropriately.
|
||||
|
||||
- `zlib.Z_DEFAULT_STRATEGY` Use for normal data.
|
||||
- `zlib.Z_FILTERED` Use for data produced by a filter (or predictor).
|
||||
Filtered data consists mostly of small values with a somewhat random
|
||||
distribution. In this case, the compression algorithm is tuned to
|
||||
compress them better. The effect is to force more Huffman coding and less
|
||||
string matching; it is somewhat intermediate between `zlib.Z_DEFAULT_STRATEGY`
|
||||
and `zlib.Z_HUFFMAN_ONLY`.
|
||||
- `zlib.Z_FIXED` Use to prevent the use of dynamic Huffman codes, allowing
|
||||
for a simpler decoder for special applications.
|
||||
- `zlib.Z_HUFFMAN_ONLY` Use to force Huffman encoding only (no string match).
|
||||
- `zlib.Z_RLE` Use to limit match distances to one (run-length encoding).
|
||||
This is designed to be almost as fast as `zlib.Z_HUFFMAN_ONLY`, but give
|
||||
better compression for PNG image data.
|
||||
|
||||
**Note** in the list above, `zlib` is from `zlib = require('zlib')`.
|
||||
|
||||
##### threshold
|
||||
|
||||
The byte threshold for the response body size before compression is considered
|
||||
for the response, defaults to `1kb`. This is a number of bytes or any string
|
||||
accepted by the [bytes](https://www.npmjs.com/package/bytes) module.
|
||||
|
||||
**Note** this is only an advisory setting; if the response size cannot be determined
|
||||
at the time the response headers are written, then it is assumed the response is
|
||||
_over_ the threshold. To guarantee the response size can be determined, be sure
|
||||
set a `Content-Length` response header.
|
||||
|
||||
##### windowBits
|
||||
|
||||
The default value is `zlib.Z_DEFAULT_WINDOWBITS`, or `15`.
|
||||
|
||||
See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning)
|
||||
regarding the usage.
|
||||
|
||||
#### .filter
|
||||
|
||||
The default `filter` function. This is used to construct a custom filter
|
||||
function that is an extension of the default function.
|
||||
|
||||
```js
|
||||
var compression = require('compression')
|
||||
var express = require('express')
|
||||
|
||||
var app = express()
|
||||
app.use(compression({ filter: shouldCompress }))
|
||||
|
||||
function shouldCompress (req, res) {
|
||||
if (req.headers['x-no-compression']) {
|
||||
// don't compress responses with this request header
|
||||
return false
|
||||
}
|
||||
|
||||
// fallback to standard filter function
|
||||
return compression.filter(req, res)
|
||||
}
|
||||
```
|
||||
|
||||
### res.flush
|
||||
|
||||
This module adds a `res.flush()` method to force the partially-compressed
|
||||
response to be flushed to the client.
|
||||
|
||||
## Examples
|
||||
|
||||
### express/connect
|
||||
|
||||
When using this module with express or connect, simply `app.use` the module as
|
||||
high as you like. Requests that pass through the middleware will be compressed.
|
||||
|
||||
```js
|
||||
var compression = require('compression')
|
||||
var express = require('express')
|
||||
|
||||
var app = express()
|
||||
|
||||
// compress all responses
|
||||
app.use(compression())
|
||||
|
||||
// add all routes
|
||||
```
|
||||
|
||||
### Server-Sent Events
|
||||
|
||||
Because of the nature of compression this module does not work out of the box
|
||||
with server-sent events. To compress content, a window of the output needs to
|
||||
be buffered up in order to get good compression. Typically when using server-sent
|
||||
events, there are certain block of data that need to reach the client.
|
||||
|
||||
You can achieve this by calling `res.flush()` when you need the data written to
|
||||
actually make it to the client.
|
||||
|
||||
```js
|
||||
var compression = require('compression')
|
||||
var express = require('express')
|
||||
|
||||
var app = express()
|
||||
|
||||
// compress responses
|
||||
app.use(compression())
|
||||
|
||||
// server-sent event stream
|
||||
app.get('/events', function (req, res) {
|
||||
res.setHeader('Content-Type', 'text/event-stream')
|
||||
res.setHeader('Cache-Control', 'no-cache')
|
||||
|
||||
// send a ping approx every 2 seconds
|
||||
var timer = setInterval(function () {
|
||||
res.write('data: ping\n\n')
|
||||
|
||||
// !!! this is the important part
|
||||
res.flush()
|
||||
}, 2000)
|
||||
|
||||
res.on('close', function () {
|
||||
clearInterval(timer)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[npm-image]: https://img.shields.io/npm/v/compression.svg
|
||||
[npm-url]: https://npmjs.org/package/compression
|
||||
[travis-image]: https://img.shields.io/travis/expressjs/compression/master.svg
|
||||
[travis-url]: https://travis-ci.org/expressjs/compression
|
||||
[coveralls-image]: https://img.shields.io/coveralls/expressjs/compression/master.svg
|
||||
[coveralls-url]: https://coveralls.io/r/expressjs/compression?branch=master
|
||||
[downloads-image]: https://img.shields.io/npm/dm/compression.svg
|
||||
[downloads-url]: https://npmjs.org/package/compression
|
288
node_modules/compression/index.js
generated
vendored
Normal file
288
node_modules/compression/index.js
generated
vendored
Normal file
@ -0,0 +1,288 @@
|
||||
/*!
|
||||
* compression
|
||||
* Copyright(c) 2010 Sencha Inc.
|
||||
* Copyright(c) 2011 TJ Holowaychuk
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var accepts = require('accepts')
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
var bytes = require('bytes')
|
||||
var compressible = require('compressible')
|
||||
var debug = require('debug')('compression')
|
||||
var onHeaders = require('on-headers')
|
||||
var vary = require('vary')
|
||||
var zlib = require('zlib')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = compression
|
||||
module.exports.filter = shouldCompress
|
||||
|
||||
/**
|
||||
* Module variables.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/
|
||||
|
||||
/**
|
||||
* Compress response data with gzip / deflate.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @return {Function} middleware
|
||||
* @public
|
||||
*/
|
||||
|
||||
function compression (options) {
|
||||
var opts = options || {}
|
||||
|
||||
// options
|
||||
var filter = opts.filter || shouldCompress
|
||||
var threshold = bytes.parse(opts.threshold)
|
||||
|
||||
if (threshold == null) {
|
||||
threshold = 1024
|
||||
}
|
||||
|
||||
return function compression (req, res, next) {
|
||||
var ended = false
|
||||
var length
|
||||
var listeners = []
|
||||
var stream
|
||||
|
||||
var _end = res.end
|
||||
var _on = res.on
|
||||
var _write = res.write
|
||||
|
||||
// flush
|
||||
res.flush = function flush () {
|
||||
if (stream) {
|
||||
stream.flush()
|
||||
}
|
||||
}
|
||||
|
||||
// proxy
|
||||
|
||||
res.write = function write (chunk, encoding) {
|
||||
if (ended) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (!this._header) {
|
||||
this._implicitHeader()
|
||||
}
|
||||
|
||||
return stream
|
||||
? stream.write(toBuffer(chunk, encoding))
|
||||
: _write.call(this, chunk, encoding)
|
||||
}
|
||||
|
||||
res.end = function end (chunk, encoding) {
|
||||
if (ended) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (!this._header) {
|
||||
// estimate the length
|
||||
if (!this.getHeader('Content-Length')) {
|
||||
length = chunkLength(chunk, encoding)
|
||||
}
|
||||
|
||||
this._implicitHeader()
|
||||
}
|
||||
|
||||
if (!stream) {
|
||||
return _end.call(this, chunk, encoding)
|
||||
}
|
||||
|
||||
// mark ended
|
||||
ended = true
|
||||
|
||||
// write Buffer for Node.js 0.8
|
||||
return chunk
|
||||
? stream.end(toBuffer(chunk, encoding))
|
||||
: stream.end()
|
||||
}
|
||||
|
||||
res.on = function on (type, listener) {
|
||||
if (!listeners || type !== 'drain') {
|
||||
return _on.call(this, type, listener)
|
||||
}
|
||||
|
||||
if (stream) {
|
||||
return stream.on(type, listener)
|
||||
}
|
||||
|
||||
// buffer listeners for future stream
|
||||
listeners.push([type, listener])
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
function nocompress (msg) {
|
||||
debug('no compression: %s', msg)
|
||||
addListeners(res, _on, listeners)
|
||||
listeners = null
|
||||
}
|
||||
|
||||
onHeaders(res, function onResponseHeaders () {
|
||||
// determine if request is filtered
|
||||
if (!filter(req, res)) {
|
||||
nocompress('filtered')
|
||||
return
|
||||
}
|
||||
|
||||
// determine if the entity should be transformed
|
||||
if (!shouldTransform(req, res)) {
|
||||
nocompress('no transform')
|
||||
return
|
||||
}
|
||||
|
||||
// vary
|
||||
vary(res, 'Accept-Encoding')
|
||||
|
||||
// content-length below threshold
|
||||
if (Number(res.getHeader('Content-Length')) < threshold || length < threshold) {
|
||||
nocompress('size below threshold')
|
||||
return
|
||||
}
|
||||
|
||||
var encoding = res.getHeader('Content-Encoding') || 'identity'
|
||||
|
||||
// already encoded
|
||||
if (encoding !== 'identity') {
|
||||
nocompress('already encoded')
|
||||
return
|
||||
}
|
||||
|
||||
// head
|
||||
if (req.method === 'HEAD') {
|
||||
nocompress('HEAD request')
|
||||
return
|
||||
}
|
||||
|
||||
// compression method
|
||||
var accept = accepts(req)
|
||||
var method = accept.encoding(['gzip', 'deflate', 'identity'])
|
||||
|
||||
// we really don't prefer deflate
|
||||
if (method === 'deflate' && accept.encoding(['gzip'])) {
|
||||
method = accept.encoding(['gzip', 'identity'])
|
||||
}
|
||||
|
||||
// negotiation failed
|
||||
if (!method || method === 'identity') {
|
||||
nocompress('not acceptable')
|
||||
return
|
||||
}
|
||||
|
||||
// compression stream
|
||||
debug('%s compression', method)
|
||||
stream = method === 'gzip'
|
||||
? zlib.createGzip(opts)
|
||||
: zlib.createDeflate(opts)
|
||||
|
||||
// add buffered listeners to stream
|
||||
addListeners(stream, stream.on, listeners)
|
||||
|
||||
// header fields
|
||||
res.setHeader('Content-Encoding', method)
|
||||
res.removeHeader('Content-Length')
|
||||
|
||||
// compression
|
||||
stream.on('data', function onStreamData (chunk) {
|
||||
if (_write.call(res, chunk) === false) {
|
||||
stream.pause()
|
||||
}
|
||||
})
|
||||
|
||||
stream.on('end', function onStreamEnd () {
|
||||
_end.call(res)
|
||||
})
|
||||
|
||||
_on.call(res, 'drain', function onResponseDrain () {
|
||||
stream.resume()
|
||||
})
|
||||
})
|
||||
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add bufferred listeners to stream
|
||||
* @private
|
||||
*/
|
||||
|
||||
function addListeners (stream, on, listeners) {
|
||||
for (var i = 0; i < listeners.length; i++) {
|
||||
on.apply(stream, listeners[i])
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the length of a given chunk
|
||||
*/
|
||||
|
||||
function chunkLength (chunk, encoding) {
|
||||
if (!chunk) {
|
||||
return 0
|
||||
}
|
||||
|
||||
return !Buffer.isBuffer(chunk)
|
||||
? Buffer.byteLength(chunk, encoding)
|
||||
: chunk.length
|
||||
}
|
||||
|
||||
/**
|
||||
* Default filter function.
|
||||
* @private
|
||||
*/
|
||||
|
||||
function shouldCompress (req, res) {
|
||||
var type = res.getHeader('Content-Type')
|
||||
|
||||
if (type === undefined || !compressible(type)) {
|
||||
debug('%s not compressible', type)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the entity should be transformed.
|
||||
* @private
|
||||
*/
|
||||
|
||||
function shouldTransform (req, res) {
|
||||
var cacheControl = res.getHeader('Cache-Control')
|
||||
|
||||
// Don't compress for Cache-Control: no-transform
|
||||
// https://tools.ietf.org/html/rfc7234#section-5.2.2.4
|
||||
return !cacheControl ||
|
||||
!cacheControlNoTransformRegExp.test(cacheControl)
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce arguments to Buffer
|
||||
* @private
|
||||
*/
|
||||
|
||||
function toBuffer (chunk, encoding) {
|
||||
return !Buffer.isBuffer(chunk)
|
||||
? Buffer.from(chunk, encoding)
|
||||
: chunk
|
||||
}
|
82
node_modules/compression/node_modules/bytes/History.md
generated
vendored
Normal file
82
node_modules/compression/node_modules/bytes/History.md
generated
vendored
Normal file
@ -0,0 +1,82 @@
|
||||
3.0.0 / 2017-08-31
|
||||
==================
|
||||
|
||||
* Change "kB" to "KB" in format output
|
||||
* Remove support for Node.js 0.6
|
||||
* Remove support for ComponentJS
|
||||
|
||||
2.5.0 / 2017-03-24
|
||||
==================
|
||||
|
||||
* Add option "unit"
|
||||
|
||||
2.4.0 / 2016-06-01
|
||||
==================
|
||||
|
||||
* Add option "unitSeparator"
|
||||
|
||||
2.3.0 / 2016-02-15
|
||||
==================
|
||||
|
||||
* Drop partial bytes on all parsed units
|
||||
* Fix non-finite numbers to `.format` to return `null`
|
||||
* Fix parsing byte string that looks like hex
|
||||
* perf: hoist regular expressions
|
||||
|
||||
2.2.0 / 2015-11-13
|
||||
==================
|
||||
|
||||
* add option "decimalPlaces"
|
||||
* add option "fixedDecimals"
|
||||
|
||||
2.1.0 / 2015-05-21
|
||||
==================
|
||||
|
||||
* add `.format` export
|
||||
* add `.parse` export
|
||||
|
||||
2.0.2 / 2015-05-20
|
||||
==================
|
||||
|
||||
* remove map recreation
|
||||
* remove unnecessary object construction
|
||||
|
||||
2.0.1 / 2015-05-07
|
||||
==================
|
||||
|
||||
* fix browserify require
|
||||
* remove node.extend dependency
|
||||
|
||||
2.0.0 / 2015-04-12
|
||||
==================
|
||||
|
||||
* add option "case"
|
||||
* add option "thousandsSeparator"
|
||||
* return "null" on invalid parse input
|
||||
* support proper round-trip: bytes(bytes(num)) === num
|
||||
* units no longer case sensitive when parsing
|
||||
|
||||
1.0.0 / 2014-05-05
|
||||
==================
|
||||
|
||||
* add negative support. fixes #6
|
||||
|
||||
0.3.0 / 2014-03-19
|
||||
==================
|
||||
|
||||
* added terabyte support
|
||||
|
||||
0.2.1 / 2013-04-01
|
||||
==================
|
||||
|
||||
* add .component
|
||||
|
||||
0.2.0 / 2012-10-28
|
||||
==================
|
||||
|
||||
* bytes(200).should.eql('200b')
|
||||
|
||||
0.1.0 / 2012-07-04
|
||||
==================
|
||||
|
||||
* add bytes to string conversion [yields]
|
23
node_modules/compression/node_modules/bytes/LICENSE
generated
vendored
Normal file
23
node_modules/compression/node_modules/bytes/LICENSE
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2012-2014 TJ Holowaychuk <tj@vision-media.ca>
|
||||
Copyright (c) 2015 Jed Watson <jed.watson@me.com>
|
||||
|
||||
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.
|
125
node_modules/compression/node_modules/bytes/Readme.md
generated
vendored
Normal file
125
node_modules/compression/node_modules/bytes/Readme.md
generated
vendored
Normal file
@ -0,0 +1,125 @@
|
||||
# Bytes utility
|
||||
|
||||
[![NPM Version][npm-image]][npm-url]
|
||||
[![NPM Downloads][downloads-image]][downloads-url]
|
||||
[![Build Status][travis-image]][travis-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa.
|
||||
|
||||
## Installation
|
||||
|
||||
This is a [Node.js](https://nodejs.org/en/) module available through the
|
||||
[npm registry](https://www.npmjs.com/). Installation is done using the
|
||||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
||||
|
||||
```bash
|
||||
$ npm install bytes
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
var bytes = require('bytes');
|
||||
```
|
||||
|
||||
#### bytes.format(number value, [options]): string|null
|
||||
|
||||
Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is
|
||||
rounded.
|
||||
|
||||
**Arguments**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|--------------------|
|
||||
| value | `number` | Value in bytes |
|
||||
| options | `Object` | Conversion options |
|
||||
|
||||
**Options**
|
||||
|
||||
| Property | Type | Description |
|
||||
|-------------------|--------|-----------------------------------------------------------------------------------------|
|
||||
| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. |
|
||||
| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` |
|
||||
| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `''`. |
|
||||
| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). |
|
||||
| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. |
|
||||
|
||||
**Returns**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|------------------|-------------------------------------------------|
|
||||
| results | `string`|`null` | Return null upon error. String value otherwise. |
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
bytes(1024);
|
||||
// output: '1KB'
|
||||
|
||||
bytes(1000);
|
||||
// output: '1000B'
|
||||
|
||||
bytes(1000, {thousandsSeparator: ' '});
|
||||
// output: '1 000B'
|
||||
|
||||
bytes(1024 * 1.7, {decimalPlaces: 0});
|
||||
// output: '2KB'
|
||||
|
||||
bytes(1024, {unitSeparator: ' '});
|
||||
// output: '1 KB'
|
||||
|
||||
```
|
||||
|
||||
#### bytes.parse(string|number value): number|null
|
||||
|
||||
Parse the string value into an integer in bytes. If no unit is given, or `value`
|
||||
is a number, it is assumed the value is in bytes.
|
||||
|
||||
Supported units and abbreviations are as follows and are case-insensitive:
|
||||
|
||||
* `b` for bytes
|
||||
* `kb` for kilobytes
|
||||
* `mb` for megabytes
|
||||
* `gb` for gigabytes
|
||||
* `tb` for terabytes
|
||||
|
||||
The units are in powers of two, not ten. This means 1kb = 1024b according to this parser.
|
||||
|
||||
**Arguments**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------------|--------|--------------------|
|
||||
| value | `string`|`number` | String to parse, or number in bytes. |
|
||||
|
||||
**Returns**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|-------------|-------------------------|
|
||||
| results | `number`|`null` | Return null upon error. Value in bytes otherwise. |
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
bytes('1KB');
|
||||
// output: 1024
|
||||
|
||||
bytes('1024');
|
||||
// output: 1024
|
||||
|
||||
bytes(1024);
|
||||
// output: 1024
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[downloads-image]: https://img.shields.io/npm/dm/bytes.svg
|
||||
[downloads-url]: https://npmjs.org/package/bytes
|
||||
[npm-image]: https://img.shields.io/npm/v/bytes.svg
|
||||
[npm-url]: https://npmjs.org/package/bytes
|
||||
[travis-image]: https://img.shields.io/travis/visionmedia/bytes.js/master.svg
|
||||
[travis-url]: https://travis-ci.org/visionmedia/bytes.js
|
||||
[coveralls-image]: https://img.shields.io/coveralls/visionmedia/bytes.js/master.svg
|
||||
[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master
|
159
node_modules/compression/node_modules/bytes/index.js
generated
vendored
Normal file
159
node_modules/compression/node_modules/bytes/index.js
generated
vendored
Normal file
@ -0,0 +1,159 @@
|
||||
/*!
|
||||
* bytes
|
||||
* Copyright(c) 2012-2014 TJ Holowaychuk
|
||||
* Copyright(c) 2015 Jed Watson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = bytes;
|
||||
module.exports.format = format;
|
||||
module.exports.parse = parse;
|
||||
|
||||
/**
|
||||
* Module variables.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
|
||||
|
||||
var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
|
||||
|
||||
var map = {
|
||||
b: 1,
|
||||
kb: 1 << 10,
|
||||
mb: 1 << 20,
|
||||
gb: 1 << 30,
|
||||
tb: ((1 << 30) * 1024)
|
||||
};
|
||||
|
||||
var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i;
|
||||
|
||||
/**
|
||||
* Convert the given value in bytes into a string or parse to string to an integer in bytes.
|
||||
*
|
||||
* @param {string|number} value
|
||||
* @param {{
|
||||
* case: [string],
|
||||
* decimalPlaces: [number]
|
||||
* fixedDecimals: [boolean]
|
||||
* thousandsSeparator: [string]
|
||||
* unitSeparator: [string]
|
||||
* }} [options] bytes options.
|
||||
*
|
||||
* @returns {string|number|null}
|
||||
*/
|
||||
|
||||
function bytes(value, options) {
|
||||
if (typeof value === 'string') {
|
||||
return parse(value);
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return format(value, options);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given value in bytes into a string.
|
||||
*
|
||||
* If the value is negative, it is kept as such. If it is a float,
|
||||
* it is rounded.
|
||||
*
|
||||
* @param {number} value
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.decimalPlaces=2]
|
||||
* @param {number} [options.fixedDecimals=false]
|
||||
* @param {string} [options.thousandsSeparator=]
|
||||
* @param {string} [options.unit=]
|
||||
* @param {string} [options.unitSeparator=]
|
||||
*
|
||||
* @returns {string|null}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function format(value, options) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var mag = Math.abs(value);
|
||||
var thousandsSeparator = (options && options.thousandsSeparator) || '';
|
||||
var unitSeparator = (options && options.unitSeparator) || '';
|
||||
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
|
||||
var fixedDecimals = Boolean(options && options.fixedDecimals);
|
||||
var unit = (options && options.unit) || '';
|
||||
|
||||
if (!unit || !map[unit.toLowerCase()]) {
|
||||
if (mag >= map.tb) {
|
||||
unit = 'TB';
|
||||
} else if (mag >= map.gb) {
|
||||
unit = 'GB';
|
||||
} else if (mag >= map.mb) {
|
||||
unit = 'MB';
|
||||
} else if (mag >= map.kb) {
|
||||
unit = 'KB';
|
||||
} else {
|
||||
unit = 'B';
|
||||
}
|
||||
}
|
||||
|
||||
var val = value / map[unit.toLowerCase()];
|
||||
var str = val.toFixed(decimalPlaces);
|
||||
|
||||
if (!fixedDecimals) {
|
||||
str = str.replace(formatDecimalsRegExp, '$1');
|
||||
}
|
||||
|
||||
if (thousandsSeparator) {
|
||||
str = str.replace(formatThousandsRegExp, thousandsSeparator);
|
||||
}
|
||||
|
||||
return str + unitSeparator + unit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the string value into an integer in bytes.
|
||||
*
|
||||
* If no unit is given, it is assumed the value is in bytes.
|
||||
*
|
||||
* @param {number|string} val
|
||||
*
|
||||
* @returns {number|null}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function parse(val) {
|
||||
if (typeof val === 'number' && !isNaN(val)) {
|
||||
return val;
|
||||
}
|
||||
|
||||
if (typeof val !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Test if the string passed is valid
|
||||
var results = parseRegExp.exec(val);
|
||||
var floatValue;
|
||||
var unit = 'b';
|
||||
|
||||
if (!results) {
|
||||
// Nothing could be extracted from the given string
|
||||
floatValue = parseInt(val, 10);
|
||||
unit = 'b'
|
||||
} else {
|
||||
// Retrieve the value and the unit
|
||||
floatValue = parseFloat(results[1]);
|
||||
unit = results[4].toLowerCase();
|
||||
}
|
||||
|
||||
return Math.floor(map[unit] * floatValue);
|
||||
}
|
39
node_modules/compression/node_modules/bytes/package.json
generated
vendored
Normal file
39
node_modules/compression/node_modules/bytes/package.json
generated
vendored
Normal file
@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "bytes",
|
||||
"description": "Utility to parse a string bytes to bytes and vice-versa",
|
||||
"version": "3.0.0",
|
||||
"author": "TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)",
|
||||
"contributors": [
|
||||
"Jed Watson <jed.watson@me.com>",
|
||||
"Théo FIDRY <theo.fidry@gmail.com>"
|
||||
],
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"byte",
|
||||
"bytes",
|
||||
"utility",
|
||||
"parse",
|
||||
"parser",
|
||||
"convert",
|
||||
"converter"
|
||||
],
|
||||
"repository": "visionmedia/bytes.js",
|
||||
"devDependencies": {
|
||||
"mocha": "2.5.3",
|
||||
"nyc": "10.3.2"
|
||||
},
|
||||
"files": [
|
||||
"History.md",
|
||||
"LICENSE",
|
||||
"Readme.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha --check-leaks --reporter spec",
|
||||
"test-ci": "nyc --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
}
|
||||
}
|
47
node_modules/compression/package.json
generated
vendored
Normal file
47
node_modules/compression/package.json
generated
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "compression",
|
||||
"description": "Node.js compression middleware",
|
||||
"version": "1.7.4",
|
||||
"contributors": [
|
||||
"Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "expressjs/compression",
|
||||
"dependencies": {
|
||||
"accepts": "~1.3.5",
|
||||
"bytes": "3.0.0",
|
||||
"compressible": "~2.0.16",
|
||||
"debug": "2.6.9",
|
||||
"on-headers": "~1.0.2",
|
||||
"safe-buffer": "5.1.2",
|
||||
"vary": "~1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"after": "0.8.2",
|
||||
"eslint": "5.15.1",
|
||||
"eslint-config-standard": "12.0.0",
|
||||
"eslint-plugin-import": "2.16.0",
|
||||
"eslint-plugin-markdown": "1.0.0",
|
||||
"eslint-plugin-node": "7.0.1",
|
||||
"eslint-plugin-promise": "4.0.1",
|
||||
"eslint-plugin-standard": "4.0.0",
|
||||
"istanbul": "0.4.5",
|
||||
"mocha": "6.0.2",
|
||||
"supertest": "4.0.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"HISTORY.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint --plugin markdown --ext js,md .",
|
||||
"test": "mocha --check-leaks --reporter spec --bail",
|
||||
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot",
|
||||
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec"
|
||||
}
|
||||
}
|
14
node_modules/connect-pause/.npmignore
generated
vendored
Normal file
14
node_modules/connect-pause/.npmignore
generated
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
lib-cov
|
||||
*.seed
|
||||
*.log
|
||||
*.csv
|
||||
*.dat
|
||||
*.out
|
||||
*.pid
|
||||
*.gz
|
||||
|
||||
pids
|
||||
logs
|
||||
results
|
||||
|
||||
npm-debug.log
|
90
node_modules/connect-pause/README.md
generated
vendored
Normal file
90
node_modules/connect-pause/README.md
generated
vendored
Normal file
@ -0,0 +1,90 @@
|
||||
Connect Pause
|
||||
=============
|
||||
|
||||
Connect/Express middleware to simulate latency for debugging
|
||||
|
||||
Installation
|
||||
===
|
||||
|
||||
npm install connect-pause
|
||||
|
||||
Usage
|
||||
===
|
||||
|
||||
Pause all [Connect](http://github.com/senchalabs/connect) requests:
|
||||
|
||||
var connect = require('connect'),
|
||||
pause = require('connect-pause');
|
||||
|
||||
Connect.createServer(
|
||||
pause(1000),
|
||||
function(req, res, next){
|
||||
res.writeHead(200, {'Content-Type':'text/plain'});
|
||||
res.end('Waited 1 second');
|
||||
}
|
||||
).listen(8080);
|
||||
|
||||
Pause all [Express](https://github.com/visionmedia/express) requests:
|
||||
|
||||
var express = require('express'),
|
||||
pause = require('connect-pause');
|
||||
|
||||
var app = express();
|
||||
app.use(pause(1000));
|
||||
app.get('/', function(req, res){
|
||||
res.send('Waited 1 second');
|
||||
});
|
||||
app.listen(3000);
|
||||
|
||||
Pause a single [Express](https://github.com/visionmedia/express) endpoint:
|
||||
|
||||
var express = require('express'),
|
||||
pause = require('connect-pause');
|
||||
|
||||
var app = express();
|
||||
app.get('/', pause(1000), function(req, res){
|
||||
res.send('Waited 1 second');
|
||||
});
|
||||
app.listen(3000);
|
||||
|
||||
Pass an error to be returned after the delay:
|
||||
|
||||
var express = require('express'),
|
||||
pause = require('connect-pause');
|
||||
|
||||
var app = express();
|
||||
app.get('/', pause(1000, new Error('Send 500')), function(req, res){
|
||||
res.send('Waited 1 second');
|
||||
});
|
||||
app.listen(3000);
|
||||
|
||||
When to use
|
||||
===
|
||||
|
||||
This middleware is meant to be used while developing and in need to simulate latency for certain requests or all.
|
||||
|
||||
License
|
||||
===
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2013 Ariel Flesler
|
||||
|
||||
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.
|
13
node_modules/connect-pause/index.js
generated
vendored
Normal file
13
node_modules/connect-pause/index.js
generated
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
/**
|
||||
* connect-pause
|
||||
* Copyright(c) 2013 Ariel Flesler <aflesler@gmail.com>
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
module.exports = function(delay, err) {
|
||||
delay = delay || 1000;
|
||||
|
||||
return function(req, res, next){
|
||||
setTimeout(next, delay, err);
|
||||
};
|
||||
};
|
19
node_modules/connect-pause/package.json
generated
vendored
Normal file
19
node_modules/connect-pause/package.json
generated
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "connect-pause"
|
||||
, "author": "Ariel Flesler <aflesler@gmail.com>"
|
||||
, "version": "0.1.1"
|
||||
, "description": "Connect/Express middleware to simulate latency for debugging"
|
||||
, "keywords": [
|
||||
"connect"
|
||||
, "express"
|
||||
, "pause"
|
||||
, "delay"
|
||||
, "latency"
|
||||
]
|
||||
, "license": "MIT"
|
||||
, "repository": "git://github.com/flesler/connect-pause"
|
||||
, "main": "./index.js"
|
||||
, "engines": { "node": "*" }
|
||||
, "dependencies": {}
|
||||
}
|
||||
|
60
node_modules/content-disposition/HISTORY.md
generated
vendored
Normal file
60
node_modules/content-disposition/HISTORY.md
generated
vendored
Normal file
@ -0,0 +1,60 @@
|
||||
0.5.4 / 2021-12-10
|
||||
==================
|
||||
|
||||
* deps: safe-buffer@5.2.1
|
||||
|
||||
0.5.3 / 2018-12-17
|
||||
==================
|
||||
|
||||
* Use `safe-buffer` for improved Buffer API
|
||||
|
||||
0.5.2 / 2016-12-08
|
||||
==================
|
||||
|
||||
* Fix `parse` to accept any linear whitespace character
|
||||
|
||||
0.5.1 / 2016-01-17
|
||||
==================
|
||||
|
||||
* perf: enable strict mode
|
||||
|
||||
0.5.0 / 2014-10-11
|
||||
==================
|
||||
|
||||
* Add `parse` function
|
||||
|
||||
0.4.0 / 2014-09-21
|
||||
==================
|
||||
|
||||
* Expand non-Unicode `filename` to the full ISO-8859-1 charset
|
||||
|
||||
0.3.0 / 2014-09-20
|
||||
==================
|
||||
|
||||
* Add `fallback` option
|
||||
* Add `type` option
|
||||
|
||||
0.2.0 / 2014-09-19
|
||||
==================
|
||||
|
||||
* Reduce ambiguity of file names with hex escape in buggy browsers
|
||||
|
||||
0.1.2 / 2014-09-19
|
||||
==================
|
||||
|
||||
* Fix periodic invalid Unicode filename header
|
||||
|
||||
0.1.1 / 2014-09-19
|
||||
==================
|
||||
|
||||
* Fix invalid characters appearing in `filename*` parameter
|
||||
|
||||
0.1.0 / 2014-09-18
|
||||
==================
|
||||
|
||||
* Make the `filename` argument optional
|
||||
|
||||
0.0.0 / 2014-09-18
|
||||
==================
|
||||
|
||||
* Initial release
|
22
node_modules/content-disposition/LICENSE
generated
vendored
Normal file
22
node_modules/content-disposition/LICENSE
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014-2017 Douglas Christopher Wilson
|
||||
|
||||
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.
|
142
node_modules/content-disposition/README.md
generated
vendored
Normal file
142
node_modules/content-disposition/README.md
generated
vendored
Normal file
@ -0,0 +1,142 @@
|
||||
# content-disposition
|
||||
|
||||
[![NPM Version][npm-image]][npm-url]
|
||||
[![NPM Downloads][downloads-image]][downloads-url]
|
||||
[![Node.js Version][node-version-image]][node-version-url]
|
||||
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Create and parse HTTP `Content-Disposition` header
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ npm install content-disposition
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
var contentDisposition = require('content-disposition')
|
||||
```
|
||||
|
||||
### contentDisposition(filename, options)
|
||||
|
||||
Create an attachment `Content-Disposition` header value using the given file name,
|
||||
if supplied. The `filename` is optional and if no file name is desired, but you
|
||||
want to specify `options`, set `filename` to `undefined`.
|
||||
|
||||
```js
|
||||
res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf'))
|
||||
```
|
||||
|
||||
**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this
|
||||
header through a means different from `setHeader` in Node.js, you'll want to specify
|
||||
the `'binary'` encoding in Node.js.
|
||||
|
||||
#### Options
|
||||
|
||||
`contentDisposition` accepts these properties in the options object.
|
||||
|
||||
##### fallback
|
||||
|
||||
If the `filename` option is outside ISO-8859-1, then the file name is actually
|
||||
stored in a supplemental field for clients that support Unicode file names and
|
||||
a ISO-8859-1 version of the file name is automatically generated.
|
||||
|
||||
This specifies the ISO-8859-1 file name to override the automatic generation or
|
||||
disables the generation all together, defaults to `true`.
|
||||
|
||||
- A string will specify the ISO-8859-1 file name to use in place of automatic
|
||||
generation.
|
||||
- `false` will disable including a ISO-8859-1 file name and only include the
|
||||
Unicode version (unless the file name is already ISO-8859-1).
|
||||
- `true` will enable automatic generation if the file name is outside ISO-8859-1.
|
||||
|
||||
If the `filename` option is ISO-8859-1 and this option is specified and has a
|
||||
different value, then the `filename` option is encoded in the extended field
|
||||
and this set as the fallback field, even though they are both ISO-8859-1.
|
||||
|
||||
##### type
|
||||
|
||||
Specifies the disposition type, defaults to `"attachment"`. This can also be
|
||||
`"inline"`, or any other value (all values except inline are treated like
|
||||
`attachment`, but can convey additional information if both parties agree to
|
||||
it). The type is normalized to lower-case.
|
||||
|
||||
### contentDisposition.parse(string)
|
||||
|
||||
```js
|
||||
var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt')
|
||||
```
|
||||
|
||||
Parse a `Content-Disposition` header string. This automatically handles extended
|
||||
("Unicode") parameters by decoding them and providing them under the standard
|
||||
parameter name. This will return an object with the following properties (examples
|
||||
are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`):
|
||||
|
||||
- `type`: The disposition type (always lower case). Example: `'attachment'`
|
||||
|
||||
- `parameters`: An object of the parameters in the disposition (name of parameter
|
||||
always lower case and extended versions replace non-extended versions). Example:
|
||||
`{filename: "€ rates.txt"}`
|
||||
|
||||
## Examples
|
||||
|
||||
### Send a file for download
|
||||
|
||||
```js
|
||||
var contentDisposition = require('content-disposition')
|
||||
var destroy = require('destroy')
|
||||
var fs = require('fs')
|
||||
var http = require('http')
|
||||
var onFinished = require('on-finished')
|
||||
|
||||
var filePath = '/path/to/public/plans.pdf'
|
||||
|
||||
http.createServer(function onRequest (req, res) {
|
||||
// set headers
|
||||
res.setHeader('Content-Type', 'application/pdf')
|
||||
res.setHeader('Content-Disposition', contentDisposition(filePath))
|
||||
|
||||
// send file
|
||||
var stream = fs.createReadStream(filePath)
|
||||
stream.pipe(res)
|
||||
onFinished(res, function () {
|
||||
destroy(stream)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
```sh
|
||||
$ npm test
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616]
|
||||
- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987]
|
||||
- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266]
|
||||
- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231]
|
||||
|
||||
[rfc-2616]: https://tools.ietf.org/html/rfc2616
|
||||
[rfc-5987]: https://tools.ietf.org/html/rfc5987
|
||||
[rfc-6266]: https://tools.ietf.org/html/rfc6266
|
||||
[tc-2231]: http://greenbytes.de/tech/tc2231/
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[npm-image]: https://img.shields.io/npm/v/content-disposition.svg
|
||||
[npm-url]: https://npmjs.org/package/content-disposition
|
||||
[node-version-image]: https://img.shields.io/node/v/content-disposition.svg
|
||||
[node-version-url]: https://nodejs.org/en/download
|
||||
[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg
|
||||
[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master
|
||||
[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg
|
||||
[downloads-url]: https://npmjs.org/package/content-disposition
|
||||
[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/content-disposition/ci/master?label=ci
|
||||
[github-actions-ci-url]: https://github.com/jshttp/content-disposition?query=workflow%3Aci
|
458
node_modules/content-disposition/index.js
generated
vendored
Normal file
458
node_modules/content-disposition/index.js
generated
vendored
Normal file
@ -0,0 +1,458 @@
|
||||
/*!
|
||||
* content-disposition
|
||||
* Copyright(c) 2014-2017 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = contentDisposition
|
||||
module.exports.parse = parse
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var basename = require('path').basename
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
|
||||
/**
|
||||
* RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%")
|
||||
* @private
|
||||
*/
|
||||
|
||||
var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex
|
||||
|
||||
/**
|
||||
* RegExp to match percent encoding escape.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/
|
||||
var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g
|
||||
|
||||
/**
|
||||
* RegExp to match non-latin1 characters.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g
|
||||
|
||||
/**
|
||||
* RegExp to match quoted-pair in RFC 2616
|
||||
*
|
||||
* quoted-pair = "\" CHAR
|
||||
* CHAR = <any US-ASCII character (octets 0 - 127)>
|
||||
* @private
|
||||
*/
|
||||
|
||||
var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex
|
||||
|
||||
/**
|
||||
* RegExp to match chars that must be quoted-pair in RFC 2616
|
||||
* @private
|
||||
*/
|
||||
|
||||
var QUOTE_REGEXP = /([\\"])/g
|
||||
|
||||
/**
|
||||
* RegExp for various RFC 2616 grammar
|
||||
*
|
||||
* parameter = token "=" ( token | quoted-string )
|
||||
* token = 1*<any CHAR except CTLs or separators>
|
||||
* separators = "(" | ")" | "<" | ">" | "@"
|
||||
* | "," | ";" | ":" | "\" | <">
|
||||
* | "/" | "[" | "]" | "?" | "="
|
||||
* | "{" | "}" | SP | HT
|
||||
* quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
|
||||
* qdtext = <any TEXT except <">>
|
||||
* quoted-pair = "\" CHAR
|
||||
* CHAR = <any US-ASCII character (octets 0 - 127)>
|
||||
* TEXT = <any OCTET except CTLs, but including LWS>
|
||||
* LWS = [CRLF] 1*( SP | HT )
|
||||
* CRLF = CR LF
|
||||
* CR = <US-ASCII CR, carriage return (13)>
|
||||
* LF = <US-ASCII LF, linefeed (10)>
|
||||
* SP = <US-ASCII SP, space (32)>
|
||||
* HT = <US-ASCII HT, horizontal-tab (9)>
|
||||
* CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
|
||||
* OCTET = <any 8-bit sequence of data>
|
||||
* @private
|
||||
*/
|
||||
|
||||
var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex
|
||||
var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/
|
||||
var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/
|
||||
|
||||
/**
|
||||
* RegExp for various RFC 5987 grammar
|
||||
*
|
||||
* ext-value = charset "'" [ language ] "'" value-chars
|
||||
* charset = "UTF-8" / "ISO-8859-1" / mime-charset
|
||||
* mime-charset = 1*mime-charsetc
|
||||
* mime-charsetc = ALPHA / DIGIT
|
||||
* / "!" / "#" / "$" / "%" / "&"
|
||||
* / "+" / "-" / "^" / "_" / "`"
|
||||
* / "{" / "}" / "~"
|
||||
* language = ( 2*3ALPHA [ extlang ] )
|
||||
* / 4ALPHA
|
||||
* / 5*8ALPHA
|
||||
* extlang = *3( "-" 3ALPHA )
|
||||
* value-chars = *( pct-encoded / attr-char )
|
||||
* pct-encoded = "%" HEXDIG HEXDIG
|
||||
* attr-char = ALPHA / DIGIT
|
||||
* / "!" / "#" / "$" / "&" / "+" / "-" / "."
|
||||
* / "^" / "_" / "`" / "|" / "~"
|
||||
* @private
|
||||
*/
|
||||
|
||||
var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/
|
||||
|
||||
/**
|
||||
* RegExp for various RFC 6266 grammar
|
||||
*
|
||||
* disposition-type = "inline" | "attachment" | disp-ext-type
|
||||
* disp-ext-type = token
|
||||
* disposition-parm = filename-parm | disp-ext-parm
|
||||
* filename-parm = "filename" "=" value
|
||||
* | "filename*" "=" ext-value
|
||||
* disp-ext-parm = token "=" value
|
||||
* | ext-token "=" ext-value
|
||||
* ext-token = <the characters in token, followed by "*">
|
||||
* @private
|
||||
*/
|
||||
|
||||
var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex
|
||||
|
||||
/**
|
||||
* Create an attachment Content-Disposition header.
|
||||
*
|
||||
* @param {string} [filename]
|
||||
* @param {object} [options]
|
||||
* @param {string} [options.type=attachment]
|
||||
* @param {string|boolean} [options.fallback=true]
|
||||
* @return {string}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function contentDisposition (filename, options) {
|
||||
var opts = options || {}
|
||||
|
||||
// get type
|
||||
var type = opts.type || 'attachment'
|
||||
|
||||
// get parameters
|
||||
var params = createparams(filename, opts.fallback)
|
||||
|
||||
// format into string
|
||||
return format(new ContentDisposition(type, params))
|
||||
}
|
||||
|
||||
/**
|
||||
* Create parameters object from filename and fallback.
|
||||
*
|
||||
* @param {string} [filename]
|
||||
* @param {string|boolean} [fallback=true]
|
||||
* @return {object}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function createparams (filename, fallback) {
|
||||
if (filename === undefined) {
|
||||
return
|
||||
}
|
||||
|
||||
var params = {}
|
||||
|
||||
if (typeof filename !== 'string') {
|
||||
throw new TypeError('filename must be a string')
|
||||
}
|
||||
|
||||
// fallback defaults to true
|
||||
if (fallback === undefined) {
|
||||
fallback = true
|
||||
}
|
||||
|
||||
if (typeof fallback !== 'string' && typeof fallback !== 'boolean') {
|
||||
throw new TypeError('fallback must be a string or boolean')
|
||||
}
|
||||
|
||||
if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) {
|
||||
throw new TypeError('fallback must be ISO-8859-1 string')
|
||||
}
|
||||
|
||||
// restrict to file base name
|
||||
var name = basename(filename)
|
||||
|
||||
// determine if name is suitable for quoted string
|
||||
var isQuotedString = TEXT_REGEXP.test(name)
|
||||
|
||||
// generate fallback name
|
||||
var fallbackName = typeof fallback !== 'string'
|
||||
? fallback && getlatin1(name)
|
||||
: basename(fallback)
|
||||
var hasFallback = typeof fallbackName === 'string' && fallbackName !== name
|
||||
|
||||
// set extended filename parameter
|
||||
if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) {
|
||||
params['filename*'] = name
|
||||
}
|
||||
|
||||
// set filename parameter
|
||||
if (isQuotedString || hasFallback) {
|
||||
params.filename = hasFallback
|
||||
? fallbackName
|
||||
: name
|
||||
}
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
/**
|
||||
* Format object to Content-Disposition header.
|
||||
*
|
||||
* @param {object} obj
|
||||
* @param {string} obj.type
|
||||
* @param {object} [obj.parameters]
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function format (obj) {
|
||||
var parameters = obj.parameters
|
||||
var type = obj.type
|
||||
|
||||
if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) {
|
||||
throw new TypeError('invalid type')
|
||||
}
|
||||
|
||||
// start with normalized type
|
||||
var string = String(type).toLowerCase()
|
||||
|
||||
// append parameters
|
||||
if (parameters && typeof parameters === 'object') {
|
||||
var param
|
||||
var params = Object.keys(parameters).sort()
|
||||
|
||||
for (var i = 0; i < params.length; i++) {
|
||||
param = params[i]
|
||||
|
||||
var val = param.substr(-1) === '*'
|
||||
? ustring(parameters[param])
|
||||
: qstring(parameters[param])
|
||||
|
||||
string += '; ' + param + '=' + val
|
||||
}
|
||||
}
|
||||
|
||||
return string
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a RFC 5987 field value (gracefully).
|
||||
*
|
||||
* @param {string} str
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function decodefield (str) {
|
||||
var match = EXT_VALUE_REGEXP.exec(str)
|
||||
|
||||
if (!match) {
|
||||
throw new TypeError('invalid extended field value')
|
||||
}
|
||||
|
||||
var charset = match[1].toLowerCase()
|
||||
var encoded = match[2]
|
||||
var value
|
||||
|
||||
// to binary string
|
||||
var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode)
|
||||
|
||||
switch (charset) {
|
||||
case 'iso-8859-1':
|
||||
value = getlatin1(binary)
|
||||
break
|
||||
case 'utf-8':
|
||||
value = Buffer.from(binary, 'binary').toString('utf8')
|
||||
break
|
||||
default:
|
||||
throw new TypeError('unsupported charset in extended field')
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ISO-8859-1 version of string.
|
||||
*
|
||||
* @param {string} val
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function getlatin1 (val) {
|
||||
// simple Unicode -> ISO-8859-1 transformation
|
||||
return String(val).replace(NON_LATIN1_REGEXP, '?')
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Content-Disposition header string.
|
||||
*
|
||||
* @param {string} string
|
||||
* @return {object}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function parse (string) {
|
||||
if (!string || typeof string !== 'string') {
|
||||
throw new TypeError('argument string is required')
|
||||
}
|
||||
|
||||
var match = DISPOSITION_TYPE_REGEXP.exec(string)
|
||||
|
||||
if (!match) {
|
||||
throw new TypeError('invalid type format')
|
||||
}
|
||||
|
||||
// normalize type
|
||||
var index = match[0].length
|
||||
var type = match[1].toLowerCase()
|
||||
|
||||
var key
|
||||
var names = []
|
||||
var params = {}
|
||||
var value
|
||||
|
||||
// calculate index to start at
|
||||
index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';'
|
||||
? index - 1
|
||||
: index
|
||||
|
||||
// match parameters
|
||||
while ((match = PARAM_REGEXP.exec(string))) {
|
||||
if (match.index !== index) {
|
||||
throw new TypeError('invalid parameter format')
|
||||
}
|
||||
|
||||
index += match[0].length
|
||||
key = match[1].toLowerCase()
|
||||
value = match[2]
|
||||
|
||||
if (names.indexOf(key) !== -1) {
|
||||
throw new TypeError('invalid duplicate parameter')
|
||||
}
|
||||
|
||||
names.push(key)
|
||||
|
||||
if (key.indexOf('*') + 1 === key.length) {
|
||||
// decode extended value
|
||||
key = key.slice(0, -1)
|
||||
value = decodefield(value)
|
||||
|
||||
// overwrite existing value
|
||||
params[key] = value
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeof params[key] === 'string') {
|
||||
continue
|
||||
}
|
||||
|
||||
if (value[0] === '"') {
|
||||
// remove quotes and escapes
|
||||
value = value
|
||||
.substr(1, value.length - 2)
|
||||
.replace(QESC_REGEXP, '$1')
|
||||
}
|
||||
|
||||
params[key] = value
|
||||
}
|
||||
|
||||
if (index !== -1 && index !== string.length) {
|
||||
throw new TypeError('invalid parameter format')
|
||||
}
|
||||
|
||||
return new ContentDisposition(type, params)
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent decode a single character.
|
||||
*
|
||||
* @param {string} str
|
||||
* @param {string} hex
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function pdecode (str, hex) {
|
||||
return String.fromCharCode(parseInt(hex, 16))
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent encode a single character.
|
||||
*
|
||||
* @param {string} char
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function pencode (char) {
|
||||
return '%' + String(char)
|
||||
.charCodeAt(0)
|
||||
.toString(16)
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote a string for HTTP.
|
||||
*
|
||||
* @param {string} val
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function qstring (val) {
|
||||
var str = String(val)
|
||||
|
||||
return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"'
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a Unicode string for HTTP (RFC 5987).
|
||||
*
|
||||
* @param {string} val
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function ustring (val) {
|
||||
var str = String(val)
|
||||
|
||||
// percent encode as UTF-8
|
||||
var encoded = encodeURIComponent(str)
|
||||
.replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode)
|
||||
|
||||
return 'UTF-8\'\'' + encoded
|
||||
}
|
||||
|
||||
/**
|
||||
* Class for parsed Content-Disposition header for v8 optimization
|
||||
*
|
||||
* @public
|
||||
* @param {string} type
|
||||
* @param {object} parameters
|
||||
* @constructor
|
||||
*/
|
||||
|
||||
function ContentDisposition (type, parameters) {
|
||||
this.type = type
|
||||
this.parameters = parameters
|
||||
}
|
21
node_modules/content-disposition/node_modules/safe-buffer/LICENSE
generated
vendored
Normal file
21
node_modules/content-disposition/node_modules/safe-buffer/LICENSE
generated
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Feross Aboukhadijeh
|
||||
|
||||
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.
|
584
node_modules/content-disposition/node_modules/safe-buffer/README.md
generated
vendored
Normal file
584
node_modules/content-disposition/node_modules/safe-buffer/README.md
generated
vendored
Normal file
@ -0,0 +1,584 @@
|
||||
# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
|
||||
|
||||
[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg
|
||||
[travis-url]: https://travis-ci.org/feross/safe-buffer
|
||||
[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg
|
||||
[npm-url]: https://npmjs.org/package/safe-buffer
|
||||
[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg
|
||||
[downloads-url]: https://npmjs.org/package/safe-buffer
|
||||
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
|
||||
[standard-url]: https://standardjs.com
|
||||
|
||||
#### Safer Node.js Buffer API
|
||||
|
||||
**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`,
|
||||
`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.**
|
||||
|
||||
**Uses the built-in implementation when available.**
|
||||
|
||||
## install
|
||||
|
||||
```
|
||||
npm install safe-buffer
|
||||
```
|
||||
|
||||
## usage
|
||||
|
||||
The goal of this package is to provide a safe replacement for the node.js `Buffer`.
|
||||
|
||||
It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to
|
||||
the top of your node.js modules:
|
||||
|
||||
```js
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
|
||||
// Existing buffer code will continue to work without issues:
|
||||
|
||||
new Buffer('hey', 'utf8')
|
||||
new Buffer([1, 2, 3], 'utf8')
|
||||
new Buffer(obj)
|
||||
new Buffer(16) // create an uninitialized buffer (potentially unsafe)
|
||||
|
||||
// But you can use these new explicit APIs to make clear what you want:
|
||||
|
||||
Buffer.from('hey', 'utf8') // convert from many types to a Buffer
|
||||
Buffer.alloc(16) // create a zero-filled buffer (safe)
|
||||
Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
|
||||
```
|
||||
|
||||
## api
|
||||
|
||||
### Class Method: Buffer.from(array)
|
||||
<!-- YAML
|
||||
added: v3.0.0
|
||||
-->
|
||||
|
||||
* `array` {Array}
|
||||
|
||||
Allocates a new `Buffer` using an `array` of octets.
|
||||
|
||||
```js
|
||||
const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
|
||||
// creates a new Buffer containing ASCII bytes
|
||||
// ['b','u','f','f','e','r']
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `array` is not an `Array`.
|
||||
|
||||
### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
|
||||
a `new ArrayBuffer()`
|
||||
* `byteOffset` {Number} Default: `0`
|
||||
* `length` {Number} Default: `arrayBuffer.length - byteOffset`
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
const arr = new Uint16Array(2);
|
||||
arr[0] = 5000;
|
||||
arr[1] = 4000;
|
||||
|
||||
const buf = Buffer.from(arr.buffer); // shares the memory with arr;
|
||||
|
||||
console.log(buf);
|
||||
// Prints: <Buffer 88 13 a0 0f>
|
||||
|
||||
// changing the TypedArray 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
|
||||
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`.
|
||||
|
||||
### Class Method: Buffer.from(buffer)
|
||||
<!-- YAML
|
||||
added: v3.0.0
|
||||
-->
|
||||
|
||||
* `buffer` {Buffer}
|
||||
|
||||
Copies the passed `buffer` data onto a new `Buffer` instance.
|
||||
|
||||
```js
|
||||
const buf1 = Buffer.from('buffer');
|
||||
const buf2 = Buffer.from(buf1);
|
||||
|
||||
buf1[0] = 0x61;
|
||||
console.log(buf1.toString());
|
||||
// 'auffer'
|
||||
console.log(buf2.toString());
|
||||
// 'buffer' (copy is not changed)
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `buffer` is not a `Buffer`.
|
||||
|
||||
### Class Method: Buffer.from(str[, encoding])
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `str` {String} String to encode.
|
||||
* `encoding` {String} Encoding to use, Default: `'utf8'`
|
||||
|
||||
Creates a new `Buffer` containing the given JavaScript string `str`. If
|
||||
provided, the `encoding` parameter identifies the character encoding.
|
||||
If not provided, `encoding` defaults to `'utf8'`.
|
||||
|
||||
```js
|
||||
const buf1 = Buffer.from('this is a tést');
|
||||
console.log(buf1.toString());
|
||||
// prints: this is a tést
|
||||
console.log(buf1.toString('ascii'));
|
||||
// prints: this is a tC)st
|
||||
|
||||
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
|
||||
console.log(buf2.toString());
|
||||
// prints: this is a tést
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `str` is not a string.
|
||||
|
||||
### Class Method: Buffer.alloc(size[, fill[, encoding]])
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `size` {Number}
|
||||
* `fill` {Value} Default: `undefined`
|
||||
* `encoding` {String} Default: `utf8`
|
||||
|
||||
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
|
||||
`Buffer` will be *zero-filled*.
|
||||
|
||||
```js
|
||||
const buf = Buffer.alloc(5);
|
||||
console.log(buf);
|
||||
// <Buffer 00 00 00 00 00>
|
||||
```
|
||||
|
||||
The `size` must be less than or equal to the value of
|
||||
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
|
||||
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
|
||||
be created if a `size` less than or equal to 0 is specified.
|
||||
|
||||
If `fill` is specified, the allocated `Buffer` will be initialized by calling
|
||||
`buf.fill(fill)`. See [`buf.fill()`][] for more information.
|
||||
|
||||
```js
|
||||
const buf = Buffer.alloc(5, 'a');
|
||||
console.log(buf);
|
||||
// <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)`. For example:
|
||||
|
||||
```js
|
||||
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
|
||||
console.log(buf);
|
||||
// <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
|
||||
```
|
||||
|
||||
Calling `Buffer.alloc(size)` can be significantly slower than the alternative
|
||||
`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
|
||||
contents will *never contain sensitive data*.
|
||||
|
||||
A `TypeError` will be thrown if `size` is not a number.
|
||||
|
||||
### Class Method: Buffer.allocUnsafe(size)
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `size` {Number}
|
||||
|
||||
Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
|
||||
be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
|
||||
architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
|
||||
thrown. A zero-length Buffer will be created if a `size` less than or equal to
|
||||
0 is specified.
|
||||
|
||||
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 to zeroes.
|
||||
|
||||
```js
|
||||
const buf = Buffer.allocUnsafe(5);
|
||||
console.log(buf);
|
||||
// <Buffer 78 e0 82 02 01>
|
||||
// (octets will be different, every time)
|
||||
buf.fill(0);
|
||||
console.log(buf);
|
||||
// <Buffer 00 00 00 00 00>
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `size` is not a number.
|
||||
|
||||
Note that 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(size)` (and the deprecated
|
||||
`new Buffer(size)` constructor) only when `size` is less than or equal to
|
||||
`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default
|
||||
value of `Buffer.poolSize` is `8192` but can be modified.
|
||||
|
||||
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(size)` provides.
|
||||
|
||||
### Class Method: Buffer.allocUnsafeSlow(size)
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `size` {Number}
|
||||
|
||||
Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
|
||||
`size` must be less than or equal to the value of
|
||||
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
|
||||
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
|
||||
be created if a `size` less than or equal to 0 is specified.
|
||||
|
||||
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 to zeroes.
|
||||
|
||||
When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
|
||||
allocations under 4KB are, by default, sliced from a single pre-allocated
|
||||
`Buffer`. This allows applications to avoid the garbage collection overhead of
|
||||
creating many individually allocated Buffers. This approach improves both
|
||||
performance and memory usage by eliminating the need to track and cleanup as
|
||||
many `Persistent` 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()` then
|
||||
copy out the relevant bits.
|
||||
|
||||
```js
|
||||
// need to keep around a few small chunks of memory
|
||||
const store = [];
|
||||
|
||||
socket.on('readable', () => {
|
||||
const data = socket.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);
|
||||
});
|
||||
```
|
||||
|
||||
Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after*
|
||||
a developer has observed undue memory retention in their applications.
|
||||
|
||||
A `TypeError` will be thrown if `size` is not a number.
|
||||
|
||||
### All the Rest
|
||||
|
||||
The rest of the `Buffer` API is exactly the same as in node.js.
|
||||
[See the docs](https://nodejs.org/api/buffer.html).
|
||||
|
||||
|
||||
## Related links
|
||||
|
||||
- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)
|
||||
- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4)
|
||||
|
||||
## Why is `Buffer` unsafe?
|
||||
|
||||
Today, the node.js `Buffer` constructor is overloaded to handle many different argument
|
||||
types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),
|
||||
`ArrayBuffer`, and also `Number`.
|
||||
|
||||
The API is optimized for convenience: you can throw any type at it, and it will try to do
|
||||
what you want.
|
||||
|
||||
Because the Buffer constructor is so powerful, you often see code like this:
|
||||
|
||||
```js
|
||||
// Convert UTF-8 strings to hex
|
||||
function toHex (str) {
|
||||
return new Buffer(str).toString('hex')
|
||||
}
|
||||
```
|
||||
|
||||
***But what happens if `toHex` is called with a `Number` argument?***
|
||||
|
||||
### Remote Memory Disclosure
|
||||
|
||||
If an attacker can make your program call the `Buffer` constructor with a `Number`
|
||||
argument, then they can make it allocate uninitialized memory from the node.js process.
|
||||
This could potentially disclose TLS private keys, user data, or database passwords.
|
||||
|
||||
When the `Buffer` constructor is passed a `Number` argument, it returns an
|
||||
**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like
|
||||
this, you **MUST** overwrite the contents before returning it to the user.
|
||||
|
||||
From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size):
|
||||
|
||||
> `new Buffer(size)`
|
||||
>
|
||||
> - `size` Number
|
||||
>
|
||||
> The underlying memory for `Buffer` instances created in this way is not initialized.
|
||||
> **The contents of a newly created `Buffer` are unknown and could contain sensitive
|
||||
> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.
|
||||
|
||||
(Emphasis our own.)
|
||||
|
||||
Whenever the programmer intended to create an uninitialized `Buffer` you often see code
|
||||
like this:
|
||||
|
||||
```js
|
||||
var buf = new Buffer(16)
|
||||
|
||||
// Immediately overwrite the uninitialized buffer with data from another buffer
|
||||
for (var i = 0; i < buf.length; i++) {
|
||||
buf[i] = otherBuf[i]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Would this ever be a problem in real code?
|
||||
|
||||
Yes. It's surprisingly common to forget to check the type of your variables in a
|
||||
dynamically-typed language like JavaScript.
|
||||
|
||||
Usually the consequences of assuming the wrong type is that your program crashes with an
|
||||
uncaught exception. But the failure mode for forgetting to check the type of arguments to
|
||||
the `Buffer` constructor is more catastrophic.
|
||||
|
||||
Here's an example of a vulnerable service that takes a JSON payload and converts it to
|
||||
hex:
|
||||
|
||||
```js
|
||||
// Take a JSON payload {str: "some string"} and convert it to hex
|
||||
var server = http.createServer(function (req, res) {
|
||||
var data = ''
|
||||
req.setEncoding('utf8')
|
||||
req.on('data', function (chunk) {
|
||||
data += chunk
|
||||
})
|
||||
req.on('end', function () {
|
||||
var body = JSON.parse(data)
|
||||
res.end(new Buffer(body.str).toString('hex'))
|
||||
})
|
||||
})
|
||||
|
||||
server.listen(8080)
|
||||
```
|
||||
|
||||
In this example, an http client just has to send:
|
||||
|
||||
```json
|
||||
{
|
||||
"str": 1000
|
||||
}
|
||||
```
|
||||
|
||||
and it will get back 1,000 bytes of uninitialized memory from the server.
|
||||
|
||||
This is a very serious bug. It's similar in severity to the
|
||||
[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process
|
||||
memory by remote attackers.
|
||||
|
||||
|
||||
### Which real-world packages were vulnerable?
|
||||
|
||||
#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)
|
||||
|
||||
[Mathias Buus](https://github.com/mafintosh) and I
|
||||
([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages,
|
||||
[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow
|
||||
anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get
|
||||
them to reveal 20 bytes at a time of uninitialized memory from the node.js process.
|
||||
|
||||
Here's
|
||||
[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8)
|
||||
that fixed it. We released a new fixed version, created a
|
||||
[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all
|
||||
vulnerable versions on npm so users will get a warning to upgrade to a newer version.
|
||||
|
||||
#### [`ws`](https://www.npmjs.com/package/ws)
|
||||
|
||||
That got us wondering if there were other vulnerable packages. Sure enough, within a short
|
||||
period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the
|
||||
most popular WebSocket implementation in node.js.
|
||||
|
||||
If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as
|
||||
expected, then uninitialized server memory would be disclosed to the remote peer.
|
||||
|
||||
These were the vulnerable methods:
|
||||
|
||||
```js
|
||||
socket.send(number)
|
||||
socket.ping(number)
|
||||
socket.pong(number)
|
||||
```
|
||||
|
||||
Here's a vulnerable socket server with some echo functionality:
|
||||
|
||||
```js
|
||||
server.on('connection', function (socket) {
|
||||
socket.on('message', function (message) {
|
||||
message = JSON.parse(message)
|
||||
if (message.type === 'echo') {
|
||||
socket.send(message.data) // send back the user's message
|
||||
}
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
`socket.send(number)` called on the server, will disclose server memory.
|
||||
|
||||
Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue
|
||||
was fixed, with a more detailed explanation. Props to
|
||||
[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the
|
||||
[Node Security Project disclosure](https://nodesecurity.io/advisories/67).
|
||||
|
||||
|
||||
### What's the solution?
|
||||
|
||||
It's important that node.js offers a fast way to get memory otherwise performance-critical
|
||||
applications would needlessly get a lot slower.
|
||||
|
||||
But we need a better way to *signal our intent* as programmers. **When we want
|
||||
uninitialized memory, we should request it explicitly.**
|
||||
|
||||
Sensitive functionality should not be packed into a developer-friendly API that loosely
|
||||
accepts many different types. This type of API encourages the lazy practice of passing
|
||||
variables in without checking the type very carefully.
|
||||
|
||||
#### A new API: `Buffer.allocUnsafe(number)`
|
||||
|
||||
The functionality of creating buffers with uninitialized memory should be part of another
|
||||
API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that
|
||||
frequently gets user input of all sorts of different types passed into it.
|
||||
|
||||
```js
|
||||
var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory!
|
||||
|
||||
// Immediately overwrite the uninitialized buffer with data from another buffer
|
||||
for (var i = 0; i < buf.length; i++) {
|
||||
buf[i] = otherBuf[i]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### How do we fix node.js core?
|
||||
|
||||
We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as
|
||||
`semver-major`) which defends against one case:
|
||||
|
||||
```js
|
||||
var str = 16
|
||||
new Buffer(str, 'utf8')
|
||||
```
|
||||
|
||||
In this situation, it's implied that the programmer intended the first argument to be a
|
||||
string, since they passed an encoding as a second argument. Today, node.js will allocate
|
||||
uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not
|
||||
what the programmer intended.
|
||||
|
||||
But this is only a partial solution, since if the programmer does `new Buffer(variable)`
|
||||
(without an `encoding` parameter) there's no way to know what they intended. If `variable`
|
||||
is sometimes a number, then uninitialized memory will sometimes be returned.
|
||||
|
||||
### What's the real long-term fix?
|
||||
|
||||
We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when
|
||||
we need uninitialized memory. But that would break 1000s of packages.
|
||||
|
||||
~~We believe the best solution is to:~~
|
||||
|
||||
~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~
|
||||
|
||||
~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~
|
||||
|
||||
#### Update
|
||||
|
||||
We now support adding three new APIs:
|
||||
|
||||
- `Buffer.from(value)` - convert from any type to a buffer
|
||||
- `Buffer.alloc(size)` - create a zero-filled buffer
|
||||
- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size
|
||||
|
||||
This solves the core problem that affected `ws` and `bittorrent-dht` which is
|
||||
`Buffer(variable)` getting tricked into taking a number argument.
|
||||
|
||||
This way, existing code continues working and the impact on the npm ecosystem will be
|
||||
minimal. Over time, npm maintainers can migrate performance-critical code to use
|
||||
`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`.
|
||||
|
||||
|
||||
### Conclusion
|
||||
|
||||
We think there's a serious design issue with the `Buffer` API as it exists today. It
|
||||
promotes insecure software by putting high-risk functionality into a convenient API
|
||||
with friendly "developer ergonomics".
|
||||
|
||||
This wasn't merely a theoretical exercise because we found the issue in some of the
|
||||
most popular npm packages.
|
||||
|
||||
Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of
|
||||
`buffer`.
|
||||
|
||||
```js
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
```
|
||||
|
||||
Eventually, we hope that node.js core can switch to this new, safer behavior. We believe
|
||||
the impact on the ecosystem would be minimal since it's not a breaking change.
|
||||
Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while
|
||||
older, insecure packages would magically become safe from this attack vector.
|
||||
|
||||
|
||||
## links
|
||||
|
||||
- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514)
|
||||
- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67)
|
||||
- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68)
|
||||
|
||||
|
||||
## credit
|
||||
|
||||
The original issues in `bittorrent-dht`
|
||||
([disclosure](https://nodesecurity.io/advisories/68)) and
|
||||
`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by
|
||||
[Mathias Buus](https://github.com/mafintosh) and
|
||||
[Feross Aboukhadijeh](http://feross.org/).
|
||||
|
||||
Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues
|
||||
and for his work running the [Node Security Project](https://nodesecurity.io/).
|
||||
|
||||
Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and
|
||||
auditing the code.
|
||||
|
||||
|
||||
## license
|
||||
|
||||
MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)
|
187
node_modules/content-disposition/node_modules/safe-buffer/index.d.ts
generated
vendored
Normal file
187
node_modules/content-disposition/node_modules/safe-buffer/index.d.ts
generated
vendored
Normal file
@ -0,0 +1,187 @@
|
||||
declare module "safe-buffer" {
|
||||
export class Buffer {
|
||||
length: number
|
||||
write(string: string, offset?: number, length?: number, encoding?: string): number;
|
||||
toString(encoding?: string, start?: number, end?: number): string;
|
||||
toJSON(): { type: 'Buffer', data: any[] };
|
||||
equals(otherBuffer: Buffer): boolean;
|
||||
compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
|
||||
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
|
||||
slice(start?: number, end?: number): Buffer;
|
||||
writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUInt8(offset: number, noAssert?: boolean): number;
|
||||
readUInt16LE(offset: number, noAssert?: boolean): number;
|
||||
readUInt16BE(offset: number, noAssert?: boolean): number;
|
||||
readUInt32LE(offset: number, noAssert?: boolean): number;
|
||||
readUInt32BE(offset: number, noAssert?: boolean): number;
|
||||
readInt8(offset: number, noAssert?: boolean): number;
|
||||
readInt16LE(offset: number, noAssert?: boolean): number;
|
||||
readInt16BE(offset: number, noAssert?: boolean): number;
|
||||
readInt32LE(offset: number, noAssert?: boolean): number;
|
||||
readInt32BE(offset: number, noAssert?: boolean): number;
|
||||
readFloatLE(offset: number, noAssert?: boolean): number;
|
||||
readFloatBE(offset: number, noAssert?: boolean): number;
|
||||
readDoubleLE(offset: number, noAssert?: boolean): number;
|
||||
readDoubleBE(offset: number, noAssert?: boolean): number;
|
||||
swap16(): Buffer;
|
||||
swap32(): Buffer;
|
||||
swap64(): Buffer;
|
||||
writeUInt8(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt8(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
|
||||
fill(value: any, offset?: number, end?: number): this;
|
||||
indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
|
||||
lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
|
||||
includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
|
||||
|
||||
/**
|
||||
* Allocates a new buffer containing the given {str}.
|
||||
*
|
||||
* @param str String to store in buffer.
|
||||
* @param encoding encoding to use, optional. Default is 'utf8'
|
||||
*/
|
||||
constructor (str: string, encoding?: string);
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
*/
|
||||
constructor (size: number);
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
*/
|
||||
constructor (array: Uint8Array);
|
||||
/**
|
||||
* Produces a Buffer backed by the same allocated memory as
|
||||
* the given {ArrayBuffer}.
|
||||
*
|
||||
*
|
||||
* @param arrayBuffer The ArrayBuffer with which to share memory.
|
||||
*/
|
||||
constructor (arrayBuffer: ArrayBuffer);
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
*/
|
||||
constructor (array: any[]);
|
||||
/**
|
||||
* Copies the passed {buffer} data onto a new {Buffer} instance.
|
||||
*
|
||||
* @param buffer The buffer to copy.
|
||||
*/
|
||||
constructor (buffer: Buffer);
|
||||
prototype: Buffer;
|
||||
/**
|
||||
* Allocates a new Buffer using an {array} of octets.
|
||||
*
|
||||
* @param array
|
||||
*/
|
||||
static from(array: any[]): Buffer;
|
||||
/**
|
||||
* 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.
|
||||
* The optional {byteOffset} and {length} arguments specify a memory range
|
||||
* within the {arrayBuffer} that will be shared by the Buffer.
|
||||
*
|
||||
* @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
|
||||
* @param byteOffset
|
||||
* @param length
|
||||
*/
|
||||
static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
|
||||
/**
|
||||
* Copies the passed {buffer} data onto a new Buffer instance.
|
||||
*
|
||||
* @param buffer
|
||||
*/
|
||||
static from(buffer: Buffer): Buffer;
|
||||
/**
|
||||
* Creates a new Buffer containing the given JavaScript string {str}.
|
||||
* If provided, the {encoding} parameter identifies the character encoding.
|
||||
* If not provided, {encoding} defaults to 'utf8'.
|
||||
*
|
||||
* @param str
|
||||
*/
|
||||
static from(str: string, encoding?: string): Buffer;
|
||||
/**
|
||||
* Returns true if {obj} is a Buffer
|
||||
*
|
||||
* @param obj object to test.
|
||||
*/
|
||||
static isBuffer(obj: any): obj is Buffer;
|
||||
/**
|
||||
* Returns true if {encoding} is a valid encoding argument.
|
||||
* Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
|
||||
*
|
||||
* @param encoding string to test.
|
||||
*/
|
||||
static isEncoding(encoding: string): boolean;
|
||||
/**
|
||||
* Gives the actual byte length of a string. encoding defaults to 'utf8'.
|
||||
* This is not the same as String.prototype.length since that returns the number of characters in a string.
|
||||
*
|
||||
* @param string string to test.
|
||||
* @param encoding encoding used to evaluate (defaults to 'utf8')
|
||||
*/
|
||||
static byteLength(string: string, encoding?: string): number;
|
||||
/**
|
||||
* Returns a buffer which is the result of concatenating all the buffers in the list together.
|
||||
*
|
||||
* If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
|
||||
* If the list has exactly one item, then the first item of the list is returned.
|
||||
* If the list has more than one item, then a new Buffer is created.
|
||||
*
|
||||
* @param list An array of Buffer objects to concatenate
|
||||
* @param totalLength Total length of the buffers when concatenated.
|
||||
* If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
|
||||
*/
|
||||
static concat(list: Buffer[], totalLength?: number): Buffer;
|
||||
/**
|
||||
* The same as buf1.compare(buf2).
|
||||
*/
|
||||
static compare(buf1: Buffer, buf2: Buffer): number;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
* @param fill if specified, buffer will be initialized by calling buf.fill(fill).
|
||||
* If parameter is omitted, buffer will be filled with zeros.
|
||||
* @param encoding encoding used for call to buf.fill while initalizing
|
||||
*/
|
||||
static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents
|
||||
* of the newly created Buffer are unknown and may contain sensitive data.
|
||||
*
|
||||
* @param size count of octets to allocate
|
||||
*/
|
||||
static allocUnsafe(size: number): Buffer;
|
||||
/**
|
||||
* Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents
|
||||
* of the newly created Buffer are unknown and may contain sensitive data.
|
||||
*
|
||||
* @param size count of octets to allocate
|
||||
*/
|
||||
static allocUnsafeSlow(size: number): Buffer;
|
||||
}
|
||||
}
|
65
node_modules/content-disposition/node_modules/safe-buffer/index.js
generated
vendored
Normal file
65
node_modules/content-disposition/node_modules/safe-buffer/index.js
generated
vendored
Normal file
@ -0,0 +1,65 @@
|
||||
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
||||
/* eslint-disable node/no-deprecated-api */
|
||||
var buffer = require('buffer')
|
||||
var Buffer = buffer.Buffer
|
||||
|
||||
// alternative to using Object.keys for old browsers
|
||||
function copyProps (src, dst) {
|
||||
for (var key in src) {
|
||||
dst[key] = src[key]
|
||||
}
|
||||
}
|
||||
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
|
||||
module.exports = buffer
|
||||
} else {
|
||||
// Copy properties from require('buffer')
|
||||
copyProps(buffer, exports)
|
||||
exports.Buffer = SafeBuffer
|
||||
}
|
||||
|
||||
function SafeBuffer (arg, encodingOrOffset, length) {
|
||||
return Buffer(arg, encodingOrOffset, length)
|
||||
}
|
||||
|
||||
SafeBuffer.prototype = Object.create(Buffer.prototype)
|
||||
|
||||
// Copy static methods from Buffer
|
||||
copyProps(Buffer, SafeBuffer)
|
||||
|
||||
SafeBuffer.from = function (arg, encodingOrOffset, length) {
|
||||
if (typeof arg === 'number') {
|
||||
throw new TypeError('Argument must not be a number')
|
||||
}
|
||||
return Buffer(arg, encodingOrOffset, length)
|
||||
}
|
||||
|
||||
SafeBuffer.alloc = function (size, fill, encoding) {
|
||||
if (typeof size !== 'number') {
|
||||
throw new TypeError('Argument must be a number')
|
||||
}
|
||||
var buf = Buffer(size)
|
||||
if (fill !== undefined) {
|
||||
if (typeof encoding === 'string') {
|
||||
buf.fill(fill, encoding)
|
||||
} else {
|
||||
buf.fill(fill)
|
||||
}
|
||||
} else {
|
||||
buf.fill(0)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
SafeBuffer.allocUnsafe = function (size) {
|
||||
if (typeof size !== 'number') {
|
||||
throw new TypeError('Argument must be a number')
|
||||
}
|
||||
return Buffer(size)
|
||||
}
|
||||
|
||||
SafeBuffer.allocUnsafeSlow = function (size) {
|
||||
if (typeof size !== 'number') {
|
||||
throw new TypeError('Argument must be a number')
|
||||
}
|
||||
return buffer.SlowBuffer(size)
|
||||
}
|
51
node_modules/content-disposition/node_modules/safe-buffer/package.json
generated
vendored
Normal file
51
node_modules/content-disposition/node_modules/safe-buffer/package.json
generated
vendored
Normal file
@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "safe-buffer",
|
||||
"description": "Safer Node.js Buffer API",
|
||||
"version": "5.2.1",
|
||||
"author": {
|
||||
"name": "Feross Aboukhadijeh",
|
||||
"email": "feross@feross.org",
|
||||
"url": "https://feross.org"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/feross/safe-buffer/issues"
|
||||
},
|
||||
"devDependencies": {
|
||||
"standard": "*",
|
||||
"tape": "^5.0.0"
|
||||
},
|
||||
"homepage": "https://github.com/feross/safe-buffer",
|
||||
"keywords": [
|
||||
"buffer",
|
||||
"buffer allocate",
|
||||
"node security",
|
||||
"safe",
|
||||
"safe-buffer",
|
||||
"security",
|
||||
"uninitialized"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/feross/safe-buffer.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "standard && tape test/*.js"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
]
|
||||
}
|
44
node_modules/content-disposition/package.json
generated
vendored
Normal file
44
node_modules/content-disposition/package.json
generated
vendored
Normal file
@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "content-disposition",
|
||||
"description": "Create and parse Content-Disposition header",
|
||||
"version": "0.5.4",
|
||||
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"content-disposition",
|
||||
"http",
|
||||
"rfc6266",
|
||||
"res"
|
||||
],
|
||||
"repository": "jshttp/content-disposition",
|
||||
"dependencies": {
|
||||
"safe-buffer": "5.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"deep-equal": "1.0.1",
|
||||
"eslint": "7.32.0",
|
||||
"eslint-config-standard": "13.0.1",
|
||||
"eslint-plugin-import": "2.25.3",
|
||||
"eslint-plugin-markdown": "2.2.1",
|
||||
"eslint-plugin-node": "11.1.0",
|
||||
"eslint-plugin-promise": "5.2.0",
|
||||
"eslint-plugin-standard": "4.1.0",
|
||||
"istanbul": "0.4.5",
|
||||
"mocha": "9.1.3"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"HISTORY.md",
|
||||
"README.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --reporter spec --bail --check-leaks test/",
|
||||
"test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/",
|
||||
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/"
|
||||
}
|
||||
}
|
29
node_modules/content-type/HISTORY.md
generated
vendored
Normal file
29
node_modules/content-type/HISTORY.md
generated
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
1.0.5 / 2023-01-29
|
||||
==================
|
||||
|
||||
* perf: skip value escaping when unnecessary
|
||||
|
||||
1.0.4 / 2017-09-11
|
||||
==================
|
||||
|
||||
* perf: skip parameter parsing when no parameters
|
||||
|
||||
1.0.3 / 2017-09-10
|
||||
==================
|
||||
|
||||
* perf: remove argument reassignment
|
||||
|
||||
1.0.2 / 2016-05-09
|
||||
==================
|
||||
|
||||
* perf: enable strict mode
|
||||
|
||||
1.0.1 / 2015-02-13
|
||||
==================
|
||||
|
||||
* Improve missing `Content-Type` header error message
|
||||
|
||||
1.0.0 / 2015-02-01
|
||||
==================
|
||||
|
||||
* Initial implementation, derived from `media-typer@0.3.0`
|
22
node_modules/content-type/LICENSE
generated
vendored
Normal file
22
node_modules/content-type/LICENSE
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2015 Douglas Christopher Wilson
|
||||
|
||||
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.
|
94
node_modules/content-type/README.md
generated
vendored
Normal file
94
node_modules/content-type/README.md
generated
vendored
Normal file
@ -0,0 +1,94 @@
|
||||
# content-type
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Node.js Version][node-image]][node-url]
|
||||
[![Build Status][ci-image]][ci-url]
|
||||
[![Coverage Status][coveralls-image]][coveralls-url]
|
||||
|
||||
Create and parse HTTP Content-Type header according to RFC 7231
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ npm install content-type
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
var contentType = require('content-type')
|
||||
```
|
||||
|
||||
### contentType.parse(string)
|
||||
|
||||
```js
|
||||
var obj = contentType.parse('image/svg+xml; charset=utf-8')
|
||||
```
|
||||
|
||||
Parse a `Content-Type` header. This will return an object with the following
|
||||
properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`):
|
||||
|
||||
- `type`: The media type (the type and subtype, always lower case).
|
||||
Example: `'image/svg+xml'`
|
||||
|
||||
- `parameters`: An object of the parameters in the media type (name of parameter
|
||||
always lower case). Example: `{charset: 'utf-8'}`
|
||||
|
||||
Throws a `TypeError` if the string is missing or invalid.
|
||||
|
||||
### contentType.parse(req)
|
||||
|
||||
```js
|
||||
var obj = contentType.parse(req)
|
||||
```
|
||||
|
||||
Parse the `Content-Type` header from the given `req`. Short-cut for
|
||||
`contentType.parse(req.headers['content-type'])`.
|
||||
|
||||
Throws a `TypeError` if the `Content-Type` header is missing or invalid.
|
||||
|
||||
### contentType.parse(res)
|
||||
|
||||
```js
|
||||
var obj = contentType.parse(res)
|
||||
```
|
||||
|
||||
Parse the `Content-Type` header set on the given `res`. Short-cut for
|
||||
`contentType.parse(res.getHeader('content-type'))`.
|
||||
|
||||
Throws a `TypeError` if the `Content-Type` header is missing or invalid.
|
||||
|
||||
### contentType.format(obj)
|
||||
|
||||
```js
|
||||
var str = contentType.format({
|
||||
type: 'image/svg+xml',
|
||||
parameters: { charset: 'utf-8' }
|
||||
})
|
||||
```
|
||||
|
||||
Format an object into a `Content-Type` header. This will return a string of the
|
||||
content type for the given object with the following properties (examples are
|
||||
shown that produce the string `'image/svg+xml; charset=utf-8'`):
|
||||
|
||||
- `type`: The media type (will be lower-cased). Example: `'image/svg+xml'`
|
||||
|
||||
- `parameters`: An object of the parameters in the media type (name of the
|
||||
parameter will be lower-cased). Example: `{charset: 'utf-8'}`
|
||||
|
||||
Throws a `TypeError` if the object contains an invalid type or parameter names.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[ci-image]: https://badgen.net/github/checks/jshttp/content-type/master?label=ci
|
||||
[ci-url]: https://github.com/jshttp/content-type/actions/workflows/ci.yml
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/content-type/master
|
||||
[coveralls-url]: https://coveralls.io/r/jshttp/content-type?branch=master
|
||||
[node-image]: https://badgen.net/npm/node/content-type
|
||||
[node-url]: https://nodejs.org/en/download
|
||||
[npm-downloads-image]: https://badgen.net/npm/dm/content-type
|
||||
[npm-url]: https://npmjs.org/package/content-type
|
||||
[npm-version-image]: https://badgen.net/npm/v/content-type
|
225
node_modules/content-type/index.js
generated
vendored
Normal file
225
node_modules/content-type/index.js
generated
vendored
Normal file
@ -0,0 +1,225 @@
|
||||
/*!
|
||||
* content-type
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
|
||||
*
|
||||
* parameter = token "=" ( token / quoted-string )
|
||||
* token = 1*tchar
|
||||
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
|
||||
* / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
|
||||
* / DIGIT / ALPHA
|
||||
* ; any VCHAR, except delimiters
|
||||
* quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
|
||||
* qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
|
||||
* obs-text = %x80-FF
|
||||
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
|
||||
*/
|
||||
var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex
|
||||
var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ // eslint-disable-line no-control-regex
|
||||
var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
|
||||
|
||||
/**
|
||||
* RegExp to match quoted-pair in RFC 7230 sec 3.2.6
|
||||
*
|
||||
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
|
||||
* obs-text = %x80-FF
|
||||
*/
|
||||
var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g // eslint-disable-line no-control-regex
|
||||
|
||||
/**
|
||||
* RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6
|
||||
*/
|
||||
var QUOTE_REGEXP = /([\\"])/g
|
||||
|
||||
/**
|
||||
* RegExp to match type in RFC 7231 sec 3.1.1.1
|
||||
*
|
||||
* media-type = type "/" subtype
|
||||
* type = token
|
||||
* subtype = token
|
||||
*/
|
||||
var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
exports.format = format
|
||||
exports.parse = parse
|
||||
|
||||
/**
|
||||
* Format object to media type.
|
||||
*
|
||||
* @param {object} obj
|
||||
* @return {string}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function format (obj) {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
throw new TypeError('argument obj is required')
|
||||
}
|
||||
|
||||
var parameters = obj.parameters
|
||||
var type = obj.type
|
||||
|
||||
if (!type || !TYPE_REGEXP.test(type)) {
|
||||
throw new TypeError('invalid type')
|
||||
}
|
||||
|
||||
var string = type
|
||||
|
||||
// append parameters
|
||||
if (parameters && typeof parameters === 'object') {
|
||||
var param
|
||||
var params = Object.keys(parameters).sort()
|
||||
|
||||
for (var i = 0; i < params.length; i++) {
|
||||
param = params[i]
|
||||
|
||||
if (!TOKEN_REGEXP.test(param)) {
|
||||
throw new TypeError('invalid parameter name')
|
||||
}
|
||||
|
||||
string += '; ' + param + '=' + qstring(parameters[param])
|
||||
}
|
||||
}
|
||||
|
||||
return string
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse media type to object.
|
||||
*
|
||||
* @param {string|object} string
|
||||
* @return {Object}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function parse (string) {
|
||||
if (!string) {
|
||||
throw new TypeError('argument string is required')
|
||||
}
|
||||
|
||||
// support req/res-like objects as argument
|
||||
var header = typeof string === 'object'
|
||||
? getcontenttype(string)
|
||||
: string
|
||||
|
||||
if (typeof header !== 'string') {
|
||||
throw new TypeError('argument string is required to be a string')
|
||||
}
|
||||
|
||||
var index = header.indexOf(';')
|
||||
var type = index !== -1
|
||||
? header.slice(0, index).trim()
|
||||
: header.trim()
|
||||
|
||||
if (!TYPE_REGEXP.test(type)) {
|
||||
throw new TypeError('invalid media type')
|
||||
}
|
||||
|
||||
var obj = new ContentType(type.toLowerCase())
|
||||
|
||||
// parse parameters
|
||||
if (index !== -1) {
|
||||
var key
|
||||
var match
|
||||
var value
|
||||
|
||||
PARAM_REGEXP.lastIndex = index
|
||||
|
||||
while ((match = PARAM_REGEXP.exec(header))) {
|
||||
if (match.index !== index) {
|
||||
throw new TypeError('invalid parameter format')
|
||||
}
|
||||
|
||||
index += match[0].length
|
||||
key = match[1].toLowerCase()
|
||||
value = match[2]
|
||||
|
||||
if (value.charCodeAt(0) === 0x22 /* " */) {
|
||||
// remove quotes
|
||||
value = value.slice(1, -1)
|
||||
|
||||
// remove escapes
|
||||
if (value.indexOf('\\') !== -1) {
|
||||
value = value.replace(QESC_REGEXP, '$1')
|
||||
}
|
||||
}
|
||||
|
||||
obj.parameters[key] = value
|
||||
}
|
||||
|
||||
if (index !== header.length) {
|
||||
throw new TypeError('invalid parameter format')
|
||||
}
|
||||
}
|
||||
|
||||
return obj
|
||||
}
|
||||
|
||||
/**
|
||||
* Get content-type from req/res objects.
|
||||
*
|
||||
* @param {object}
|
||||
* @return {Object}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function getcontenttype (obj) {
|
||||
var header
|
||||
|
||||
if (typeof obj.getHeader === 'function') {
|
||||
// res-like
|
||||
header = obj.getHeader('content-type')
|
||||
} else if (typeof obj.headers === 'object') {
|
||||
// req-like
|
||||
header = obj.headers && obj.headers['content-type']
|
||||
}
|
||||
|
||||
if (typeof header !== 'string') {
|
||||
throw new TypeError('content-type header is missing from object')
|
||||
}
|
||||
|
||||
return header
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote a string if necessary.
|
||||
*
|
||||
* @param {string} val
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function qstring (val) {
|
||||
var str = String(val)
|
||||
|
||||
// no need to quote tokens
|
||||
if (TOKEN_REGEXP.test(str)) {
|
||||
return str
|
||||
}
|
||||
|
||||
if (str.length > 0 && !TEXT_REGEXP.test(str)) {
|
||||
throw new TypeError('invalid parameter value')
|
||||
}
|
||||
|
||||
return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"'
|
||||
}
|
||||
|
||||
/**
|
||||
* Class to represent a content type.
|
||||
* @private
|
||||
*/
|
||||
function ContentType (type) {
|
||||
this.parameters = Object.create(null)
|
||||
this.type = type
|
||||
}
|
42
node_modules/content-type/package.json
generated
vendored
Normal file
42
node_modules/content-type/package.json
generated
vendored
Normal file
@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "content-type",
|
||||
"description": "Create and parse HTTP Content-Type header",
|
||||
"version": "1.0.5",
|
||||
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"content-type",
|
||||
"http",
|
||||
"req",
|
||||
"res",
|
||||
"rfc7231"
|
||||
],
|
||||
"repository": "jshttp/content-type",
|
||||
"devDependencies": {
|
||||
"deep-equal": "1.0.1",
|
||||
"eslint": "8.32.0",
|
||||
"eslint-config-standard": "15.0.1",
|
||||
"eslint-plugin-import": "2.27.5",
|
||||
"eslint-plugin-node": "11.1.0",
|
||||
"eslint-plugin-promise": "6.1.1",
|
||||
"eslint-plugin-standard": "4.1.0",
|
||||
"mocha": "10.2.0",
|
||||
"nyc": "15.1.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"HISTORY.md",
|
||||
"README.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --reporter spec --check-leaks --bail test/",
|
||||
"test-ci": "nyc --reporter=lcovonly --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test",
|
||||
"version": "node scripts/version-history.js && git add HISTORY.md"
|
||||
}
|
||||
}
|
4
node_modules/cookie-signature/.npmignore
generated
vendored
Normal file
4
node_modules/cookie-signature/.npmignore
generated
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
support
|
||||
test
|
||||
examples
|
||||
*.sock
|
38
node_modules/cookie-signature/History.md
generated
vendored
Normal file
38
node_modules/cookie-signature/History.md
generated
vendored
Normal file
@ -0,0 +1,38 @@
|
||||
1.0.6 / 2015-02-03
|
||||
==================
|
||||
|
||||
* use `npm test` instead of `make test` to run tests
|
||||
* clearer assertion messages when checking input
|
||||
|
||||
|
||||
1.0.5 / 2014-09-05
|
||||
==================
|
||||
|
||||
* add license to package.json
|
||||
|
||||
1.0.4 / 2014-06-25
|
||||
==================
|
||||
|
||||
* corrected avoidance of timing attacks (thanks @tenbits!)
|
||||
|
||||
1.0.3 / 2014-01-28
|
||||
==================
|
||||
|
||||
* [incorrect] fix for timing attacks
|
||||
|
||||
1.0.2 / 2014-01-28
|
||||
==================
|
||||
|
||||
* fix missing repository warning
|
||||
* fix typo in test
|
||||
|
||||
1.0.1 / 2013-04-15
|
||||
==================
|
||||
|
||||
* Revert "Changed underlying HMAC algo. to sha512."
|
||||
* Revert "Fix for timing attacks on MAC verification."
|
||||
|
||||
0.0.1 / 2010-01-03
|
||||
==================
|
||||
|
||||
* Initial release
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user